diff --git a/README.md b/README.md index 29c94b804..1ead84bb8 100755 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ List of Definitions * [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov)) * [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber)) * [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay)) +* [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik)) * [CodeMirror](http://codemirror.net) (by [François de Campredon](https://github.com/fdecampredon)) * [Commander](http://github.com/visionmedia/commander.js) (by [Marcelo Dezem](https://github.com/mdezem)) * [Couchbase / Couchnode](https://github.com/couchbase/couchnode) (by [Basarat Ali Syed](https://github.com/basarat)) @@ -62,6 +63,7 @@ List of Definitions * [d3.js](http://d3js.org/) (from TypeScript samples) * [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) (by [Maksim Kozhukh](http://github.com/mkozhukh)) * [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) (by [Maksim Kozhukh](http://github.com/mkozhukh)) +* [Dock Spawn](http://dockspawn.com) (by [Drew Noakes](https://drewnoakes.com)) * [docCookies](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) (by [Jon Egerton](https://github.com/jonegerton)) * [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton)) * [doT](https://github.com/olado/doT) (by [ZombieHunter](https://github.com/ZombieHunter)) @@ -137,6 +139,7 @@ List of Definitions * [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [François Guillot](http://fguillot.developpez.com/)) * [jQuery.Cycle2](http://jquery.malsup.com/cycle2/) (by [Donny Nadolny](https://github.com/dnadolny)) * [jQuery.dataTables](http://www.datatables.net) (by [Armin Sander](https://github.com/pragmatrix)) +* [jQuery.datetimepicker](http://trentrichardson.com/examples/timepicker/) (by [Doug McDonald](https://github.com/dougajmcdonald)) * [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [François de Campredon](https://github.com/fdecampredon)) * [jQuery.Flot](http://www.flotcharts.org/) (by [Matt Burland](https://github.com/burlandm)) * [jQuery.form](http://malsup.com/jquery/form/) (by [François Guillot](http://fguillot.developpez.com/)) @@ -144,6 +147,7 @@ List of Definitions * [jQuery.gridster](http://gridster.net) (by [Josh Baldwin](https://github.com/jbaldwin/gridster.d.ts)) * [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/)) * [jQuery.joyride](http://zurb.com/playground/jquery-joyride-feature-tour-plugin) (by [Vincent Bortone](https://github.com/vbortone)) +* [jQuery.jSignature] (https://github.com/willowsystems/jSignature) (by [Patrick Magee](https://github.com/pjmagee)) * [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/)) * [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb)) * [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/)) @@ -155,6 +159,7 @@ List of Definitions * [jQuery.Timer](http://jchavannes.com/jquery-timer/demo) (by [Joshua Strobl](https://github.com/JoshStrobl)) * [jQuery.TinyCarousel](http://baijs.nl/tinycarousel/) (by [Christiaan Rakowski](https://github.com/csrakowski)) * [jQuery.TinyScrollbar](http://baijs.nl/tinyscrollbar/) (by [Christiaan Rakowski](https://github.com/csrakowski)) +* [jQuery.tooltipster] (https://github.com/iamceege/tooltipster) (by [Patrick Magee](https://github.com/pjmagee)) * [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U)) * [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov)) * [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved)) @@ -238,7 +243,7 @@ List of Definitions * [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame)) * [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u)) * [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin)) -* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley)) +* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com)) * [socket.io](http://socket.io) (by [William Orr](https://github.com/worr)) * [socket.io-client](http://socket.io) (by [Maido Kaara](https://github.com/v3rm0n)) * [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev)) @@ -264,6 +269,7 @@ List of Definitions * [Underscore.js (Typed)](http://underscorejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/)) * [Underscore-ko.js](https://github.com/kamranayub/UnderscoreKO) (by [Maurits Elbers](https://github.com/MagicMau)) * [universal-analytics](https://github.com/peaksandpies/universal-analytics) (by [Bart van der Schoor](https://github.com/Bartvds)) +* [urlrouter](https://github.com/fengmk2/urlrouter) (by [Carlos Ballesteros Velasco](https://github.com/soywiz)) * [UUID.js](https://github.com/LiosK/UUID.js) (by [Jason Jarrett](https://github.com/staxmanade)) * [Valerie](https://github.com/davewatts/valerie) (by [Howard Richards](https://github.com/conficient)) * [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov)) diff --git a/_infrastructure/tests/compile-runner.bat b/_infrastructure/tests/compile-runner.bat index e54803ec8..49f737c5d 100644 --- a/_infrastructure/tests/compile-runner.bat +++ b/_infrastructure/tests/compile-runner.bat @@ -1 +1 @@ -tsc runner.ts --target ES5 --out runner.js --module commonjs \ No newline at end of file +tsc runner.ts --target ES5 --out runner.js --module commonjs --sourcemap diff --git a/_infrastructure/tests/runner.js b/_infrastructure/tests/runner.js index 649569923..9a3647abd 100644 --- a/_infrastructure/tests/runner.js +++ b/_infrastructure/tests/runner.js @@ -850,7 +850,7 @@ var DT; var Promise = require('bluebird'); - var endDts = /\w\.ts$/i; + var endDts = /\w\.d\.ts$/i; ///////////////////////////////// // .d.ts syntax inspection @@ -1035,9 +1035,6 @@ var DT; // add a closure to queue this.queue.push(function () { - // when activate, add test to active list - _this.active.push(test); - // run it var p = test.run(); p.then(defer.resolve.bind(defer), defer.reject.bind(defer)); @@ -1048,6 +1045,9 @@ var DT; } _this.step(); }); + + // return it + return test; }); this.step(); @@ -1056,13 +1056,9 @@ var DT; }; TestQueue.prototype.step = function () { - var _this = this; - // setTimeout to make it flush - setTimeout(function () { - while (_this.queue.length > 0 && _this.active.length < _this.concurrent) { - _this.queue.pop().call(null); - } - }, 1); + while (this.queue.length > 0 && this.active.length < this.concurrent) { + this.active.push(this.queue.pop().call(null)); + } }; return TestQueue; })(); @@ -1297,10 +1293,12 @@ var DT; process.exit(0); } + var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false; + new TestRunner(dtPath, { concurrent: argv['single-thread'] ? 1 : Math.max(cpuCores, 2), tscVersion: argv['tsc-version'], - testChanges: argv['test-changes'], + testChanges: testFull ? false : argv['test-changes'], skipTests: argv['skip-tests'], printFiles: argv['print-files'], printRefMap: argv['print-refmap'], @@ -1314,4 +1312,7 @@ var DT; process.exit(2); }); })(DT || (DT = {})); +//grunt-start +/// +//grunt-end //# sourceMappingURL=runner.js.map diff --git a/_infrastructure/tests/runner.ts b/_infrastructure/tests/runner.ts index 6e71d621a..5d4f42815 100644 --- a/_infrastructure/tests/runner.ts +++ b/_infrastructure/tests/runner.ts @@ -75,8 +75,6 @@ module DT { var defer = Promise.defer(); // add a closure to queue this.queue.push(() => { - // when activate, add test to active list - this.active.push(test); // run it var p = test.run(); p.then(defer.resolve.bind(defer), defer.reject.bind(defer)); @@ -87,6 +85,8 @@ module DT { } this.step(); }); + // return it + return test; }); this.step(); // defer it @@ -94,12 +94,9 @@ module DT { } private step(): void { - // setTimeout to make it flush - setTimeout(() => { - while (this.queue.length > 0 && this.active.length < this.concurrent) { - this.queue.pop().call(null); - } - }, 1); + while (this.queue.length > 0 && this.active.length < this.concurrent) { + this.active.push(this.queue.pop().call(null)); + } } } @@ -339,10 +336,12 @@ module DT { process.exit(0); } + var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false; + new TestRunner(dtPath, { concurrent: argv['single-thread'] ? 1 : Math.max(cpuCores, 2), tscVersion: argv['tsc-version'], - testChanges: argv['test-changes'], + testChanges: testFull ? false : argv['test-changes'], // allow magic branch skipTests: argv['skip-tests'], printFiles: argv['print-files'], printRefMap: argv['print-refmap'], diff --git a/_infrastructure/tests/src/suite/syntax.ts b/_infrastructure/tests/src/suite/syntax.ts index 9211c3fde..915fd18d0 100644 --- a/_infrastructure/tests/src/suite/syntax.ts +++ b/_infrastructure/tests/src/suite/syntax.ts @@ -6,7 +6,7 @@ module DT { var Promise: typeof Promise = require('bluebird'); - var endDts = /\w\.ts$/i; + var endDts = /\w\.d\.ts$/i; ///////////////////////////////// // .d.ts syntax inspection diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index 9b29ef98f..97dd3a3ff 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -885,7 +885,9 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val /** AmChart is a base class of all charts. It can not be instantiated explicitly. AmCoordinateChart, AmPieChart and AmMap extend AmChart class. */ class AmChart { - /** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. #FFFFFF */ + /** used when constructing a chart with a theme */ + constructor(theme: any); + /** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. #FFFFFF */ backgroundColor: string; /** The chart creates AmBalloon class itself. If you want to customize balloon, get balloon instance using this property, and then change balloon's properties. AmBalloon */ balloon: AmBalloon; @@ -943,7 +945,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val @param legend @param legendDivId - Id of the legend div (optional). */ - addLegend(legend: AmLegend, legendDivId: string); + addLegend(legend: AmLegend, legendDivId?: string); /** Adds a legend to the chart. By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. (NOTE: This method will not work on StockPanel.) @@ -1437,7 +1439,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val chart.write("chartdiv"); */ class AmSerialChart extends AmRectangularChart { - /** Read-only. Chart creates category axis itself. If you want to change some properties, you should get this axis from the chart and set properties to this object. */ + /** Read-only. Chart creates category axis itself. If you want to change some properties, you should get this axis from the chart and set properties to this object. */ categoryAxis: CategoryAxis; /** Category field name tells the chart the name of the field in your dataProvider object which will be used for category axis values. */ categoryField: string; diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 0317e17b7..a0cd4ab85 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -51,6 +51,7 @@ declare module ng.resource { // to be considered as parameters to the request. // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465 interface IResourceClass { + new(dataOrParams? : any) : T; get(): T; get(dataOrParams: any): T; get(dataOrParams: any, success: Function): T; diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index b8d1db50b..628d746df 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -41,6 +41,7 @@ declare module ng.route { resolve?: any; redirectTo?: any; reloadOnSearch?: boolean; + caseInsensitiveMatch?: boolean; } // see http://docs.angularjs.org/api/ng.$route#current diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 4ce311698..8ab1efc72 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -94,6 +94,7 @@ module HttpAndRegularPromiseTests { person: Person; theAnswer: number; letters: string[]; + snack: string; } var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { @@ -132,6 +133,12 @@ module HttpAndRegularPromiseTests { cPromise.then((letters: string[]) => { $scope.letters = letters; }); + + // When $q.when is passed an IPromise, it returns an IPromise + var dPromise: ng.IPromise = $q.when($q.when("ALBATROSS!")); + dPromise.then((snack: string) => { + $scope.snack = snack; + }); } // Test that we can pass around a type-checked success/error Promise Callback diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index b369a271f..4a9f12822 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -430,7 +430,7 @@ declare module ng { // DocumentService // see http://docs.angularjs.org/api/ng.$document /////////////////////////////////////////////////////////////////////////// - interface IDocumentService extends Document {} + interface IDocumentService extends IAugmentedJQuery {} /////////////////////////////////////////////////////////////////////////// // ExceptionHandlerService @@ -455,6 +455,7 @@ declare module ng { all(promises: {[id: string]: IPromise;}): IPromise<{[id: string]: any}>; defer(): IDeferred; reject(reason?: any): IPromise; + when(value: IPromise): IPromise; when(value: T): IPromise; } diff --git a/async/async.d.ts b/async/async.d.ts index 12aa4123f..68f2f192f 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -53,6 +53,8 @@ interface Async { 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; whilst(test: Function, fn: Function, callback: Function): void; until(test: Function, fn: Function, callback: Function): void; waterfall(tasks: T[], callback?: AsyncMultipleResultsCallback): void; diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index 14528b9b5..abead4237 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -1,319 +1,882 @@ /// -// Note: try to maintain the ordering and separators +// Tests by: Bart van der Schoor -var obj:Object; -var bool:boolean; -var num:number; -var str:string; -var x:any = null; -var f:Function; -var arr:any[]; -var exp:RegExp; -var strArr:string[]; -var numArr:string[]; +// Note: replicate changes to all overloads in both definition and test file +// Note: keep both static and instance members inline (so similar) +// Note: try to maintain the ordering and separators, and keep to the pattern -var value:any = null; -var reason:any = null; +var obj: Object; +var bool: boolean; +var num: number; +var str: string; +var err: Error; +var x: any; +var f: Function; +var func: Function; +var arr: any[]; +var exp: RegExp; +var anyArr: any[]; +var strArr: string[]; +var numArr: number[]; -var promise:Promise; -var p:Promise; +// - - - - - - - - - - - - - - - - - -var resolver:Promise.Resolver; -var inspection:Promise.Inspection; +var value: any; +var reason: any; +var insanity: any; -// - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -var promise = new Promise((resolve:(value:any) => void, reject:(reason:any) => void) => { - if(true) { - resolve(123); +interface Foo { + foo(): string; +} +interface Bar { + bar(): string; +} + +// - - - - - - - - - - - - - - - - - + +interface StrFooMap { + [key:string]:Foo; +} + +interface StrBarMap { + [key:string]:Bar; +} + +// - - - - - - - - - - - - - - - - - + +interface StrFooArrMap { + [key:string]:Foo[]; +} + +interface StrBarArrMap { + [key:string]:Bar[]; +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var foo: Foo; +var bar: Bar; + +var fooArr: Foo[]; +var barArr: Bar[]; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numProm: Promise; +var strProm: Promise; +var anyProm: Promise; +var boolProm: Promise; +var objProm: Promise; +var voidProm: Promise; + +var fooProm: Promise; +var barProm: Promise; + +// - - - - - - - - - - - - - - - - - + +var numThen: Promise.Thenable; +var strThen: Promise.Thenable; +var anyThen: Promise.Thenable; +var boolThen: Promise.Thenable; +var objThen: Promise.Thenable; +var voidThen: Promise.Thenable; + +var fooThen: Promise.Thenable; +var barThen: Promise.Thenable; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numArrProm: Promise; +var strArrProm: Promise; +var anyArrProm: Promise; + +var fooArrProm: Promise; +var barArrProm: Promise; + +// - - - - - - - - - - - - - - - - - + +var numArrThen: Promise.Thenable; +var strArrThen: Promise.Thenable; +var anyArrThen: Promise.Thenable; + +var fooArrThen: Promise.Thenable; +var barArrThen: Promise.Thenable; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var numPromArr: Promise[]; +var strPromArr: Promise[]; +var anyPromArr: Promise[]; + +var fooPromArr: Promise[]; +var barPromArr: Promise[]; + +// - - - - - - - - - - - - - - - - - + +var numThenArr: Promise.Thenable[]; +var strThenArr: Promise.Thenable[]; +var anyThenArr: Promise.Thenable[]; + +var fooThenArr: Promise.Thenable[]; +var barThenArr: Promise.Thenable[]; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// booya! +var fooThenArrThen: Promise.Thenable[]>; +var barThenArrThen: Promise.Thenable[]>; + +var fooResolver: Promise.Resolver; +var barResolver: Promise.Resolver; + +var fooInspection: Promise.Inspection; +var barInspection: Promise.Inspection; + +var fooInspectionArrProm: Promise[]>; +var barInspectionArrProm: Promise[]>; + +var BlueBird: typeof Promise; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooThen = fooProm; +barThen = barProm; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = new Promise((resolve: (value: Foo) => void, reject: (reason: any) => void) => { + if (bool) { + resolve(foo); } else { - reject(new Error('nope')); + reject(new Error(str)); + } +}); +fooProm = new Promise((resolve: (value: Foo) => void) => { + if (bool) { + resolve(foo); } }); -// - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - -resolver.resolve(x); +// needs a hint when used untyped? +fooProm = new Promise((resolve, reject) => { + if (bool) { + resolve(fooThen); + } + else { + reject(new Error(str)); + } +}); +fooProm = new Promise((resolve) => { + resolve(fooThen); +}); -resolver.reject(x); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -resolver.progress(x); +fooResolver.resolve(foo); -resolver.callback = () => { +fooResolver.reject(err); + +fooResolver.progress(bar); + +fooResolver.callback = (err: any, value: Foo) => { }; -// - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -bool = inspection.isFulfilled(); +bool = fooInspection.isFulfilled(); -bool = inspection.isRejected(); +bool = fooInspection.isRejected(); -bool = inspection.isPending(); +bool = fooInspection.isPending(); -x = inspection.value(); +foo = fooInspection.value(); -x = inspection.error(); +x = fooInspection.error(); -// - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = promise.then((value:any) => { +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { + return bar; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooProm.then((value: Foo) => { + return bar; +}); -}, (reason:any) => { +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}, (note:any) => { +barProm = fooProm.catch((reason: any) => { + return bar; +}); +barProm = fooProm.caught((reason: any) => { + return bar; +}); + +barProm = fooProm.catch((reason: any) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooProm.caught((reason: any) => { + return bar; +}, (reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.catch(Error, (reason: any) => { + return bar; +}); +barProm = fooProm.caught(Error, (reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.error((reason: any) => { + return bar; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.finally((value: Foo) => { + // return is ignored + return foo; +}); +fooProm = fooProm.finally((value: Foo) => { + // return is ignored + return fooThen; +}); +fooProm = fooProm.finally((value: Foo) => { + // return is ignored +}); +fooProm = fooProm.finally(() => { + // return is ignored +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.lastly((value: Foo) => { + // return is ignored + return foo; +}); +fooProm = fooProm.lastly((value: Foo) => { + // return is ignored + return fooThen; +}); +fooProm = fooProm.lastly((value: Foo) => { + // return is ignored +}); +fooProm = fooProm.lastly(() => { + // return is ignored +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.bind(obj); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.done((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { }); -p = promise.then((value:any) => { +barProm = fooProm.done((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooProm.done((value: Foo) => { + return bar; +}); -}, (reason:any) => { +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.done((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}, (note: any) => { }); -p = promise.then((value:any) => { +barProm = fooProm.done((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}); +barProm = fooProm.done((value: Foo) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.progressed((note: any) => { + return foo; +}); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.delay(num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.timeout(num); +fooProm = fooProm.timeout(num, str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm.nodeify(); +fooProm = fooProm.nodeify((err: any) => { + +}); +fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = promise.catch((reason:any) => { +barProm = fooProm.fork((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; +}, (note: any) => { }); -p = promise.caught((reason:any) => { - +barProm = fooProm.fork((value: Foo) => { + return bar; +}, (reason: any) => { + return bar; }); -p = promise.catch((reason:any) => { - return true; -}, (reason:any) => { - -}); -p = promise.caught((reason:any) => { - return true; -}, (reason:any) => { - +barProm = fooProm.fork((value: Foo) => { + return bar; }); -p = promise.catch(Error, (reason:any) => { +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.fork((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}, (note: any) => { }); -p = promise.caught(Error, (reason:any) => { - +barProm = fooProm.fork((value: Foo) => { + return barThen; +}, (reason: any) => { + return barThen; +}); +barProm = fooProm.fork((value: Foo) => { + return barThen; }); -p = promise.error((reason:any) => { +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +barProm = fooProm.cancel(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.cancellable(); +fooProm = fooProm.uncancellable(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +bool = fooProm.isCancellable(); +bool = fooProm.isFulfilled(); +bool = fooProm.isRejected(); +bool = fooProm.isPending(); +bool = fooProm.isResolved(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooInspection = fooProm.inspect(); + +anyProm = fooProm.call(str); +anyProm = fooProm.call(str, 1, 2, 3); + +//TODO enable get() test when implemented +// barProm = fooProm.get(str); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooProm.return(bar); +barProm = fooProm.thenReturn(bar); + +voidProm = fooProm.return(); +voidProm = fooProm.thenReturn(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooProm +fooProm = fooProm.throw(err); +fooProm = fooProm.thenThrow(err); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +str = fooProm.toString(); + +obj = fooProm.toJSON(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooArrProm.spread((one: Foo, two: Bar) => { + return bar; +}, (reason: any) => { + return bar; +}); +barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { + return bar; }); -p = promise.finally((value:any) => { +// - - - - - - - - - - - - - - - - - +barProm = fooArrProm.spread((one: Foo, two: Bar) => { + return barThen; +}, (reason: any) => { + return barThen; }); -p = promise.lastly((value:any) => { - +barProm = fooArrProm.spread((one: Foo, two: Bar, twotwo: Foo) => { + return barThen; }); -p = promise.bind(x); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = promise.done((value:any) => { +//TODO fix collection inference -}, (reason:any) => { +barArrProm = fooProm.all(); -}, (note:any) => { +objProm = fooProm.props(); +barInspectionArrProm = fooProm.settle(); + +barProm = fooProm.any(); + +barArrProm = fooProm.some(num); + +barProm = fooProm.race(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO fix collection inference + +barProm = fooProm.map((item: Foo, index: number, arrayLength: number) => { + return bar; }); -p = promise.done((value:any) => { - -}, (reason:any) => { - -}); -p = promise.done((value:any) => { - +barProm = fooProm.map((item: Foo) => { + return bar; }); -p = promise.progressed((note:any) => { +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -}); - -p = promise.delay(x); - -p = promise.timeout(x); -p = promise.timeout(x, str); - -p = promise.nodeify(); -p = promise.nodeify(function(err:any) { - -}); - -p = promise.cancellable(); - -p = promise.cancel(); - -p = promise.fork((value:any) => { - -}, (reason:any) => { - -}, (note:any) => { - -}); -p = promise.fork((value:any) => { - -}, (reason:any) => { - -}); -p = promise.fork((value:any) => { - -}); - -p = promise.uncancellable(); - -bool = promise.isCancellable(); - -bool = promise.isFulfilled(); - -bool = promise.isRejected(); - -bool = promise.isPending(); - -bool = promise.isResolved(); - -inspection = promise.inspect(); - -p = promise.call(str, 1, 2, 3); - -p = promise.get(str); - -p = promise.return(value); -p = promise.thenReturn(); - -p = promise.throw(x); -p = promise.thenThrow(); - -str = promise.toString(); - -obj = promise.toJSON(); - -p = promise.all(); - -p = promise.props(); - -p = promise.settle(); - -p = promise.any(); - -p = promise.some(x); - -p = promise.race(); - -p = promise.spread((value:any) => { - -}, (reason:any) => { - -}); -p = promise.spread((value:any) => { - -}); - -p = promise.map((item:any, index:number, arrayLength:number) => { - return x; -}); - -p = promise.reduce((total:number, memo:any, index:number, arrayLength:number) => { +barProm = fooProm.reduce((memo: Bar, item: Foo, index: number, arrayLength: number) => { return memo; }); -p = promise.reduce((total:number, memo:any, index:number, arrayLength:number) => { +barProm = fooProm.reduce((memo: Bar, item: Foo) => { return memo; -}, x); +}, bar); -p = promise.filter((item:any, index?:number, arrayLength?:number) => { - return true; +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = fooProm.filter((item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooProm = fooProm.filter((item: Foo) => { + return bool; }); -// - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = new Promise((resolve:(value:any) => any, reject:(reason:any) => any) => { - if(true) { - resolve(value); - } - else { - reject(new Error('xyz')); - } + +fooProm = Promise.try(() => { + return foo; }); +fooProm = Promise.try(() => { + return foo; +}, arr); +fooProm = Promise.try(() => { + return foo; +}, arr, x); -/* - p = Promise.try(() => {}); - p = Promise.try(() => {}, arr); - p = Promise.try(() => {}, arr, x); - */ +// - - - - - - - - - - - - - - - - - -p = Promise.attempt(() => {}); -p = Promise.attempt(() => {}, arr); -p = Promise.attempt(() => {}, arr, x); +fooProm = Promise.try(() => { + return fooThen; +}); +fooProm = Promise.try(() => { + return fooThen; +}, arr); +fooProm = Promise.try(() => { + return fooThen; +}, arr, x); -f = Promise.method(function() { +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = Promise.attempt(() => { + return foo; +}); +fooProm = Promise.attempt(() => { + return foo; +}, arr); +fooProm = Promise.attempt(() => { + return foo; +}, arr, x); + +// - - - - - - - - - - - - - - - - - + +fooProm = Promise.attempt(() => { + return fooThen; +}); +fooProm = Promise.attempt(() => { + return fooThen; +}, arr); +fooProm = Promise.attempt(() => { + return fooThen; +}, arr, x); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +func = Promise.method(function () { }); -p = Promise.resolve(value); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = Promise.reject(reason); +fooProm = Promise.resolve(foo); +fooProm = Promise.resolve(fooThen); -resolver = Promise.defer(); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = Promise.cast(value); +voidProm = Promise.reject(reason); -p = Promise.bind(x); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooResolver = Promise.defer(); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooProm = Promise.cast(foo); +fooProm = Promise.cast(fooThen); + +voidProm = Promise.bind(x); bool = Promise.is(value); Promise.longStackTraces(); -p = Promise.delay(p, x); -p = Promise.delay(value, x); -p = Promise.delay(x); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -f = Promise.promisify(f); -f = Promise.promisify(f, x); +//TODO enable delay -obj = Promise.promisify(obj); +fooProm = Promise.delay(fooThen, num); +fooProm = Promise.delay(foo, num); +voidProm = Promise.delay(num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +func = Promise.promisify(f); +func = Promise.promisify(f, obj); +; obj = Promise.promisifyAll(obj); -f = Promise.coroutine(f); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = Promise.spawn(f); +//TODO enable generator +/* + func = Promise.coroutine(f); -obj = Promise.noConflict(); + barProm = Promise.spawn(f); + */ +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Promise.onPossiblyUnhandledRejection((reason:any) => { +BlueBird = Promise.noConflict(); + +Promise.onPossiblyUnhandledRejection((reason: any) => { }); -p = Promise.all(arr); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = Promise.props(p); -p = Promise.props(obj); +//TODO expand tests to overloads +fooArrProm = Promise.all(fooThenArrThen); +fooArrProm = Promise.all(fooArrProm); +fooArrProm = Promise.all(fooThenArr); +fooArrProm = Promise.all(fooArr); -p = Promise.settle(arr); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = Promise.any(arr); +objProm = Promise.props(objProm); +objProm = Promise.props(obj); -p = Promise.race(arr); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = Promise.some(arr, x); +//TODO expand tests to overloads +fooInspectionArrProm = Promise.settle(fooThenArrThen); +fooInspectionArrProm = Promise.settle(fooArrProm); +fooInspectionArrProm = Promise.settle(fooThenArr); +fooInspectionArrProm = Promise.settle(fooArr); -p = Promise.join(1, 2, 3); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -p = Promise.map(arr, (item:any, index:number, arrayLength:number) => { - return x; +//TODO expand tests to overloads +fooProm = Promise.any(fooThenArrThen); +fooProm = Promise.any(fooArrProm); +fooProm = Promise.any(fooThenArr); +fooProm = Promise.any(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooProm = Promise.race(fooThenArrThen); +fooProm = Promise.race(fooArrProm); +fooProm = Promise.race(fooThenArr); +fooProm = Promise.race(fooArr); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +//TODO expand tests to overloads +fooArrProm = Promise.some(fooThenArrThen, num); +fooArrProm = Promise.some(fooArrThen, num); +fooArrProm = Promise.some(fooThenArr, num); +fooArrProm = Promise.some(fooArr, num); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +fooArrProm = Promise.join(foo, foo, foo); +fooArrProm = Promise.join(fooThen, fooThen, fooThen); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// map() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; }); -p = Promise.reduce(arr, (total:number, memo:any, index:number, arrayLength:number) => { +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barArrProm = Promise.map(fooArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.map(fooArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// reduce() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo) => { return memo; -}); -p = Promise.reduce(arr, (total:number, memo:any, index:number, arrayLength:number) => { +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { return memo; -}, x); +}, bar); +barProm = Promise.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); -p = Promise.filter(arr, (item:any, index?:number, arrayLength?:number) => { - return true; +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo) => { + return barThen; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return memo; +}, bar); +barProm = Promise.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => { + return barThen; +}, bar); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// filter() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return bool; }); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return bool; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return boolThen; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index 5db21d63e..8912ebb88 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -3,27 +3,44 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -// Note: these are preliminary non-generic typings using `any`: the generic versions are ready but need (tsc >= v1.0.0) due to issues in the compiler -// - https://github.com/borisyankov/DefinitelyTyped/issues/1563 -// - https://github.com/borisyankov/DefinitelyTyped/tree/def/bluebird/bluebird +// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts +// By: Campredon -declare class Promise { +// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code): +// - https://github.com/borisyankov/DefinitelyTyped/issues/1563 + +// Note: replicate changes to all overloads in both definition and test file +// Note: keep both static and instance members inline (so similar) + +// TODO fix remaining TODO annotations in both definition and test + +// TODO verify support to have no return statement in handlers to get a Promise (more overloads?) + +declare class Promise implements Promise.Thenable { /** * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. */ - constructor(resolver: (resolve: (value: any) => void, reject: (reason: any) => any) => void); + constructor(callback: (resolve: (thenable: Promise.Thenable) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void); + /** * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. */ - then(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any):Promise; + then(onFulfill: (value: R) => Promise.Thenable, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + then(onFulfill: (value: R) => Promise.Thenable, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; + then(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + then(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; /** * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ - catch(handler: (reason: any) => any):Promise; - caught(handler: (reason: any) => any):Promise; + catch(onReject?: (error: any) => Promise.Thenable): Promise; + caught(onReject?: (error: any) => Promise.Thenable): Promise; + + catch(onReject?: (error: any) => U): Promise; + caught(onReject?: (error: any) => U): Promise; /** * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. @@ -32,64 +49,78 @@ declare class Promise { * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ - //TODO expand this complex overload (weird) - catch(predicate: (reason: any) => boolean, handler: (reason: any) => any): Promise; - caught(predicate: (reason: any) => boolean, handler: (reason: any) => any): Promise; + catch(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; - catch(ErrorClass: Function, handler: (reason: any) => any): Promise; - caught(ErrorClass: Function, handler: (reason: any) => any): Promise; + catch(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; + + catch(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; + caught(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; + + catch(ErrorClass: Function, onReject: (error: any) => U): Promise; + caught(ErrorClass: Function, onReject: (error: any) => U): Promise; /** * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. */ - error(rejectedHandler: (reason: any) => any): Promise; + error(onReject: (reason: any) => Promise.Thenable): Promise; + error(onReject: (reason: any) => U): Promise; /** * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. * * Alias `.lastly();` for compatibility with earlier ECMAScript version. */ - finally(handler: (value: any) => any): Promise; - lastly(handler: (value: any) => any): Promise; + finally(handler: (value: R) => Promise.Thenable): Promise; + finally(handler: (value: R) => R): Promise; + finally(handler: (value: R) => void): Promise; + + lastly(handler: (value: R) => Promise.Thenable): Promise; + lastly(handler: (value: R) => R): Promise; + lastly(handler: (value: R) => void): Promise; /** * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. */ - bind(thisArg: any): Promise; + bind(thisArg: any): Promise; /** * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. */ - done(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any): Promise; + done(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + done(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; + done(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + done(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; /** * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. */ - progressed(handler: (note: any) => any): Promise; + progressed(handler: (note: any) => any): Promise; /** * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - delay(ms: number): Promise; + delay(ms: number): Promise; /** * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. * * You may specify a custom error message with the `message` parameter. */ - - timeout(ms: number, message?: string): Promise; + timeout(ms: number, message?: string): Promise; /** * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. */ - nodeify(callback?: Function): Promise; + nodeify(callback: (err: any, value?: R) => void): Promise; + nodeify(...sink: any[]): void; /** * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. */ - cancellable(): Promise; + cancellable(): Promise; /** * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. @@ -100,17 +131,21 @@ declare class Promise { * * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. */ - cancel(): Promise; + // TODO what to do with this? + cancel(): Promise; /** * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. */ - fork(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any): Promise; + fork(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + fork(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; + fork(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; + fork(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; /** * Create an uncancellable promise based on this promise. */ - uncancellable(): Promise; + uncancellable(): Promise; /** * See if this promise can be cancelled. @@ -138,62 +173,65 @@ declare class Promise { isResolved(): boolean; /** - * Synchronously inspect the state of this `promise`. The `Promise.Inspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. */ - inspect(): Promise.Inspection; + inspect(): Promise.Inspection; /** * This is a convenience method for doing: * * * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); + * return obj[propertyName].call(obj, arg...); + * }); * */ - call(propertyName: string, ...args: any[]): Promise; + call(propertyName: string, ...args: any[]): Promise; /** * This is a convenience method for doing: * * * promise.then(function(obj){ - * return obj[propertyName]; - * }); + * return obj[propertyName]; + * }); * */ - get(propertyName: string): Promise; + // TODO find way to fix get() + // get(propertyName: string): Promise; /** * Convenience method for: * * * .then(function() { - * return value; - * }); + * return value; + * }); * * * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` * * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. */ - return(value: any): Promise; - thenReturn(): Promise; + return(): Promise; + thenReturn(): Promise; + return(value: U): Promise; + thenReturn(value: U): Promise; /** * Convenience method for: * * * .then(function() { - * throw reason; - * }); + * throw reason; + * }); * * Same limitations apply as with `.return()`. * * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. */ - throw(reason: any): Promise; - thenThrow(): Promise; + throw(reason: Error): Promise; + thenThrow(reason: Error): Promise; /** * Convert to String. @@ -205,64 +243,376 @@ declare class Promise { */ toJSON(): Object; + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + // TODO how to model instance.spread()? like Q? + spread(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable): Promise; + spread(onFulfill: Function, onReject?: (reason: any) => U): Promise; + /* + // TODO or something like this? + spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => Promise.Thenable): Promise; + spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => U): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; + */ /** * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - all(): Promise; + // TODO type inference from array-resolving promise? + all(): Promise; /** * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - props(): Promise; + // TODO how to model instance.props()? + props(): Promise; /** * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - settle(): Promise; + // TODO type inference from array-resolving promise? + settle(): Promise[]>; /** * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - any(): Promise; + // TODO type inference from array-resolving promise? + any(): Promise; /** - * Same as calling `Promise.race(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - some(count: number): Promise; + // TODO type inference from array-resolving promise? + some(count: number): Promise; /** - * Same as calling `Promise.some(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - race(): Promise; - - /** - * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. - */ - spread(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any): Promise; + // TODO type inference from array-resolving promise? + race(): Promise; /** * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - map(mapper: (item: any, index: number, arrayLength: number) => any): Promise; + // TODO type inference from array-resolving promise? + map(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable): Promise; + map(mapper: (item: Q, index: number, arrayLength: number) => U): Promise; /** * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - reduce(reducer: (total: number, current: any, index: number, arrayLength: number) => any, initialValue?: any): Promise; + // TODO type inference from array-resolving promise? + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise; /** * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ - filter(filterer: (item: any, index: number, arrayLength: number) => any): Promise; + // TODO type inference from array-resolving promise? + filter(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable): Promise; + filter(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise; + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + static try(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; + static try(fn: () => R, args?: any[], ctx?: any): Promise; + + static attempt(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; + static attempt(fn: () => R, args?: any[], ctx?: any): Promise; + + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + static method(fn: Function): Function; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + static resolve(): Promise; + static resolve(value: Promise.Thenable): Promise; + static resolve(value: R): Promise; + + /** + * Create a promise that is rejected with the given `reason`. + */ + static reject(reason: any): Promise; + static reject(reason: any): Promise; + + /** + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + */ + static defer(): Promise.Resolver; + + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + static cast(value: Promise.Thenable): Promise; + static cast(value: R): Promise; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + static bind(thisArg: any): Promise; + + /** + * See if `value` is a trusted Promise. + */ + static is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + static longStackTraces(): void; + + /** + * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. + */ + // TODO enable more overloads + static delay(value: Promise.Thenable, ms: number): Promise; + static delay(value: R, ms: number): Promise; + static delay(ms: number): Promise; + + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + // TODO how to model promisify? + static promisify(nodeFunction: Function, receiver?: any): Function; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + static promisifyAll(target: Object): Object; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix coroutine GeneratorFunction + static coroutine(generatorFunction: Function): Function; + + /** + * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix spawn GeneratorFunction + static spawn(generatorFunction: Function): Promise; + + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. + */ + static noConflict(): typeof Promise; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // promise of array with promises of value + static all(values: Promise.Thenable[]>): Promise; + // promise of array with values + static all(values: Promise.Thenable): Promise; + // array with promises of value + static all(values: Promise.Thenable[]): Promise; + // array with values + static all(values: R[]): Promise; + + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // TODO verify this is correct + // trusted promise for object + static props(object: Promise): Promise; + // object + static props(object: Object): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. + * + * *original: The array is not modified. The input array sparsity is retained in the resulting array.* + */ + // promise of array with promises of value + static settle(values: Promise.Thenable[]>): Promise[]>; + // promise of array with values + static settle(values: Promise.Thenable): Promise[]>; + // array with promises of value + static settle(values: Promise.Thenable[]): Promise[]>; + // array with values + static settle(values: R[]): Promise[]>; + + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + // promise of array with promises of value + static any(values: Promise.Thenable[]>): Promise; + // promise of array with values + static any(values: Promise.Thenable): Promise; + // array with promises of value + static any(values: Promise.Thenable[]): Promise; + // array with values + static any(values: R[]): Promise; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + // promise of array with promises of value + static race(values: Promise.Thenable[]>): Promise; + // promise of array with values + static race(values: Promise.Thenable): Promise; + // array with promises of value + static race(values: Promise.Thenable[]): Promise; + // array with values + static race(values: R[]): Promise; + + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + static some(values: Promise.Thenable[]>, count: number): Promise; + // promise of array with values + static some(values: Promise.Thenable, count: number): Promise; + // array with promises of value + static some(values: Promise.Thenable[], count: number): Promise; + // array with values + static some(values: R[], count: number): Promise; + + /** + * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. + */ + // variadic array with promises of value + static join(...values: Promise.Thenable[]): Promise; + // variadic array with values + static join(...values: R[]): Promise; + + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise; + + // promise of array with values + static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => U): Promise; + + // array with promises of value + static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; + + // array with values + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; + + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + // promise of array with promises of value + static reduce(values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + static reduce(values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + // promise of array with values + static reduce(values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + static reduce(values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + // array with promises of value + static reduce(values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + static reduce(values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + // array with values + static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + // promise of array with promises of value + static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + + // promise of array with values + static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + + // array with promises of value + static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + + // array with values + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; } declare module Promise { + export interface RangeError extends Error { + } + export interface CancellationError extends Error { + } + export interface TimeoutError extends Error { + } + export interface TypeError extends Error { + } + export interface RejectionError extends Error { + } + + export interface Thenable { + then(onFulfilled: (value: R) => Thenable, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled: (value: R) => Thenable, onRejected?: (error: any) => U): Thenable; + then(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable): Thenable; + then(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable; + } + + export interface Resolver { + /** + * Returns a reference to the controlled promise that can be passed to clients. + */ + promise: Promise; - interface Resolver { /** * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. */ - resolve(value: any): void; + resolve(value: R): void; + resolve(): void; /** * Reject the underlying promise with `reason` as the rejection reason. @@ -275,14 +625,15 @@ declare module Promise { progress(value: any): void; /** - * Gives you a callback representation of the `Promise.Resolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. * * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. */ - callback:Function; + // TODO specify resolver callback + callback: (err: any, value: R, ...values: R[]) => void; } - interface Inspection { + export interface Inspection { /** * See if the underlying promise was fulfilled at the creation time of this inspection object. */ @@ -303,7 +654,7 @@ declare module Promise { * * throws `TypeError` */ - value(): any; + value(): R; /** * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. @@ -312,190 +663,8 @@ declare module Promise { */ error(): any; } - - /** - * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. - * - * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. - * - * Alias for `attempt();` for compatibility with earlier ECMAScript version. - */ - // function try(fn: () => any, args?: any[], ctx?: any): Promise; - - function attempt(fn: () => any, args?: any[], ctx?: any): Promise; - - /** - * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. - * This method is convenient when a function can sometimes return synchronously or throw synchronously. - */ - function method(fn: Function): Function; - - /** - * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. - */ - function resolve(value: any): Promise; - - /** - * Create a promise that is rejected with the given `reason`. - */ - function reject(reason: any): Promise; - - /** - * Create a promise with undecided fate and return a `Promise.Resolver` to control it. See resolution?:Promise(#promise-resolution). - */ - function defer(): Promise.Resolver; - - /** - * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is:Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that:Promise assimilates the state of the thenable. - */ - function cast(value: any): Promise; - - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - function bind(thisArg: any): Promise; - - /** - * See if `value` is a trusted Promise. - */ - function is(value: any): boolean; - - /** - * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. - */ - function longStackTraces(): void; - - /** - * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. - */ - function delay(value: Promise, ms: number): Promise; - - function delay(value: any, ms: number): Promise; - - function delay(ms: number): Promise; - - /** - * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. - * - * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. - * - * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. - */ - function promisify(nodeFunction: Function, receiver?: any): Function; - - /** - * This overload has been **deprecated**. The overload will continue working for now. The recommended method for promisifying multiple methods at once is ``Promise.promisifyAll(Object target)`` - */ - function promisify(target: Object): Object; - - /** - * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. - * - * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. - */ - function promisifyAll(target: Object): Object; - - /** - * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - function coroutine(generatorFunction: Function): Function; - - /** - * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - function spawn(generatorFunction: Function): Promise; - - /** - * This is relevant to browser environments with no module loader. - * - * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. - */ - function noConflict(): Object; - - /** - * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. - * - * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. - */ - function onPossiblyUnhandledRejection(handler: (reason: any) => any): void; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. - */ - function all(values: any[]): Promise; - - /** - * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. - * - * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. - * - * *The original object is not modified.* - */ - function props(object: Promise): Promise; - - function props(object: Object): Promise; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``Promise.Inspection`` instances at respective positions in relation to the input array. - * - * *original:The array is not modified. The input array sparsity is retained in the resulting array.* - */ - function settle(values: any[]): Promise; - - /** - * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. - */ - function any(values: any[]): Promise; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. - * - * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. - */ - function race(values: any[]): Promise; - - /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. - * - * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. - * - * *The original array is not modified.* - */ - function some(values: any[], count: number): Promise; - - /** - * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. - */ - function join(...values: any[]): Promise; - - /** - * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - function map(values: any[], mapper: (item: any, index: number, arrayLength: number) => any): Promise; - - /** - * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* - */ - function reduce(values: any[], reducer: (total: number, current: any, index: number, arrayLength: number) => any, initialValue?: any): Promise; - - /** - * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. - * - * *The original array is not modified. - */ - function filter(values: any[], filterer: (item: any, index?: number, arrayLength?: number) => any): Promise; } declare module 'bluebird' { -export = Promise; + export = Promise; } diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap.datepicker/bootstrap.datepicker.d.ts index 0664b2aa0..41f2fcd25 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap.datepicker/bootstrap.datepicker.d.ts @@ -8,11 +8,11 @@ interface DatepickerOptions { format?: string; weekStart?: number; - startDate?: Date; - endDate?: Date; + startDate?: any; + endDate?: any; autoclose?: boolean; startView?: number; - todayBtn?: boolean; + todayBtn?: any; todayHighlight?: boolean; keyboardNavigation?: boolean; language?: string; diff --git a/bootstrap.paginator/bootstrap.paginator.d.ts b/bootstrap.paginator/bootstrap.paginator.d.ts index e45f1c3ce..1e6c17c28 100644 --- a/bootstrap.paginator/bootstrap.paginator.d.ts +++ b/bootstrap.paginator/bootstrap.paginator.d.ts @@ -14,10 +14,11 @@ interface PaginatorOptions{ totalPages?: number; pageUrl?: (type, page, current) => string; shouldShowPage?: boolean; - itemText?: (type, page, current) => any; + itemTexts?: (type:string, page:number, current:number) => string; tooltipTitles?: (type, page, current) => string; useBootstrapTooltip?: boolean; bootstrapTooltipOptions?: {}; + bootstrapMajorVersion?: number; onPageClicked?: (event, originalEvent, type, page) => void; onPageChanged?: (event, originalEvent, type, page) => void; } diff --git a/ckeditor/ckeditor-tests.ts b/ckeditor/ckeditor-tests.ts new file mode 100644 index 000000000..976b85717 --- /dev/null +++ b/ckeditor/ckeditor-tests.ts @@ -0,0 +1,254 @@ +/// + +function test_CKEDITOR() { + CKEDITOR.basePath = 'test'; + CKEDITOR.replaceClass = 'rich_editor'; + CKEDITOR.skinName = 'moono'; + CKEDITOR.skinName = 'myskin,/customstuff/myskin/'; + var editor = new CKEDITOR.editor(); + if (editor.getSelection().getType() == CKEDITOR.SELECTION_ELEMENT) + if (editor.getSelection().getType() == CKEDITOR.SELECTION_NONE) + if (editor.getSelection().getType() == CKEDITOR.SELECTION_TEXT) + alert(CKEDITOR.basePath); + if (CKEDITOR.currentInstance) + alert(CKEDITOR.currentInstance.name); + alert(CKEDITOR.document.getBody().getName()); + alert(CKEDITOR.instances[0].name); + CKEDITOR.loadFullCoreTimeout = 5; + alert(CKEDITOR.revision); + alert(CKEDITOR.rnd); + if (CKEDITOR.status == 'loaded') { + CKEDITOR.loadFullCore(); + } + alert(CKEDITOR.timestamp); + CKEDITOR.addCss('.cke_editable h1,.cke_editable h2,.cke_editable h3 { border-bottom: 1px dotted red }'); + CKEDITOR.appendTo('editorSpace'); + alert(CKEDITOR.getUrl('skins/default/editor.css')); + alert(CKEDITOR.getUrl('/skins/default/editor.css')); + alert(CKEDITOR.getUrl('http://www.somesite.com/skins/default/editor.css')); + CKEDITOR.inline('content'); + if (CKEDITOR.loadFullCore) + CKEDITOR.loadFullCore(); + CKEDITOR.replace('myfield'); + var textarea = document.createElement('textarea'); + CKEDITOR.replace(textarea); + CKEDITOR.replaceAll(); + CKEDITOR.replaceAll('myClassName'); + CKEDITOR.replaceAll((textarea, config) => false); +} + +function test_dom_comment() { + var type = CKEDITOR.NODE_COMMENT; + var nativeNode = document.createComment('Example'); + var comment = new CKEDITOR.dom.comment(nativeNode); + var comment2 = new CKEDITOR.dom.comment('Example'); +} + +function test_dom_document() { + var document = new CKEDITOR.dom.document(window.document); + var type = CKEDITOR.NODE_DOCUMENT; + CKEDITOR.document.appendStyleSheet('/mystyles.css'); + var element = CKEDITOR.document.getBody(); + alert(element.getName()); + var element2 = CKEDITOR.document.getById('myElement'); + alert(element.getId()); + var element3 = CKEDITOR.document.getHead(); + alert(element.getName()); + var selection = CKEDITOR.instances[0].document.getSelection(); + alert(selection.getType()); + document.write( + '' + + 'Sample Doc' + + 'Document contents created by code' + + '' + ); +} + +function test_dom_documentFragment() { + var type = CKEDITOR.NODE_DOCUMENT_FRAGMENT; +} + +function test_dom_domObject() { + var element = new CKEDITOR.dom.element('span'); + alert(element.$.nodeType); + var nativeElement = element.$; + var doc = new CKEDITOR.dom.document(document); + alert(doc.equals(CKEDITOR.document)); + alert(doc == CKEDITOR.document); + var element2 = new CKEDITOR.dom.element('span'); + alert(element.getCustomData('hasCustomData')); + alert(element.getCustomData('nonExistingKey')); + var elementA = new CKEDITOR.dom.element(nativeElement); + elementA.getPrivate().value = 1; + var elementB = new CKEDITOR.dom.element(nativeElement).getPrivate().value; + var element3 = new CKEDITOR.dom.element('span'); + element.setCustomData('hasCustomData', true); +} + +function test_dom_element() { + var element = new CKEDITOR.dom.element('span'); + alert(element.$.nodeType); + element.addClass('classA'); + element.addClass('classB'); + element.addClass('classA'); + var p = new CKEDITOR.dom.element('p'); + var strong = new CKEDITOR.dom.element('strong'); + p.append(strong); + var em = p.append('em'); + var p = new CKEDITOR.dom.element('p'); + p.appendText('This is'); + p.appendText(' some text'); + element.breakParent(strong); + element.data('extra-info', 'test'); + alert(element.data('extra-info')); + element.data('extra-info', false); + var element5 = CKEDITOR.document.getById('myTextarea'); + element.focus(); + element.focusNext(); + element.focusPrevious(); + element.forEach(node=> { + console.log(node); + }); + var element2 = CKEDITOR.dom.element.createFromHtml(''); + alert(element.getAttribute('type')); + alert(element.getComputedStyle('display')); + element.appendTo(CKEDITOR.document.getBody()); + alert(element.getEditor().name); + var first = element.getFirst(); + alert(element.getHtml()); + alert(element.getId()); + alert(element.getName()); + alert('' + element.getNameAtt() + ''); + alert(element.getOuterHtml()); + alert(element.getTabIndex()); + alert(element.getText()); + alert(element.hasAttributes()); + alert(element.hasAttributes()); + element.hide(); + alert(element.is('span')); + alert(element.is('p', 'span')); + alert(element.is('p')); + alert(element.is('p', 'div')); + alert(element.is({ p: 1, span: 1 })); + element.removeAttribute('class'); + element.addClass('classA'); + element.addClass('classB'); + element.removeClass('classA'); + element.removeClass('classB'); + element.removeStyle('display'); + element.setAttribute('class', 'myClass'); + element.setAttribute('title', 'This is an example'); + element.setAttributes({ + 'class': 'myClass', + title: 'This is an example' + }); + p.setHtml('Inner HTML'); + element.setOpacity(0.75); + element.setStyle('background-color', '#ff0000'); + element.setStyle('margin-top', '10px'); + element.setStyle('float', 'right'); + element.setStyles({ + position: 'absolute', + float: 'right' + }); + element.setText('A > B & C < D'); + element.show(); + element.unselectable(); + alert(element.getName()); + alert(element == CKEDITOR.dom.element.get(element)); + var htmlElement = document.getElementById('myElement'); + alert(CKEDITOR.dom.element.get(htmlElement).getName()); +} + +function test_dom_event() { + var event = new CKEDITOR.dom.event(new Event()); + alert(event.getKey()); + alert(event.getKeystroke() == 65); + alert(event.getKeystroke() == CKEDITOR.CTRL + 65); + alert(event.getKeystroke() == CKEDITOR.CTRL + CKEDITOR.SHIFT + 65); + var element = new CKEDITOR.dom.element('div'); + element.on('mousemouse', ev=> { + var pageOffset = ev.data.getPageOffset(); + alert(pageOffset.x); + alert(pageOffset.y); + }); + element.on('click', ev=> { + var domEvent = ev.data; + domEvent.getTarget().addClass('clicked'); + }); + element.on('click', ev=> { + var domEvent = ev.data; + domEvent.preventDefault(); + }); +} + +function test_dom_iterator() { + var range = new CKEDITOR.dom.range(new CKEDITOR.dom.element('div')); + var iterator = range.createIterator(); + iterator.getNextParagraph(); + iterator.getNextParagraph(); +} + +function test_dom_node() { + var p = new CKEDITOR.dom.element('p'); + var strong = new CKEDITOR.dom.element('strong'); + strong.appendTo(p); + var node = new CKEDITOR.dom.node(new Node()); + node = node.getAscendant('b'); + node = node.getAscendant('b', true); + var element = CKEDITOR.document.getById('example'); + alert(element.getDocument().equals(CKEDITOR.document)); + element.getIndex(); + element.getIndex(true); + var last = element.getFirst().getNext(); + var parent = node.getParent(); + alert(parent.getName()); + var parents = node.getParents(); + var em = new CKEDITOR.dom.element('em'); + strong.insertAfter(em); + strong.insertBefore(em); + strong.insertBeforeMe(em); + element.isReadOnly(); +} + +function test_dom_nodeList() { + var nodeList = CKEDITOR.document.getBody().getChildren(); + alert(nodeList.count()); +} + +function test_dom_range() { + var editor = new CKEDITOR.editor(); + var range = new CKEDITOR.dom.range(editor.document); + range.selectNodeContents(editor.document.getBody()); + range.deleteContents(); + range.selectNodeContents(editor.document.getBody()); + alert(range.collapsed); + range.collapse(); + alert(range.collapsed); + range.selectNodeContents(range.document.getBody()); + range.selectNodeContents(editor.document.getBody()); + alert(range.endContainer.getName()); + range.selectNodeContents(editor.document.getBody()); + alert(range.endOffset); + range.selectNodeContents(editor.document.getBody()); + alert(range.startContainer.getName()); + range.selectNodeContents(editor.document.getBody()); + alert(range.startOffset); +} + +function test_dom_text() { + var nativeNode = document.createTextNode('Example'); + var text = new CKEDITOR.dom.text(nativeNode); + var text2 = new CKEDITOR.dom.text('Example'); +} + +function test_dom_window() { + var document = new CKEDITOR.dom.window(window); + var win = new CKEDITOR.dom.window(window); + var pos = win.getScrollPosition(); + alert(pos.x); + alert(pos.y); + var size = win.getViewPaneSize(); + alert(size.width); + alert(size.height); +} \ No newline at end of file diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts new file mode 100644 index 000000000..8d5b2f815 --- /dev/null +++ b/ckeditor/ckeditor.d.ts @@ -0,0 +1,954 @@ +// Type definitions for CKEditor +// Project: http://ckeditor.com/ +// Definitions by: Ondrej Sevcik +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// WORK-IN-PROGRESS: Any contribution support welcomed. +// See https://github.com/borisyankov/DefinitelyTyped/issues/1827 for more informations. +declare module CKEDITOR { + + // Config options + var disableAutoInline: boolean; + var replaceClass: string; + var skinName: string; + + // Properties + var ALT: number; + var CTRL: number; + var DIALOG_RESIZE_BOTH: number; + var DIALOG_RESIZE_HEIGHT: number; + var DIALOG_RESIZE_NONE: number; + var DIALOG_RESIZE_WIDTH: number; + var ELEMENT_MODE_APPENDTO: number; + var ELEMENT_MODE_INLINE: number; + var ELEMENT_MODE_NONE: number; + var ELEMENT_MODE_REPLACE: number; + var END: number; + var ENTER_BR: number; + var ENTER_P: number; + var EVENT_PHASE_AT_TARGET: number; + var EVENT_PHASE_BUBBLING: number; + var EVENT_PHASE_CAPTURING: number; + var LINEUTILS_AFTER: number; + var LINEUTILS_BEFORE: number; + var LINEUTIS_INSIDE: number; + var NODE_COMMENT: number; + var NODE_DOCUMENT: number; + var NODE_DOCUMENT_FRAGMENT: number; + var NODE_ELEMENT: number; + var NODE_TEXT: number; + var SELECTION_ELEMENT: number; + var SELECTION_NONE: number; + var SELECTION_TEXT: number; + var SHIFT: number; + var SHRINK_ELEMENT: number; + var SHRINK_TEXT: number; + var START: number; + var TRISTATE_DISABLED: number; + var TRISTATE_OFF: number; + var TRISTATE_ON: number; + var UI_BUTTON: string; + var UI_MENUBUTTON: string; + var UI_PANEL: string; + var UI_PANELBUTTON: string; + var UI_RICHCOMBO: string; + var UI_SEPARATOR: string; + var basePath: string; + var currentInstance: editor; + var document: dom.document; + var instances: editor[]; + var loadFullCoreTimeout: number; + var revision: string; + var rnd: number; + var status: string; + var timestamp: string; + var version: string; + + + // Methods + function add(editor: editor): void; + function addCss(css: string): void; + function addTemplate(name: string, source: string): template; + function appendTo(element: string, config?: config, data?: string): editor; + function appendTo(element: HTMLTextAreaElement, config?: config, data?: string): editor; + function domReady(): void; + function editorConfig(config: config): void; + function getCss(): string; + function getTemplate(name: string): template; + function getUrl(resource: string): string; + function inline(element: string, instanceConfig?: config): editor; + function inline(element: HTMLTextAreaElement, instanceConfig?: config): editor; + function inlineAll(): void; + function loadFullCore(): void; + function replace(element: string, config?: config): editor; + function replace(element: HTMLTextAreaElement, config?: config): editor; + function replaceAll(className?: string): void; + function replaceAll(assertionFunction: (textarea: HTMLTextAreaElement, config: config) => boolean): void; + + + module dom { + + class comment { + + // Properties + type: number; + + // Methods + constructor(comment: string, ownerDocument?: document); + constructor(comment: Object, ownerDocument?: document); + getOuterHtml(): string; + + } + + + class document extends domObject { + + // Properties + type: number; + + // Methods + constructor(domDocument: Object); + appendStyleSheet(cssFileUrl: string): void; + appendStyleText(cssStyleText: string): Object; + createElement(name: string, attribsAndStyles?: { attributes: Object; styles: Object; }): element; + createText(text: string): element; + find(selector: string): nodeList; + findOne(selector: string): element; + focus(): void; + getActive(): element; + getBody(): element; + getByAddress(address: any[], normalized?: boolean): node; + getById(elementId: string): element; + getDocumentElement(): element; + getElementsByTag(tagName: string): nodeList; + getHead(): element; + getSelection(): selection; + getWindow(): window; + write(html: string): void; + + } + + + class documentFragment { + + // Properties + type: number; + + // Methods + constructor(nodeOrDoc: Object); + insertAfterNode(node: node): void; + + } + + + class domObject extends event { + + // Properties + $: HTMLElement; + + // Methods + constructor(nativeDomObject: Object); + clearCustomData(): void; + equals(object: any): boolean; + getCustomData(key: string): any; + getPrivate(): any; + getUniqueId(): number; + removeAllListeners(): void; + removeCustomData(key: string): Object; + setCustomData(key: string, value: Object): domObject; + + } + + + class element extends node { + + // Properties + type: number; + + // Methods + constructor(element: string, ownerDocument?: document); + constructor(element: HTMLElement, ownerDocument?: document); + addClass(className: string): void; + append(node: node, toStart?: boolean): node; + append(node: string, toStart?: boolean): node; + appendBogus(force: boolean): void; + appendHtml(html: string): void; + appendText(text: string): node; + breakParent(parent: element): void; + contains(node: node): boolean; + copyAttributes(dest: element, skipAttributes: Object): void; + data(name: string): string; + data(name: string, value: string): void; + data(name: string, value: boolean): void; + disableContextMenu(): void; + find(selector: string): nodeList; + findOne(selector: string): element; + focus(defer?: boolean): void; + focusNext(ignoreChildren?: boolean, indexToUse?: number): void; + focusPrevious(ignoreChildren?: boolean, indexToUse?: number): void; + forEach(callback: (node: node) => void, type?: number, skipRoot?: boolean): void; + getAttribute(name: string): string; + getBogus(): Object; + getChild(indices: number): node; + getChild(indices: number[]): node; + getChildCount(): number; + getChildren(): nodeList; + getClientRect(): any; + getComputedStyle(propertyName: string): string; + getDirection(useComputed: boolean): string; + getDocumentPosition(refDocument: document): position; + getDtd(): any; + getEditor(): editor; + getElementsByTag(tagName: string): nodeList; + getFirst(evaluator?: Function): node; + getFrameDocument(): document; + getHtml(): string; + getId(): string; + getLast(evaluator?: Function): node; + getName(): string; + getNameAtt(): string; + getOuterHtml(): string; + getPositionedAncestor(): element; + getSize(type: string, isBorderBox: boolean): void; + getStyle(name: string): string; + getTabIndex(): number; + getText(): string; + getValue(): string; + getWindow(): window; + hasAttributes(): boolean; + hasAttribute(name: string): boolean; + hasClass(className: string): boolean; + hide(): void; + is(...name: string[]): boolean; + is(name: any): boolean; + isBlockBoundary(customNodeNames: Object): boolean; + isEditable(textCursor?: boolean): boolean; + isEmptyInlineRemoveable(): boolean; + isIdentical(otherElement: element): boolean; + isVisible(): boolean; + mergeSiblings(inlineOnly?: boolean): void; + moveChildren(target: element, toStart?: boolean): void; + removeAttribute(name: string): void; + removeAttributes(attributes?: string[]): void; + removeClass(className: string): void; + removeStyle(name: string): void; + renameNode(newTag: string): void; + scrollIntoParent(parent: element, alignToTop: boolean, hscroll: boolean): void; + scrollIntoParent(parent: window, alignToTop: boolean, hscroll: boolean): void; + scrollIntoView(alignToTop?: boolean): void; + setAttribute(name: string, value: string): element; + setAttributes(attributesPairs: Object): element; + setHtml(html: string): string; + setOpacity(opacity: number): void; + setSize(type: string, size: number, isBorderBox: boolean): void; + setState(state: number, base?: Object, useAria?: Object): void; + setStyle(name: string, value: string): element; + setStyles(stylesPair: Object): element; + setText(text: string): string; + setValue(value: string): element; + show(): void; + unselectable(): void; + + //static method + static clearAllMarkers(database: Object): Object; + static clearMarkers(database: Object, element: Object, removeFromDatabase: Object): void; + static createFromHtml(html: string): element; + static get(element: string): element; + static get(element: any): element; + static setMarker(database: Object, element: Object, name: Object, value: Object): domObject; + + } + + + class elementPath { + constructor(startNode: element, root: element); + block: element; + blockLimit: element; + root: element; + elements: element[]; + compare(otherPath: elementPath): boolean; + contains(query: string, excludeRoot: boolean, fromTop: boolean): element; + contains(query: string[], excludeRoot: boolean, fromTop: boolean): element; + contains(query: (element: element) => boolean, excludeRoot: boolean, fromTop: boolean): element; + contains(query: Object, excludeRoot: boolean, fromTop: boolean): element; + contains(query: element, excludeRoot: boolean, fromTop: boolean): element; + isContextFor(tag: string): boolean; + direction(): string; + } + + + class range { + constructor(root: element); + constructor(root: document); + startContainer: any; + startOffset: number; + endContainer: any; + endOffset: number; + collapsed: boolean; + isDocRoot: boolean; + document: document; + root: element; + clone(): range; + collapse(toStart?: boolean): Boolean; + cloneContents(): documentFragment; + deleteContents(mergeThen?: boolean): void; + extractContents(mergeThen?: boolean): documentFragment; + createBookmark(serializable: boolean): Object; + createBookmark2(normalized: boolean): Object; + createIterator(): iterator; + moveToBookmark(bookmark: Object): void; + getBoundaryNodes(): { startNode: node; endNode: node; }; + getCommonAncestor(includeSelf: boolean, ignoreTextNode: boolean): element; + optimize(): void; + optimizeBookmark(): void; + trim(ignoreStart?: boolean, ignoreEnd?: boolean): void; + enlarge(unit: number, excludeBrs?: boolean): void; + shrink(mode: number, selectContents: boolean): void; + insertNode(node: node): void; + moveToPosition(node: node, position: Object): void; + moveToRange(range: range): void; + selectNodeContents(node: node): void; + setStart(startNode: node, startOffset: number): void; + setEnd(endNode: node, endOffset: number): void; + setStartAfter(node: node): void; + setStartBefore(node: node): void; + setStartAt(node: node, position: number): void; + setEndAt(node: node, position: number): void; + fixBlock(isStart: boolean, blockTag: Object): Object; + splitBlock(blockTag: Object): Object; + splitElement(toSplit: element): element; + removeEmptyBlocksAtEnd(atEnd: boolean): void; + startPath(): elementPath; + endPath(): elementPath; + checkBoundaryOfElement(element: element, checkType: number): boolean; + checkStartOfBlock(): boolean; + checkEndOfBlock(): boolean; + getPreviousNode(evaluator: Function, guard: Function, boundary: element): element; + getNextNode(evaluator: Function, guard: Function, boundary: element): element; + checkReadOnly(): boolean; + moveToElementEditablePosition(element: element, isMoveToEnd: boolean): boolean; + movetoClosestEditablePosition(element: element, isMoveToEnd: boolean): boolean; + moveToElementEditStart(target: Object): boolean; + moveToElementEditEnd(target: Object): boolean; + getEnclosedNode(): node; + getTouchedStartNode(): node; + getTouchedEndNode(): node; + getNextEditableNode(): Object; + getPreviousEditableNode(): Object; + scrollIntoView(): void; + } + + + interface rangeListIterator { + + } + + class selection { + document: document; + isFake: boolean; + isLocked: boolean; + rev: number; + root: element; + constructor(target: document); + constructor(target: element); + constructor(target: selection); + createBookmarks(serializable: Object): any[]; + createBookmarks2(normalized?: Object): any[]; + fake(element: element): void; + getCommonAncestor(): element; + getNative(): Object; + getRanges(onlyEditables?: boolean): any[]; + getSelectedElement(): element; + getSelectedText(): string; + getStartElement(): element; + getType(): number; + isHidden(): boolean; + lock(): void; + removeAllRanges(): void; + reset(): void; + scrollIntoView(): void; + selectBookmarks(bookmarks: any[]): selection; + selectElement(element: element): void; + selectRanges(ranges: any[]): void; + unlock(restore: Object): void; + } + + + class rangeList { + constructor(ranges: range[]); + constructor(range: range); + createIterator(): rangeListIterator; + createBokmark(serializable: boolean): Object[]; + createBookmark2(normalized: boolean): Object[]; + moveToBookmark(bookmarks: Object[]): void; + } + + + class iterator { + constructor(range: range); + getNextParagraph(blockTag?: string): element; + activeFilter: filter; + enforceRealBlocks: Boolean; + enlargeBr: Boolean; + filter: filter; + } + + + class node extends domObject { + constructor(domNode: Node); + appendTo(element: element): element; + clone(includeChildren: boolean, cloneId: boolean): node; + hasPrevious(): boolean; + hasNext(): boolean; + insertAfter(node: node): node; + insertBefore(node: node): node; + insertBeforeMe(node: node): node; + getAddress(normalized: boolean): Object[]; + getDocument(): document; + getIndex(normalized?: boolean): number; + getNextSourceNode(startFromSibling: Object, nodeType: Object, guard: Object): void; + getPreviousSourceNode(startFromSibling: Object, nodeType: Object, guard: Object): void; + getPrevious(evaluator?: Function): node; + getNext(evaluator?: Function): node; + getParent(allowFragmentParent?: boolean): element; + getParents(closerFirst?: boolean): node[]; + getCommonAncestor(node: Object): void; + getPosition(otherNode: Object): void; + getAscendant(reference: string, includeSelf?: boolean): node; + hasAscendant(name: Object, includeSelf: any): boolean; + move(preserveChildren?: boolean): node; + replace(nodeToReplace: node): void; + trim(): void; + ltrim(): void; + rtrim(): void; + isReadOnly(): boolean; + } + + + class nodeList { + constructor(nativeList: Object); + count(): number; + getItem(index: number): node; + } + + + class event { + constructor(domEvent: Event); + getKey(): number; + getKeystroke(): number; + preventDefault(stopPropagation: boolean): void; + stopPropagation(): void; + getTarget(): node; + getPhase(): number; + getPhaseOffset(): position; + on(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object, listenerData?: Object, priority?: number): Object; + } + + + interface position { + x: number; + y: number; + } + + + interface widthAndHeight { + width: number; + height: number; + } + + + class text extends node { + constructor(text: Text, ownerDocument?: document); + constructor(text: string, ownerDocument?: document); + type: number; + getLength(): number; + getText(): string; + setText(text: string): void; + split(offset: number): text; + substring(indexA: number, indexB: number): void; + } + + + class window extends domObject { + constructor(domWindow: Object); + focus(): void; + getViewPaneSize(): widthAndHeight; + getScrollPosition(): position; + getFrame(): element; + } + + + class walker { + constructor(range: range); + end(): void; + next(): node; + previous(): node; + checkForward(): boolean; + checkBackward(): boolean; + lastForward(): node; + lastBackward(): node; + reset(): void; + //static methods till the end + blockBoundary(customNodeNames: Object): Function; + listItemBoundary(): Function; + bookmark(contentOnly?: boolean, isReject?: boolean): Function; + whitespaces(isReject?: boolean): Function; + invisible(isReject?: boolean): Function; + nodeType(type: number, isReject?: boolean): Function; + bogus(isReject?: boolean): Function; + temp(isReject?: boolean): Function; + ignored(isReject?: boolean): Function; + editable(isReject?: boolean): Function; + } + + } + + + module ajax { + + // Methods + function load(url: string, callback?: Function): string; + function loadXml(url: string, callback?: Function): xml; + + } + + + interface xml { + + } + + + class command extends event { + + // Properties + contextSensitive: boolean; + editorFocus: boolean; + modes: any; + previousState: number; + state: number; + uiItems: any[]; + + // Methods + constructor(editor: editor, commandDefinition: commandDefinition); + checkAllowed(noCache: boolean): boolean; + disable(): void; + enable(): void; + exec(data?: Object): boolean; + refresh(editor: editor, path: dom.elementPath): void; + setState(newState: number): boolean; + toggleState(): void; + + } + + + interface focusManager { + + } + + interface keystrokeHandler { + + } + + + interface config { + startupMode: string; + removeButtons: string; + toolbar?: any; + } + + + interface feature { + + } + + + interface style { + + } + + + interface editable { + + } + + + class menu { + constructor(); + add(item: any): void; + addListener(listenerFn: (startElement: dom.element, selection: dom.selection, path: dom.elementPath) => any): void; + hide(returnFocus?: boolean): void; + removeAll(): void; + show(offsetParent: dom.element, corner?: number, offsetX?: number, offsetY?: number): void; + } + + + module plugins { + + class contextMenu extends menu { + constructor(editor: editor); + addTarget(element: dom.element, nativeContextMenuOnCtrl?: boolean): void; + open(offsetParent: dom.element, corner?: number, offsetX?: number, offsetY?: number): void; + } + + + module link { + var emptyAnchorFix: boolean; + var fakeAnchor: boolean; + var synAnchorSelector: boolean; + function getEditorAnchors(editor: editor): dom.element[]; + function getSelectedLink(editor: editor): dom.elementPath; + function tryRestoreFakeAnchor(editor: editor, element: dom.element): dom.element; + } + + + module widget { + class repository { + + } + } + + } + + + class editor extends event { + activeEnterMode: number; + activeFilter: filter; + activeShiftEnterMode: number; + blockless: boolean; + config: config; + container: dom.element; + contextMenu: plugins.contextMenu; + dataProcessor: dataProcessor; + document: dom.document; + element: dom.element; + elementMode: number; + enterMode: number; + filter: filter; + focusManager: focusManager; + id: string; + keystrokeHandler: keystrokeHandler; + lang: any; + langCode: string; + mode: string; + name: string; + plugins: Object; + readOnly: boolean; + shiftEnterMode: number; + status: string; + tabIndex: number; + templates: Object; + title: any; + toolbar: Object; + ui: ui; + widgets: plugins.widget.repository; + window: dom.window; + constructor(instanceConfig?: Object, element?: dom.element, mode?: number); + addCommand(commandName: string, commandDefinition: commandDefinition): void; + addFeature(feature: feature): boolean; + addMenuGroup(name: string, order?: number): void; + addMenuItem(name: string, definition?: any): void; + addMenuItems(definitions: any[]): void; + addMode(mode: string, exec: () => void): void; + addRemoveFormatFilter(func: Function): void; + applyStyle(style: style): void; + attachStyleStateChange(style: style, callback: Function): void; + checkDirty(): boolean; + createFakeElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void; + createFakeParserElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void; + createRange(): dom.range; + destroy(noUpdate?: boolean): void; + editable(elementOrEditable: dom.element): void; + editable(elementOrEditable: editable): void; + elementPath(startNode?: dom.node): dom.elementPath; + execCommand(commandName: string, data?: Object): boolean; + focus(): void; + forceNextSelectionCheck(): void; + getClipboardData(options: Object, callback: Function): void; + getColorFromDialog(callback: Function, scope?: Object): void; + getCommand(commandName: string): command; + getData(noEvents: Object): string; + getMenuItem(name: string): Object; + getResizable(forContents: boolean): dom.element; + getSelection(forceRealSelection?: boolean): dom.selection; + getSnapshot(): string; + getStylesSet(callback: Function): void; + getUiColor(): string; + insertElement(element: dom.element): void; + insertHtml(html: string, mode?: string): void; + insertText(text: string): void; + loadSnapshot(snapshot: Object): void; + lockSelection(sel?: dom.selection): boolean; + openDialog(dialogName: string, callback: Function): dialog; + popup(url: string, width?: number, height?: number, options?: string): void; + popup(url: string, width?: string, height?: number, options?: string): void; + popup(url: string, width?: number, height?: string, options?: string): void; + popup(url: string, width?: string, height?: string, options?: string): void; + removeMenuItem(name: string): void; + removeStyle(style: style): void; + resetDirty(): void; + resetUndo(): void; + resize(width: number, height: number, isContentHeight?: boolean, resizeInner?: boolean): void; + resize(width: string, height: number, isContentHeight?: boolean, resizeInner?: boolean): void; + resize(width: number, height: string, isContentHeight?: boolean, resizeInner?: boolean): void; + resize(width: string, height: string, isContentHeight?: boolean, resizeInner?: boolean): void; + restoreRealElement(fakeElement: Object): dom.element; + selectionChange(checkNow?: boolean): void; + setActiveEnterMode(enterMode: number, shiftEnterMode: number): void; + setActiveFilter(filter: filter): void; + setData(data: string, callback: Function, internal: boolean): void; + setKeystroke(keystroke: number, behavior?: string): void; + setKeystroke(keystroke: any[], behavior?: string): void; + setKeystroke(keystroke: number, behavior?: boolean): void; + setKeystroke(keystroke: any[], behavior?: boolean): void; + setMode(newMode: string, callback: Function): void; + setReadOnly(isReadOnly?: boolean): void; + setUiColor(color: string): void; + unlockSelection(restore?: boolean): void; + updateElement(): void; + } + + + interface eventInfo { + data: any; + editor: editor; + listenerData: any; + name: string; + sender: any; + cancel(): void; + removeListener(): void; + stop(): void; + } + + + class filter { + + } + + + interface template { + + } + + + interface dataProcessor { + toDataFormat(html: string, fixForBody: string): void; + toHtml(data: string, fixForBody?: string): void; + } + + + class event { + constructor(); + useCapture: boolean; + capture(): void; + define(name: string, meta: Object): void; + fire(eventName: string, data?: Object, editor?: editor): any; + fireOnce(eventName: string, data?: Object, editor?: editor): any; + hasListeners(eventName: string): boolean; + on(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object, listenerData?: Object, priority?: number): void; + once(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object, listenerData?: Object, priority?: number): void; + removeAllListeners(): void; + removeListener(eventName: string, listenerFunction: (eventInfo: eventInfo) => void): void; + static implementOn(targetObject: Object): void; + } + + + interface commandDefinition { + async?: boolean; + canUndo?: boolean; + context?: boolean; + contextSensitive?: boolean; + editorFocus?: boolean; + modes?: Object; + startDisabled?: boolean; + exec(editor: editor, data?: Object): boolean; + refresh? (editor: editor, path: dom.elementPath): void; + } + + + class dtd { + + } + + + class ui extends event { + constructor(editor: editor); + add(name: string, type: Object, definition: Object): void; + addButton(name: string, definition: dialog.definition.button): void; + addHandler(type: Object, handler: Object): void; + } + + + module dialog { + + module definition { + + interface button extends uiElement { + disabled?: boolean; + label?: string; + } + + + interface uiElement { + align?: string; + className?: string; + commit?: Function; + id?: string; + onHide?: Function; + onLoad?: Function; + requiredcontent?: any; + setup?: Function; + style?: string; + title?: string; + type?: string; + } + + } + + } + + + module htmlParser { + + class basicWriter { + constructor(); + openTag(tagName: string, attributes: Object): void; + openTagClose(tagName: string, isSelfClose: boolean): void; + attribute(attName: string, attValue: string): void; + closeTag(tagName: string): void; + text(text: string): void; + comment(comment: string): void; + write(data: string): void; + reset(): void; + getHtml(reset: boolean): string; + } + + + class node { + constructor(); + remove(preserveChildren?: boolean): node; + replaceWith(node: node): void; + insertAfter(node: node): void; + insertBefore(node: node): void; + getAscendant(condition: string): element; + getAscendant(condition: Object): element; + getAscendant(condition: Function): element; + wrapWith(wrapper: element): element; + getIndex(): number; + } + + + class filter { + constructor(rules?: filterRulesDefinition); + id: number; + elementNameRules: filterRulesGroup; + attributeNameRules: filterRulesGroup; + elementsRules: Object; + attributesRules: Object; + textRules: filterRulesGroup; + commentRules: filterRulesGroup; + rootRules: filterRulesGroup; + addRules(rules: filterRulesDefinition, options?: number): void; + addRules(rules: filterRulesDefinition, options?: { priority?: number; applyToAll?: boolean; }): void; + applyTo(node: node): void; + } + + + interface filterRulesDefinition { + + } + + + class filterRulesGroup { + rules: Object[]; + add(rule: Function, priority: number, options: Object): void; + add(rule: Object[], priority: number, options: Object): void; + addMany(rules: Object[], priority: number, options: Object): void; + findIndex(priority: number): number; + exec(currentValue: Object): Object; + execOnName(currentName: string): string; + } + + + class cdata extends node { + constructor(value: string); + type: number; + writeHtml(writer: basicWriter): void; + } + + + class comment extends node { + constructor(value: string); + type: number; + filter(filter: filter): boolean; + writeHtml(writer: basicWriter, filter: filter): void; + } + + + class element extends node { + constructor(name: string, attributes: Object); + name: string; + attributes: Object; + children: Object[]; + type: number; + add(node: node): number; + clone(): element; + filter(filter: filter): boolean; + filterChildren(filter: filter): void; + writeHtml(writer: basicWriter, filter: filter): void; + writeChildrenHtml(writer: basicWriter, filter: filter): void; + replaceWithChildren(): void; + forEach(callback: (node: node, type?: number) => boolean): void; + getFirst(condition: string): node; + getFirst(condition: Object): node; + getFirst(condition: Function): node; + getHtml(): string; + setHtml(html: string): void; + getOuterHtml(): string; + split(index: number): element; + removeClass(className: string): void; + hasClass(className: string): boolean; + } + + + class fragment { + constructor(); + children: Object[]; + parent: Object; + type: number; + fromHtml(fragmentHtml: string, parent?: element, fixingBlock?: string): void; + fromHtml(fragmentHtml: string, parent?: string, fixingBlock?: string): void; + fromHtml(fragmentHtml: string, parent?: element, fixingBlock?: boolean): void; + fromHtml(fragmentHtml: string, parent?: string, fixingBlock?: boolean): void; + add(node: node, index?: number): void; + filter(filter: filter): void; + filterChildren(filter: filter, filterRoot?: boolean): void; + writeHtml(writer: basicWriter, filter?: filter): void; + writeChildrenHtml(writer: basicWriter, filter?: filter, filterRoot?: boolean): void; + forEach(callback: (node: node, type?: number) => boolean, type?: number, skipRoot?: boolean): void; + } + + + class cssStyle { + constructor(element: element); + constructor(styleText: string); + populate(obj: element): void; + populate(obj: dom.element): void; + populate(obj: Object): void; + } + + + class text extends node { + constructor(value: string); + type: number; + filter(filter: filter): boolean; + writeHtml(writer: basicWriter, filter?: filter): void; + } + + } + + + interface dialog { + addFocusable(element: CKEDITOR.dom.element, index: number): void; + } + +} \ No newline at end of file diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index 02623aa9f..aab65c06c 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -1160,7 +1160,7 @@ function azimuthalEquidistant() { } //Example from http://bl.ocks.org/mbostock/4060366 -function voroniTesselation() { +function voronoiTesselation() { var width = 960, height = 500; @@ -1168,6 +1168,9 @@ function voroniTesselation() { return [Math.random() * width, Math.random() * height]; } ); + var voronoi = d3.geom.voronoi() + .clipExtent([[0, 0], [width, height]]); + var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) @@ -1185,13 +1188,129 @@ function voroniTesselation() { redraw(); function redraw() { - path = path.data(d3.geom.voronoi(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String); + path = path.data(voronoi(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String); path.exit().remove(); path.enter().append("path").attr("class", function (d, i) { return "q" + (i % 9) + "-9"; } ).attr("d", String); path.order(); } } +// Example from https://gist.github.com/christophermanning/1734663 +function forceDirectedVoronoi() { + var w = window.innerWidth > 960 ? 960 : (window.innerWidth || 960), + h = window.innerHeight > 500 ? 500 : (window.innerHeight || 500), + radius = 5.25, + links = [], + simulate = true, + zoomToAdd = true, + color = d3.scale.quantize().domain([10000, 7250]).range(["#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]) + + var numVertices = (w*h) / 3000; + var vertices = d3.range(numVertices).map(function(i) { + var angle = radius * (i+10); + return {x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}; + }); + var d3_geom_voronoi = d3.geom.voronoi() + .x(function(d) { return d.x; }) + .y(function(d) { return d.y; }) + var prevEventScale = 1; + var zoom = d3.behavior.zoom().on("zoom", function(d,i) { + if (zoomToAdd){ + if (d3.event.scale > prevEventScale) { + var angle = radius * vertices.length; + vertices.push({x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}) + } else if (vertices.length > 2 && d3.event.scale != prevEventScale) { + vertices.pop(); + } + force.nodes(vertices).start() + } else { + if (d3.event.scale > prevEventScale) { + radius+= .01 + } else { + radius -= .01 + } + vertices.forEach(function(d, i) { + var angle = radius * (i+10); + vertices[i] = {x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}; + }); + force.nodes(vertices).start() + } + prevEventScale = d3.event.scale; + }); + + d3.select(window) + .on("keydown", function() { + // shift + if(d3.event.keyCode == 16) { + zoomToAdd = false + } + + // s + if(d3.event.keyCode == 83) { + simulate = !simulate + if(simulate) { + force.start() + } else { + force.stop() + } + } + }) + .on("keyup", function() { + zoomToAdd = true + }) + + var svg = d3.select("#chart") + .append("svg") + .attr("width", w) + .attr("height", h) + .call(zoom) + + var force = d3.layout.force() + .charge(-300) + .size([w, h]) + .on("tick", update); + + force.nodes(vertices).start(); + + var circle = svg.selectAll("circle"); + var path = svg.selectAll("path"); + var link = svg.selectAll("line"); + + function update() { + path = path.data(d3_geom_voronoi(vertices)); + path.enter().append("path") + // drag node by dragging cell + .call(d3.behavior.drag() + .on("drag", function(d, i) { + vertices[i] = {x: vertices[i].x + d3.event.dx, y: vertices[i].y + d3.event.dy} + }) + ) + .style("fill", function(d, i) { return color(0) }) + path.attr("d", function(d) { return "M" + d.join("L") + "Z"; }) + .transition().duration(150).style("fill", function(d, i) { return color(d3.geom.polygon(d).area()) }) + path.exit().remove(); + + circle = circle.data(vertices) + circle.enter().append("circle") + .attr("r", 0) + .transition().duration(1000).attr("r", 5); + circle.attr("cx", function(d) { return d.x; }) + .attr("cy", function(d) { return d.y; }); + circle.exit().transition().attr("r", 0).remove(); + + link = link.data(d3_geom_voronoi.links(vertices)) + link.enter().append("line") + link.attr("x1", function(d) { return d.source.x; }) + .attr("y1", function(d) { return d.source.y; }) + .attr("x2", function(d) { return d.target.x; }) + .attr("y2", function(d) { return d.target.y; }) + + link.exit().remove() + + if(!simulate) force.stop() + } +} + //Example from http://bl.ocks.org/mbostock/4341156 function delaunayTesselation() { var width = 960, diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 4bce47e2b..50d9eb6e6 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -812,6 +812,8 @@ declare module D3 { select: (selector: string) => Selection; empty: () => boolean; node: () => Element; + call: (callback: (selection: EnterSelection) => void) => EnterSelection; + size: () => number; } export interface UpdateSelection extends Selection { @@ -1148,17 +1150,17 @@ declare module D3 { }; startAngle: { (): number; - (angle: number): D3.Svg.Arc; - (angle: () => number): D3.Svg.Arc; - (angle: (d : any) => number): D3.Svg.Arc; - (angle: (d : any, i: number) => number): D3.Svg.Arc; + (angle: number): PieLayout; + (angle: () => number): PieLayout; + (angle: (d : any) => number): PieLayout; + (angle: (d : any, i: number) => number): PieLayout; }; endAngle: { (): number; - (angle: number): D3.Svg.Arc; - (angle: () => number): D3.Svg.Arc; - (angle: (d : any) => number): D3.Svg.Arc; - (angle: (d : any, i: number) => number): D3.Svg.Arc; + (angle: number): PieLayout; + (angle: () => number): PieLayout; + (angle: (d : any) => number): PieLayout + (angle: (d : any, i: number) => number): PieLayout; }; } @@ -3211,10 +3213,11 @@ declare module D3 { // Geometry export module Geom { export interface Geom { + voronoi(): Voronoi; /** * compute the Voronoi diagram for the specified points. */ - voronoi: Voronoi + voronoi(vertices: Array): Array; /** * compute the Delaunay triangulation for the specified points. */ @@ -3295,15 +3298,82 @@ declare module D3 { y: number; } - export interface Voronoi { - (vertices?: Array): Array; + export interface Voronoi { + /** + * Compute the Voronoi diagram for the specified data. + */ + (data: Array): Array; + /** + * Compute the graph links for the Voronoi diagram for the specified data. + */ + links(data: Array): Array; + /** + * Compute the triangles for the Voronoi diagram for the specified data. + */ + triangles(data: Array): Array>; x: { - (): (d: any) => any; - (accesor: (d: any) => any): any; + /** + * Get the x-coordinate accessor. + */ + (): (data: T, index ?: number) => number; + + /** + * Set the x-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: T, index: number) => number): Voronoi; + + /** + * Set the x-coordinate to a constant. + * + * @param constant The new constant value. + */ + (constant: number): Voronoi; } y: { - (): (d: any) => any; - (accesor: (d: any) => any): any; + /** + * Get the y-coordinate accessor. + */ + (): (data: T, index ?: number) => number; + + /** + * Set the y-coordinate accessor. + * + * @param accessor The new accessor function + */ + (accessor: (data: T, index: number) => number): Voronoi; + + /** + * Set the y-coordinate to a constant. + * + * @param constant The new constant value. + */ + (constant: number): Voronoi; + } + clipExtent: { + /** + * Get the clip extent. + */ + (): Array>; + /** + * Set the clip extent. + * + * @param extent The new clip extent. + */ + (extent: Array>): Voronoi; + } + size: { + /** + * Get the size. + */ + (): Array; + /** + * Set the size, equivalent to a clip extent starting from (0,0). + * + * @param size The new size. + */ + (size: Array): Voronoi; } } diff --git a/dcjs/dc-tests.ts b/dcjs/dc-tests.ts new file mode 100644 index 000000000..60d3aa059 --- /dev/null +++ b/dcjs/dc-tests.ts @@ -0,0 +1,242 @@ +/// +/// +/// + +interface IYelpData { + city: string; + review_count: number; + name: string; + neighborhoods: string[]; + type: string; + business_id: string; + full_address: string; + state: string; + longitude: number; + stars: number; + latitude: number; + open: boolean; + categories: string[] +} + +interface IYelpDataExtended { + count: number; + review_sum: number; + star_sum: number; + review_avg: number; + star_avg: number; +} + + +/******************************************************** +* * +* dj.js example using Yelp Kaggle Test Dataset * +* Eamonn O'Loughlin 9th May 2013 * +* * +********************************************************/ + +/******************************************************** +* * +* Step0: Load data from json file * +* * +********************************************************/ +d3.json("data/yelp_test_set_business.json", function (yelp_data:IYelpData[]) { + +/******************************************************** +* * +* Step1: Create the dc.js chart objects & ling to div * +* * +********************************************************/ +var bubbleChart = dc.bubbleChart("#dc-bubble-graph"); +var pieChart = dc.pieChart("#dc-pie-graph"); +var volumeChart = dc.barChart("#dc-volume-chart"); +var lineChart = dc.lineChart("#dc-line-chart"); +var dataTable = dc.dataTable("#dc-table-graph"); +var rowChart = dc.rowChart("#dc-row-graph"); + +/******************************************************** +* * +* Step2: Run data through crossfilter * +* * +********************************************************/ +var ndx = crossfilter(yelp_data); + +/******************************************************** +* * +* Step3: Create Dimension that we'll need * +* * +********************************************************/ + + // for volumechart + var cityDimension = ndx.dimension(function (d) { return d.city; }); + var cityGroup = cityDimension.group(); + var cityDimensionGroup = cityDimension.group().reduce( + //add + function(p: IYelpDataExtended,v:IYelpData){ + ++p.count; + p.review_sum += v.review_count; + p.star_sum += v.stars; + p.review_avg = p.review_sum / p.count; + p.star_avg = p.star_sum / p.count; + return p; + }, + //remove + function(p: IYelpDataExtended,v:IYelpData){ + --p.count; + p.review_sum -= v.review_count; + p.star_sum -= v.stars; + p.review_avg = p.review_sum / p.count; + p.star_avg = p.star_sum / p.count; + return p; + }, + //init + function(){ + return {count:0, review_sum: 0, star_sum: 0, review_avg: 0, star_avg: 0}; + } + ); + + // for pieChart + var startValue = ndx.dimension(function (d) { + return d.stars*1.0; + }); + var startValueGroup = startValue.group(); + + // For datatable + var businessDimension = ndx.dimension(function (d) { return d.business_id; }); +/******************************************************** +* * +* Step4: Create the Visualisations * +* * +********************************************************/ + + bubbleChart.width(650) + .height(300) + .dimension(cityDimension) + .group(cityDimensionGroup) + .transitionDuration(1500) + .colors(["#a60000","#ff0000", "#ff4040","#ff7373","#67e667","#39e639","#00cc00"]) + .colorDomain([-12000, 12000]) + + .x(d3.scale.linear().domain([0, 5.5])) + .y(d3.scale.linear().domain([0, 5.5])) + .r(d3.scale.linear().domain([0, 2500])) + .keyAccessor(function (p) { + return p.value.star_avg; + }) + .valueAccessor(function (p) { + return p.value.review_avg; + }) + .radiusValueAccessor(function (p) { + return p.value.count; + }) + .transitionDuration(1500) + .elasticY(true) + .yAxisPadding(1) + .xAxisPadding(1) + .label(function (p) { + return p.key; + }) + .renderLabel(true) + .renderlet(function (chart) { + rowChart.filter(chart.filter()); + }) + .on("postRedraw", function (chart) { + dc.events.trigger(function () { + rowChart.filter(chart.filter()); + }); + }); + ; + + +pieChart.width(200) + .height(200) + .transitionDuration(1500) + .dimension(startValue) + .group(startValueGroup) + .radius(90) + .minAngleForLabel(0) + .label(function(d) { return d.data.key; }) + .on("filtered", function (chart) { + dc.events.trigger(function () { + if(chart.filter()) { + console.log(chart.filter()); + volumeChart.filter([chart.filter()-.25,chart.filter()-(-0.25)]); + } + else volumeChart.filterAll(); + }); + }); + +volumeChart.width(230) + .height(200) + .dimension(startValue) + .group(startValueGroup) + .transitionDuration(1500) + .centerBar(true) + .gap(17) + .x(d3.scale.linear().domain([0.5, 5.5])) + .elasticY(true) + .on("filtered", function (chart) { + dc.events.trigger(function () { + if(chart.filter()) { + console.log(chart.filter()); + lineChart.filter(chart.filter()); + } + else + {lineChart.filterAll()} + }); + }) + .xAxis().tickFormat(function(v) {return v;}); + +console.log(startValueGroup.top(1)[0].value); + +lineChart.width(230) + .height(200) + .dimension(startValue) + .group(startValueGroup) + .x(d3.scale.linear().domain([0.5, 5.5])) + .valueAccessor(function(d) { + return d.value; + }) + .renderHorizontalGridLines(true) + .elasticY(true) + .xAxis().tickFormat(function(v) {return v;}); ; + +rowChart.width(340) + .height(850) + .dimension(cityDimension) + .group(cityGroup) + .renderLabel(true) + .colors(["#a60000","#ff0000", "#ff4040","#ff7373","#67e667","#39e639","#00cc00"]) + .colorDomain([0, 0]) + .renderlet(function (chart) { + bubbleChart.filter(chart.filter()); + }) + .on("filtered", function (chart) { + dc.events.trigger(function () { + bubbleChart.filter(chart.filter()); + }); + }); + + +dataTable.width(800).height(800) + .dimension(businessDimension) + .group(function(d:Object) { return "List of all Selected Businesses" + }) + .size(100) + .columns([ + function(d) { return d.name; }, + function(d) { return d.city; }, + function(d) { return d.stars; }, + function(d) { return d.review_count; }, + function(d) { return 'Map"} + ]) + .sortBy(function(d){ return d.stars; }) + // (optional) sort order, :default ascending + .order(d3.ascending); +/******************************************************** +* * +* Step6: Render the Charts * +* * +********************************************************/ + + dc.renderAll(); +}); diff --git a/dcjs/dc.d.ts b/dcjs/dc.d.ts new file mode 100644 index 000000000..0391d2502 --- /dev/null +++ b/dcjs/dc.d.ts @@ -0,0 +1,198 @@ +// Type definitions for DCJS +// Project: https://github.com/dc-js +// Definitions by: hans windhoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// this makes only sense together with d3 and crossfilter so you need the d3.d.ts and crossfilter.d.ts files + +/// +/// + + + +declare module dc { + + // helper for get/set situation + interface IGetSet { + (): T; + (t:T): V; + } +export interface ILegendwidget { + x: IGetSet; + y: IGetSet; + gap: IGetSet; + itemHeight: IGetSet; + horizontal: IGetSet; + legendWidth: IGetSet; + itemWidth: IGetSet; + } + export interface IBaseChart { + width: IGetSet; + height: IGetSet; + minWidth: IGetSet; + minHeight: IGetSet; + dimension: IGetSet; + group: IGetSet; // not sure here + transitionDuration: IGetSet; + colors: IGetSet; + keyAccessor: IGetSet<(d:any) => number, T>; + valueAccessor: IGetSet<(d:any) => number, T>; + label: IGetSet<(l:any) => string, T>; + renderLabel: IGetSet; + renderlet: (fnctn: (t:T) => void) => T; + title: IGetSet<(t:string) => string, T>; + filter: IGetSet; + filterAll: () => void; + expireCache: () => void; + legend: (l:ILegendwidget) => T; + chartID: () => number; + options: (o:Object)=>void ; + select: (selector: D3.Selection) => D3.Selection; + selectAll: (selector: D3.Selection) => D3.Selection; + } + + export interface IEvents { + trigger(fnctn: () => void, delay?: number):void; + } + + export var events: IEvents; + + export interface IListener { + on: (eventName: string, fnctn: (c:T) => void) => T; + } + + export interface ImarginObj { + top: number; + right: number; + bottom: number; + left: number; + + } + + export interface IMarginable { + margins: IGetSet; + } + + // abstract interfaces + export interface IAbstractColorChart { + colorDomain: IGetSet; + } + export interface IAbstractStackableChart { + stack: (group: IChartGroup, name?:string, retriever?: (d:Object)=>number) => T; + } + + export interface IAbstractCoordinateGridChart { + x: IGetSet; + y: IGetSet; + elasticY: IGetSet; + xAxis: IGetSet; + yAxis: IGetSet; + yAxisPadding: IGetSet; + xAxisPadding: IGetSet; + renderHorizontalGridLines: IGetSet; + + } + + export interface IAbstractBubblechart { + r: IGetSet; + radiusValueAccessor: IGetSet<(d:any) => number, T>; + } + + + + // function interfaces + export interface columnFunction { + (rowinfo:any): string; + } + export interface sortbyFunction { + (rowinfo:any): any; + } + export interface orderFunction { + (a: T, b: T): number; + } + + + // chart interfaces + + + export interface IBubblechart extends + IBaseChart, + IAbstractColorChart, + IAbstractBubblechart, + IAbstractCoordinateGridChart, + IMarginable, + IListener { + } + + export interface IPiechart extends + IBaseChart, + IAbstractColorChart, + IAbstractBubblechart, + IAbstractCoordinateGridChart, + IMarginable, + IListener { + radius: IGetSet; + minAngleForLabel: IGetSet; + + } + + export interface IBarchart extends + IBaseChart, + IAbstractStackableChart, + IAbstractCoordinateGridChart, + IMarginable, + IListener { + centerBar: (b:boolean) => IBarchart; + gap: (gapBetweenBars: number) => IBarchart; + } + + export interface ILinechart extends + IBaseChart, + IAbstractStackableChart, + IAbstractCoordinateGridChart, + IMarginable, + IListener { + } + + + export interface IDatachart extends + IBaseChart, + IAbstractStackableChart, + IAbstractCoordinateGridChart, + IMarginable, + IListener { + size: IGetSet; + columns: IGetSet; + sortBy: IGetSet; + order: IGetSet; + } + + + export interface IRowchart extends + IBaseChart, + IAbstractColorChart, + IAbstractStackableChart, + IAbstractCoordinateGridChart, + IMarginable, + IListener { + } + + + + + // utilities + export interface IChartGroup { } + + export function filterAll(chartGroup?: IChartGroup): void; + export function renderAll(chartGroup?: IChartGroup): void; + export function redrawAll(chartGroup?: IChartGroup): void; + + + export function bubbleChart(cssSel: string): IBubblechart; + export function pieChart(cssSel: string): IPiechart; + export function barChart(cssSel: string): IBarchart; + export function lineChart(cssSel: string): ILinechart; + export function dataTable(cssSel: string): IDatachart; + export function rowChart(cssSel: string): IRowchart; + + +} \ No newline at end of file diff --git a/dock-spawn/dock-spawn-tests.ts b/dock-spawn/dock-spawn-tests.ts new file mode 100644 index 000000000..7bda821de --- /dev/null +++ b/dock-spawn/dock-spawn-tests.ts @@ -0,0 +1,22 @@ +/// + +var dockManagerDiv = document.createElement('div'), + panelDiv1 = document.createElement('div'), + panelDiv2 = document.createElement('div'), + panelDiv3 = document.createElement('div'); + +document.body.appendChild(dockManagerDiv); + +var dockManager = new dockspawn.DockManager(dockManagerDiv); +dockManager.initialize(); + +var panelContainer1 = new dockspawn.PanelContainer(panelDiv1, dockManager), + panelContainer2 = new dockspawn.PanelContainer(panelDiv2, dockManager), + panelContainer3 = new dockspawn.PanelContainer(panelDiv3, dockManager); + +var documentNode = dockManager.context.model.documentManagerNode; + +var panelNode1 = dockManager.dockLeft(documentNode, panelContainer1, 0.33), + panelNode2 = dockManager.dockRight(documentNode, panelContainer2, 0.33), + panelNode3 = dockManager.dockFill(documentNode, panelContainer3); + diff --git a/dock-spawn/dock-spawn.d.ts b/dock-spawn/dock-spawn.d.ts new file mode 100644 index 000000000..0c9d8fb4d --- /dev/null +++ b/dock-spawn/dock-spawn.d.ts @@ -0,0 +1,180 @@ +// Type definitions for Dock Spawn +// Project: http://dockspawn.com +// https://github.com/coderespawn/dock-spawn +// Definitions by: Drew Noakes +// Definitions: https://github.com/borisyankov/DefinitelyTyped/dock-spawn + +declare module dockspawn +{ + /** + * Dock manager manages all the dock panels in a hierarchy, similar to Visual Studio. + * It owns an HTMLDivElement inside which all panels are docked. + * Initially the document manager takes up the central space and acts as the root node. + */ + class DockManager + { + context: DockManagerContext; + + constructor(element: HTMLDivElement); + + initialize(): void; + + rebuildLayout(node: DockNode): void; + + invalidate(): void; + + resize(width: number, height: number): void; + + /** + * Reset the dock model. This happens when state is loaded from JSON. + */ + setModel(model: DockModel): void; + + setRootNode(node: DockNode): void; + + + /** Dock the [dialog] to the left of the [referenceNode] node */ + + dockDialogLeft(referenceNode: DockNode, dialog: Dialog): DockNode; + /** Dock the [dialog] to the right of the [referenceNode] node */ + dockDialogRight(referenceNode: DockNode, dialog: Dialog): DockNode; + /** Dock the [dialog] above the [referenceNode] node */ + dockDialogUp(referenceNode: DockNode, dialog: Dialog): DockNode; + /** Dock the [dialog] below the [referenceNode] node */ + dockDialogDown(referenceNode: DockNode, dialog: Dialog): DockNode; + /** Dock the [dialog] as a tab inside the [referenceNode] node */ + dockDialogFill(referenceNode: DockNode, container: PanelContainer): DockNode; + + /** Dock the [container] to the left of the [referenceNode] node */ + dockLeft(referenceNode: DockNode, container: PanelContainer, ratio: number): DockNode; + /** Dock the [container] to the right of the [referenceNode] node */ + dockRight(referenceNode: DockNode, container: PanelContainer, ratio: number): DockNode; + /** Dock the [container] above the [referenceNode] node */ + dockUp(referenceNode: DockNode, container: PanelContainer, ratio: number): DockNode; + /** Dock the [container] below the [referenceNode] node */ + dockDown(referenceNode: DockNode, container: PanelContainer, ratio: number): DockNode; + /** Dock the [container] as a tab inside the [referenceNode] node */ + dockFill(referenceNode: DockNode, container: PanelContainer): DockNode; + + suspendLayout(): void; + + resumeLayout(): void; + + saveState(): string; + loadState(state: string): void; + } + + class DockManagerContext + { + dockManager: DockManager; + model: DockModel; + documentManagerView: DocumentManagerContainer; + + constructor(dockManager: DockManager); + } + + class DockModel + { + rootNode: DockNode; + documentManagerNode: DockNode; + } + + class DockNode + { + constructor(container: PanelContainer); + + detachFromParent(): void; + } + + /** + * Tab Host control contains tabs known as TabPages. + * The tab strip can be aligned in different orientations + */ + class TabHost + { + tabStripDirection: TabStripDirection; + displayCloseButton: boolean; + pages: TabPage[]; + hostElement: HTMLDivElement; + tabListElement: HTMLDivElement; + separatorElement: HTMLDivElement; + contentElement: HTMLDivElement; + + constructor(tabStripDirection?: TabStripDirection, displayCloseButton?: boolean) + + setActiveTab(container: PanelContainer): void; + + /** Set the selected TabPage. */ + onTabPageSelected(page: TabPage): void; + + resize(width: number, height: number): void; + } + + class TabPage + { + constructor(host: TabHost, container: PanelContainer); + } + + enum TabStripDirection + { + DIRECTION_TOP = 0, + DIRECTION_BOTTOM = 1, + DIRECTION_LEFT = 2, + DIRECTION_RIGHT = 3 + } + + class FillDockContainer + { + tabOrientation: TabStripDirection; + element: HTMLDivElement; + tabHost: TabHost; + dockManager: DockManager; + name: string; + containerType: string; + minimumAllowedChildNodes: number; + + constructor(dockManager: DockManager, tabStripDirection?: TabStripDirection) + } + + /** + * The document manager is then central area of the dock layout hierarchy. + * This is where more important panels are placed (e.g. the text editor in an IDE, + * 3D view in a modelling package etc + */ + class DocumentManagerContainer extends FillDockContainer + { + selectedTab: TabPage; + + constructor(dockManager: DockManager); + + saveState(state: string): void; + } + + class PanelContainer + { + width: number; + height: number; + + constructor(element: HTMLElement, dockManager: DockManager, title?: string); + + setTitle(title: string): void; + setTitleIcon(iconName: string): void; + } + + class Dialog + { + static fromElement(id: string, dockManager: DockManager): Dialog; + + constructor(panel: PanelContainer, dockManager: DockManager); + + setPosition(x: number, y: number): void; + + resize(width: number, height: number): void; + + setTitle(title: string): void; + + setTitleIcon(iconName: string): void; + + bringToFront(): void; + } +} diff --git a/googlemaps.infobubble/google.maps.infobubble-tests.ts b/googlemaps.infobubble/google.maps.infobubble-tests.ts index 61f6b7ac5..7dcfa739b 100644 --- a/googlemaps.infobubble/google.maps.infobubble-tests.ts +++ b/googlemaps.infobubble/google.maps.infobubble-tests.ts @@ -26,8 +26,11 @@ function test_bubble() { var map: google.maps.Map; var marker: google.maps.Marker; var bubble: google.maps.infobubble.InfoBubble; + var position: google.maps.LatLng; bubble.open(map, marker); var isOpen = bubble.isOpen(); bubble.close(); + + position = bubble.getPosition(); } \ No newline at end of file diff --git a/googlemaps.infobubble/google.maps.infobubble.d.ts b/googlemaps.infobubble/google.maps.infobubble.d.ts index f65dd1114..2d88d8645 100644 --- a/googlemaps.infobubble/google.maps.infobubble.d.ts +++ b/googlemaps.infobubble/google.maps.infobubble.d.ts @@ -57,6 +57,11 @@ declare module google.maps.infobubble { * @marker The marker used for anchoring the infobubble to */ open(map: google.maps.Map, marker: google.maps.Marker) : void; + + /** + * Returns the position of the InfoBubble + */ + getPosition(): google.maps.LatLng; } export interface InfoBubbleOptions { diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 4589e09f0..86a446508 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -367,7 +367,7 @@ declare module google.maps { getEditable(): boolean; getMap(): Map; getPath(): MVCArray; - getPaths(): MVCArray[]; + getPaths(): MVCArray; getVisible(): boolean; setDraggable(draggable: boolean): void; setEditable(editable: boolean): void; diff --git a/gruntjs/gruntjs.d.ts b/gruntjs/gruntjs.d.ts index cfe2825e4..f646bcbf2 100644 --- a/gruntjs/gruntjs.d.ts +++ b/gruntjs/gruntjs.d.ts @@ -393,7 +393,8 @@ declare module grunt { * @param contents If `contents` is a Buffer, encoding is ignored. * @param options If an encoding is not specified, default to grunt.file.defaultEncoding. */ - write(filepath: string, contents: NodeBuffer, options?: IFileEncodedOption): void + write(filepath: string, contents: string, options?: IFileEncodedOption): void + write(filepath: string, contents: NodeBuffer): void /** * Copy a source file to a destination path, creating intermediate directories if necessary. @@ -809,6 +810,12 @@ declare module grunt { * This method is used internally by the multi task system this.files / grunt.task.current.files property. */ normalizeMultiTaskFiles(data: grunt.config.IProjectConfig, targetname?: string): Array + + /** + * The currently running task or multitask. + * @see http://gruntjs.com/api/inside-tasks + */ + current: grunt.task.IMultiTask } interface AsyncResultCatcher { @@ -1232,13 +1239,6 @@ declare module grunt { } interface ITaskComponents extends grunt.task.CommonTaskModule { - - /** - * The currently running task or multitask. - * @see IMultiTask for when to cast - */ - current: grunt.task.ITask - /** * Load task-related files from the specified directory, relative to the Gruntfile. * This method can be used to load task-related files from a local Grunt plugin by diff --git a/highland/highland-tests.ts b/highland/highland-tests.ts index 7acc6c50b..3625b3f81 100644 --- a/highland/highland-tests.ts +++ b/highland/highland-tests.ts @@ -73,15 +73,15 @@ var barArr: Bar[]; var fooStream: Highland.Stream; var barStream: Highland.Stream; +var fooStreamStream: Highland.Stream>; +var barStreamStream: Highland.Stream>; + var fooArrStream: Highland.Stream; var barArrStream: Highland.Stream; var fooStreamArr: Highland.Stream[]; var barStreamArr: Highland.Stream[]; -var fooStreamArr: Highland.Stream[]; -var barStreamArr: Highland.Stream[]; - var strFooArrMapStream: Highland.Stream; var strBarArrMapStream: Highland.Stream; @@ -184,13 +184,13 @@ strStream = _.keys(obj); anyArrStream = _.pairs(obj); anyArrStream = _.pairs(fooArr); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - obj = _.extend(obj, obj); objCurObj = _.extend(obj); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - x = _.get(str, obj); @@ -200,26 +200,26 @@ obj = _.set(str, foo, obj); objCurAny = _.set(str, foo); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - _.log(str); _.log(str, num, foo); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - f = _.wrapCallback(func); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - num = _.add(num, num); numCurNum = _.add(num); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // instance methods -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fooStream.pause(); fooStream.resume(); @@ -323,6 +323,10 @@ fooStream = fooStream.flatFilter((x: Foo) => { return boolStream; }); +fooStream = fooStream.reject((x: Foo) => { + return bool; +}); + fooStream = fooStream.find((x: Foo) => { return bool; }); @@ -343,6 +347,7 @@ fooStream = fooStream.where(obj); fooStream = fooStream.zip(fooStream); fooStream = fooStream.zip([foo, foo]); +fooStream = fooStream.head(); fooStream = fooStream.take(num); fooStream = fooStream.last(); @@ -383,6 +388,10 @@ fooStream = fooStream.concat(fooArr); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +fooStream = fooStream.merge(fooStreamStream); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + barStream = fooStream.invoke(str, anyArr); fooStream = fooStream.throttle(num); @@ -393,4 +402,4 @@ fooStream = fooStream.debounce(num); fooStream = fooStream.latest(); -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/highland/highland.d.ts b/highland/highland.d.ts index 252c617ea..8760a5c2d 100644 --- a/highland/highland.d.ts +++ b/highland/highland.d.ts @@ -8,6 +8,7 @@ // TODO export the top-level functions // TODO figure out curry arguments +// TODO create more overloads for nested data, like streams-of-streams or streams-of-array-of-streams etc // TODO use externalised Thenable // TODO use externalised Readable/Writable (not node's) @@ -19,7 +20,6 @@ * Copyright (c) Caolan McMahon * */ - interface HighlandStatic { /** * The Stream constructor, accepts an array of values or a generator function @@ -320,8 +320,9 @@ interface HighlandStatic { * @api public */ add(a: number, b: number): number; - add(a: number): (b: number) => number; + + not(a: any): boolean; } declare module Highland { @@ -660,6 +661,21 @@ declare module Highland { */ flatFilter(f: (x: R) => Stream): Stream; + /** + * The inverse of [filter](#filter). + * + * @id reject + * @section Streams + * @name Stream.reject(f) + * @param {Function} f - the truth test function + * @api public + * + * var odds = _([1, 2, 3, 4]).reject(function (x) { + * return x % 2 === 0; + * }); + */ + reject(f: (x: R) => boolean): Stream; + /** * A convenient form of filter, which returns the first object from a * Stream that passes the provided truth test @@ -733,6 +749,18 @@ declare module Highland { */ take(n: number): Stream; + /** + * Creates a new Stream with only the first value from the source. + * + * @id head + * @section Streams + * @name Stream.head() + * @api public + * + * _([1, 2, 3, 4]).head() // => 1 + */ + head(): Stream; + /** * Drops all values from the Stream apart from the last one (if any). * @@ -871,6 +899,20 @@ declare module Highland { */ scan(memo: U, x: (memo: U, x: R) => U): Stream; + /** + * Same as [scan](#scan), but uses the first element as the initial + * state instead of passing in a `memo` value. + * + * @id scan1 + * @section Streams + * @name Stream.scan1(iterator) + * @param {Function} iterator - the function which reduces the values + * @api public + * + * _([1, 2, 3, 4]).scan1(add) // => 1, 3, 6, 10 + */ + scan1(memo: U, x: (memo: U, x: R) => U): Stream; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** @@ -889,6 +931,29 @@ declare module Highland { concat(ys: Stream): Stream; concat(ys: R[]): Stream; + /** + * Takes a Stream of Streams and merges their values and errors into a + * single new Stream. The merged stream ends when all source streams have + * ended. + * + * Note that no guarantee is made with respect to the order in which + * values for each stream end up in the merged stream. Values in the + * merged stream will, however, respect the order they were emitted from + * their respective streams. + * + * @id merge + * @section Streams + * @name Stream.merge() + * @api public + * + * var txt = _(['foo.txt', 'bar.txt']).map(readFile) + * var md = _(['baz.md']).map(readFile) + * + * _([txt, md]).merge(); + * // => contents of foo.txt, bar.txt and baz.txt in the order they were read + */ + merge (ys: Stream>): Stream; + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** diff --git a/jasmine-jquery/jasmine-jquery-tests.ts b/jasmine-jquery/jasmine-jquery-tests.ts index 15877ed60..ef6d8cc79 100644 --- a/jasmine-jquery/jasmine-jquery-tests.ts +++ b/jasmine-jquery/jasmine-jquery-tests.ts @@ -16,7 +16,9 @@ describe("Jasmine jQuery extension", () => { expect($('').addClass('js-something')).toBeMatchedBy('.js-something'); expect($('')).toExist(); expect($('
')).toHaveAttr('id', 'some-id'); + expect($('')).toHaveAttr('type'); expect($('
')).toHaveProp('id', 'some-id'); + expect($('')).toHaveProp('checked'); expect($('')).toHaveBeenTriggered(); expect($('')).toHaveBeenTriggeredOn('#some-id'); expect($('')).toHaveBeenTriggeredOnAndWith('#some-id', 'eventParam'); @@ -132,4 +134,4 @@ describe("Jasmine jQuery extension", () => { expect(spyEvent).toHaveBeenStopped(); }); }); -}) +}); diff --git a/jasmine-jquery/jasmine-jquery.d.ts b/jasmine-jquery/jasmine-jquery.d.ts index 520445a23..1d3c30cda 100644 --- a/jasmine-jquery/jasmine-jquery.d.ts +++ b/jasmine-jquery/jasmine-jquery.d.ts @@ -3,142 +3,142 @@ // Definitions by: Gregor Stamac // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped -/// -/// - -declare function sandbox(attributes?: any): string; - -declare function readFixtures(...uls: string[]): string; -declare function preloadFixtures(...uls: string[]); -declare function loadFixtures(...uls: string[]); -declare function appendLoadFixtures(...uls: string[]); -declare function setFixtures(html: string): string; -declare function appendSetFixtures(html: string); - -declare function preloadStyleFixtures(...uls: string[]); -declare function loadStyleFixtures(...uls: string[]); -declare function appendLoadStyleFixtures(...uls: string[]); -declare function setStyleFixtures(html: string); -declare function appendSetStyleFixtures(html: string); - -declare function loadJSONFixtures(...uls: string[]): jasmine.JSONFixtures; -declare function getJSONFixture(url: string): any; +/// +/// + +declare function sandbox(attributes?: any): string; + +declare function readFixtures(...uls: string[]): string; +declare function preloadFixtures(...uls: string[]); +declare function loadFixtures(...uls: string[]); +declare function appendLoadFixtures(...uls: string[]); +declare function setFixtures(html: string): string; +declare function appendSetFixtures(html: string); + +declare function preloadStyleFixtures(...uls: string[]); +declare function loadStyleFixtures(...uls: string[]); +declare function appendLoadStyleFixtures(...uls: string[]); +declare function setStyleFixtures(html: string); +declare function appendSetStyleFixtures(html: string); + +declare function loadJSONFixtures(...uls: string[]): jasmine.JSONFixtures; +declare function getJSONFixture(url: string): any; + +declare function spyOnEvent(selector: string, eventName: string): jasmine.JQueryEventSpy; -declare function spyOnEvent(selector: string, eventName: string): jasmine.JQueryEventSpy; - declare module jasmine { - function spiedEventsKey(selector: JQuery, eventName: string): string; + function spiedEventsKey(selector: JQuery, eventName: string): string; - function getFixtures(): Fixtures; - function getStyleFixtures(): StyleFixtures; - function getJSONFixtures(): JSONFixtures; + function getFixtures(): Fixtures; + function getStyleFixtures(): StyleFixtures; + function getJSONFixtures(): JSONFixtures; interface Fixtures { fixturesPath: string; containerId: string; - set(html: string): string; - appendSet(html: string); - preload(...uls: string[]); - load(...uls: string[]); - appendLoad(...uls: string[]); - read(...uls: string[]): string; - clearCache(); - cleanUp(); - sandbox(attributes?: any): string; - createContainer_(html: string); - addToContainer_(html: string); - getFixtureHtml_(url: string): string; - loadFixtureIntoCache_(relativeUrl: string); - makeFixtureUrl_(relativeUrl: string): string; - proxyCallTo_(methodName: string, passedArguments): any; + set(html: string): string; + appendSet(html: string); + preload(...uls: string[]); + load(...uls: string[]); + appendLoad(...uls: string[]); + read(...uls: string[]): string; + clearCache(); + cleanUp(); + sandbox(attributes?: any): string; + createContainer_(html: string); + addToContainer_(html: string); + getFixtureHtml_(url: string): string; + loadFixtureIntoCache_(relativeUrl: string); + makeFixtureUrl_(relativeUrl: string): string; + proxyCallTo_(methodName: string, passedArguments): any; } interface StyleFixtures { fixturesPath: string; - set(html: string): string; - appendSet(html: string); - preload(...uls: string[]); - load(...uls: string[]); - appendLoad(...uls: string[]); - read_(...uls: string[]): string; - clearCache(); - cleanUp(); - createStyle_(html: string); - getFixtureHtml_(url: string): string; - loadFixtureIntoCache_(relativeUrl: string); - makeFixtureUrl_(relativeUrl: string): string; - proxyCallTo_(methodName: string, passedArguments): any; + set(html: string): string; + appendSet(html: string); + preload(...uls: string[]); + load(...uls: string[]); + appendLoad(...uls: string[]); + read_(...uls: string[]): string; + clearCache(); + cleanUp(); + createStyle_(html: string); + getFixtureHtml_(url: string): string; + loadFixtureIntoCache_(relativeUrl: string); + makeFixtureUrl_(relativeUrl: string): string; + proxyCallTo_(methodName: string, passedArguments): any; } interface JSONFixtures { fixturesPath: string; - load(...uls: string[]); - read(...uls: string[]): string; - clearCache(); - getFixtureData_(url: string): any; - loadFixtureIntoCache_(relativeUrl: string); + load(...uls: string[]); + read(...uls: string[]): string; + clearCache(); + getFixtureData_(url: string): any; + loadFixtureIntoCache_(relativeUrl: string); proxyCallTo_(methodName: string, passedArguments): any; } interface Matchers { toHaveClass(className: string): boolean; - toHaveCss(css): boolean; - toBeVisible(): boolean; - toBeHidden(): boolean; - toBeSelected(): boolean; - toBeChecked(): boolean; - toBeEmpty(): boolean; - toExist(): boolean; - toHaveLength(length: number): boolean; - toHaveAttr(attributeName: string, expectedAttributeValue): boolean; - toHaveProp(propertyName: string, expectedPropertyValue): boolean; - toHaveId(id: string): boolean; - toHaveHtml(html: string): boolean; - //toContainHtml(html: string): boolean; - toHaveText(text: string): boolean; - //toContainText(text: string): boolean; - toHaveValue(value): boolean; - toHaveData(key, expectedValue): boolean; - toBe(selector: JQuery): boolean; - toContain(selector: JQuery): boolean; - toBeMatchedBy(selector: string): boolean; - toBeDisabled(): boolean; - toBeFocused(): boolean; - toHandle(event): boolean; - toHandleWith(eventName: string, eventHandler): boolean; - - toHaveBeenTriggered(): boolean; - toHaveBeenTriggeredOn(selector: string): boolean; - toHaveBeenTriggeredOnAndWith(selector: string, ...args: any[]): boolean; - toHaveBeenPrevented(): boolean; - toHaveBeenPreventedOn(selector: string): boolean; - toHaveBeenStopped(): boolean; - toHaveBeenStoppedOn(selector: string): boolean; + toHaveCss(css): boolean; + toBeVisible(): boolean; + toBeHidden(): boolean; + toBeSelected(): boolean; + toBeChecked(): boolean; + toBeEmpty(): boolean; + toExist(): boolean; + toHaveLength(length: number): boolean; + toHaveAttr(attributeName: string, expectedAttributeValue?): boolean; + toHaveProp(propertyName: string, expectedPropertyValue?): boolean; + toHaveId(id: string): boolean; + toHaveHtml(html: string): boolean; + //toContainHtml(html: string): boolean; + toHaveText(text: string): boolean; + //toContainText(text: string): boolean; + toHaveValue(value): boolean; + toHaveData(key, expectedValue): boolean; + toBe(selector: JQuery): boolean; + toContain(selector: JQuery): boolean; + toBeMatchedBy(selector: string): boolean; + toBeDisabled(): boolean; + toBeFocused(): boolean; + toHandle(event): boolean; + toHandleWith(eventName: string, eventHandler): boolean; + + toHaveBeenTriggered(): boolean; + toHaveBeenTriggeredOn(selector: string): boolean; + toHaveBeenTriggeredOnAndWith(selector: string, ...args: any[]): boolean; + toHaveBeenPrevented(): boolean; + toHaveBeenPreventedOn(selector: string): boolean; + toHaveBeenStopped(): boolean; + toHaveBeenStoppedOn(selector: string): boolean; } interface JQueryEventSpy { - selector: string; - eventName: string; - handler(eventObject: JQueryEventObject): any; + selector: string; + eventName: string; + handler(eventObject: JQueryEventObject): any; reset(): any; } interface JasmineJQuery { - browserTagCaseIndependentHtml(html: string): string; - elementToString(element: JQuery): string; - matchersClass: any; - events: JasmineJQueryEvents; - } - - interface JasmineJQueryEvents { - spyOn(selector: string, eventName: string): JQueryEventSpy; - args(selector: string, eventName: string): any; - wasTriggered(selector: string, eventName: string): boolean; - wasTriggeredWith(selector: string, eventName: string, expectedArgs: any, env: jasmine.Env): boolean; - wasPrevented(selector: string, eventName: string): boolean; - wasStopped(selector: string, eventName: string): boolean; - cleanUp(); - } + browserTagCaseIndependentHtml(html: string): string; + elementToString(element: JQuery): string; + matchersClass: any; + events: JasmineJQueryEvents; + } + + interface JasmineJQueryEvents { + spyOn(selector: string, eventName: string): JQueryEventSpy; + args(selector: string, eventName: string): any; + wasTriggered(selector: string, eventName: string): boolean; + wasTriggeredWith(selector: string, eventName: string, expectedArgs: any, env: jasmine.Env): boolean; + wasPrevented(selector: string, eventName: string): boolean; + wasStopped(selector: string, eventName: string): boolean; + cleanUp(); + } var JQuery: JasmineJQuery; } diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 4c01b347b..794538ec5 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -5,10 +5,13 @@ declare function describe(description: string, specDefinitions: () => void): void; +declare function ddescribe(description: string, specDefinitions: () => void): void; declare function xdescribe(description: string, specDefinitions: () => void): void; declare function it(expectation: string, assertion?: () => void): void; declare function it(expectation: string, assertion?: (done: () => void) => void): void; +declare function iit(expectation: string, assertion?: () => void): void; +declare function iit(expectation: string, assertion?: (done: () => void) => void): void; declare function xit(expectation: string, assertion?: () => void): void; declare function xit(expectation: string, assertion?: (done: () => void) => void): void; @@ -95,11 +98,13 @@ declare module jasmine { addReporter(reporter: Reporter): void; execute(): void; describe(description: string, specDefinitions: () => void): Suite; + ddescribe(description: string, specDefinitions: () => void): Suite; beforeEach(beforeEachFunction: () => void): void; currentRunner(): Runner; afterEach(afterEachFunction: () => void): void; xdescribe(desc: string, specDefinitions: () => void): XSuite; it(description: string, func: () => void): Spec; + iit(description: string, func: () => void): Spec; xit(desc: string, func: () => void): XSpec; compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; @@ -349,7 +354,7 @@ declare module jasmine { identity: string; and: SpyAnd; - calls: any[]; + calls: any; mostRecentCall: { args: any[]; }; argsForCall: any[]; wasCalled: boolean; @@ -362,7 +367,7 @@ declare module jasmine { /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ returnValue(val: any): void; /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ - callFake(fn: () => any): void; + callFake(fn: Function): void; /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ throwError(msg: string): void; /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ diff --git a/jquery.address/jquery.address.d.ts b/jquery.address/jquery.address.d.ts index cb7117245..bbf91d84a 100644 --- a/jquery.address/jquery.address.d.ts +++ b/jquery.address/jquery.address.d.ts @@ -10,6 +10,13 @@ interface JQueryAddressStatic { change(callback: any): void; value(url: any): void; update(): void; + path(): string; + path(value: string): void; + internalChange(eventhandler: Function): void; + externalChange(eventhandler: Function): void; + parameter(name: string, value?: string): string; + value(): string; + history(value: boolean): void; } interface JQueryAddress { diff --git a/jquery.jsignature/jquery.jsignature-tests.ts b/jquery.jsignature/jquery.jsignature-tests.ts new file mode 100644 index 000000000..b7e9631a5 --- /dev/null +++ b/jquery.jsignature/jquery.jsignature-tests.ts @@ -0,0 +1,19 @@ +/// +/// + +/* + * Taken from the tests section on jSignature + */ +$(document).ready(function () { + + var $sigdiv = $('#signature'); + + $sigdiv.jSignature(); + + $sigdiv.jSignature("reset"); + + var data = $sigdiv.jSignature("getData", "svgbase64"); + + $sigdiv.jSignature("setData", "data:" + data); + +}); \ No newline at end of file diff --git a/jquery.jsignature/jquery.jsignature.d.ts b/jquery.jsignature/jquery.jsignature.d.ts new file mode 100644 index 000000000..f4ffa498b --- /dev/null +++ b/jquery.jsignature/jquery.jsignature.d.ts @@ -0,0 +1,46 @@ +// Type definitions for jQuery.jsignature v2 +// Project: https://github.com/willowsystems/jSignature +// Definitions by: Patrick Magee +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Project by: Willow Systems Corp + +/// + +interface JQuery { + + /** + * inits the jSignature widget + */ + jSignature(): JQuery; + + /** + * Arguments vary per command. When provided, command is expected to be a string with a command for jSignature. Commands supported at this time: init, reset, getData, setData, listPlugins + * @summary + * init is the default, assumed action. init takes one argument - a settings Object. You can omit the command and just pass the settings object in upon init. Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied. + * clear (also aliased as reset) clears the signature pad, data store (and puts back signature line and other decor). Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied. + * getData takes an argument - the name of the data format. Returns a data object appropriate for the data format. + * setData (also aliased as importData) takes two arguments - data object, (optional) data format name. When data object is a string formatted in data-url pattern you don't need to specify the data dormat name. The data format name (mime) will be implied from the data-url prefix. Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied. + * listPlugins takes an argument - a string denoting the category (Only export, import supported at this time) of plugins to list. Returns an array of strings. + * + * @param command the command used to perform an action on the jSignature canvas + * @see http://willowsystems.github.io/jSignature/#/about/ + * + */ + jSignature(command: string): any; + + /** + * Arguments vary per command. When provided, command is expected to be a string with a command for jSignature. Commands supported at this time: init, reset, getData, setData, listPlugins + * @summary + * init is the default, assumed action. init takes one argument - a settings Object. You can omit the command and just pass the settings object in upon init. Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied. + * clear (also aliased as reset) clears the signature pad, data store (and puts back signature line and other decor). Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied. + * getData takes an argument - the name of the data format. Returns a data object appropriate for the data format. + * setData (also aliased as importData) takes two arguments - data object, (optional) data format name. When data object is a string formatted in data-url pattern you don't need to specify the data dormat name. The data format name (mime) will be implied from the data-url prefix. Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied. + * listPlugins takes an argument - a string denoting the category (Only export, import supported at this time) of plugins to list. Returns an array of strings. + * + * @param command the command used to perform an action on the jSignature canvas + * @param arg the argument used with the specified command + * @see http://willowsystems.github.io/jSignature/#/about/ + * + */ + jSignature(command: string, ...arg: string[]): any; +} diff --git a/jquery.placeholder/jquery.placeholder-tests.ts b/jquery.placeholder/jquery.placeholder-tests.ts new file mode 100644 index 000000000..072c03721 --- /dev/null +++ b/jquery.placeholder/jquery.placeholder-tests.ts @@ -0,0 +1,4 @@ +/// +/// + +$('input').placeholder(); diff --git a/jquery.placeholder/jquery.placeholder.d.ts b/jquery.placeholder/jquery.placeholder.d.ts new file mode 100644 index 000000000..b9af72494 --- /dev/null +++ b/jquery.placeholder/jquery.placeholder.d.ts @@ -0,0 +1,13 @@ +// Type definitions for jquery.placeholder.js 2.0.7 +// Project: https://github.com/mathiasbynens/jquery-placeholder +// Definitions by: Peter Gill +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQuery { + + placeholder() : void; + +} + diff --git a/jquery.tooltipster/jquery.tooltipster-tests.ts b/jquery.tooltipster/jquery.tooltipster-tests.ts new file mode 100644 index 000000000..fe68605b2 --- /dev/null +++ b/jquery.tooltipster/jquery.tooltipster-tests.ts @@ -0,0 +1,194 @@ +/// + +// Type definition tests for jQuery Tooltipster 3.0.5 +// Project: https://github.com/iamceege/tooltipster +// Definitions by: Patrick Magee +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Tests taken from the getting started section of the Tooltipster website + +$(document).ready(function () { + + $('.tooltip').tooltipster(); + + $('#my-tooltip').tooltipster({ + content: $(' This text is in bold case !') + }); +}); + + +$(document).ready(function () { + $('.tooltip').tooltipster({ + contentAsHTML: true + }); +}); + +$('.tooltip').tooltipster({ + theme: 'tooltipster-noir' +}); + +$('.tooltip').tooltipster({ + animation: 'fade', + delay: 200, + theme: 'tooltipster-default', + touchDevices: false, + trigger: 'hover' +}); + +$.fn.tooltipster('setDefaults', { + position: 'bottom' +}); + +var myNewContent = ''; + +function callback(): void { + +} + +// temporarily disable a tooltip from being able to open +$('.tooltip').tooltipster('disable'); + +// if a tooltip was disabled from opening, reenable its previous functionality +$('.tooltip').tooltipster('enable'); + +// hide and destroy tooltip functionality +$('.tooltip').tooltipster('destroy'); + +// return a tooltip's current content (if selector contains multiple origins, only the value of the first will be returned) +$('.tooltip').tooltipster('content'); + +// update tooltip content +$('.tooltip').tooltipster('content', myNewContent); + +// reposition and resize the tooltip +$('.tooltip').tooltipster('reposition'); + +// return the HTML root element of the tooltip +$('.tooltip').tooltipster('elementTooltip'); + +// return the HTML root element of the icon if there is one, 'undefined' otherwise +$('.tooltip').tooltipster('elementIcon'); + +$('.tooltip').tooltipster({ + content: 'Loading...', + functionBefore: function (origin, continueTooltip) { + + // we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data + continueTooltip(); + + // next, we want to check if our data has already been cached + if (origin.data('ajax') !== 'cached') { + $.ajax({ + type: 'POST', + url: 'example.php', + success: function (data) { + // update our tooltip content with our returned data and cache it + origin.tooltipster('content', data).data('ajax', 'cached'); + } + }); + } + } +}); + + + +$('.tooltip').tooltipster({ + content: 'Loading...', + functionBefore: (origin, continueTooltip) => { + + // we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data + continueTooltip(); + + // next, we want to check if our data has already been cached + if (origin.data('ajax') !== 'cached') { + $.ajax({ + type: 'POST', + url: 'example.php', + success: function (data) { + // update our tooltip content with our returned data and cache it + origin.tooltipster('content', data).data('ajax', 'cached'); + } + }); + } + } +}); + +$('.tooltip').tooltipster({ + functionInit: function (origin, content) { + + if (content === 'This is bad content') { + + // when the request has finished loading, we will change the tooltip's content + $.ajax({ + type: 'POST', + url: 'example.php', + success: function (data) { + origin.tooltipster('content', 'New content has been loaded : ' + data); + } + }); + + // this returned string will overwrite the content of the tooltip for the time being + return 'Wait while we load new content...'; + } + else { + // return nothing : the initialization continues normally with its content unchanged. + } + } +}); + +$('.tooltip').tooltipster({ + functionInit: (origin, content) => { + + if (content === 'This is bad content') { + + // when the request has finished loading, we will change the tooltip's content + $.ajax({ + type: 'POST', + url: 'example.php', + success: function (data) { + origin.tooltipster('content', 'New content has been loaded : ' + data); + } + }); + + // this returned string will overwrite the content of the tooltip for the time being + return 'Wait while we load new content...'; + } + else { + // return nothing : the initialization continues normally with its content unchanged. + } + } +}); + +$(document).ready(function () { + + // first on page load, initiate the Tooltipster plugin + $('.tooltip').tooltipster(); + + // then immediately show the tooltip + $('#example').tooltipster('show'); + + // as soon as a key is pressed on the keyboard, hide the tooltip. + $(window).keypress(function () { + $('#example').tooltipster('hide'); + }); +}); + +$(document).ready(function () { + + $('.tooltip').tooltipster(); + + $('#example').tooltipster('show', function () { + alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); + }); + + $('#example').tooltipster('show', () => { + alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); + }); + + $(window).keypress(function () { + $('#example').tooltipster('hide', function () { + alert('The tooltip is now fully closed'); + }); + }); +}); + +$('#my-special-tooltip').tooltipster('content', 'My new content'); \ No newline at end of file diff --git a/casperjs/casperjs.d.ts.tscparams b/jquery.tooltipster/jquery.tooltipster-tests.ts.tscparams similarity index 100% rename from casperjs/casperjs.d.ts.tscparams rename to jquery.tooltipster/jquery.tooltipster-tests.ts.tscparams diff --git a/jquery.tooltipster/jquery.tooltipster.d.ts b/jquery.tooltipster/jquery.tooltipster.d.ts new file mode 100644 index 000000000..e9057f4b0 --- /dev/null +++ b/jquery.tooltipster/jquery.tooltipster.d.ts @@ -0,0 +1,186 @@ +// Type definitions for jQuery Tooltipster 3.0.5 +// Project: https://github.com/iamceege/tooltipster +// Definitions by: Patrick Magee +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQueryTooltipsterOptions { + /** + * Determines how the tooltip will animate in and out. Feel free to modify or create custom transitions in the tooltipster.css file. In IE9 and 8, all animations default to a JavaScript generated, fade animation. Default: 'fade' + * fade, grow, swing, slide, fall + */ + animation?: string; + /** + * Adds the "speech bubble arrow" to the tooltip. Default: true + */ + arrow?: boolean; + /** + * Select a specific color for the "speech bubble arrow". Default: will inherit the tooltip's background color + * hex code / rgb + */ + arrowColor?: any; + /** + * If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true + */ + autoClose?: boolean; + /** + * If set, this will override the content of the tooltip. Default: null + * @type string, jQuery object + */ + content?: any; + /** + * If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false + */ + contentAsHTML?: boolean; + /** + * If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object that should actually be used. Default: true + */ + contentCloning?: boolean; + /** + * Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200 + */ + delay?: number; + /** + * Set a fixed width for the tooltip. The tooltip will always be a consistent width - no matter your content size. Default: 0 (auto width) + */ + fixedWidth?: number; + /** + * Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width) + */ + maxWidth?: number; + /** + * Create a custom function to be fired only once at instantiation. If the function returns a value, this value will become the content of the tooltip. See the advanced section to learn more. Default: function(origin, content) {} + */ + functionInit?: (origin, content) => any; + /** + * Create a custom function to be fired before the tooltip opens. This function may prevent or hold off the opening. See the advanced section to learn more. Default: function(origin, continueTooltip) { continueTooltip(); } + */ + functionBefore?: (origin, continueTooltip) => void; + /** + * Create a custom function to be fired when the tooltip and its contents have been added to the DOM. Default: function(origin, tooltip) {} + */ + functionReady?: (origin, tooltip) => void; + /** + * Create a custom function to be fired once the tooltip has been closed and removed from the DOM. Default: function(origin) {} + */ + functionAfter?: (origin) => void; + /** + * If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)' + * @type string, jQuery object + */ + icon?: any; + /** + * If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true + */ + iconCloning?: boolean; + /** + * Generate an icon next to your content that is responsible for activating the tooltip on non-touch devices. Default: false + */ + iconDesktop?: boolean; + /** + * If using the iconDesktop or iconTouch options, this sets the class on the icon (used to style the icon). Default: 'tooltipster-icon' + */ + iconTheme?: string; + /** + * Generate an icon next to your content that is responsible for activating the tooltip on touch devices (tablets, phones, etc). Default: false + */ + iconTouch?: boolean; + /** + * Give users the possibility to interact with the tooltip. Unless autoClose is set to false, the tooltip will still close if the user moves away from or clicks out of the tooltip. Default: false + */ + interactive?: boolean; + /** + * If the tooltip is interactive and activated by a hover event, set the amount of time (milliseconds) allowed for a user to hover off of the tooltip activator (origin) on to the tooltip itself - keeping the tooltip from closing. Default: 350 + */ + interactiveTolerance?: number; + /** + * Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0 + */ + offsetX?: number; + /** + * Offsets the tooltip (in pixels) farther up/down from the origin. Default: 0 + */ + offsetY?: number; + /** + * If true, only one tooltip will be allowed to be active at a time. Non-autoclosing tooltips will not be closed though. Default: false + */ + onlyOne?: boolean; + /** + * Set the position of the tooltip. Default: 'top' + * right, left, top, top-right, top-left, bottom, bottom-right, bottom-left + */ + position?: string; + /** + * Will reposition the tooltip if the origin moves. As this option may have an impact on performance, we suggest you enable it only if you need to. Default: false + */ + positionTracker?: boolean; + /** + * Set the speed of the animation. Default: 350 + */ + speed?: number; + /** + * How long the tooltip should be allowed to live before closing. Default: 0 (disabled) + */ + timer?: number; + /** + * Set the theme used for your tooltip. Default: 'tooltipster-default' + */ + theme?: string; + /** + * If set to false, tooltips will not show on pure-touch devices, unless you open them yourself with the 'show' method. Touch gestures on devices which also have a mouse will still open the tooltips though. Default: true + */ + touchDevices?: boolean; + /** + * Set how tooltips should be activated and closed. See the advanced section to learn how to build custom triggers. Default: 'hover' + * hover, click, custom + */ + trigger?: string; + /** + * If a tooltip is open while its content is updated, play a subtle animation when the content changes. Default: true + */ + updateAnimation?: boolean; +} + +interface JQuery { + /** + * Initiate the Tooltipster plugin + */ + tooltipster(): void; + /** + * Creates a new tooltip with the specified, or default, options. + * @param options The options + * @example + * $('.tooltip').tooltipster({ + * animation: 'fade', + * delay: 200, + * theme: 'tooltipster-default', + * touchDevices: false, + * trigger: 'hover' + * }); + */ + tooltipster(options?: JQueryTooltipsterOptions): JQuery; + /** + * Updates an existing tinyscrollbar with the specified, or default, options. + * @param options The options + * @param callback optional argument callback + * @example + * $(window).keypress(function() { + * $('#example').tooltipster('hide', function() { + * alert('The tooltip is now fully closed'); + * }); + * }); + */ + tooltipster(method: string, callback?: Function): JQuery; + /** + * Call a method trigger with optional paramter + * @example $('#my-special-tooltip').tooltipster('content', 'My new content'); + * @example + * $('#example').tooltipster('show', function() { + * alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); + * }); + */ + tooltipster(method: string, param?: string): any; + +} + diff --git a/phantomjs/phantomjs.d.ts.tscparams b/jquery.tooltipster/jquery.tooltipster.d.ts.tscparams similarity index 100% rename from phantomjs/phantomjs.d.ts.tscparams rename to jquery.tooltipster/jquery.tooltipster.d.ts.tscparams diff --git a/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts b/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts new file mode 100644 index 000000000..52ae3e2e6 --- /dev/null +++ b/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts @@ -0,0 +1,22 @@ +/// +/// + +// basic no options +$('#datetimepicker').datetimepicker({ + +}); + +// basic with some options +$('#datetimepicker').datetimepicker({ + dateFormat: "yy-mm-dd", + timeFormat: 'HH:mm', + nextText: "", + prevText: "" +}); + +// function within the plugin +$('#datetimepicker').datetimepicker('formatTime', { + format: "HH:mm", + time: { hours: 1, minutes: 1, seconds: 1 } +}); + diff --git a/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts b/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts new file mode 100644 index 000000000..9d452332b --- /dev/null +++ b/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts @@ -0,0 +1,132 @@ +// Type definitions for jQuery UI DateTimePicker 0.3 Addon +// +// Project: http://trentrichardson.com/examples/timepicker/ +// Definitions by: https://github.com/dougajmcdonald +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +interface DateTimePickerOptions extends JQueryUI.DatepickerOptions { + + // Control options + showButtonPanel?: boolean; //Default: true - Whether to show the button panel at the bottom.This is generally needed. + timeOnly?: boolean; //Default: false - Hide the datepicker and only provide a time interface. + onSelect?: () => any; //Default: null - Function to be called when a date is chosen or time has changed(parameters: datetimeText, datepickerInstance). + alwaysSetTime?: boolean; //Default: true - Always have a time set internally, even before user has chosen one. + separator?: string; //Default: " " - When formatting the time this string is placed between the formatted date and formatted time. + pickerTimeFormat?: string; //Default: (timeFormat option) - How to format the time displayed within the timepicker. + pickerTimeSuffix?: string; //Default: (timeSuffix option) - String to place after the formatted time within the timepicker. + showTimepicker?: boolean; //Default: true - Whether to show the timepicker within the datepicker. + addSliderAccess?: boolean; //Default: false - Adds the sliderAccess plugin to sliders within timepicker + sliderAccessArgs?: any; //Default: null - Object to pass to sliderAccess when used. + defaultValue?: string; //Default: null - String of the default time value placed in the input on focus when the input is empty. + minDateTime?: Date; //Default: null - Date object of the minimum datetime allowed.Also available as minDate. + maxDateTime?: Date; //Default: null - Date object of the maximum datetime allowed.Also Available as maxDate. + parse?: string; //Default: 'strict' - How to parse the time string. Two methods are provided: 'strict' which must match the timeFormat exactly, and 'loose' which uses javascript's new Date(timeString) to guess the time. You may also pass in a function(timeFormat, timeString, options) to handle the parsing yourself, returning a simple object: + + // Alt field options + altFieldTimeOnly?: boolean; //Default: true - When altField is used from datepicker altField will only receive the formatted time and the original field only receives date. + altSeparator?: string; //Default: (separator option) - String placed between formatted date and formatted time in the altField. + altTimeSuffix?: string; //Default: (timeSuffix option) - String always placed after the formatted time in the altField. + altTimeFormat?: string; //Default: (timeFormat option) - The time format to use with the altField. + + // Localization options + currentText?: string; //Default: "Now", A Localization Setting - Text for the Now button. + closeText?: string; //Default: "Done", A Localization Setting - Text for the Close button. + amNames?: string; //Default: ['AM', 'A'], A Localization Setting - Array of strings to try and parse against to determine AM. + pmNames?: string; //Default: ['PM', 'P'], A Localization Setting - Array of strings to try and parse against to determine PM. + timeFormat?: string; //Default: "HH:mm", A Localization Setting - String of format tokens to be replaced with the time.See Formatting. + timeSuffix?: string; //Default: "", A Localization Setting - String to place after the formatted time. + timeOnlyTitle?: string; //Default: "Choose Time", A Localization Setting - Title of the wigit when using only timepicker. + timeText?: string; //Default: "Time", A Localization Setting - Label used within timepicker for the formatted time. + hourText?: string; //Default: "Hour", A Localization Setting - Label used to identify the hour slider. + minuteText?: string; //Default: "Minute", A Localization Setting - Label used to identify the minute slider. + secondText?: string; //Default: "Second", A Localization Setting - Label used to identify the second slider. + millisecText?: string; //Default: "Millisecond", A Localization Setting - Label used to identify the millisecond slider. + microsecText?: string; //Default: "Microsecond", A Localization Setting - Label used to identify the microsecond slider. + timezoneText?: string; //Default: "Timezone", A Localization Setting - Label used to identify the timezone slider. + isRTL?: boolean; //Default: false, A Localization Setting - Right to Left support. + + // Timefield options + controlType?: string; //Default: 'slider' - Whether to use 'slider' or 'select'.If 'slider' is unavailable through jQueryUI, 'select' will be used.For advanced usage you may pass an object which implements "create", "options", "value" methods to use controls other than sliders or selects.See the _controls property in the source code for more details. + showHour?: boolean; //Default: null - Whether to show the hour control. The default of null will use detection from timeFormat. + showMinute?: boolean; //Default: null - Whether to show the minute control. The default of null will use detection from timeFormat. + showSecond?: boolean; //Default: null - Whether to show the second control. The default of null will use detection from timeFormat. + showMillisec?: boolean; //Default: null - Whether to show the millisecond control. The default of null will use detection from timeFormat. + showMicrosec?: boolean; //Default: null - Whether to show the microsecond control. The default of null will use detection from timeFormat. + showTimezone?: boolean; //Default: null - Whether to show the timezone select. + showTime?: boolean; //Default: true - Whether to show the time selected within the datetimepicker. + stepHour?: number; //Default: 1 - Hours per step the slider makes. + stepMinute?: number; //Default: 1 - Minutes per step the slider makes. + stepSecond?: number; //Default: 1 - Seconds per step the slider makes. + stepMillisec?: number; //Default: 1 - Milliseconds per step the slider makes. + stepMicrosec?: number; //Default: 1 - Microseconds per step the slider makes. + hour?: number; //Default: 0 - Initial hour set. + minute?: number; //Default: 0 - Initial minute set. + second?: number; //Default: 0 - Initial second set. + millisec?: number; //Default: 0 - Initial millisecond set. + microsec?: number; //Default: 0 - Initial microsecond set. Note: Javascript's native Date object does not natively support microseconds. Timepicker adds ability to simply Date.setMicroseconds(m) and Date.getMicroseconds(). Date comparisons will not acknowledge microseconds. Use this only for display purposes. + timezone?: number; //Default: null - Initial timezone set.This is the offset in minutes.If null the browser's local timezone will be used. If you're timezone is "-0400" you would use - 240. For backwards compatibility you may pass "-0400", however the timezone is stored in minutes and more reliable. + hourMin?: number; //Default: 0 - The minimum hour allowed for all dates. + minuteMin?: number; //Default: 0 - The minimum minute allowed for all dates. + secondMin?: number; //Default: 0 - The minimum second allowed for all dates. + millisecMin?: number; //Default: 0 - The minimum millisecond allowed for all dates. + microsecMin?: number; //Default: 0 - The minimum microsecond allowed for all dates. + hourMax?: number; //Default: 23 - The maximum hour allowed for all dates. + minuteMax?: number; //Default: 59 - The maximum minute allowed for all dates. + secondMax?: number; //Default: 59 - The maximum second allowed for all dates. + millisecMax?: number; //Default: 999 - The maximum millisecond allowed for all dates. + microsecMax?: number; //Default: 999 - The maximum microsecond allowed for all dates. + hourGrid?: number; //Default: 0 - When greater than 0 a label grid will be generated under the slider.This number represents the units (in hours) between labels. + minuteGrid?: number; //Default: 0 - When greater than 0 a label grid will be generated under the slider.This number represents the units (in minutes) between labels. + secondGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in seconds) between labels. + millisecGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in milliseconds) between labels. + microsecGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in microseconds) between labels. + + // Timezone options + timezoneList?: Array //Default: [generated timezones] - An array of timezones used to populate the timezone select.Can be an array of values or an array of objects: { label: "EDT", value: -240 }. The value should be the offset number in minutes.So "-0400" which is the format "-hhmm", would equate to - 240 minutes. +} + +interface TimezoneOptions { + label: string; + value: number; +} + +interface Time { + hour?: number; + minute?: number; + second?: number; + millisecond?: number; + timezone?: string; +} + +interface formatTimeOptions { + format: string; + time: Time; + options?: DateTimePickerOptions; +} + +interface parseTimeOptions { + format: string; + time: string; + options?: DateTimePickerOptions; +} + +interface parseDateTimeOptions { + dateFormat: string; + timeFormat: string; + dateTimeString: string; + dateSettings: string; + timeSettings: string; +} + +interface JQuery { + datetimepicker(): JQuery; + datetimepicker(options?: DateTimePickerOptions): JQuery; + datetimepicker(method: string, methodParameter: any): any; + datetimepicker(method: 'formatTime', methodParameter: formatTimeOptions): string; + datetimepicker(method: 'parseTime', methodParameter: parseTimeOptions): Time; + datetimepicker(method: 'parseDateTime', methodParameter: parseDateTimeOptions): Date; +} + diff --git a/jquery.validation/jquery.validation.d.ts b/jquery.validation/jquery.validation.d.ts index 301bf6bc6..ec2114f08 100644 --- a/jquery.validation/jquery.validation.d.ts +++ b/jquery.validation/jquery.validation.d.ts @@ -51,7 +51,7 @@ interface Validator { addClassRules(name: string, rules: any): void; addClassRules(rules: any): void; - addMethod(name: string, method: (value: any, element: any, ...params: any[]) => any, message?: any): void; + addMethod(name: string, method: (value: any, element: any, params: any) => any, message?: any): void; element(element: any): boolean; form(): boolean; format(template: string, ...arguments: string[]): string; @@ -82,4 +82,4 @@ interface JQueryStatic { format(template: string, ...arguments: string[]): string; validator: Validator; -} \ No newline at end of file +} diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 06f19801d..37e03aa88 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -763,7 +763,7 @@ function test_children() { var $kids = $(e.target).children(); var len = $kids.addClass("hilite").length; - $("#results span:first").text(len.toString()); + $("#results span:first").text(len); //$("#results span:last").text(e.target.tagName); e.preventDefault(); @@ -887,6 +887,12 @@ function test_clone() { .clone()); } +function test_prependTo() { + $("

Test

").prependTo(".inner"); + $("h2").prependTo($(".container")); + $("span").prependTo("#foo"); +} + function test_closest() { $('li.item-a').closest('ul') .css('background-color', 'red'); @@ -1091,90 +1097,6 @@ function test_dblclick() { $('#target').dblclick(); } -function test_deferred() { - - function returnPromise(): JQueryPromise<(data: { MyString: string; MyNumber: number; }, textStatus: string, jqXHR: JQueryXHR) => any> { - return $.ajax("test.php"); - } - var x = returnPromise(); - x.done((data, textStatus, jqXHR) => { - var myNumber: number = data.MyNumber; - var myString: string = data.MyString; - var theTextStatus: string = textStatus; - var thejqXHR: JQueryXHR = jqXHR; - }); - - $.get("test.php").always(function () { - alert("$.get completed with success or error callback arguments"); - }); - $.get("test.php").done(function () { - alert("$.get succeeded"); - }); - function fn1() { - $("p").append(" 1 "); - } - function fn2() { - $("p").append(" 2 "); - } - function fn3(n) { - $("p").append(n + " 3 " + n); - } - var dfd = $.Deferred(); - dfd - .done([fn1, fn2], fn3, [fn2, fn1]) - .done(function (n) { - $("p").append(n + " we're done."); - }); - $("button").bind("click", function () { - dfd.resolve("and"); - }); - $.get("test.php") - .done(function () { alert("$.get succeeded"); }) - .fail(function () { alert("$.get failed!"); }); - dfd.state(); - var defer = $.Deferred(), - filtered = defer.pipe(function (value) { - return value * 2; - }); - defer.resolve(5); - filtered.done(function (value) { - alert("Value is ( 2*5 = ) 10: " + value); - }); - filtered.fail(function (value) { - alert("Value is ( 3*6 = ) 18: " + value); - }); - filtered.done(function (data) { }); - - function asyncEvent() { - var dfd: JQueryDeferred = $.Deferred(); - setTimeout(function () { - dfd.resolve("hurray"); - }, Math.floor(400 + Math.random() * 2000)); - setTimeout(function () { - dfd.reject("sorry"); - }, Math.floor(400 + Math.random() * 2000)); - setTimeout(function working() { - if (dfd.state() === "pending") { - dfd.notify("working... "); - setTimeout(null, 500); - } - }, 1); - return dfd.promise(); - } - var obj = { - hello: function (name) { - alert("Hello " + name); - } - }, - defer = $.Deferred(); - defer.promise(obj); - defer.resolve("John"); - $.get("test.php").then( - function () { alert("$.get succeeded"); }, - function () { alert("$.get failed!"); } - ); -} - function test_delay() { $('#foo').slideUp(300).delay(800).fadeIn(400); $("button").click(function () { @@ -1851,6 +1773,26 @@ function test_getScript() { }); } +function test_jQueryget() { + console.log($("li").get(0)); + console.log($("li")[0]); + console.log($("li").get(-1)); + $("*", document.body).click(function (event) { + event.stopPropagation(); + var domElement = $(this).get(0); + $("span:first").text("Clicked on - " + domElement.nodeName); + }); + + function display(divs) { + var a = []; + for (var i = 0; i < divs.length; i++) { + a.push(divs[i].innerHTML); + } + $("span").text(a.join(" ")); + } + display($("div").get().reverse()); +} + function test_globalEval() { jQuery.globalEval("var newVar = true;"); } @@ -2015,6 +1957,38 @@ function test_height() { }); } +function test_wrap() { + $(".inner").wrap("
"); + $(".inner").wrap(function () { + return "
"; + }); + $("span").wrap("

"); + $("p").wrap(document.createElement("div")); + $("p").wrap($(".doublediv")); +} + +function test_wrapAll() { + $(".inner").wrapAll("
"); + $("p").wrapAll("
"); + $("span").wrapAll("

"); + $("p").wrapAll(document.createElement("div")); + $("p").wrapAll($(".doublediv")); +} + +function test_wrapInner() { + $(".inner").wrapInner("
"); + $(".inner").wrapInner(function () { + return "
"; + }); + var elem: Element; + $(elem).wrapInner("
"); + $(elem).wrapInner("
"); + $("p").wrapInner(""); + $("body").wrapInner("

"); + $("p").wrapInner(document.createElement("b")); + $("p").wrapInner($("")); +} + function test_width() { // Returns width of browser viewport $(window).width(); @@ -2175,6 +2149,7 @@ function test_innerWidth() { var p = $("p:first"); $("p:last").text("innerWidth:" + p.innerWidth()); + p.innerWidth(123); p.innerWidth('123px'); } @@ -2213,6 +2188,37 @@ function test_scrollTop() { $("div.demo").scrollTop(300); } +function test_parent() { + $("*", document.body).each(function () { + var parentTag = $(this).parent().get(0).tagName; + $(this).prepend(document.createTextNode(parentTag + " > ")); + }); + $("p").parent(".selected").css("background", "yellow"); +} + +function test_parents() { + var parentEls = $("b").parents() + .map(function () { + return this.tagName; + }) + .get() + .join(", "); + $("b").append("" + parentEls + ""); + + function showParents() { + $("div").css("border-color", "white"); + var len = $("span.selected") + .parents("div") + .css("border", "2px red solid") + .length; + $("b").text("Unique div parents: " + len); + } + $("span").click(function () { + $(this).toggleClass("selected"); + showParents(); + }); +} + function test_param() { function test1() { @@ -2876,6 +2882,36 @@ function test_makeArray() { jQuery.isArray(arr) === true; } +function test_replaceAll() { + $("

New heading

").replaceAll(".inner"); + $(".first").replaceAll(".third"); + $("Paragraph. ").replaceAll("p"); +} + +function test_replaceWith() { + $("div.second").replaceWith("

New heading

"); + $("div.inner").replaceWith("

New heading

"); + $("div.third").replaceWith($(".first")); + + $("button").click(function () { + $(this).replaceWith("
" + $(this).text() + "
"); + }); + + $("p").replaceWith("Paragraph. "); + + $("p").click(function () { + $(this).replaceWith($("div")); + }); + + $("button").on("click", function () { + var $container = $("div.container").replaceWith(function () { + return $(this).contents(); + }); + + $("p").append($container.attr("class")); + }); +} + function test_map() { $(':checkbox').map(function () { return this.id; @@ -2884,16 +2920,25 @@ function test_map() { return $(this).val(); }).get().join(", ")); var mappedItems = $("li").map(function (index) { - var replacement = $("
  • ").text($(this).text()).get(0); - if (index == 0) { + var replacement:any = $("
  • ").text($(this).text()).get(0); + if (index === 0) { + + // Make the first item all caps $(replacement).text($(replacement).text().toUpperCase()); - } else if (index == 1 || index == 3) { + } else if (index === 1 || index === 3) { + + // Delete the second and fourth items replacement = null; - } else if (index == 2) { + } else if (index === 2) { + + // Make two of the third item and add some text replacement = [replacement, $("
  • ").get(0)]; $(replacement[0]).append(" - A"); $(replacement[1]).append("Extra - B"); } + + // Replacement will be a dom element, null, + // or an array of dom elements return replacement; }); $("#results").append(mappedItems); @@ -3071,6 +3116,22 @@ function test_parseHTML() { .appendTo( $log ); } +function test_not() { + $("li").not(":even").css("background-color", "red"); + + $("li").not(document.getElementById("notli")) + .css("background-color", "red"); + + $("div").not(".green, #blueone") + .css("border-color", "red"); + + $("p").not($("#selected")[0]); + + $("p").not("#selected"); + + $("p").not($("div p.selected")); +} + function test_EventIsNewable() { var ev = new jQuery.Event('click'); } @@ -3100,3 +3161,113 @@ $.ajax({ alert(data); } }); + +function test_deferred() { + + function returnPromise(): JQueryPromise<(data: { MyString: string; MyNumber: number; }, textStatus: string, jqXHR: JQueryXHR) => any> { + return $.ajax("test.php"); + } + var x = returnPromise(); + x.done((data, textStatus, jqXHR) => { + var myNumber: number = data.MyNumber; + var myString: string = data.MyString; + var theTextStatus: string = textStatus; + var thejqXHR: JQueryXHR = jqXHR; + }); + + $.get("test.php").always(function () { + alert("$.get completed with success or error callback arguments"); + }); + $.get("test.php").done(function () { + alert("$.get succeeded"); + }); + function fn1() { + $("p").append(" 1 "); + } + function fn2() { + $("p").append(" 2 "); + } + function fn3(n) { + $("p").append(n + " 3 " + n); + } + var dfd = $.Deferred(); + dfd + .done([fn1, fn2], fn3, [fn2, fn1]) + .done(function (n) { + $("p").append(n + " we're done."); + }); + $("button").bind("click", function () { + dfd.resolve("and"); + }); + $.get("test.php") + .done(function () { alert("$.get succeeded"); }) + .fail(function () { alert("$.get failed!"); }); + dfd.state(); + var defer = $.Deferred(), + filtered = defer.pipe(function (value) { + return value * 2; + }); + defer.resolve(5); + filtered.done(function (value) { + alert("Value is ( 2*5 = ) 10: " + value); + }); + filtered.fail(function (value) { + alert("Value is ( 3*6 = ) 18: " + value); + }); + filtered.done(function (data) { }); + + var obj = { + hello: function (name) { + alert("Hello " + name); + } + }, + defer = $.Deferred(); + defer.promise(obj); + defer.resolve("John"); + $.get("test.php").then( + function () { alert("$.get succeeded"); }, + function () { alert("$.get failed!"); } + ); +} + +function test_deferred_promise() { + + function asyncEvent() { + var dfd = $.Deferred(); + + // Resolve after a random interval + setTimeout(function () { + dfd.resolve("hurray"); + }, Math.floor(400 + Math.random() * 2000)); + + // Reject after a random interval + setTimeout(function () { + dfd.reject("sorry"); + }, Math.floor(400 + Math.random() * 2000)); + + // Show a "working..." message every half-second + setTimeout(function working() { + if (dfd.state() === "pending") { + dfd.notify("working... "); + setTimeout(working, 500); + } + }, 1); + + // Return the Promise so caller can't change the Deferred + return dfd.promise(); + } + + // Attach a done, fail, and progress handler for the asyncEvent + $.when(asyncEvent()).then( + function (status) { + alert(status + ", things are going well"); + }, + function (status) { + alert(status + ", you fail this time"); + }, + function (status) { + $("body").append(status); + } + ); +} + diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 958128e2c..558453ab3 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -253,79 +253,268 @@ interface JQueryCallback { remove(callbacks: Function[]): JQueryCallback; } -/* - Allows jQuery Promises to interop with non-jQuery promises -*/ +/** + * Allows jQuery Promises to interop with non-jQuery promises + */ interface JQueryGenericPromise { - then(onFulfill: (value: T) => U, onReject?: (reason: any) => U): JQueryGenericPromise; - then(onFulfill: (value: T) => JQueryGenericPromise, onReject?: (reason: any) => U): JQueryGenericPromise; - then(onFulfill: (value: T) => U, onReject?: (reason: any) => JQueryGenericPromise): JQueryGenericPromise; - then(onFulfill: (value: T) => JQueryGenericPromise, onReject?: (reason: any) => JQueryGenericPromise): JQueryGenericPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value: T) => U, failFilter?: (reason: any) => U): JQueryGenericPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value: T) => JQueryGenericPromise, failFilter?: (reason: any) => U): JQueryGenericPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value: T) => U, failFilter?: (reason: any) => JQueryGenericPromise): JQueryGenericPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value: T) => JQueryGenericPromise, failFilter?: (reason: any) => JQueryGenericPromise): JQueryGenericPromise; } -/* - Interface for the JQuery promise, part of callbacks -*/ +/** + * Interface for the JQuery promise, part of callbacks + */ interface JQueryPromise { - // Generic versions of callbacks - always(...alwaysCallbacks: T[]): JQueryPromise; - done(...doneCallbacks: T[]): JQueryPromise; - fail(...failCallbacks: T[]): JQueryPromise; - progress(...progressCallbacks: T[]): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallbacks1?: T, ...alwaysCallbacks2: T[]): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallbacks1?: T, ...doneCallbacks2: T[]): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallbacks1?: T, ...failCallbacks2: T[]): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(...progressCallbacks: T[]): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks A function, or array of functions, that is called when the Deferred is resolved or rejected. + */ always(...alwaysCallbacks: any[]): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks A function, or array of functions, that are called when the Deferred is resolved. + */ done(...doneCallbacks: any[]): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks A function, or array of functions, that are called when the Deferred is rejected. + */ fail(...failCallbacks: any[]): JQueryPromise; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ progress(...progressCallbacks: any[]): JQueryPromise; // Deprecated - given no typings pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; - then(onFulfill: (value: T) => U, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise; - then(onFulfill: (value: T) => JQueryGenericPromise, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise; - then(onFulfill: (value: T) => U, onReject?: (...reasons: any[]) => JQueryGenericPromise, onProgress?: (...progression: any[]) => any): JQueryPromise; - then(onFulfill: (value: T) => JQueryGenericPromise, onReject?: (...reasons: any[]) => JQueryGenericPromise, onProgress?: (...progression: any[]) => any): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + */ + then(doneFilter: (value: T) => U, failFilter?: (...reasons: any[]) => U, progressFilter?: (...progression: any[]) => any): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + */ + then(doneFilter: (value: T) => JQueryGenericPromise, failFilter?: (...reasons: any[]) => U, progressFilter?: (...progression: any[]) => any): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + */ + then(doneFilter: (value: T) => U, failFilter?: (...reasons: any[]) => JQueryGenericPromise, progressFilter?: (...progression: any[]) => any): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + */ + then(doneFilter: (value: T) => JQueryGenericPromise, failFilter?: (...reasons: any[]) => JQueryGenericPromise, progressFilter?: (...progression: any[]) => any): JQueryPromise; // Because JQuery Promises Suck - then(onFulfill: (...values: any[]) => U, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise; - then(onFulfill: (...values: any[]) => JQueryGenericPromise, onReject?: (...reasons: any[]) => U, onProgress?: (...progression: any[]) => any): JQueryPromise; - then(onFulfill: (...values: any[]) => U, onReject?: (...reasons: any[]) => JQueryGenericPromise, onProgress?: (...progression: any[]) => any): JQueryPromise; - then(onFulfill: (...values: any[]) => JQueryGenericPromise, onReject?: (...reasons: any[]) => JQueryGenericPromise, onProgress?: (...progression: any[]) => any): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + */ + then(doneFilter: (...values: any[]) => U, failFilter?: (...reasons: any[]) => U, progressFilter?: (...progression: any[]) => any): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + */ + then(doneFilter: (...values: any[]) => JQueryGenericPromise, failFilter?: (...reasons: any[]) => U, progressFilter?: (...progression: any[]) => any): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + */ + then(doneFilter: (...values: any[]) => U, failFilter?: (...reasons: any[]) => JQueryGenericPromise, progressFilter?: (...progression: any[]) => any): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + */ + then(doneFilter: (...values: any[]) => JQueryGenericPromise, failFilter?: (...reasons: any[]) => JQueryGenericPromise, progressFilter?: (...progression: any[]) => any): JQueryPromise; } -/* - Interface for the JQuery deferred, part of callbacks -*/ +/** + * Interface for the JQuery deferred, part of callbacks + */ interface JQueryDeferred extends JQueryPromise { - // Generic versions of callbacks - always(...alwaysCallbacks: T[]): JQueryDeferred; - done(...doneCallbacks: T[]): JQueryDeferred; - fail(...failCallbacks: T[]): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallbacks1?: T, ...alwaysCallbacks2: T[]): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallbacks1?: T, ...doneCallbacks2: T[]): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallbacks1?: T, ...failCallbacks2: T[]): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ progress(...progressCallbacks: T[]): JQueryDeferred; - always(...alwaysCallbacks: any[]): JQueryDeferred; - done(...doneCallbacks: any[]): JQueryDeferred; - fail(...failCallbacks: any[]): JQueryDeferred; - progress(...progressCallbacks: any[]): JQueryDeferred; - + /** + * Call the progressCallbacks on a Deferred object with the given args. + * + * @param args Optional arguments that are passed to the progressCallbacks. + */ notify(...args: any[]): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given context and args. + * + * @param context Context passed to the progressCallbacks as the this object. + * @param args Optional arguments that are passed to the progressCallbacks. + */ notifyWith(context: any, ...args: any[]): JQueryDeferred; + /** + * Reject a Deferred object and call any failCallbacks with the given args. + * + * @param args Optional arguments that are passed to the failCallbacks. + */ reject(...args: any[]): JQueryDeferred; + /** + * Reject a Deferred object and call any failCallbacks with the given context and args. + * + * @param context Context passed to the failCallbacks as the this object. + * @param args An optional array of arguments that are passed to the failCallbacks. + */ rejectWith(context: any, ...args: any[]): JQueryDeferred; - resolve(val: T): JQueryDeferred; - resolve(...args: any[]): JQueryDeferred; + /** + * Resolve a Deferred object and call any doneCallbacks with the given args. + * + * @param value First argument passed to doneCallbacks. + * @param args Optional subsequent arguments that are passed to the doneCallbacks. + */ + resolve(value: T, ...args: any[]): JQueryDeferred; + + // COMMENTED OUT AS MAKES resolve LESS USEFUL - PERHAPS REMOVE ENTIRELY LATER + /** + * Resolve a Deferred object and call any doneCallbacks with the given args. + * + * @param args Optional arguments that are passed to the doneCallbacks. + */ + //resolve(...args: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given context and args. + * + * @param context Context passed to the doneCallbacks as the this object. + * @param args An optional array of arguments that are passed to the doneCallbacks. + */ resolveWith(context: any, ...args: any[]): JQueryDeferred; + /** + * Determine the current state of a Deferred object. + */ state(): string; + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + */ promise(target?: any): JQueryPromise; } -/* - Interface of the JQuery extension of the W3C event object -*/ - +/** + * Interface of the JQuery extension of the W3C event object + */ interface BaseJQueryEventObject extends Event { data: any; delegateTarget: Element; @@ -1431,7 +1620,7 @@ interface JQuery { * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). */ innerHeight(height: string): JQuery; - + /** * Get the current computed width for the first element in the set of matched elements, including padding but not border. */ @@ -1450,7 +1639,7 @@ interface JQuery { * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). */ innerWidth(width: string): JQuery; - + /** * Get the current coordinates of the first element in the set of matched elements, relative to the document. */ @@ -1475,12 +1664,12 @@ interface JQuery { */ outerHeight(includeMargin?: boolean): number; - /** - * Sets the outer height on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerHeight(height: number): JQuery; + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: number): JQuery; /** * Sets the outer height on elements in the set of matched elements, including padding and border. @@ -1488,7 +1677,7 @@ interface JQuery { * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). */ outerHeight(height: string): JQuery; - + /** * Get the current computed width for the first element in the set of matched elements, including padding and border. * @@ -2875,44 +3064,373 @@ interface JQuery { */ appendTo(target: string): JQuery; - before(...content: any[]): JQuery; - before(func: (index: any) => any): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: JQuery, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: any[], ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: Element, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: Text, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + before(func: (index: number) => any): JQuery; + /** + * Create a deep copy of the set of matched elements. + * + * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. + * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). + */ clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; - detach(selector?: any): JQuery; + /** + * Remove the set of matched elements from the DOM. + * + * param selector A selector expression that filters the set of matched elements to be removed. + */ + detach(selector?: string): JQuery; + /** + * Remove all child nodes of the set of matched elements from the DOM. + */ empty(): JQuery; - insertAfter(target: any): JQuery; - insertBefore(target: any): JQuery; + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: JQuery): JQuery; + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: any[]): JQuery; + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: Element): JQuery; + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: Text): JQuery; + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: string): JQuery; - prepend(...content: any[]): JQuery; - prepend(func: (index: any, html: any) => any): JQuery; + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: JQuery): JQuery; + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: any[]): JQuery; + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: Element): JQuery; + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: Text): JQuery; + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: string): JQuery; - prependTo(target: any): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: JQuery, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: any[], ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: Element, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: Text, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + prepend(func: (index: number, html: string) => any): JQuery; - remove(selector?: any): JQuery; + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: JQuery): JQuery; + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: any[]): JQuery; + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: Element): JQuery; + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: string): JQuery; - replaceAll(target: any): JQuery; + /** + * Remove the set of matched elements from the DOM. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + */ + remove(selector?: string): JQuery; - replaceWith(func: any): JQuery; + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: JQuery): JQuery; + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: any[]): JQuery; + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: Element): JQuery; + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: string): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: JQuery): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: any[]): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: Element): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: Text): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: string): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param func A function that returns content with which to replace the set of matched elements. + */ + replaceWith(func: () => any): JQuery; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + */ text(): string; - text(textString: any): JQuery; - text(textString: (index: number, text: string) => string): JQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. + */ + text(text: string): JQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. + */ + text(text: number): JQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. + */ + text(text: boolean): JQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. + */ + text(func: (index: number, text: string) => string): JQuery; + /** + * Retrieve all the elements contained in the jQuery set, as an array. + */ toArray(): any[]; + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + */ unwrap(): JQuery; - wrap(wrappingElement: any): JQuery; - wrap(func: (index: any) => any): JQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: JQuery): JQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: Element): JQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: string): JQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrap(func: (index: number) => any): JQuery; - wrapAll(wrappingElement: any): JQuery; + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: JQuery): JQuery; + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: Element): JQuery; + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: string): JQuery; - wrapInner(wrappingElement: any): JQuery; - wrapInner(func: (index: any) => any): JQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: JQuery): JQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: Element): JQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: string): JQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrapInner(func: (index: number) => any): JQuery; /** * Iterate over a jQuery object, executing a function for each matched element. @@ -2921,101 +3439,421 @@ interface JQuery { */ each(func: (index: number, elem: Element) => any): JQuery; - get(index?: number): any; + /** + * Retrieve one of the elements matched by the jQuery object. + * + * @param index A zero-based integer indicating which element to retrieve. + */ + get(index: number): HTMLElement; + /** + * Retrieve the elements matched by the jQuery object. + */ + get(): any[]; + /** + * Search for a given element from among the matched elements. + */ index(): number; + /** + * Search for a given element from among the matched elements. + * + * @param selector A selector representing a jQuery collection in which to look for an element. + */ index(selector: string): number; - index(element: any): number; + /** + * Search for a given element from among the matched elements. + * + * @param element The DOM element or first element within the jQuery object to look for. + */ + index(element: JQuery): number; + /** + * Search for a given element from among the matched elements. + * + * @param element The DOM element or first element within the jQuery object to look for. + */ + index(element: Element): number; - // Properties + /** + * The number of elements in the jQuery object. + */ length: number; + /** + * A selector representing selector passed to jQuery(), if any, when creating the original set. + * version deprecated: 1.7, removed: 1.9 + */ selector: string; - [x: string]: any; - [x: number]: HTMLElement; + [index: string]: any; + [index: number]: HTMLElement; - // Traversing - add(selector: string, context?: any): JQuery; - add(...elements: any[]): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. + * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. + */ + add(selector: string, context?: Element): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param elements One or more elements to add to the set of matched elements. + */ + add(...elements: Element[]): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param html An HTML fragment to add to the set of matched elements. + */ add(html: string): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param obj An existing jQuery object to add to the set of matched elements. + */ add(obj: JQuery): JQuery; - children(selector?: any): JQuery; + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + children(selector?: string): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + */ closest(selector: string): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ closest(selector: string, context?: Element): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param obj A jQuery object to match elements against. + */ closest(obj: JQuery): JQuery; - closest(element: any): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param element An element to match elements against. + */ + closest(element: Element): JQuery; + + /** + * Get an array of all the elements and selectors matched against the current element up through the DOM tree. + * + * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ closest(selectors: any, context?: Element): any[]; + /** + * Get the children of each element in the set of matched elements, including text and comment nodes. + */ contents(): JQuery; + /** + * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. + */ end(): JQuery; + /** + * Reduce the set of matched elements to the one at the specified index. + * + * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. + * + */ eq(index: number): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param selector A string containing a selector expression to match the current set of elements against. + */ filter(selector: string): JQuery; - filter(func: (index: any) => any): JQuery; - filter(element: any): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + filter(func: (index: number) => any): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param element An element to match the current set of elements against. + */ + filter(element: Element): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ filter(obj: JQuery): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param selector A string containing a selector expression to match elements against. + */ find(selector: string): JQuery; - find(element: any): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param element An element to match elements against. + */ + find(element: Element): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param obj A jQuery object to match elements against. + */ find(obj: JQuery): JQuery; + /** + * Reduce the set of matched elements to the first in the set. + */ first(): JQuery; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + */ has(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + */ has(contained: Element): JQuery; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + */ is(selector: string): boolean; - is(func: (index: any) => any): boolean; - is(element: any): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. + */ + is(func: (index: number) => any): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ is(obj: JQuery): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + */ + is(elements: any): boolean; + /** + * Reduce the set of matched elements to the final one in the set. + */ last(): JQuery; - map(callback: (index: any, domElement: Element) => any): JQuery; + /** + * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. + * + * @param callback A function object that will be invoked for each element in the current set. + */ + map(callback: (index: number, domElement: Element) => any): JQuery; + /** + * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. + * + * @param selector A string containing a selector expression to match elements against. + */ next(selector?: string): JQuery; + /** + * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ nextAll(selector?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ nextUntil(selector?: string, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ nextUntil(element?: Element, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ nextUntil(obj?: JQuery, filter?: string): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param selector A string containing a selector expression to match elements against. + */ not(selector: string): JQuery; - not(func: (index: any) => any): JQuery; - not(element: any): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + not(func: (index: number) => any): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param elements One or more DOM elements to remove from the matched set. + */ + not(...elements: Element[]): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ not(obj: JQuery): JQuery; + /** + * Get the closest ancestor element that is positioned. + */ offsetParent(): JQuery; + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ parent(selector?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ parents(selector?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ parentsUntil(selector?: string, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ parentsUntil(element?: Element, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ parentsUntil(obj?: JQuery, filter?: string): JQuery; + /** + * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ prev(selector?: string): JQuery; + /** + * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ prevAll(selector?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ prevUntil(selector?: string, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ prevUntil(element?: Element, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ prevUntil(obj?: JQuery, filter?: string): JQuery; + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ siblings(selector?: string): JQuery; + /** + * Reduce the set of matched elements to a subset specified by a range of indices. + * + * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. + * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. + */ slice(start: number, end?: number): JQuery; - // Utilities - + /** + * Show the queue of functions to be executed on the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ queue(queueName?: string): any[]; - queue(queueName: string, newQueueOrCallback: any): JQuery; - queue(newQueueOrCallback: any): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(callback: Function): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(queueName: string, callback: Function): JQuery; } declare module "jquery" { export = $; diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 41cc3214d..52d7d6d6a 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -976,6 +976,7 @@ interface JQuery { sortable(methodName: 'disable'): void; sortable(methodName: 'enable'): void; sortable(methodName: 'widget'): JQuery; + sortable(methodName: 'toArray'): string[]; sortable(methodName: string): JQuery; sortable(options: JQueryUI.SortableOptions): JQuery; sortable(optionLiteral: string, optionName: string): any; diff --git a/jwplayer/jwplayer.d.ts b/jwplayer/jwplayer.d.ts index be4ab4fd3..92377b309 100644 --- a/jwplayer/jwplayer.d.ts +++ b/jwplayer/jwplayer.d.ts @@ -17,6 +17,7 @@ interface JWPlayer { getFullscreen(): boolean; getMute(): boolean; getPlaylist(): any[]; + getPlaylistIndex(): number; getPlaylistItem(index: number): any; getPosition(): number; getQualityLevels(): any[]; diff --git a/knockout.mapping/knockout.mapping.d.ts b/knockout.mapping/knockout.mapping.d.ts index 2213d87c3..cc116096d 100644 --- a/knockout.mapping/knockout.mapping.d.ts +++ b/knockout.mapping/knockout.mapping.d.ts @@ -46,3 +46,7 @@ interface KnockoutMapping { interface KnockoutStatic { mapping: KnockoutMapping; } + +declare module "knockout.mapping" { + export = KnockoutMapping; +} diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index b41846ca5..66ebe2719 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -310,7 +310,7 @@ interface KnockoutUtils { parseJson(jsonString: string): any; - stringifyJson(data: any, replacer: Function, space: string): string; + stringifyJson(data: any, replacer?: Function, space?: string): string; postJson(urlOrForm: any, data: any, options: any): void; diff --git a/lazy.js/lazy.js-tests.ts b/lazy.js/lazy.js-tests.ts index 356ee177b..7689bcaf7 100644 --- a/lazy.js/lazy.js-tests.ts +++ b/lazy.js/lazy.js-tests.ts @@ -1,9 +1,33 @@ /// -var sequence: LazyJS.Sequence; -var arraySeq: LazyJS.ArrayLikeSequence; -var objectSeq: LazyJS.ObjectLikeSequence; -var asyncSeq: LazyJS.AsyncSequence; +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +interface Foo { + foo(): string; +} +interface Bar { + bar(): string; +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var foo: Foo; +var bar: Bar; + +var fooArr: Foo[]; +var barArr: Bar[]; + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +var fooSequence: LazyJS.Sequence; +var barSequence: LazyJS.Sequence; +var fooArraySeq: LazyJS.ArrayLikeSequence; +var barArraySeq: LazyJS.ArrayLikeSequence; +var fooObjectSeq: LazyJS.ObjectLikeSequence; +var anyObjectSeq: LazyJS.ObjectLikeSequence; +var fooAsyncSeq: LazyJS.AsyncSequence; + +var strSequence: LazyJS.Sequence; var stringSeq: LazyJS.StringLikeSequence; var obj: Object; @@ -23,141 +47,142 @@ function fnErrorCallback(error: any): void { } -function fnValueCallback(value: any): void { +function fnValueCallback(value: Foo): void { } -function fnGetKeyCallback(value: any): string { - return ''; +function fnGetKeyCallback(value: Foo): string { + return str; } -function fnTestCallback(value: any): boolean { - return false; +function fnTestCallback(value: Foo): boolean { + return bool; } -function fnMapCallback(value: any): any { - return null; +function fnMapCallback(value: Foo): Bar { + return bar; } function fnMapStringCallback(value: string): string { - return ''; + return str; } -function fnNumberCallback(value: any): number { - return 0; +function fnNumberCallback(value: Foo): number { + return num; } -function fnMemoCallback(memo: any, value: any): any { - return null; +function fnMemoCallback(memo: Bar, value: Foo): Bar { + return bar; } -function fnGeneratorCallback(index: number): any { - return null; +function fnGeneratorCallback(index: number): Foo { + return foo; } // Lazy -arraySeq = Lazy([]); -objectSeq = Lazy({}); -stringSeq = Lazy(''); +fooArraySeq = Lazy(fooArr); +fooObjectSeq = Lazy({a:foo, b:foo}); +anyObjectSeq = Lazy({a:num, b:str}); +stringSeq = Lazy(str); // Strict var Strict = Lazy.strict(); -arraySeq = Strict([1, 2, num]).pop(); +fooArraySeq = Strict([foo, foo]).pop(); // Sequence -asyncSeq = sequence.async(num); -sequence = sequence.chunk(num); -sequence = sequence.compact(); -sequence = sequence.concat(arr); -sequence = sequence.consecutive(num); -bool = sequence.contains(x); -sequence = sequence.countBy(str); -sequence = sequence.countBy(fnGetKeyCallback); -sequence = sequence.dropWhile(fnTestCallback); -sequence = sequence.each(fnValueCallback); -bool = sequence.every(fnTestCallback); -sequence = sequence.filter(fnTestCallback); -sequence = sequence.find(fnTestCallback); -sequence = sequence.findWhere(obj); +fooAsyncSeq = fooSequence.async(num); +fooSequence = fooSequence.chunk(num); +fooSequence = fooSequence.compact(); +fooSequence = fooSequence.concat(arr); +fooSequence = fooSequence.consecutive(num); +bool = fooSequence.contains(foo); +fooSequence = fooSequence.countBy(str); +fooObjectSeq = fooSequence.countBy(fnGetKeyCallback); +fooSequence = fooSequence.dropWhile(fnTestCallback); +fooSequence = fooSequence.each(fnValueCallback); +bool = fooSequence.every(fnTestCallback); +fooSequence = fooSequence.filter(fnTestCallback); +fooSequence = fooSequence.find(fnTestCallback); +fooSequence = fooSequence.findWhere(obj); -x = sequence.first(); -sequence = sequence.first(num); +x = fooSequence.first(); +fooSequence = fooSequence.first(num); -sequence = sequence.flatten(); -objectSeq = sequence.groupBy(fnGetKeyCallback); -sequence = sequence.indexOf(x); -sequence = sequence.initial(); -sequence = sequence.initial(num); -sequence = sequence.intersection(arr); -sequence = sequence.invoke(str); -bool = sequence.isEmpty(); -str = sequence.join(); -str = sequence.join(str); +fooSequence = fooSequence.flatten(); +fooObjectSeq = fooSequence.groupBy(fnGetKeyCallback); +fooSequence = fooSequence.indexOf(x); +fooSequence = fooSequence.initial(); +fooSequence = fooSequence.initial(num); +fooSequence = fooSequence.intersection(arr); +fooSequence = fooSequence.invoke(str); +bool = fooSequence.isEmpty(); +str = fooSequence.join(); +str = fooSequence.join(str); -x = sequence.last(); -sequence = sequence.last(num); +foo = fooSequence.last(); +fooSequence = fooSequence.last(num); -sequence = sequence.lastIndexOf(x); -sequence = sequence.map(fnMapCallback); -x = sequence.max(); -x = sequence.max(fnNumberCallback); -x = sequence.min(); -x = sequence.min(fnNumberCallback); -sequence = sequence.pluck(str); -x = sequence.reduce(fnMemoCallback); -x = sequence.reduce(fnMemoCallback, x); -x = sequence.reduceRight(fnMemoCallback, x); -sequence = sequence.reject(fnTestCallback); -sequence = sequence.rest(num); -sequence = sequence.reverse(); -sequence = sequence.shuffle(); -bool = sequence.some(); -bool = sequence.some(fnTestCallback); -sequence = sequence.sortBy(fnNumberCallback); -sequence = sequence.sortedIndex(x); -sequence = sequence.sum(); -sequence = sequence.sum(fnNumberCallback); -sequence = sequence.takeWhile(fnTestCallback); -sequence = sequence.union(arr); -sequence = sequence.uniq(); -sequence = sequence.where(obj); -sequence = sequence.without(arr); -sequence = sequence.zip(arr); +fooSequence = fooSequence.lastIndexOf(foo); +barSequence = fooSequence.map(fnMapCallback); +foo = fooSequence.max(); +foo = fooSequence.max(fnNumberCallback); +foo = fooSequence.min(); +foo = fooSequence.min(fnNumberCallback); +fooSequence = fooSequence.pluck(str); +bar = fooSequence.reduce(fnMemoCallback); +bar = fooSequence.reduce(fnMemoCallback, bar); +bar = fooSequence.reduceRight(fnMemoCallback, bar); +fooSequence = fooSequence.reject(fnTestCallback); +fooSequence = fooSequence.rest(num); +fooSequence = fooSequence.reverse(); +fooSequence = fooSequence.shuffle(); +bool = fooSequence.some(); +bool = fooSequence.some(fnTestCallback); +fooSequence = fooSequence.sortBy(fnNumberCallback); +fooSequence = fooSequence.sortedIndex(foo); +fooSequence = fooSequence.sum(); +fooSequence = fooSequence.sum(fnNumberCallback); +fooSequence = fooSequence.takeWhile(fnTestCallback); +fooSequence = fooSequence.union(fooArr); +fooSequence = fooSequence.uniq(); +fooSequence = fooSequence.where(obj); +fooSequence = fooSequence.without(fooArr); +fooSequence = fooSequence.zip(arr); -arr = sequence.toArray(); -obj = sequence.toObject(); +fooArr = fooSequence.toArray(); +obj = fooSequence.toObject(); // ArrayLikeSequence -arraySeq = arraySeq.concat(); -arraySeq = arraySeq.first(); -arraySeq = arraySeq.first(num); -x = arraySeq.get(num); -num = arraySeq.length(); -arraySeq = arraySeq.map(fnMapCallback); -arraySeq = arraySeq.pop(); -arraySeq = arraySeq.rest(); -arraySeq = arraySeq.rest(num); -arraySeq = arraySeq.reverse(); -arraySeq = arraySeq.shift(); -arraySeq = arraySeq.slice(num); -arraySeq = arraySeq.slice(num, num); +fooArraySeq = fooArraySeq.concat(); +fooArraySeq = fooArraySeq.first(); +fooArraySeq = fooArraySeq.first(num); +foo = fooArraySeq.get(num); +num = fooArraySeq.length(); +barArraySeq = fooArraySeq.map(fnMapCallback); +fooArraySeq = fooArraySeq.pop(); +fooArraySeq = fooArraySeq.rest(); +fooArraySeq = fooArraySeq.rest(num); +fooArraySeq = fooArraySeq.reverse(); +fooArraySeq = fooArraySeq.shift(); +fooArraySeq = fooArraySeq.slice(num); +fooArraySeq = fooArraySeq.slice(num, num); // ObjectLikeSequence -objectSeq = objectSeq.defaults(obj); -sequence = objectSeq.functions(); -objectSeq = objectSeq.get(str); -objectSeq = objectSeq.invert(); -sequence = objectSeq.keys(); -objectSeq = objectSeq.omit(strArr); -sequence = objectSeq.pairs(); -objectSeq = objectSeq.pick(strArr); -arr = objectSeq.toArray(); -obj = objectSeq.toObject(); -sequence = objectSeq.values(); +fooObjectSeq = fooObjectSeq.defaults(obj); +fooSequence = fooObjectSeq.functions(); +fooObjectSeq = fooObjectSeq.get(str); +fooObjectSeq = fooObjectSeq.invert(); +strSequence = fooObjectSeq.keys(); +fooObjectSeq = fooObjectSeq.omit(strArr); +fooSequence = fooObjectSeq.pairs(); +fooObjectSeq = fooObjectSeq.pick(strArr); +arr = fooObjectSeq.toArray(); +obj = fooObjectSeq.toObject(); +fooSequence = fooObjectSeq.values(); // StringLikeSequence @@ -181,8 +206,8 @@ stringSeq = stringSeq.mapString(fnMapStringCallback); stringSeq = stringSeq.match(exp); stringSeq = stringSeq.reverse(); -sequence = stringSeq.split(str); -sequence = stringSeq.split(exp); +stringSeq = stringSeq.split(str); +stringSeq = stringSeq.split(exp); bool = stringSeq.startsWith(str); stringSeq = stringSeq.substring(num); diff --git a/lazy.js/lazy.js.d.ts b/lazy.js/lazy.js.d.ts index 47925bdf9..ca19aed98 100644 --- a/lazy.js/lazy.js.d.ts +++ b/lazy.js/lazy.js.d.ts @@ -6,28 +6,31 @@ declare module LazyJS { interface LazyStatic { - (value:string):StringLikeSequence; - (value:any[]):ArrayLikeSequence; - (value:Object):ObjectLikeSequence; - (value:ArrayLike):ArrayLikeSequence; + + (value: string):StringLikeSequence; + (value: T[]):ArrayLikeSequence; + (value: any[]):ArrayLikeSequence; + (value: Object):ObjectLikeSequence; + (value: Object):ObjectLikeSequence; strict():LazyStatic; - generate(generatorFn:GeneratorCallback, length?:number):GeneratedSequence; + generate(generatorFn: GeneratorCallback, length?: number):GeneratedSequence; - range(to:number):GeneratedSequence; - range(from:number, to:number, step?:number):GeneratedSequence; + range(to: number):GeneratedSequence; + range(from: number, to: number, step?: number):GeneratedSequence; - repeat(value:any, count?:number):GeneratedSequence; + repeat(value: T, count?: number):GeneratedSequence; - on(eventType:string):Sequence; + on(eventType: string):Sequence; - readFile(path:string):StringLikeSequence; - makeHttpRequest(path:string):StringLikeSequence; + readFile(path: string):StringLikeSequence; + makeHttpRequest(path: string):StringLikeSequence; } - interface ArrayLike { + interface ArrayLike { length:number; + [index:number]:T; } interface Callback { @@ -35,212 +38,213 @@ declare module LazyJS { } interface ErrorCallback { - (error:any):void; + (error: any):void; } - interface ValueCallback { - (value:any):void; + interface ValueCallback { + (value: T):void; } - interface GetKeyCallback { - (value:any):string; + interface GetKeyCallback { + (value: T):string; } - interface TestCallback { - (value:any):boolean; + interface TestCallback { + (value: T):boolean; } - interface MapCallback { - (value:any):any; + interface MapCallback { + (value: T):U; } interface MapStringCallback { - (value:string):string; + (value: string):string; } - interface NumberCallback { - (value:any):number; + interface NumberCallback { + (value: T):number; } - interface MemoCallback { - (memo:any, value:any):any; + interface MemoCallback { + (memo: U, value: T):U; } - interface GeneratorCallback { - (index:number):any; + interface GeneratorCallback { + (index: number):T; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - interface Iterator { - new(sequence:Sequence):Iterator; - current():any; + interface Iterator { + new (sequence: Sequence):Iterator; + current():T; moveNext():boolean; } - interface GeneratedSequence extends Sequence { - new(generatorFn:GeneratorCallback, length:number):GeneratedSequence; + interface GeneratedSequence extends Sequence { + new(generatorFn: GeneratorCallback, length: number):GeneratedSequence; length():number; } - interface AsyncSequence extends SequenceBase { - each(callback:ValueCallback):AsyncHandle; + interface AsyncSequence extends SequenceBase { + each(callback: ValueCallback):AsyncHandle; } - interface AsyncHandle { + interface AsyncHandle { cancel():void; - onComplete(callback:Callback):void; - onError(callback:ErrorCallback):void; + onComplete(callback: Callback):void; + onError(callback: ErrorCallback):void; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - module Sequence { - function define(methodName:string[], overrides:Object):Function; + function define(methodName: string[], overrides: Object): Function; } - interface Sequence extends SequenceBase { - each(eachFn:ValueCallback):Sequence; + interface Sequence extends SequenceBase { + each(eachFn: ValueCallback):Sequence; } - interface SequenceBase extends SequenceBaser { + interface SequenceBase extends SequenceBaser { first():any; - first(count:number):Sequence; - indexOf(value:any, startIndex?:number):Sequence; + first(count: number):Sequence; + indexOf(value: any, startIndex?: number):Sequence; last():any; - last(count:number):Sequence; - lastIndexOf(value:any):Sequence; + last(count: number):Sequence; + lastIndexOf(value: any):Sequence; - reverse():Sequence; + reverse():Sequence; } - interface SequenceBaser { + interface SequenceBaser { // TODO improve define() (needs ugly overload) - async(interval:number):AsyncSequence; - chunk(size:number):Sequence; - compact():Sequence; - concat(var_args:any[]):Sequence; - consecutive(length:number):Sequence; - contains(value:any):boolean; - countBy(propertyName:string):Sequence; - countBy(keyFn:GetKeyCallback):Sequence; - dropWhile(predicateFn:TestCallback):Sequence; - every(predicateFn:TestCallback):boolean; - filter(predicateFn:TestCallback):Sequence; - find(predicateFn:TestCallback):Sequence; - findWhere(properties:Object):Sequence; + async(interval: number):AsyncSequence; + chunk(size: number):Sequence; + compact():Sequence; + concat(var_args: T[]):Sequence; + consecutive(length: number):Sequence; + contains(value: T):boolean; + countBy(keyFn: GetKeyCallback): ObjectLikeSequence; + countBy(propertyName: string): ObjectLikeSequence; + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): Sequence; + findWhere(properties: Object): Sequence; - flatten():Sequence; - groupBy(keyFn:GetKeyCallback):ObjectLikeSequence; - initial(count?:number):Sequence; - intersection(var_args:any[]):Sequence; - invoke(methodName:string):Sequence; - isEmpty():boolean; - join(delimiter?:string):string; - map(mapFn:MapCallback):Sequence; - max(valueFn?:NumberCallback):any; - min(valueFn?:NumberCallback):any; - pluck(propertyName:string):Sequence; - reduce(aggregatorFn:MemoCallback, memo?:any):any; - reduceRight(aggregatorFn:MemoCallback, memo:any):any; - reject(predicateFn:TestCallback):Sequence; - rest(count?:number):Sequence; - shuffle():Sequence; - some(predicateFn?:TestCallback):boolean; - sortBy(sortFn:NumberCallback):Sequence; - sortedIndex(value:any):Sequence; - sum(valueFn?:NumberCallback):Sequence; - takeWhile(predicateFn:TestCallback):Sequence; - union(var_args:any[]):Sequence; - uniq():Sequence; - where(properties:Object):Sequence; - without(var_args:any[]):Sequence; - zip(var_args:any[]):Sequence; + flatten(): Sequence; + groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; + initial(count?: number): Sequence; + intersection(var_args: T[]): Sequence; + invoke(methodName: string): Sequence; + isEmpty(): boolean; + join(delimiter?: string): string; + map(mapFn: MapCallback): Sequence; - toArray():any[]; - toObject():Object; + max(valueFn?: NumberCallback): T; + min(valueFn?: NumberCallback): T; + pluck(propertyName: string): Sequence; + reduce(aggregatorFn: MemoCallback, memo?: U): U; + reduceRight(aggregatorFn: MemoCallback, memo: U): U; + reject(predicateFn: TestCallback): Sequence; + rest(count?: number): Sequence; + shuffle(): Sequence; + some(predicateFn?: TestCallback): boolean; + sortBy(sortFn: NumberCallback): Sequence; + sortedIndex(value: T): Sequence; + sum(valueFn?: NumberCallback): Sequence; + takeWhile(predicateFn: TestCallback): Sequence; + union(var_args: T[]): Sequence; + uniq(): Sequence; + where(properties: Object): Sequence; + without(var_args: T[]): Sequence; + zip(var_args: T[]): Sequence; + + toArray(): T[]; + toObject(): Object; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - module ArrayLikeSequence { - function define(methodName:string[], overrides:Object):Function; + function define(methodName: string[], overrides: Object): Function; } - interface ArrayLikeSequence extends Sequence { + interface ArrayLikeSequence extends Sequence { // define()X; - concat():ArrayLikeSequence; - first(count?:number):ArrayLikeSequence; - get(index:number):any; - length():number; - map(mapFn:MapCallback):ArrayLikeSequence; - pop():ArrayLikeSequence; - rest(count?:number):ArrayLikeSequence; - reverse():ArrayLikeSequence; - shift():ArrayLikeSequence; - slice(begin:number, end?:number):ArrayLikeSequence; + concat(): ArrayLikeSequence; + first(count?: number): ArrayLikeSequence; + get(index: number): T; + length(): number; + map(mapFn: MapCallback): ArrayLikeSequence; + pop(): ArrayLikeSequence; + rest(count?: number): ArrayLikeSequence; + reverse(): ArrayLikeSequence; + shift(): ArrayLikeSequence; + slice(begin: number, end?: number): ArrayLikeSequence; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - module ObjectLikeSequence { - function define(methodName:string[], overrides:Object):Function; + function define(methodName: string[], overrides: Object): Function; } - interface ObjectLikeSequence extends Sequence { - assign(other:Object):ObjectLikeSequence; + interface ObjectLikeSequence extends Sequence { + assign(other: Object): ObjectLikeSequence; // throws error - //async():X; - defaults(defaults:Object):ObjectLikeSequence; - functions():Sequence; - get(property:string):ObjectLikeSequence; - invert():ObjectLikeSequence; - keys():Sequence; - omit(properties:string[]):ObjectLikeSequence; - pairs():Sequence; - pick(properties:string[]):ObjectLikeSequence; - toArray():any[]; - toObject():Object; - values():Sequence; + //async(): X; + defaults(defaults: Object): ObjectLikeSequence; + functions(): Sequence; + get(property: string): ObjectLikeSequence; + invert(): ObjectLikeSequence; + keys(): Sequence; + omit(properties: string[]): ObjectLikeSequence; + pairs(): Sequence; + pick(properties: string[]): ObjectLikeSequence; + toArray(): T[]; + toObject(): Object; + values(): Sequence; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - module StringLikeSequence { - function define(methodName:string[], overrides:Object):Function; + function define(methodName: string[], overrides: Object): Function; } - interface StringLikeSequence extends SequenceBaser { - charAt(index:number):string; - charCodeAt(index:number):number; - contains(value:string):boolean; - endsWith(suffix:string):boolean; + interface StringLikeSequence extends SequenceBaser { + charAt(index: number): string; + charCodeAt(index: number): number; + contains(value: string): boolean; + endsWith(suffix: string): boolean; - first():string; - first(count:number):StringLikeSequence; + first(): string; + first(count: number): StringLikeSequence; - indexOf(substring:string, startIndex?:number):number; + indexOf(substring: string, startIndex?: number): number; - last():string; - last(count:number):StringLikeSequence; + last(): string; + last(count: number): StringLikeSequence; - lastIndexOf(substring:string, startIndex?:number):number; - mapString(mapFn:MapStringCallback):StringLikeSequence; - match(pattern:RegExp):StringLikeSequence; - reverse():StringLikeSequence; + lastIndexOf(substring: string, startIndex?: number): number; + mapString(mapFn: MapStringCallback): StringLikeSequence; + match(pattern: RegExp): StringLikeSequence; + reverse(): StringLikeSequence; - split(delimiter:string):Sequence; - split(delimiter:RegExp):Sequence; + split(delimiter: string): StringLikeSequence; + split(delimiter: RegExp): StringLikeSequence; - startsWith(prefix:string):boolean; - substring(start:number, stop?:number):StringLikeSequence; - toLowerCase():StringLikeSequence; - toUpperCase():StringLikeSequence; + startsWith(prefix: string): boolean; + substring(start: number, stop?: number): StringLikeSequence; + toLowerCase(): StringLikeSequence; + toUpperCase(): StringLikeSequence; } } -declare var Lazy:LazyJS.LazyStatic; +declare var Lazy: LazyJS.LazyStatic; declare module 'lazy.js' { export = Lazy; diff --git a/microsoft-live-connect/microsoft-live-connect.ts b/microsoft-live-connect/microsoft-live-connect-tests.ts similarity index 99% rename from microsoft-live-connect/microsoft-live-connect.ts rename to microsoft-live-connect/microsoft-live-connect-tests.ts index 98fcf5a3b..e6c1e2ad0 100644 --- a/microsoft-live-connect/microsoft-live-connect.ts +++ b/microsoft-live-connect/microsoft-live-connect-tests.ts @@ -310,7 +310,7 @@ skyDriveProps = { WL.ui(skyDriveProps); function onDownloadFileCompleted(response: Microsoft.Live.IFilePickerResult) { - var msg = "", folder, file; + var msg = "", folder: number, file: number; // For each folder selected... if (response.data.folders.length > 0) { for (folder = 0; folder < response.data.folders.length; folder++) { @@ -536,7 +536,7 @@ var errorObj: Microsoft.Live.IError = { } }; -var event: Microsoft.Live.IEvent = { +var eventI: Microsoft.Live.IEvent = { "id": "event.611afb17fa9448f28cdb8277e8ffeb77.e9f015000d0249ce847c5306a25d7d75", "name": "Global Project Risk Management Meeting", "description": "Generate and assess risks for the project", @@ -854,7 +854,7 @@ var videoCollection: Microsoft.Live.IObjectCollection = { * already exercised above. */ -function log(message) { +function log(message: string) { var child = document.createTextNode(message); var parent = document.getElementById('JsOutputDiv') || document.body; parent.appendChild(child); @@ -974,7 +974,7 @@ function showUserContactInfo() { ); } -function enablePurchase(response) { +function enablePurchase() { var date = new Date(); var year = date.getFullYear(); diff --git a/ng-grid/ng-grid-tests.ts b/ng-grid/ng-grid-tests.ts index 5f4ab6ce5..53763b1a5 100644 --- a/ng-grid/ng-grid-tests.ts +++ b/ng-grid/ng-grid-tests.ts @@ -1,27 +1,27 @@ /// -var options1: ngGrid.GridOptions = { +var options1: ngGrid.IGridOptions = { data: [{ 'Name': 'Bob' }, { 'Name': 'Jane' }] }; -var options2: ngGrid.GridOptions = { +var options2: ngGrid.IGridOptions = { afterSelectionChange: () => { }, - beforeSelectionChange: () => { }, + beforeSelectionChange: () => {return true; }, dataUpdated: () => { } }; -var options3: ngGrid.GridOptions = { +var options3: ngGrid.IGridOptions = { columnDefs: [ { field: 'name', displayName: 'Name' }, { field: 'age', displayName: 'Age' } ] }; -var options4: ngGrid.GridOptions = { +var options4: ngGrid.IGridOptions = { pagingOptions: { pageSizes: [1, 2, 3, 4], pageSize: 2, totalServerItems: 100, currentPage: 1 } -}; \ No newline at end of file +}; diff --git a/ng-grid/ng-grid.d.ts b/ng-grid/ng-grid.d.ts index 48eec367a..e72344d34 100644 --- a/ng-grid/ng-grid.d.ts +++ b/ng-grid/ng-grid.d.ts @@ -11,13 +11,13 @@ declare class ngGridReorderable { declare module ngGrid { - export interface GridOptions { + export interface IGridOptions { /** Define an aggregate template to customize the rows when grouped. See github wiki for more details. */ - aggregateTemplate?: any; + aggregateTemplate?: string; /** Callback for when you want to validate something after selection. */ - afterSelectionChange?: Function; + afterSelectionChange?: (rowItem?: any, event?: any) => void ; /** Callback if you want to inspect something before selection, return false if you want to cancel the selection. return true otherwise. @@ -25,19 +25,21 @@ declare module ngGrid { use rowItem.changeSelection(event) method after returning false initially. Note: when shift+ Selecting multiple items in the grid this will only get called once and the rowItem will be an array of items that are queued to be selected. */ - beforeSelectionChange?: Function; + beforeSelectionChange?: (rowItem?: any, event?: any) => boolean ; /** checkbox templates. */ - checkboxCellTemplate?: any; + checkboxCellTemplate?: string; /** checkbox templates. */ - checkboxHeaderTemplate?: any; + checkboxHeaderTemplate?: string; /** definitions of columns as an array [], if not defined columns are auto-generated. See github wiki for more details. */ - columnDefs?: ColumnDef[]; + columnDefs?: IColumnDef[]; - /** Data being displayed in the grid. Each item in the array is mapped to a row being displayed. */ - data?: any[]; + /** Data being displayed in the grid. This can be either a string of object ID or object reference. + Using string is preferred, as this turns on change tracking in ng-grid + */ + data?: any; /** Data updated callback, fires every time the data is modified from outside the grid. */ dataUpdated?: Function; @@ -79,7 +81,7 @@ declare module ngGrid { filterText: The text bound to the built-in search box. useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box. */ - filterOptions?: FilterOptions; + filterOptions?: IFilterOptions; /** Defining the height of the footer in pixels. */ footerRowHeight?: number; @@ -91,7 +93,7 @@ declare module ngGrid { headerRowHeight?: number; /** Define a header row template for further customization. See github wiki for more details. */ - headerRowTemplate?: any; + headerRowTemplate?: string; /** Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled. Useful if you want drag + drop but your users insist on crappy browsers. */ @@ -105,13 +107,13 @@ declare module ngGrid { /** Maintains the column widths while resizing. Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false. */ - maintainColumnRatios?: any; + maintainColumnRatios?: boolean; /** Set this to false if you only want one item selected at a time */ multiSelect?: boolean; /** pagingOptions - */ - pagingOptions?: PagingOptions; + pagingOptions?: IPagingOptions; /** Array of plugin functions to register in ng-grid */ pinSelectionCheckbox?: boolean; @@ -123,7 +125,7 @@ declare module ngGrid { rowHeight?: number; /** Define a row template to customize output. See github wiki for more details. */ - rowTemplate?: any; + rowTemplate?: string; /** all of the items selected in the grid. In single select mode there will only be one item in the array. */ selectedItems?: any[]; @@ -170,15 +172,21 @@ declare module ngGrid { enableHighlighting?: boolean; } - export interface ColumnDef { + export interface IColumnDef { + field?: string; + width?: any; //**this can be a string containing a relatively, absolute size units or a number: '30%','54px',45 /* + displayName?: string; + cellTemplate?: string; + enableCellEdit?: boolean; + pinned?: boolean; } - export interface FilterOptions { + export interface IFilterOptions { filterText?: string; useExternalFilter?: boolean; } - export interface PagingOptions { + export interface IPagingOptions { /** pageSizes: list of available page sizes. */ pageSizes?: number[]; /** pageSize: currently selected page size. */ diff --git a/node-ffi/node-ffi-tests.ts b/node-ffi/node-ffi-tests.ts index 407036d39..383470503 100644 --- a/node-ffi/node-ffi-tests.ts +++ b/node-ffi/node-ffi-tests.ts @@ -28,6 +28,10 @@ import TArray = require('ref-array'); func(-5); func.async(-5, function(err: any, res: any) {}); } +{ + var funcPtr = ffi.Callback('int', [ 'int' ], Math.abs); + var func = ffi.ForeignFunction(funcPtr, 'int', [ 'int' ]); +} { var printfPointer = ffi.DynamicLibrary().get('printf'); var printfGen = ffi.VariadicForeignFunction(printfPointer, 'void', [ 'string' ]); diff --git a/node-ffi/node-ffi.d.ts b/node-ffi/node-ffi.d.ts index b2bdd522d..957cf5793 100644 --- a/node-ffi/node-ffi.d.ts +++ b/node-ffi/node-ffi.d.ts @@ -140,10 +140,10 @@ declare module "ffi" { * accept C callback functions. */ export var Callback: { - new (retType: any, argTypes: any[], abi: number, fn: Function): NodeBuffer; - new (retType: any, argTypes: any[], fn: Function): NodeBuffer; - (retType: any, argTypes: any[], abi: number, fn: Function): NodeBuffer; - (retType: any, argTypes: any[], fn: Function): NodeBuffer; + new (retType: any, argTypes: any[], abi: number, fn: any): NodeBuffer; + new (retType: any, argTypes: any[], fn: any): NodeBuffer; + (retType: any, argTypes: any[], abi: number, fn: any): NodeBuffer; + (retType: any, argTypes: any[], fn: any): NodeBuffer; } export var ffiType: { @@ -154,8 +154,8 @@ declare module "ffi" { FFI_TYPE: StructType; } - export var CIF: Function; - export var CIF_var: Function; + export var CIF: (retType: any, types: any[], abi?: any) => NodeBuffer + export var CIF_var: (retType: any, types: any[], numFixedArgs: number, abi?: any) => NodeBuffer; export var HAS_OBJC: boolean; export var FFI_TYPES: {[key: string]: NodeBuffer}; export var FFI_OK: number; diff --git a/node/node-tests.ts b/node/node-tests.ts index 49b43302b..397a9dfa4 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -21,7 +21,9 @@ assert.doesNotThrow(() => { if (false) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - +//////////////////////////////////////////////////// +/// File system tests : http://nodejs.org/api/fs.html +//////////////////////////////////////////////////// fs.writeFile("thebible.txt", "Do unto others as you would have them do unto you.", assert.ifError); @@ -33,6 +35,18 @@ fs.writeFile("Harry Potter", }, assert.ifError); +var content: string, + buffer: NodeBuffer; + +content = fs.readFileSync('testfile', 'utf8'); +content = fs.readFileSync('testfile', {encoding : 'utf8'}); +buffer = fs.readFileSync('testfile'); +buffer = fs.readFileSync('testfile', {flag : 'r'}); +fs.readFile('testfile', 'utf8', (err, data) => content = data); +fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); +fs.readFile('testfile', (err, data) => buffer = data); +fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + class Networker extends events.EventEmitter { constructor() { super(); @@ -65,4 +79,4 @@ function stream_readable_pipe_test() { var z = zlib.createGzip(); var w = fs.createWriteStream('file.txt.gz'); r.pipe(z).pipe(w); -} \ No newline at end of file +} diff --git a/node/node.d.ts b/node/node.d.ts index fe7fbd324..a0473ad8b 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -848,10 +848,13 @@ declare module "fs" { export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, bytesRead: number, buffer: NodeBuffer) => void): void; export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; - export function readFile(filename: string, options: { encoding?: string; flag?: string; }, callback: (err: ErrnoException, data: any) => void): void; + export function readFile(filename: string, encoding: string, callback: (err: ErrnoException, data: string) => void): void; + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: ErrnoException, data: string) => void): void; + export function readFile(filename: string, options: { flag?: string; }, callback: (err: ErrnoException, data: NodeBuffer) => void): void; export function readFile(filename: string, callback: (err: ErrnoException, data: NodeBuffer) => void ): void; - export function readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer; + export function readFileSync(filename: string, encoding: string): string; export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + export function readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer; export function writeFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void; export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void; export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void; diff --git a/phantomjs/phantomjs.d.ts b/phantomjs/phantomjs.d.ts index b85e356a9..58e202ac8 100644 --- a/phantomjs/phantomjs.d.ts +++ b/phantomjs/phantomjs.d.ts @@ -1,8 +1,12 @@ -// Type definitions for PlantomJS v1.8.0 API +// Type definitions for PhantomJS v1.9.0 API // Project: https://github.com/ariya/phantomjs/wiki/API-Reference -// Definitions by: Jed Hunsaker +// Definitions by: Jed Hunsaker and Mike Keesey // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare function require(module: string): any; + +declare var phantom: Phantom; + interface Phantom { // Properties @@ -11,33 +15,35 @@ interface Phantom { cookiesEnabled: boolean; libraryPath: string; scriptName: string; // DEPRECATED - version: any; + version: { + major: number; + minor: number; + patch: number; + }; // Functions addCookie(cookie: Cookie): boolean; - clearCookies(); + clearCookies(): void; deleteCookie(cookieName: string): boolean; - exit(returnValue: any): boolean; + exit(returnValue?: any): boolean; injectJs(filename: string): boolean; // Callbacks - onError: Function; + onError: (msg: string, trace: string[]) => any; } interface System { pid: number; platform: string; - os: OS; - env: any; + os: { + architecture: string; + name: string; + version: string; + }; + env: { [name: string]: string; }; args: string[]; } -interface OS { - architecture: string; - name: string; - version: string; -} - interface WebPage { // Properties @@ -46,8 +52,8 @@ interface WebPage { clipRect: ClipRect; content: string; cookies: Cookie[]; - customHeaders: any; - event; + customHeaders: { [name: string]: string; }; + event: any; // :TODO: elaborate this when documentation improves focusedFrameName: string; frameContent: string; frameName: string; @@ -55,13 +61,13 @@ interface WebPage { frameTitle: string; frameUrl: string; framesCount: number; - framesName; + framesName: any; // :TODO: elaborate this when documentation improves libraryPath: string; navigationLocked: boolean; offlineStoragePath: string; offlineStorageQuota: number; ownsPages: boolean; - pages; + pages: WebPage[]; pagesWindowName: string; paperSize: PaperSize; plainText: string; @@ -77,76 +83,113 @@ interface WebPage { addCookie(cookie: Cookie): boolean; childFramesCount(): number; // DEPRECATED childFramesName(): string; // DEPRECATED - clearCookies(); - close(); + clearCookies(): void; + close(): void; currentFrameName(): string; // DEPRECATED deleteCookie(cookieName: string): boolean; evaluate(fn: Function, ...args: any[]): any; - evaluateAsync(fn: Function); - evaluateJavascript(str: string); - getPage(windowName: string); - go(index: number); - goBack(); - goForward(); - includeJs(url: string, callback: Function); + evaluateAsync(fn: Function): void; + evaluateJavascript(str: string): any; // :TODO: elaborate this when documentation improves + getPage(windowName: string): WebPage; + go(index: number): void; + goBack(): void; + goForward(): void; + includeJs(url: string, callback: Function): void; injectJs(filename: string): boolean; - open(url: string, callback: (status: string) => void); - openUrl(url: string, httpConf: any, settings: any); - release(); // DEPRECATED - reload(); - render(filename: string); - renderBase64(format: any): string; - sendEvent(mouseEventType: string, mouseX?: number, mouseY?: number, button?: string); - sendEvent(keyboardEventType: string, keyOrKeys, aNull?, bNull?, modifier?); - setContent(content: string, url: string); - stop(); - switchToFocusedFrame(); - switchToFrame(frameName: string); - switchToFrame(framePosition); - switchToChildFrame(frameName: string); - switchToChildFrame(framePosition); - switchToMainFrame(); // DEPRECATED - switchToParentFrame(); // DEPRECATED - uploadFile(selector: string, filename: string); + open(url: string, callback: (status: string) => any): void; + open(url: string, method: string, callback: (status: string) => any): void; + open(url: string, method: string, data: any, callback: (status: string) => any): void; + openUrl(url: string, httpConf: any, settings: any): void; // :TODO: elaborate this when documentation improves + release(): void; // DEPRECATED + reload(): void; + render(filename: string): void; + renderBase64(format: string): string; + sendEvent(mouseEventType: string, mouseX?: number, mouseY?: number, button?: string): void; + sendEvent(keyboardEventType: string, keyOrKeys: any, aNull?: any, bNull?: any, modifier?: number): void; + setContent(content: string, url: string): void; + stop(): void; + switchToFocusedFrame(): void; + switchToFrame(frameName: string): void; + switchToFrame(framePosition: number): void; + switchToChildFrame(frameName: string): void; + switchToChildFrame(framePosition: number): void; + switchToMainFrame(): void; // DEPRECATED + switchToParentFrame(): void; // DEPRECATED + uploadFile(selector: string, filename: string): void; // Callbacks - onAlert: Function; + onAlert: (msg: string) => any; onCallback: Function; // EXPERIMENTAL - onClosing: Function; - onConfirm: Function; - onConsoleMessage: Function; - onError: Function; - onFilePicker: Function; - onInitialized: Function; - onLoadFinished: Function; - onLoadStarted: Function; - onNavigationRequested: Function; - onPageCreated: Function; - onPrompt: Function; - onResourceRequested: Function; - onResourceReceived: Function; - onUrlChanged: Function; + onClosing: (closingPage: WebPage) => any; + onConfirm: (msg: string) => boolean; + onConsoleMessage: (msg: string, lineNum?: number, sourceId?: string) => any; + onError: (msg: string, trace: string[]) => any; + onFilePicker: (oldFile: string) => string; + onInitialized: () => any; + onLoadFinished: (status: string) => any; + onLoadStarted: () => any; + onNavigationRequested: (url: string, type: string, willNavigate: boolean, main: boolean) => any; + onPageCreated: (newPage: WebPage) => any; + onPrompt: (msg: string, defaultVal: string) => string; + onResourceError: (resourceError: ResourceError) => any; + onResourceReceived: (response: ResourceResponse) => any; + onResourceRequested: (requestData: ResourceRequest, networkRequest: NetworkRequest) => any; + onUrlChanged: (targetUrl: string) => any; // Callback triggers - closing(page); - initialized(); - javaScriptAlertSent(message: string); - javaScriptConsoleMessageSent(message: string); - loadFinished(status); - loadStarted(); - navigationRequested(url: string, navigationType, navigationLocked, isMainFrame: boolean); - rawPageCreated(page); - resourceReceived(request); - resourceRequested(resource); - urlChanged(url: string); + closing(closingPage: WebPage): void; + initialized(): void; + javaScriptAlertSent(msg: string): void; + javaScriptConsoleMessageSent(msg: string, lineNum?: number, sourceId?: string): void; + loadFinished(status: string): void; + loadStarted(): void; + navigationRequested(url: string, type: string, willNavigate: boolean, main: boolean): void; + rawPageCreated(newPage: WebPage): void; + resourceReceived(response: ResourceResponse): void; + resourceRequested(requestData: ResourceRequest, networkRequest: NetworkRequest): void; + urlChanged(targetUrl: string): void; +} + +interface ResourceError { + id: number; + url: string; + errorCode: string; + errorString: string; +} + +interface ResourceResponse { + id: number; + url: string; + time: Date; + headers: { [name: string]: string; }; + bodySize: number; + contentType?: string; + redirectURL?: string; + stage: string; + status: number; + statusText: string; +} + +interface ResourceRequest { + id: number; + method: string; + ur: string; + time: Date; + headers: { [name: string]: string; }; +} + +interface NetworkRequest { + abort(): void; + changeUrl(url: string): void; + setHeader(name: string, value: string): void; } interface PaperSize { - width: string; - height: string; + width?: string; + height?: string; border: string; - format: string; - orientation: string; + format?: string; + orientation?: string; } interface WebPageSettings { @@ -154,9 +197,11 @@ interface WebPageSettings { loadImages: boolean; localToRemoteUrlAccessEnabled: boolean; userAgent: string; + userName: string; password: string; XSSAuditingEnabled: boolean; webSecurityEnabled: boolean; + resourceTimeout: number; } interface FileSystem { @@ -181,59 +226,62 @@ interface FileSystem { readLink(path: string): string; // Directory Functions - changeWorkingDirectory(path: string); - makeDirectory(path: string); - makeTree(path: string); - removeDirectory(path: string); - removeTree(path: string); - copyTree(source: string, destination: string); + changeWorkingDirectory(path: string): void; + makeDirectory(path: string): void; + makeTree(path: string): void; + removeDirectory(path: string): void; + removeTree(path: string): void; + copyTree(source: string, destination: string): void; // File Functions open(path: string, mode: string): Stream; + open(path: string, options: { mode: string; charset?: string; }): Stream; read(path: string): string; - write(path: string, content: string, mode: string); + write(path: string, content: string, mode: string): void; size(path: string): number; - remove(path: string); - copy(source: string, destination: string); - move(source: string, destination: string); - touch(path: string); + remove(path: string): void; + copy(source: string, destination: string): void; + move(source: string, destination: string): void; + touch(path: string): void; } interface Stream { + atEnd(): boolean; + close(): void; + flush(): void; read(): string; readLine(): string; - write(data: string); - writeLine(data: string); - flush(); - close(); + seek(position: number): void; + write(data: string): void; + writeLine(data: string): void; } interface WebServer { port: number; - listen(port: number, cb?:(request, response) => void): boolean; - listen(ipAddressPort: string, cb?:(request, response) => void): boolean; - close(); + listen(port: number, cb?: (request: WebServerRequest, response: WebServerResponse) => void): boolean; + listen(ipAddressPort: string, cb?: (request: WebServerRequest, response: WebServerResponse) => void): boolean; + close(): void; } -interface Request { +interface WebServerRequest { method: string; url: string; httpVersion: number; - headers: any; + headers: { [name: string]: string; }; post: string; postRaw: string; } -interface Response { - headers: any; - setHeader(name: string, value: string); +interface WebServerResponse { + headers: { [name: string]: string; }; + setHeader(name: string, value: string): void; header(name: string): string; statusCode: number; - setEncoding(encoding: string); - write(data: string); - writeHead(statusCode: number, headers?: any); - close(); - closeGracefully(); + setEncoding(encoding: string): void; + write(data: string): void; + writeHead(statusCode: number, headers?: { [name: string]: string; }): void; + close(): void; + closeGracefully(): void; } interface TopLeft { @@ -247,11 +295,10 @@ interface Size { } interface ClipRect extends TopLeft, Size { - width: number; - height: number; } interface Cookie { name: string; value: string; + domain?: string; } diff --git a/phonegap/phonegap.d.ts b/phonegap/phonegap.d.ts index 01935142e..37585887b 100644 --- a/phonegap/phonegap.d.ts +++ b/phonegap/phonegap.d.ts @@ -121,9 +121,9 @@ interface CaptureError { } interface Capture { - captureAudio(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureAudioOptions); - captureImage(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions); - captureVideo(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions); + captureAudio(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureAudioOptions): void; + captureImage(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions): void; + captureVideo(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions): void; } interface Connection { @@ -204,9 +204,9 @@ interface Contact { categories: ContactField[]; urls: ContactField[]; - save(onSuccess?: (contacts: Contacts) => any, onError?: (contactError: ContactError) => any); - remove(onSuccess?: (contacts: Contacts) => any, onError?: (contactError: ContactError) => any); - clone(): Contact; + save(onSuccess?: (contacts: Contacts) => void, onError?: (contactError: ContactError) => void): void; + remove(onSuccess?: (contacts: Contacts) => void, onError?: (contactError: ContactError) => void): void; + clone(): Contact; } interface ContactFindOptions { @@ -289,10 +289,10 @@ interface FileWriter { onerror: Function; onwriteend: Function; - abort(); - seek(); - truncate(); - write(); + abort(): void; + seek(arg: number): void; + truncate(arg: number): void; + write(arg: any): void; } interface FileSystem { @@ -310,29 +310,29 @@ interface FileSystemEntry { fullPath: string; filesystem: FileSystem; - getMetadata(onSuccess?: (arg) => any, onError?: (arg) => any); - setMetadata(onSuccess?: (arg) => any, onError?: (arg) => any, options?); - toURL(); - remove(onSuccess?: (arg) => any, onError?: (arg) => any); - getParent(onSuccess?: (arg) => any, onError?: (arg) => any); + getMetadata(onSuccess?: (arg: Metadata) => void, onError?: (arg: FileError) => void): void; + setMetadata(onSuccess?: (arg: Metadata) => void, onError?: (arg: FileError) => void, options?: any): void; + toURL(): string; + remove(onSuccess?: () => void, onError?: (arg: FileError) => void): void; + getParent(onSuccess?: (arg: DirectoryEntry) => void, onError?: (arg: FileError) => void): void; } interface FileEntry extends FileSystemEntry { - moveTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg) => any, onError: (arg) => any); - copyTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg) => any, onError: (arg) => any); - createWriter(onSuccess?: (arg) => any, onError?: (arg) => any); - file(onSuccess?: (arg) => any, onError?: (arg) => any); + moveTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg: DirectoryEntry) => void, onError: (arg: FileError) => void): void; + copyTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg: DirectoryEntry) => void, onError: (arg: FileError) => void): void; + createWriter(onSuccess?: (arg: FileWriter) => void, onError?: (arg: FileError) => void): void; + file(onSuccess?: (arg: File) => void, onError?: (arg: FileError) => void): void; } interface DirectoryEntry extends FileSystemEntry { - createReader(); - getDirectory(); - getFile(); - removeRecursively(); + createReader(): DirectoryReader; + getDirectory(path: string, options: Flags, successCallback: (result: DirectoryEntry) => void, errorCallback: (error: FileError) => void): void; + getFile(path: string, options: Flags, successCallback: (result: FileEntry) => void, errorCallback: (error: FileError) => void): void; + removeRecursively(successCallback: () => void, errorCallback: (error: FileError) => void): void; } interface DirectoryReader { - readEntries(successCallback: (entries: FileSystemEntry) => void , errorCallback: (error: FileError) => void ); + readEntries(successCallback: (entries: FileSystemEntry) => void, errorCallback: (error: FileError) => void): void; } interface FileTransfer { @@ -365,7 +365,10 @@ interface FileUploadResult { response: string; } -// TODO Flags +interface Flags { + create: boolean; + exclusive: boolean; +} /* interface LocalFileSystem { @@ -432,19 +435,70 @@ declare var GlobalizationError: { PATTERN_ERROR: number; } +interface GlobalizationDate { + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; + millisecond: number; +} + +interface GlobalizationDateOptions { + formatLength?: string; + selector?: string; +} + +interface GlobalizationDatePattern { + pattern: string; + timezone: string; + utc_offset: number; + dst_offset: number; +} + +interface GlobalizationDateNameOptions { + type?: string; + item?: string; +} + +interface GlobalizationNumberOptions { + type?: string; +} + +interface GlobalizationNumberPattern { + pattern: string; + symbol: string; + fraction: number; + rounding: number; + positive: string; + negative: string; + decimal: string; + grouping: string; +} + +interface GlobalizationCurrencyPattern { + pattern: string; + code: string; + fraction: number; + rounding: number; + decimal: string; + grouping: string; +} + interface Globalization { - getPreferredLanguage(successCB, errorCB): void; - getLocaleName(successCB, errorCB): void; - dateToString(date, successCB, errorCB, options): void; - stringToDate(dateString, successCB, errorCB, options): void; - getDatePattern(successCB, errorCB, options): void; - getDateNames(successCB, errorCB, options): void; - isDayLightSavingsTime(date, successCB, errorCB): void; - getFirstDayOfWeek(successCB, errorCB): void; - numberToString(number, successCB, errorCB, options): void; - stringToNumber(string, successCB, errorCB, options): void; - getNumberPattern(successCB, errorCB, options): void; - getCurrencyPattern(currencyCode, successCB, errorCB): void; + getPreferredLanguage(successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void): void; + getLocaleName(successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void): void; + dateToString(date: Date, successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void; + stringToDate(dateString: string, successCallback: (properties: GlobalizationDate) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void; + getDatePattern(successCallback: (properties: GlobalizationDatePattern) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void; + getDateNames(successCallback: (properties: {value: string[]}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateNameOptions): void; + isDayLightSavingsTime(date: Date, successCallback: (properties: {dst: boolean}) => void, errorCallback: (error: GlobalizationError) => void): void; + getFirstDayOfWeek(successCallback: (properties: {value: number}) => void, errorCallback: (error: GlobalizationError) => void): void; + numberToString(number: number, successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void; + stringToNumber(string: string, successCallback: (properties: {value: number}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void; + getNumberPattern(successCallback: (parameters: GlobalizationNumberPattern) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void; + getCurrencyPattern(currencyCode: string, successCallback: (parameters: GlobalizationCurrencyPattern) => void, errorCallback: (error: GlobalizationError) => void): void; } /* @@ -457,7 +511,7 @@ interface InAppBrowser { */ interface Media { - new (src: string, mediaSuccess: Function, mediaError?: (mediaError: MediaError) => any, mediaStatus?: Function); + new (src: string, mediaSuccess: Function, mediaError?: (mediaError: MediaError) => any, mediaStatus?: Function): Media; getCurrentPosition(mediaSuccess: Function, mediaError?: (mediaError: MediaError) => any): void; getDuration(): any; play(): void; @@ -469,7 +523,7 @@ interface Media { stop(): void; } declare var Media: { - new(src: string, onSuccess: (arg) => any, onError: (arg) => any): Media; + new(src: string, onSuccess: (arg: any) => any, onError: (error: any) => any): Media; } interface Notification { @@ -486,8 +540,8 @@ interface Splashscreen { } interface Database { - transaction(populateDB?: (tx: SQLTransaction) => any, errorCB?: (err) => any, successCB?: () => any); - changeVersion(var1: string, var2: string); + transaction(populateDB?: (tx: SQLTransaction) => any, errorCB?: (err: any) => any, successCB?: () => any): void; + changeVersion(var1: string, var2: string): void; } interface SQLResultSetRowList { diff --git a/phonegap/phonegap.d.ts.tscparams b/phonegap/phonegap.d.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/phonegap/phonegap.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/restangular/restangular.d.ts.tscparams b/restangular/restangular.d.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/restangular/restangular.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/restify/restify-tests.ts b/restify/restify-tests.ts index 79a56f578..3ff16da55 100644 --- a/restify/restify-tests.ts +++ b/restify/restify-tests.ts @@ -28,6 +28,8 @@ server = restify.createServer({ responseTimeFormatter : (durationInMilliseconds: number) => {} }); +server.pre(restify.pre.sanitizePath()); + server.on('someEvent', ()=>{}); @@ -98,7 +100,7 @@ server.get( /(.*)/, send); server.head(/(.*)/, send); new restify.ConflictError("test"); -new restify.InvalidArguementError("message"); +new restify.InvalidArgumentError("message"); new restify.RestError("message"); new restify.BadDigestError("message"); new restify.BadMethodError("message"); diff --git a/restify/restify.d.ts b/restify/restify.d.ts index cd65e6666..6bcbb5412 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -3,13 +3,20 @@ // Definitions by: Bret Little // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface addressInterface { +/// + + +declare module "restify" { + import http = require('http'); + + + interface addressInterface { port: number; family: string; address: string; -} + } -interface Request { + interface Request extends http.ServerRequest { header: (key: string, defaultValue?: string) => any; accepts: (type: string) => boolean; is: (type: string) => boolean; @@ -20,13 +27,15 @@ interface Request { log: Object; id: string; path: () => string; - query: string; + query: any; secure: boolean; time: number; params: any; -} -interface Response { + body?: any; //available when bodyParser plugin is used + } + + interface Response extends http.ServerResponse { header: (key: string, value ?: any) => any; cache: (type?: any, options?: Object) => any; status: (code: number) => any; @@ -39,30 +48,57 @@ interface Response { headers: Object; statusCode: number; id: string; -} + } + + interface Server extends http.Server { + use(handler: RequestHandler, ...handlers: RequestHandler[]): any; + use(handler: RequestHandler[], ...handlers: RequestHandler[]): any; + use(handler: RequestHandler, ...handlers: RequestHandler[][]): any; + use(handler: RequestHandler[], ...handlers: RequestHandler[][]): any; + + post(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any; + post(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any; + post(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any; + post(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any; + + patch(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any; + patch(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any; + patch(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any; + patch(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any; + + put(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any; + put(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any; + put(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any; + put(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any; + + del(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any; + del(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any; + del(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any; + del(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any; + + get(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any; + get(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any; + get(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any; + get(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any; + + head(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any; + head(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any; + head(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any; + head(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any; -interface Server { - use: (... handler: any[]) => any; - post: (route: any, routeCallBack: RequestHadler) => any; - patch: (route: any, routeCallBack: RequestHadler) => any; - put: (route: any, routeCallBack: RequestHadler) => any; - del: (route: any, routeCallBack: RequestHadler) => any; - get: (route: any, routeCallBack: RequestHadler) => any; - head: (route: any, routeCallBack: RequestHadler) => any; - on: (event: string, callback: Function) => any; name: string; version: string; log: Object; acceptable: string[]; url: string; address: () => addressInterface; - listen: (... args: any[]) => any; - close: (... args: any[]) => any; - pre: (routeCallBack: RequestHadler) => any; + listen(... args: any[]): any; + close(... args: any[]): any; + pre(routeCallBack: RequestHandler): any; -} + } -interface ServerOptions { + interface ServerOptions { certificate ?: string; key ?: string; formatters ?: Object; @@ -72,9 +108,9 @@ interface ServerOptions { version ?: string; responseTimeHeader ?: string; responseTimeFormatter ?: (durationInMilliseconds: number) => any; -} + } -interface ClientOptions { + interface ClientOptions { accept?: string; connectTimeout?: number; dtrace?: Object; @@ -86,26 +122,26 @@ interface ClientOptions { url?: string; userAgent?: string; version?: string; -} + } -interface Client { + interface Client { get: (path: string, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; head: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; post: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; put: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; del: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; basicAuth: (username: string, password: string) => any; -} + } -interface HttpClient extends Client { + interface HttpClient extends Client { get: (path?: any, callback?: Function) => any; head: (path?:any, callback?: Function) => any; post: (opts?: any, callback?: Function) => any; put: (opts?: any, callback?: Function) => any; del: (opts?: any, callback?: Function) => any; -} + } -interface ThrottleOptions { + interface ThrottleOptions { burst?: number; rate?: number; ip?: boolean; @@ -114,50 +150,71 @@ interface ThrottleOptions { tokensTable?: Object; maxKeys?: number; overrides?: Object; -} + } -interface RequestHadler { - (req: Request, res: Response, next: Function): any; -} + interface Next { + (err?: any): any; + } -declare module "restify" { - export function createServer(options?: ServerOptions): Server; + interface RequestHandler { + (req: Request, res: Response, next: Next): any; + } - export function createJsonClient(options?: ClientOptions): Client; - export function createStringClient(options?: ClientOptions): Client; - export function createClient(options?: ClientOptions): HttpClient; + interface CORS { + (cors?: { + origins?: string[]; + credentials?: boolean; + headers?: string[]; + }): RequestHandler; + origins: string[]; + ALLOW_HEADERS: string[]; + credentials: boolean; + } - export class ConflictError { constructor(message?: any); } - export class InvalidArguementError { constructor(message?: any); } - export class RestError { constructor(message?: any); } - export class BadDigestError { constructor(message: any); } - export class BadMethodError { constructor(message: any); } - export class BadRequestError { constructor(message: any); } - export class InternalError { constructor(message: any); } - export class InvalidContentError { constructor(message: any); } - export class InvalidCredentialsError { constructor(message: any); } - export class InvalidHeaderError { constructor(message: any); } - export class InvalidVersionError { constructor(message: any); } - export class MissingParameterError { constructor(message: any); } - export class NotAuthorizedError { constructor(message: any); } - export class RequestExpiredError { constructor(message: any); } - export class RequestThrottledError { constructor(message: any); } - export class ResourceNotFoundError { constructor(message: any); } - export class WrongAcceptError { constructor(message: any); } + export function createServer(options?: ServerOptions): Server; - export function acceptParser(parser: any): RequestHadler; - export function authorizationParser(): RequestHadler; - export function dateParser(skew?: number): RequestHadler; - export function queryParser(options?: Object): RequestHadler; - export function urlEncodedBodyParser(options?: Object): RequestHadler[]; - export function jsonp(): RequestHadler; - export function gzipResponse(options?: Object): RequestHadler; - export function bodyParser(options?: Object): RequestHadler[]; - export function requestLogger(options?: Object): RequestHadler; - export function serveStatic(options?: Object): RequestHadler; - export function throttle(options?: ThrottleOptions): RequestHadler; - export function conditionalRequest(): RequestHadler[]; - export function auditLogger(options?: Object): Function; - export function fullResponse(): RequestHadler; - export var defaultResponseHeaders : any; + export function createJsonClient(options?: ClientOptions): Client; + export function createStringClient(options?: ClientOptions): Client; + export function createClient(options?: ClientOptions): HttpClient; + + export class ConflictError { constructor(message?: any); } + export class InvalidArgumentError { constructor(message?: any); } + export class RestError { constructor(message?: any); } + export class BadDigestError { constructor(message: any); } + export class BadMethodError { constructor(message: any); } + export class BadRequestError { constructor(message: any); } + export class InternalError { constructor(message: any); } + export class InvalidContentError { constructor(message: any); } + export class InvalidCredentialsError { constructor(message: any); } + export class InvalidHeaderError { constructor(message: any); } + export class InvalidVersionError { constructor(message: any); } + export class MissingParameterError { constructor(message: any); } + export class NotAuthorizedError { constructor(message: any); } + export class RequestExpiredError { constructor(message: any); } + export class RequestThrottledError { constructor(message: any); } + export class ResourceNotFoundError { constructor(message: any); } + export class WrongAcceptError { constructor(message: any); } + + export function acceptParser(parser: any): RequestHandler; + export function authorizationParser(): RequestHandler; + export function dateParser(skew?: number): RequestHandler; + export function queryParser(options?: Object): RequestHandler; + export function urlEncodedBodyParser(options?: Object): RequestHandler[]; + export function jsonp(): RequestHandler; + export function gzipResponse(options?: Object): RequestHandler; + export function bodyParser(options?: Object): RequestHandler[]; + export function requestLogger(options?: Object): RequestHandler; + export function serveStatic(options?: Object): RequestHandler; + export function throttle(options?: ThrottleOptions): RequestHandler; + export function conditionalRequest(): RequestHandler[]; + export function auditLogger(options?: Object): Function; + export function fullResponse(): RequestHandler; + export var defaultResponseHeaders : any; + export var CORS: CORS; + + export module pre { + export function pause(): RequestHandler; + export function sanitizePath(options?: any): RequestHandler; + export function userAgentConnection(options?: any): RequestHandler; + } } diff --git a/rx.js/rx.d.ts b/rx.js/rx.d.ts index 1100bc618..3de410d30 100644 --- a/rx.js/rx.d.ts +++ b/rx.js/rx.d.ts @@ -436,3 +436,7 @@ declare module Rx { export var AsyncSubject: AsyncSubjectStatic; } + +declare module "rx" { + export = Rx +} diff --git a/smoothie/smoothie-tests.ts b/smoothie/smoothie-tests.ts index 8fb75de8d..9da8eebf6 100644 --- a/smoothie/smoothie-tests.ts +++ b/smoothie/smoothie-tests.ts @@ -1,14 +1,14 @@ /// // Smoothie supports browserify -import Smoothie = require('smoothie'); +import smoothie = require('smoothie'); var canvas: HTMLCanvasElement = document.createElement('canvas'); document.body.appendChild(canvas); -var series: Smoothie.TimeSeries = new Smoothie.TimeSeries(), - chart: Smoothie.SmoothieChart = new Smoothie.SmoothieChart({ +var series: smoothie.TimeSeries = new smoothie.TimeSeries(), + chart: smoothie.SmoothieChart = new smoothie.SmoothieChart({ grid : { strokeStyle : '#404040' }, diff --git a/smoothie/smoothie.d.ts b/smoothie/smoothie.d.ts index d5ba175e9..3353c3dbf 100644 --- a/smoothie/smoothie.d.ts +++ b/smoothie/smoothie.d.ts @@ -1,66 +1,184 @@ -// Type definitions for smoothie +// Type definitions for Smoothie Charts 1.21 // Project: https://github.com/joewalnes/smoothie -// Definitions by: Mike H. Hawley -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Drew Noakes +// Mike H. Hawley +// Definitions: https://github.com/borisyankov/DefinitelyTyped/smoothie +// NOTE this reference is here to make the DefinitelyTyped `npm test` suite pass and +// may be removed if you are using this module declaration in isolation from the +// rest of DefinitelyTyped. /// -declare module "smoothie" { - export class TimeSeries { - constructor(options?: { - resetBoundsInterval?: number; - resetBounds?: boolean - }); - - public resetBounds(): void; - - public append(timestamp: number, value: number, sumRepeatedTimeStampValues?: boolean): void; - - public dropOldData(oldestValidTime: number, maxDataSetLength: number): void; +declare module "smoothie" +{ + export interface ITimeSeriesOptions + { + resetBounds?: boolean; + resetBoundsInterval?: number; } - export class SmoothieChart { - constructor(options?: { - millisPerPixel?: number; - maxValueScale?: number; - interpolation?: string; - scaleSmoothing?: number; - maxDataSetLength?: number; - - grid?: { - fillStyle?: string; - strokeStyle?: string; - lineWidth?: number; - sharpLines?: boolean; - millisPerLine?: number; - verticalSections?: number; - borderVisible?: boolean - }; - - labels?: { - fillStyle?: string; - disabled?: boolean; - fontSize?: number; - fontFamily?: string; - precision?: number - }; - - horizontalLines?: number[] - }); + export interface ITimeSeriesPresentationOptions + { + stokeStyle?: string; + fillStyle?: string; + lineWidth?: number; + } - public addTimeSeries(timeSeries: TimeSeries, options?: { - lineWidth?: number; - strokeStyle?: string - }): void; + export class TimeSeries + { + /** + * Initialises a new TimeSeries with optional data options. + * + * Options are of the form (defaults shown): + * + *
    +         * {
    +         *   resetBounds: true,        // enables/disables automatic scaling of the y-axis
    +         *   resetBoundsInterval: 3000 // the period between scaling calculations, in millis
    +         * }
    +         * 
    + * + * Presentation options for TimeSeries are specified as an argument to SmoothieChart.addTimeSeries. + */ + constructor(options?: ITimeSeriesOptions); - public removeTimeSeries(timeSeries: TimeSeries): void; + /** + * Recalculate the min/max values for this TimeSeries object. + * + * This causes the graph to scale itself in the y-axis. + */ + resetBounds(): void; - public streamTo(canvas: HTMLCanvasElement, delayMillis: number): void; + /** + * Adds a new data point to the TimeSeries, preserving chronological order. + * + * @param timestamp the position, in time, of this data point + * @param value the value of this data point + * @param sumRepeatedTimeStampValues if timestamp has an exact match in the series, this flag controls + * whether it is replaced, or the values summed (defaults to false.) + */ + append(timestamp: number, value: number, sumRepeatedTimeStampValues?: boolean): void; - public start(): void; - public stop(): void; + dropOldData(oldestValidTime: number, maxDataSetLength: number): void; + } - public updateValueRange(): void; - public render(canvas?: HTMLCanvasElement, time?: number): void; + export interface IGridOptions + { + /** The background colour of the chart. */ + fillStyle?: string; + /** The pixel width of grid lines. */ + lineWidth?: number; + /** Colour of grid lines. */ + stokeStyle?: string; + /** Distance between vertical grid lines. */ + millisPerLine?: number; + /** Controls whether grid lines are 1px sharp, or softened. */ + sharpLines?: boolean; + /** Number of vertical sections marked out by horizontal grid lines. */ + verticalSections?: number; + /** Whether the grid lines trace the border of the chart or not. */ + borderVisible?: boolean; + } + + export interface ILabelOptions + { + /** Enables/disables labels showing the min/max values. */ + disabled?: boolean; + /** Colour for text of labels. */ + fillStyle?: string; + fontSize?: number; + fontFamily?: string; + precision?: number; + } + + export interface IRange { min: number; max: number } + + export interface IHorizontalLine + { + value?: number; + color?: string; + lineWidth?: number; + } + + export interface IChartOptions + { + /** Specify to clamp the lower y-axis to a given value. */ + minValue?: number; + /** Specify to clamp the upper y-axis to a given value. */ + maxValue?: number; + /** Allows proportional padding to be added above the chart. for 10% padding, specify 1.1. */ + maxValueScale?: number; + yRangeFunction?: (range:IRange)=>IRange; + /** Controls the rate at which y-value zoom animation occurs. */ + scaleSmoothing?: number; + /** Sets the speed at which the chart pans by. */ + millisPerPixel?: number; + maxDataSetLength?: number; + /** One of: 'bezier', 'linear', 'step' */ + interpolation?: string; + /** Optional function to format time stamps for bottom of chart. You may use SmoothieChart.timeFormatter, or your own/ */ + timestampFormatter?: (date:Date)=>string; + horizontalLines?: IHorizontalLine[]; + + grid?: IGridOptions; + + labels?: ILabelOptions; + } + + /** + * Initialises a new SmoothieChart. + * + * Options are optional and may be sparsely populated. Just specify the values you + * need and the rest will be given sensible defaults. + */ + export class SmoothieChart + { + constructor(chartOptions?: IChartOptions); + + /** + * Adds a TimeSeries to this chart, with optional presentation options. + */ + addTimeSeries(series: TimeSeries, seriesOptions?: ITimeSeriesPresentationOptions): void; + + /** + * Removes the specified TimeSeries from the chart. + */ + removeTimeSeries(series: TimeSeries): void; + + /** + * Gets render options for the specified TimeSeries. + * + * As you may use a single TimeSeries in multiple charts with different formatting in each usage, + * these settings are stored in the chart. + */ + getTimeSeriesOptions(timeSeries: TimeSeries): ITimeSeriesPresentationOptions; + + /** + * Brings the specified TimeSeries to the top of the chart. It will be rendered last. + */ + bringToFront(timeSeries: TimeSeries): void; + + /** + * Instructs the SmoothieChart to start rendering to the provided canvas, with specified delay. + * + * @param canvas the target canvas element + * @param delayMillis an amount of time to wait before a data point is shown. This can prevent the end of the series + * from appearing on screen, with new values flashing into view, at the expense of some latency. + */ + streamTo(canvas: HTMLCanvasElement, delayMillis?: number): void; + + /** + * Starts the animation of this chart. Called by streamTo. + */ + start(): void; + + /** + * Stops the animation of this chart. + */ + stop(): void; + + updateValueRange(): void; + + render(canvas?: HTMLCanvasElement, time?: number): void; } } diff --git a/socket.io/socket.io.d.ts b/socket.io/socket.io.d.ts index 8d137d7af..be79b2dcd 100644 --- a/socket.io/socket.io.d.ts +++ b/socket.io/socket.io.d.ts @@ -12,55 +12,58 @@ declare module "socket.io" { export function listen(server: http.Server, options: any, fn: Function): SocketManager; export function listen(server: http.Server, fn?: Function): SocketManager; export function listen(port: Number): SocketManager; -} -interface Socket { - id: string; - json:any; - log: any; - volatile: any; - broadcast: any; - in(room: string): Socket; - to(room: string): Socket; - join(name: string, fn: Function): Socket; - leave(name: string, fn: Function): Socket; - set(key: string, value: any, fn: Function): Socket; - get(key: string, fn: Function): Socket; - has(key: string, fn: Function): Socket; - del(key: string, fn: Function): Socket; - disconnect(): Socket; - send(data: any, fn: Function): Socket; - emit(ev: any, ...data:any[]): Socket; - on(ns: string, fn: Function): Socket; -} -interface SocketNamespace { - clients(room: string): Socket[]; - log: any; - store: any; - json: any; - volatile: any; - in(room: string): SocketNamespace; - on(evt: string, fn: (socket: Socket) => void): SocketNamespace; - to(room: string): SocketNamespace; - except(id: any): SocketNamespace; - send(data: any): any; - emit(ev: any, ...data:any[]): Socket; - socket(sid: any, readable: boolean): Socket; - authorization(fn: Function); -} + interface Socket { + id: string; + json:any; + log: any; + volatile: any; + broadcast: any; + in(room: string): Socket; + to(room: string): Socket; + join(name: string, fn: Function): Socket; + leave(name: string, fn: Function): Socket; + set(key: string, value: any, fn: Function): Socket; + get(key: string, fn: Function): Socket; + has(key: string, fn: Function): Socket; + del(key: string, fn: Function): Socket; + disconnect(): Socket; + send(data: any, fn: Function): Socket; + emit(ev: any, ...data:any[]): Socket; + on(ns: string, fn: Function): Socket; + } + + interface SocketNamespace { + clients(room: string): Socket[]; + log: any; + store: any; + json: any; + volatile: any; + in(room: string): SocketNamespace; + on(evt: string, fn: (socket: Socket) => void): SocketNamespace; + to(room: string): SocketNamespace; + except(id: any): SocketNamespace; + send(data: any): any; + emit(ev: any, ...data:any[]): Socket; + socket(sid: any, readable: boolean): Socket; + authorization(fn: Function): SocketNamespace; + } + + interface SocketManager { + get(key: any): any; + set(key: any, value: any): SocketManager; + enable(key: any): SocketManager; + disable(key: any): SocketManager; + enabled(key: any): boolean; + disabled(key: any): boolean; + configure(env: string, fn: Function): SocketManager; + configure(fn: Function): SocketManager; + of(nsp: string): SocketNamespace; + on(ns: string, fn: Function): SocketManager; + sockets: SocketNamespace; + } + -interface SocketManager { - get(key: any): any; - set(key: any, value: any): SocketManager; - enable(key: any): SocketManager; - disable(key: any): SocketManager; - enabled(key: any): boolean; - disabled(key: any): boolean; - configure(env: string, fn: Function): SocketManager; - configure(fn: Function): SocketManager; - of(nsp: string): SocketNamespace; - on(ns: string, fn: Function): SocketManager; - sockets: SocketNamespace; } diff --git a/socket.io/socket.io.d.ts.tscparams b/socket.io/socket.io.d.ts.tscparams deleted file mode 100644 index e16c76dff..000000000 --- a/socket.io/socket.io.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ -"" diff --git a/state-machine/state-machine.d.ts b/state-machine/state-machine.d.ts index 0805a1db3..c5c9c83bf 100644 --- a/state-machine/state-machine.d.ts +++ b/state-machine/state-machine.d.ts @@ -79,3 +79,7 @@ interface StateMachine { } declare var StateMachine: StateMachineStatic; + +declare module "state-machine" { + export = StateMachineStatic; +} diff --git a/svgjs/svgjs-tests.ts b/svgjs/svgjs-tests.ts index 845702ac4..fce9c3a74 100644 --- a/svgjs/svgjs-tests.ts +++ b/svgjs/svgjs-tests.ts @@ -1,5 +1,5 @@ -/// /// +/// // create svg drawing paper @@ -46,7 +46,7 @@ function renderSVG(data:string) { var container = SVG(div) // this creates an SVG tag inside container.svg(data) // this creates an SVG inside the SVG var $inner = $(div).find("svg svg") - var inner:svgjs.Element = $inner.get(0).instance + var inner:svgjs.Element = ($inner.get(0)).instance // Copy in the important attributes root.attr('x', inner.attr('x')) @@ -61,8 +61,8 @@ function renderSVG(data:string) { // Activate and Label all child paths var index = 0 el.find("rect, path, circle, ellipse").each(function() { - var $path = $(this) - var path = $path.get(0).instance + var $path: JQuery = $(this) + var path = ($path.get(0)).instance var uniqueId = "path"+index++ path.attr({"path-id": uniqueId}) }) diff --git a/svgjs/svgjs.d.ts b/svgjs/svgjs.d.ts index 5ff8303ff..44f32d9b1 100644 --- a/svgjs/svgjs.d.ts +++ b/svgjs/svgjs.d.ts @@ -88,6 +88,8 @@ declare module svgjs { move(x:number, y:number, anchor?:boolean):Element; x(x:number, anchor?:boolean):Element; y(y:number, anchor?:boolean):Element; + x(): number; + y(): number; center(x:number, y:number, anchor?:boolean):Element; cx(x:number, anchor?:boolean):Element; @@ -267,4 +269,4 @@ declare module svgjs { e?: number; f?: number; } -} \ No newline at end of file +} diff --git a/threejs/three-tests.ts b/threejs/three-tests.ts index afb4b2300..8207933bc 100644 --- a/threejs/three-tests.ts +++ b/threejs/three-tests.ts @@ -13896,51 +13896,6 @@ declare var ballPosition: THREE.Vector3; new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true, transparent: true, opacity: 0.1 } ) ]; - - // tetrahedron - - var points = [ - new THREE.Vector3( 100, 0, 0 ), - new THREE.Vector3( 0, 100, 0 ), - new THREE.Vector3( 0, 0, 100 ), - new THREE.Vector3( 0, 0, 0 ) - ]; - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials ); - object.position.set( 0, 0, 0 ); - scene.add( object ); - - // cube - - var points = [ - new THREE.Vector3( 50, 50, 50 ), - new THREE.Vector3( 50, 50, -50 ), - new THREE.Vector3( -50, 50, -50 ), - new THREE.Vector3( -50, 50, 50 ), - new THREE.Vector3( 50, -50, 50 ), - new THREE.Vector3( 50, -50, -50 ), - new THREE.Vector3( -50, -50, -50 ), - new THREE.Vector3( -50, -50, 50 ), - ]; - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials ); - object.position.set( -200, 0, -200 ); - scene.add( object ); - - // random convex - - points = []; - for ( var i = 0; i < 30; i ++ ) { - - points.push( randomPointInSphere( 50 ) ); - - } - - object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials ); - object.position.set( -200, 0, 200 ); - scene.add( object ); - - object = new THREE.AxisHelper( 50 ); object.position.set( 200, 0, -200 ); scene.add( object ); diff --git a/threejs/three.d.ts b/threejs/three.d.ts index b76430f92..687bb8123 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -171,6 +171,7 @@ declare module THREE { * @param vector point to look at */ lookAt(vector: Vector3): void; + clone(camera?: Camera): Camera; } /** @@ -227,6 +228,8 @@ declare module THREE { * Updates the camera projection matrix. Must be called after change of parameters. */ updateProjectionMatrix(): void; + + clone(): OrthographicCamera; } /** @@ -318,6 +321,7 @@ declare module THREE { * Updates the camera projection matrix. Must be called after change of parameters. */ updateProjectionMatrix(): void; + clone(): PerspectiveCamera; } // Core /////////////////////////////////////////////////////////////////////////////////////////////// @@ -383,6 +387,8 @@ declare module THREE { morphTargets: any[]; hasTangents: boolean; + addAttribute(name: string, type: Function, numItems: number, itemSize: number): any; + /** * Bakes matrix transform directly into vertex coordinates. */ @@ -419,6 +425,8 @@ declare module THREE { dispose(): void; normalizeNormals(): void; + + clone(): BufferGeometry; } /** @@ -450,8 +458,8 @@ declare module THREE { oldTime: number; /** - * When the clock is running, It holds the time elapsed btween the start of the clock to the previous update. - * This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. + * When the clock is running, It holds the time elapsed between the start of the clock to the previous update. + * This parameter is in seconds of three decimal places. */ elapsedTime: number; @@ -471,12 +479,12 @@ declare module THREE { stop(): void; /** - * Get milliseconds passed since the clock started. + * Get the seconds passed since the clock started. */ getElapsedTime(): number; /** - * Get the milliseconds passed since the last call to this method. + * Get the seconds passed since the last call to this method. */ getDelta(): number; } @@ -914,6 +922,13 @@ declare module THREE { computeLineDistances(): void; } + export class Geometry2 extends BufferGeometry { + vertices: Float32Array; + normals: Float32Array; + uvs: Float32Array; + + } + /** * Base class for scene graph objects */ @@ -1108,11 +1123,6 @@ declare module THREE { clone(object?: Object3D, recursive?: boolean): Object3D; - /** - * Creates a new clone of this object and all descendants. - */ - clone(object?: Object3D): Object3D; - /** * Searches through the object's children and returns the first with a matching name, optionally recursive. * @param name String to match to the children's Object3d.name property. @@ -1198,6 +1208,8 @@ declare module THREE { export class Light extends Object3D { constructor(hex?: number); color: Color; + + clone(light?: Light): Light; } /** @@ -1215,6 +1227,8 @@ declare module THREE { * @param hex Numeric value of the RGB component of the color. */ constructor(hex?: number); + + clone(): AmbientLight; } export class AreaLight extends Light{ @@ -1405,6 +1419,8 @@ declare module THREE { * Default — null. */ shadowMatrix: Matrix4; + + clone(): DirectionalLight; } export class HemisphereLight extends Light { @@ -1413,6 +1429,8 @@ declare module THREE { position: Vector3; groundColor: Color; intensity: number; + + clone(): HemisphereLight; } /** @@ -1443,6 +1461,8 @@ declare module THREE { * Default — 0.0. */ distance: number; + + clone(): PointLight; } /** @@ -1563,6 +1583,8 @@ declare module THREE { shadowMapSize: Vector2; shadowCamera: Camera; shadowMap: RenderTarget; + + clone(): SpotLight; } // Loaders ////////////////////////////////////////////////////////////////////////////////// @@ -1630,19 +1652,36 @@ declare module THREE { addStatusElement(): HTMLElement; } + export class BufferGeometryLoader { + constructor(manager?: LoadingManager); + + load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void): void; + setCrossOrigin(crossOrigin: string): void; + parse(json: any): BufferGeometry; + + } + + export class Geometry2Loader { + constructor(manager?: LoadingManager); + + load(url: string, onLoad: (geometry2: Geometry2) => void): void; + setCrossOrigin(crossOrigin: string): void; + parse(json: any): Geometry2; + } + /** * A loader for loading an image. * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. */ - export class ImageLoader extends EventDispatcher { - constructor(); + export class ImageLoader { + constructor(manager?: LoadingManager); crossOrigin: string; /** * Begin loading from url * @param url */ - load(url: string, onLoad?: (event: any) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement; + load(url: string, onLoad?: (image: HTMLImageElement) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement; setCrossOrigin(crossOrigin: string): void; } @@ -1669,7 +1708,7 @@ declare module THREE { * Handles and keeps track of loaded and pending data. */ export class LoadingManager { - constructor(onLoad?: (event: any) => void, onProgress?: (event: any) => void, onError?: (event: any) => void); + constructor(onLoad?: () => void, onProgress?: (url: string, loaded: number, total: number) => void, onError?: () => void); /** * Will be called when load starts. @@ -1687,13 +1726,32 @@ declare module THREE { * Will be called when each element in the scene completes loading. * The default is a function with empty body. */ - onError: (event: () => void) => void; + onError: () => void; itemStart(url: string): void; itemEnd(url: string): void; } + export class MaterialLoader extends EventDispatcher { + constructor(manager?: LoadingManager); + + load(url: string, onLoad: (material: Material) => void): void; + setCrossOrigin(crossOrigin: string): void; + parse(json: any): Material; + } + + export class ObjectLoader extends EventDispatcher { + constructor(manager?: LoadingManager); + + load(url: string, onLoad: (object: Object3D) => void): void; + setCrossOrigin(crossOrigin: string): void; + parse(json: any): T; + parseGeometries(json: any): any[]; // Array of BufferGeometry or Geometry or Geometry2. + parseMaterials(json: any): Material[]; // Array of Classes that inherits from Matrial. + parseObject(data: any, geometries: any[], materials: Material[]): T; + } + interface SceneLoaderResult{ scene: Scene; geometries: {[id:string]:Geometry;}; @@ -1739,7 +1797,6 @@ declare module THREE { */ onLoadComplete: () => void; - /** * Will be called when load completes. * The default is a function with empty body. @@ -1751,17 +1808,18 @@ declare module THREE { * The default is a function with empty body. */ callbackProgress: (progress: SceneLoaderProgress, result: SceneLoaderResult) => void; - hierarchyHandlerMap: any; - geometryHandlerMap: any; + hierarchyHandlers: any; + geometryHandlers: any; /** * @param url * @param callbackFinished This function will be called with the loaded model as an instance of scene when the load is completed. */ - load(url: string, callbackFinished: (scene: Scene) => void ): void; - addHierarchyHandler(typeID: string, loaderClass: Object): void; + load(url: string, onLoad: (result: SceneLoaderResult) => void): void; + setCrossOrigin(crossOrigin: string): void; + addHierarchyHandler(typeID: string, loaderClass: any): void; parse(json: any, callbackFinished: (result: SceneLoaderResult) => void, url: string): void; - addGeometryHandler(typeID: string, loaderClass: Object): void; + addGeometryHandler(typeID: string, loaderClass: any): void; } /** @@ -1769,14 +1827,28 @@ declare module THREE { * Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object. */ export class TextureLoader extends EventDispatcher { - constructor(); + constructor(manager?: LoadingManager); crossOrigin: string; /** * Begin loading from url * * @param url */ - load(url: string): void; + load(url: string, onLoad: (texture: Texture) => void): void; + setCrossOrigin(crossOrigin: string): void; + } + + export class XHRLoader extends EventDispatcher { + constructor(manager?: LoadingManager); + crossOrigin: string; + /** + * Begin loading from url + * + * @param url + */ + constructor(onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void); + load(onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + setCrossOrigin(crossOrigin: string): void; } // Materials ////////////////////////////////////////////////////////////////////////////////// @@ -1881,7 +1953,7 @@ declare module THREE { */ needsUpdate: boolean; - clone(): Material; + clone(material?:Material): Material; dispose(): void; setValues(values: Object): void; @@ -2325,12 +2397,10 @@ declare module THREE { * @see src/math/Color.js */ export class Color { - constructor(hex?: string); - - /** - * @param hex initial color in hexadecimal - */ - constructor(hex?: number); + constructor(color?: Color); + constructor(color?: string); + constructor(color?: number); + constructor(r: number, g: number, b: number); /** * Red channel value between 0 and 1. Default is 1. @@ -2347,6 +2417,10 @@ declare module THREE { */ b: number; + set(color: Color): Color; + set(color: number): Color; + set(color: string): Color; + /** * Copies given color. * @param color Color to copy. @@ -2433,9 +2507,6 @@ declare module THREE { * Clones this color. */ clone(): Color; - - set(value: number): void; - set(value: string): void; } export class Euler { @@ -3851,6 +3922,8 @@ declare module THREE { render(scene: Scene, camera: Camera): void; clear(): void; setClearColor(color: Color, opacity?: number): void; + setClearColor(color: string, opacity?: number): void; + setClearColor(color: number, opacity?: number): void; setFaceCulling(): void; supportsVertexTextures(): void; setSize(width: number, height: number, updateStyle?: boolean): void; @@ -4068,7 +4141,7 @@ declare module THREE { /** * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). */ - setSize(width: number, height: number): void; + setSize(width: number, height: number, updateStyle?: boolean): void; /** * Sets the viewport to render from (x, y) to (x + width, y + height). @@ -4088,7 +4161,9 @@ declare module THREE { /** * Sets the clear color, using color for the color and alpha for the opacity. */ - setClearColor(color: Color, alpha: number): void; + setClearColor(color: Color, alpha?: number): void; + setClearColor(color: string, alpha?: number): void; + setClearColor(color: number, alpha?: number): void; /** * Returns a THREE.Color instance with the current clear color. @@ -4249,7 +4324,7 @@ declare module THREE { id: number; } - export class RenderableParticle { + export class RenderableSprite { constructor(); scale: Vector2; @@ -4663,22 +4738,18 @@ declare module THREE { addToUpdate(animation: Animation): void; }; - export class AnimationMorphTarget { - constructor(root: Bone, data: any); - - root: Bone; - data: Object; - hierarchy: KeyFrames[]; - currentTime: number; - timeScale: number; - isPlaying: boolean; - isPaused: boolean; - loop: boolean; - influence: number; + export class MorphAnimation { + constructor(mesh: Mesh); - play(loop?: boolean, startTimeMS?: number): void; + mesh: Mesh; + frames: number; + currentTime: number; + duration: number; + loop: boolean; + isPlaying: boolean; + + play(): void; pause(): void; - stop(): void; update(deltaTimeMS: number): void; } @@ -4963,15 +5034,6 @@ declare module THREE { // Extras / Geomerties ///////////////////////////////////////////////////////////////////// - - export class CircleGeometry extends Geometry { - constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); - } - - export class ConvexGeometry extends Geometry { - constructor(vertices: Vector3[]); - } - /** * CubeGeometry is the quadrilateral primitive geometry class. It is typically used for creating a cube or irregular quadrilateral of the dimensions provided within the (optional) 'width', 'height', & 'depth' constructor arguments. */ @@ -4987,6 +5049,22 @@ declare module THREE { constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); } + export class BoxGeometry2 extends Geometry2 { + /** + * @param width — Width of the sides on the X axis. + * @param height — Height of the sides on the Y axis. + * @param depth — Depth of the sides on the Z axis. + * @param widthSegments — Number of segmented faces along the width of the sides. + * @param heightSegments — Number of segmented faces along the height of the sides. + * @param depthSegments — Number of segmented faces along the depth of the sides. + */ + constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); + } + + export class CircleGeometry extends Geometry { + constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); + } + export class CubeGeometry extends BoxGeometry { } @@ -5030,6 +5108,10 @@ declare module THREE { constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); } + export class PlaneGeometry2 extends Geometry2 { + constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); + } + export class PolyhedronGeometry extends Geometry { constructor(vertices: Vector3[], faces: Face[], radius?: number, detail?: number); } @@ -5128,10 +5210,20 @@ declare module THREE { constructor(object: Object3D, hex: number); object: Object3D; - box: Box3; + vertices: Vector3[]; update(): void; } + + export class BoxHelper extends Line { + constructor(object: Object3D); + + object: Object3D; + box: Box3; + + update(object?: Object3D): void; + } + export class CameraHelper extends Line { constructor(camera: Camera); @@ -5151,6 +5243,23 @@ declare module THREE { update(): void; } + export class EdgesHelper extends Line { + constructor(object: Object3D, hex?: number); + + matrixAutoUpdate: boolean; + matrixWorld: Matrix4; + } + + export class FaceNormalsHelper extends Line { + constructor(object: Object3D, size?: number, hex?: number, linewidth?: number); + + size: number; + matrixAutoUpdate: boolean; + normalMatrix: Matrix3; + + update(object?: Object3D): void; + } + export class GridHelper extends Line { constructor(size: number, step: number); @@ -5184,6 +5293,32 @@ declare module THREE { update(): void; } + export class VertexNormalsHelper extends Line { + constructor(object: Object3D, size?: number, hex?: number, linewidth?: number); + + size: number; + matrixAutoUpdate: boolean; + normalMatrix: Matrix3; + + update(object?: Object3D): void; + } + + export class VertexTangentsHelper extends Line { + constructor(object: Object3D, size?: number, hex?: number, linewidth?: number); + + size: number; + matrixAutoUpdate: boolean; + + update(object?: Object3D): void; + } + + export class WireframeHelper extends Line { + constructor(object: Object3D, hex?: number); + + matrixAutoUpdate: boolean; + matrixWorld: Matrix4; + } + // Extras / Objects ///////////////////////////////////////////////////////////////////// export class ImmediateRenderObject extends Object3D { diff --git a/urlrouter/urlrouter-tests.ts b/urlrouter/urlrouter-tests.ts new file mode 100644 index 000000000..c1411c3a3 --- /dev/null +++ b/urlrouter/urlrouter-tests.ts @@ -0,0 +1,19 @@ +/// + +import http = require("http"); +import urlrouter = require("urlrouter"); + +var result = urlrouter((app) => { + app.get('/', (req, res, next) => { + res.end('hello urlrouter'); + }); + app.get('/user/:id([0-9]+)', (req, res, next) => { + res.end('hello user ' + req.params.id); + }); +}); + +var req: urlrouter.ServerRequest; +var res: urlrouter.ServerResponse; +function next() { } + +result(req, res, next); \ No newline at end of file diff --git a/urlrouter/urlrouter.d.ts b/urlrouter/urlrouter.d.ts new file mode 100644 index 000000000..925484308 --- /dev/null +++ b/urlrouter/urlrouter.d.ts @@ -0,0 +1,69 @@ +// Type definitions for urlrouter +// Project: https://github.com/fengmk2/urlrouter +// Definitions by: soywiz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "_UrlRouterInternal" { + import http = require("http"); + + export interface ServerRequest extends http.ServerRequest { + params: any; + } + + export interface ServerResponse extends http.ServerResponse { + + } + + export interface App { + // https://github.com/visionmedia/node-methods/blob/master/index.js + get(urlpattern: string, handler: HttpHandler): void; + post(urlpattern: string, handler: HttpHandler): void; + put(urlpattern: string, handler: HttpHandler): void; + head(urlpattern: string, handler: HttpHandler): void; + delete(urlpattern: string, handler: HttpHandler): void; + options(urlpattern: string, handler: HttpHandler): void; + trace(urlpattern: string, handler: HttpHandler): void; + copy(urlpattern: string, handler: HttpHandler): void; + lock(urlpattern: string, handler: HttpHandler): void; + mkcol(urlpattern: string, handler: HttpHandler): void; + move(urlpattern: string, handler: HttpHandler): void; + propfind(urlpattern: string, handler: HttpHandler): void; + proppatch(urlpattern: string, handler: HttpHandler): void; + unlock(urlpattern: string, handler: HttpHandler): void; + report(urlpattern: string, handler: HttpHandler): void; + mkactivity(urlpattern: string, handler: HttpHandler): void; + checkout(urlpattern: string, handler: HttpHandler): void; + merge(urlpattern: string, handler: HttpHandler): void; + "m-search"(urlpattern: string, handler: HttpHandler): void; + notify(urlpattern: string, handler: HttpHandler): void; + subscribe(urlpattern: string, handler: HttpHandler): void; + unsubscribe(urlpattern: string, handler: HttpHandler): void; + patch(urlpattern: string, handler: HttpHandler): void; + search(urlpattern: string, handler: HttpHandler): void; + + all(urlpattern: string, handler: HttpHandler): void; + redirect(urlpattern: string, to: string): void; + } + + export interface Options { + paramsName?: string; + pageNotFound?: (req: ServerRequest, res: ServerResponse) => void; + errorHandler?: (err:Error, req: ServerRequest, res: ServerResponse) => void; + } + + export function _UrlRouterfunc(handler: (app: App) => void, options?: any): void; + + export interface HttpHandler { + (req: ServerRequest, res: ServerResponse, next?: () => void): void; + } + +} + +declare module "urlrouter" { + import _UrlRouterInternal = require("_UrlRouterInternal"); + + function _UrlRouterInternal(handler: (app: _UrlRouterInternal.App) => void): _UrlRouterInternal.HttpHandler; + export = _UrlRouterInternal; +} \ No newline at end of file diff --git a/vega/vega.d.ts b/vega/vega.d.ts index 29ed1ba15..ebe89da02 100644 --- a/vega/vega.d.ts +++ b/vega/vega.d.ts @@ -4,14 +4,11 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module Vega { - export interface VG { - parse: Parse; - } export interface Parse { spec(url: string, callback: (chart: (args: ViewArgs) => View) => void): void; spec(spec: Spec, callback: (chart: (args: ViewArgs) => View) => void): void; - data(dataSet: Vega.Data[], callback: () => void): void; + data(dataSet: Data[], callback: () => void): void; // TODO all the other stuff } @@ -39,14 +36,20 @@ declare module Vega { renderer(r: string): View; - data(): any; - data(d: any): View; + data(): Runtime.DataSets; + data(d: any/*TODO*/): View; - initialize(i: any): View; + initialize(selector: string): View; + initialize(node: Element): View; render(r?: any[]): View; update(options?: UpdateOptions): View; + + model(): Vega.Model; + + defs(): Defs; + defs(defs: Defs): View; } export interface Padding { @@ -65,6 +68,123 @@ declare module Vega { ease?: string; } + export interface Bounds { + x1: number; + y1: number; + x2: number; + y2: number; + clear(): Bounds; + set(x1: number, y1: number, x2: number, y2: number): Bounds; + add(x: number, y: number): Bounds; + expand(d: number): Bounds; + round(): Bounds; + translate(dx: number, dy: number): Bounds; + rotate(angle: number, x: number, y: number): Bounds; + union(b: Bounds): Bounds; + encloses(b: Bounds): boolean; + intersects(b: Bounds): boolean; + contains(x: number, y: number): boolean; + width(): number; + height(): number; + } + + export interface Model { + defs(): Defs; + defs(defs: Defs): Model; + + data(): Runtime.DataSets; + data(data: Runtime.DataSets): Model; + + ingest(name: string, tx: any/*TODO*/, input: any/*TODO*/): void; + + dependencies(name: string, tx: any/*TODO*/): void; + + width(w: number): Model; + + height(h: number): Model; + + scene(): Node; + scene(node: Node): Model; + + build(): Model; + + encode(trans?: any/*TODO*/, request?: string, item?: any): Model; + + reset(): Model; + } + + export module Runtime { + export interface DataSets { + [name: string]: Datum[]; + } + + export interface Datum { + [key: string]: any + } + + export interface Marks { + type: string; + width: number; + height: number; + scales: Scale[]; + axes: Axis[]; + legends: Legend[]; + marks: Mark[]; + } + + export interface Mark { + // Stuff from Spec.Mark + type: string; + name?: string; + description?: string; + from?: Mark.From; + key?: string; + delay?: Properties; + + // Runtime PropertySets + properties?: PropertySets; + } + + export interface PropertySets { + enter?: Properties; + exit?: Properties; + update?: Properties; + hover?: Properties; + } + + export interface Properties { + (item: Node, group: Node, trans: any/*TODO*/): void; + } + } + + export interface Node { + def: Runtime.Mark; + marktype: string; + interactive: boolean; + items: Node[]; + bounds: Bounds; + + // mark item members + hasPropertySet(name: string): boolean; + cousin(offset: number, index: number): Node; + sibling(offset: number): Node; + remove(): Node; + touch(): void; + + // group members + scales?: {[name: string]: any}; + axisItems?: Node[]; + } + + export interface Defs { + width: number; + height: number; + viewport?: number[]; + padding: any; + marks: Runtime.Marks; + data: Data[]; + } + export interface Spec { /** * A unique name for the visualization specification. @@ -227,12 +347,12 @@ declare module Vega { export module Axis { export interface Properties { - majorTicks?: Mark.PropertySet; - minorTicks?: Mark.PropertySet; - grid?: Mark.PropertySet; - labels?: Mark.PropertySet; - title?: Mark.PropertySet; - axis?: Mark.PropertySet; + majorTicks?: PropertySet; + minorTicks?: PropertySet; + grid?: PropertySet; + labels?: PropertySet; + title?: PropertySet; + axis?: PropertySet; } } @@ -246,9 +366,9 @@ declare module Vega { name?: string; description?: string; from?: Mark.From; - properties?: Mark.PropertySets; + properties?: PropertySets; key?: string; - delay?: Mark.ValueRef; + delay?: ValueRef; } export module Mark { @@ -257,80 +377,107 @@ declare module Vega { data?: string; transform?: Data.Transform[]; } + } - export interface PropertySets { - // TODO docs - enter?: PropertySet; - exit?: PropertySet; - update?: PropertySet; - hover?: PropertySet; - } + export interface PropertySets { + // TODO docs + enter?: PropertySet; + exit?: PropertySet; + update?: PropertySet; + hover?: PropertySet; + } - export interface PropertySet { - // TODO docs + export interface PropertySet { + // TODO docs - // -- Shared visual properties - x?: ValueRef; - x2?: ValueRef; - width?: ValueRef; - y?: ValueRef; - y2?: ValueRef; - height?: ValueRef; - opacity?: ValueRef; - fill?: ValueRef; - fillOpacity?: ValueRef; - stroke?: ValueRef; - strokeWidth?: ValueRef; - strokeOpacity?: ValueRef; - strokeDash?: ValueRef; - strokeDashOffset?: ValueRef; + // -- Shared visual properties + x?: ValueRef; + x2?: ValueRef; + width?: ValueRef; + y?: ValueRef; + y2?: ValueRef; + height?: ValueRef; + opacity?: ValueRef; + fill?: ValueRef; + fillOpacity?: ValueRef; + stroke?: ValueRef; + strokeWidth?: ValueRef; + strokeOpacity?: ValueRef; + strokeDash?: ValueRef; + strokeDashOffset?: ValueRef; - // -- symbol - size?: ValueRef; - shape?: ValueRef; + // -- symbol + size?: ValueRef; + shape?: ValueRef; - // -- path - path?: ValueRef; + // -- path + path?: ValueRef; - // -- arc - innerRadius?: ValueRef; - outerRadius?: ValueRef; - startAngle?: ValueRef; - endAngle?: ValueRef; + // -- arc + innerRadius?: ValueRef; + outerRadius?: ValueRef; + startAngle?: ValueRef; + endAngle?: ValueRef; - // -- area / line - interpolate?: ValueRef; - tension?: ValueRef; + // -- area / line + interpolate?: ValueRef; + tension?: ValueRef; - // -- image / text - align?: ValueRef; - baseline?: ValueRef; + // -- image / text + align?: ValueRef; + baseline?: ValueRef; - // -- image - url?: ValueRef; + // -- image + url?: ValueRef; - // -- text - text?: ValueRef; - dx?: ValueRef; - dy?: ValueRef; - angle?: ValueRef; - font?: ValueRef; - fontSize?: ValueRef; - fontWeight?: ValueRef; - fontStyle?: ValueRef; - } + // -- text + text?: ValueRef; + dx?: ValueRef; + dy?: ValueRef; + angle?: ValueRef; + font?: ValueRef; + fontSize?: ValueRef; + fontWeight?: ValueRef; + fontStyle?: ValueRef; + } - export interface ValueRef { - // TODO docs - value?: any; - field?: any; - group?: any; - scale?: any; - mult?: number; - offset?: number; - band?: boolean; - } + export interface ValueRef { + // TODO docs + value?: any; + field?: any; + group?: any; + scale?: any; + mult?: number; + offset?: number; + band?: boolean; } } -declare var vg: Vega.VG; \ No newline at end of file +declare module vg { + export var parse: Vega.Parse; + export module scene { + export function item(mark: Vega.Node): Vega.Node; + } + + export class Bounds implements Vega.Bounds { + x1: number; + y1: number; + x2: number; + y2: number; + clear(): Bounds; + set(x1: number, y1: number, x2: number, y2: number): Bounds; + add(x: number, y: number): Bounds; + expand(d: number): Bounds; + round(): Bounds; + translate(dx: number, dy: number): Bounds; + rotate(angle: number, x: number, y: number): Bounds; + union(b: Bounds): Bounds; + encloses(b: Bounds): boolean; + intersects(b: Bounds): boolean; + contains(x: number, y: number): boolean; + width(): number; + height(): number; + } + + // TODO: classes for View, Model, etc. +} \ No newline at end of file diff --git a/zeroclipboard/zeroclipboard.d.ts b/zeroclipboard/zeroclipboard.d.ts index 847593df8..b8f0ebb92 100644 --- a/zeroclipboard/zeroclipboard.d.ts +++ b/zeroclipboard/zeroclipboard.d.ts @@ -2,40 +2,77 @@ // Project: https://github.com/jonrohan/ZeroClipboard // Definitions by: Eric J. Smith // Definitions by: Blake Niemyjski +// Definitions by: György Balássy // Definitions: https://github.com/borisyankov/DefinitelyTyped declare class ZeroClipboard { constructor(elements?: any, options?: ZeroClipboardOptions); - setCurrent(element: any): void; + activate(element: any): void; setText(newText: string): void; - setTitle(newTitle: string): void; + title(newTitle: string): void; setSize(width: number, height: number): void; - setHandCursor(enabled: boolean): void; + forceHandCursor(enabled: boolean): void; version: string; moviePath: string; trustedDomains: any; text: string; hoverClass: string; activeClass: string; - resetBridge(): void; + deactivate(): void; ready: boolean; reposition(): void; // returns false in some scenarios, but never returns true on(eventName: string, func: Function): void; - addEventListener(eventName: string, func: Function): void; off(eventName: string, func: Function): void; - removeEventListener(eventName: string, func: Function): void; - receiveEvent(eventName: string, args: any): void; - glue(elements: any): void; - unglue(elements: any): void; - static setDefaults(options: ZeroClipboardOptions): void; + clip(elements: any): void; + unclip(elements: any): void; + static config(options: ZeroClipboardOptions): void; static destroy(): void; - static detectFlashSupport(): boolean; - static dispatch(eventName: string, args: any): void; + static emit(eventName: string, args: any): void; } interface ZeroClipboardOptions { + /** Setting this to false would allow users to handle calling ZeroClipboard.activate(...); themselves instead of relying on our per-element mouseover handler */ + autoActivate?: boolean; + + /** Include a "nocache" query parameter on requests for the SWF. */ + cacheBust?: boolean; + + /** Debug enabled: send console messages with deprecation warnings, etc. */ + debug?: boolean; + + /** Forcibly set the hand cursor ("pointer") for all clipped elements. */ + forceHandCursor?: boolean; + + /** URL to the movie. NOTE: For versions >= v1.3.x and < v2.x, you must use swfPath by setting moviePath! */ moviePath?: string; + + /** URL to the movie, relative to the page. NOTE: For versions >= v1.3.x and < v2.x, you must use swfPath by setting moviePath! */ + swfPath?: string; + + /** Forcibly set the hand cursor ("pointer") for all clipped elements. */ trustedDomains?: any; - hoverClass?: string; + + /** Sets the title of the div encapsulating the Flash object. */ + title?: string; + + /** The z-index used by the Flash object. */ + zIndex?: number; + + /** DEPRECATED. The class used to indicate that a clipped element is active (is being clicked). */ activeClass?: string; + + /** DEPRECATED. The class used to indicate that a clipped element is being hovered over. */ + hoverClass?: string; + + /** DEPRECATED. SWF outbound scripting policy. Possible values: "never", "sameDomain", "always". */ + allowScriptAccess?: string; + + /** DEPRECATED, use trustedDomains instead! SWF inbound scripting policy: page origins that the SWF should trust. (single string or array of strings. */ + trustedOrigins?: any; + + /** DEPRECATED, use cacheBust instead! Include a "nocache" query parameter on requests for the SWF. */ + useNoCache?: boolean; } + +// Support AMD. +declare module "zeroclipboard" { export = ZeroClipboard; }