diff --git a/README.md b/README.md index 3484db60d..2d552bfc1 100755 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ List of Definitions * [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone)) * [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame)) * [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei)) +* [Flight by Twitter](http://flightjs.github.com/flight/) (by [Jonathan Hedrén](https://github.com/jonathanhedren)) * [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov)) * [FPSMeter](http://darsa.in/fpsmeter/) (by [Aaron Lampros](https://github.com/alampros)) * [FullCalendar](http://arshaw.com/fullcalendar/) (by [Neil Stalker](https://github.com/nestalk)) @@ -75,8 +76,9 @@ List of Definitions * [Giraffe](https://github.com/barc/backbone.giraffe) (by [Matt McCray](https://github.com/darthapo)) * [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dániel Tar](https://github.com/qcz)) * [GoJS](http://gojs.net/) (by [Barbara Duckworth](https://github.com/barbara42)) +* [Greasemonkey](http://www.greasespot.net/) (by [Kota Saito](https://github.com/kotas)) * [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt)) -* [Grunt JS](http://gruntjs.com/) (by [Basarat Ali Syed](https://github.com/basarat)) +* [Grunt JS](http://gruntjs.com/) (by [Jeff May](https://github.com/jeffmay) and [Basarat Ali Syed](https://github.com/basarat)) * [Google API Client](https://code.google.com/p/google-api-javascript-client/) (by [Frank M](https://github.com/sgtfrankieboy)) * [Google App Engine Channel API](https://developers.google.com/appengine/docs/java/channel/javascript) (by [vvakame](https://github.com/vvakame)) * [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper)) @@ -93,7 +95,6 @@ List of Definitions * [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter)) * [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz)) * [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov)) -* [Intl](http://www.ecma-international.org/ecma-402/1.0/) (by [Jeffery Grajkowski](http://github.com/pushplay)) * [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski)) * [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/)) * [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov)) @@ -107,9 +108,10 @@ List of Definitions * [jQuery.areYouSure](https://github.com/codedance/jquery.AreYouSure) (by [Jon Egerton](https://github.com/jonegerton)) * [jQuery.autosize](http://www.jacklmoore.com/autosize/) (by [Jack Moore](http://www.jacklmoore.com/)) * [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos)) -* [jQuery.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/)) +* [jQuery.CLEditor](http://premiumsoftware.net/CLEditor) (by [Jeffery Grajkowski](https://github.com/pushplay)) * [jQuery.clientSideLogging](https://github.com/remybach/jQuery.clientSideLogging/) (by [Diullei Gomes](https://github.com/diullei/)) * [jQuery.Colorbox](http://www.jacklmoore.com/colorbox/) (by [Gidon Junge](https://github.com/gjunge)) +* [jQuery.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/)) * [jQuery.Cookie](https://github.com/carhartl/jquery-cookie) (by [Roy Goode](https://github.com/RoyGoode)) * [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [François Guillot](http://fguillot.developpez.com/)) * [jQuery.dataTables](http://www.datatables.net) (by [Armin Sander](https://github.com/pragmatrix)) @@ -133,6 +135,7 @@ List of Definitions * [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)) +* [jQuery.base64](https://github.com/yatt/jquery.base64) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki)) * [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz)) * [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk)) * [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/)) @@ -145,7 +148,7 @@ List of Definitions * [Knockout.ES5](https://github.com/SteveSanderson/knockout-es5) (by [Sebastián Galiano](https://github.com/sgaliano)) * [Knockout.Mapper](https://github.com/LucasLorentz/knockout.mapper) (by [Brandon Meyer](https://github.com/BMeyerKC)) * [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) (by [Boris Yankov](https://github.com/borisyankov)) -* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel](https://github.com/JudahGabriel)) +* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel Himango](https://github.com/JudahGabriel)) * [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig)) * [Knockout.Viewmodel](http://coderenaissance.github.com/knockout.viewmodel/) (by [Oisin Grehan](https://github.com/oising)) * [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising)) @@ -156,6 +159,7 @@ List of Definitions * [Levelup](https://github.com/rvagg/node-levelup) (by [Bret Little](https://github.com/blittle)) * [linq.js](http://linqjs.codeplex.com/) (by [Marcin Najder](https://github.com/marcinnajder)) * [Livestamp.js](https://github.com/mattbradley/livestampjs) (by [Vincent Bortone](https://github.com/vbortone)) +* [Lodash](http://lodash.com/) (by [Brian Zengel](https://github.com/bczengel)) * [Logg](https://github.com/dpup/node-logg) (by [Bret Little](https://github.com/blittle)) * [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr)) * [mCustomScrollbar](https://github.com/malihu/malihu-custom-scrollbar-plugin) (by [Sarah Williams] (https://github.com/flurg)) @@ -170,7 +174,9 @@ List of Definitions * [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd)) * [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown)) * [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov)) +* [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel)) * [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/)) +* [OpenLayers] (https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/)) * [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin)) * [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin)) * [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto)) @@ -238,7 +244,6 @@ Requested Definitions * [google.visualizations](https://developers.google.com/chart/) * [Prelude.ls](http://gkz.github.com/prelude-ls/) * [MooTools](http://mootools.net/) -* [Lo-Dash](http://lodash.com/) * [java](https://github.com/nearinfinity/node-java) * [SVG.js](http://www.svgjs.com/) diff --git a/_infrastructure/tests/compile-runner.bat b/_infrastructure/tests/compile-runner.bat new file mode 100644 index 000000000..53e014841 --- /dev/null +++ b/_infrastructure/tests/compile-runner.bat @@ -0,0 +1 @@ +tsc runner.ts --out runner.js --module commonjs \ No newline at end of file diff --git a/_infrastructure/tests/runner.js b/_infrastructure/tests/runner.js index fd926bcb1..3721f7e11 100644 --- a/_infrastructure/tests/runner.js +++ b/_infrastructure/tests/runner.js @@ -552,10 +552,11 @@ else if (typeof require === "function") else return null; })(); -/// -/// var DefinitelyTyped; (function (DefinitelyTyped) { + /// + /// + /// (function (TestManager) { var path = require('path'); @@ -614,6 +615,10 @@ var DefinitelyTyped; return Typing; })(); + ///////////////////////////////// + // Given a document root + ts file pattern this class returns: + // all the TS files OR just tests OR just definition files + ///////////////////////////////// var FileHandler = (function () { function FileHandler(path, pattern) { this.path = path; @@ -659,6 +664,10 @@ var DefinitelyTyped; return FileHandler; })(); + ///////////////////////////////// + // Timer.start starts a timer + // Timer.end stops the timer and sets asString to the pretty print value + ///////////////////////////////// var Timer = (function () { function Timer() { this.time = 0; @@ -688,6 +697,9 @@ var DefinitelyTyped; return Timer; })(); + ///////////////////////////////// + // All the common things that we pring are functions of this class + ///////////////////////////////// var Print = (function () { function Print(version, typings, tsFiles) { this.version = version; @@ -707,19 +719,19 @@ var DefinitelyTyped; this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); }; - Print.prototype.printSyntaxChecking = function () { + Print.prototype.printSyntaxCheckingHeader = function () { this.out('============================ \33[34m\33[1mSyntax checking\33[0m ================================\n'); }; - Print.prototype.printTypingTests = function () { + Print.prototype.printTypingTestsHeader = function () { this.out('============================= \33[34m\33[1mTyping tests\33[0m ==================================\n'); }; - Print.prototype.printSuccess = function () { + Print.prototype.printSuccessCharacter = function () { this.out('\33[36m\33[1m.\33[0m'); }; - Print.prototype.printFailure = function () { + Print.prototype.printFailureCharacter = function () { this.out('x'); }; @@ -727,6 +739,23 @@ var DefinitelyTyped; this.out('-----------------------------------------------------------------------------\n'); }; + Print.prototype.printBoldDiv = function () { + this.out('=============================================================================\n'); + }; + + Print.prototype.printErrorsHeader = function () { + this.out('=============================================================================\n'); + this.out(' \33[34m\33[1mErrors in files\33[0m \n'); + this.out('=============================================================================\n'); + }; + + Print.prototype.printErrorsForFile = function (file) { + this.out('----------------- For file:' + file.formatName()); + this.printBreak(); + this.out(file.execResult.stderr); + this.printBreak(); + }; + Print.prototype.printfilesWithSintaxErrorMessage = function () { this.out(' \33[36m\33[1mFiles with syntax error\33[0m\n'); }; @@ -751,7 +780,7 @@ var DefinitelyTyped; this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); }; - Print.prototype.breack = function () { + Print.prototype.printBreak = function () { this.out('\n'); }; @@ -781,22 +810,30 @@ var DefinitelyTyped; return Print; })(); + ///////////////////////////// + // Represents the results of a test file execution + ///////////////////////////// var File = (function () { - function File(name, hasError) { - this.name = name; - this.hasError = hasError; + function File(baseDir, filePathWithName, execResult) { + this.baseDir = baseDir; + this.filePathWithName = filePathWithName; + this.execResult = execResult; } - File.prototype.formatName = function (baseDir) { - var dirName = path.dirname(this.name.substr(baseDir.length + 1)).replace('\\', '/'); + // From '/complete/path/to/file' to 'specfolder/specfile.d.ts' + File.prototype.formatName = function () { + var dirName = path.dirname(this.filePathWithName.substr(this.baseDir.length + 1)).replace('\\', '/'); var dir = dirName.split('/')[0]; - var file = path.basename(this.name, '.ts'); - var ext = path.extname(this.name); + var file = path.basename(this.filePathWithName, '.ts'); + var ext = path.extname(this.filePathWithName); return dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + '\33[36m\33[1m' + file + '\33[0m' + ext; }; return File; })(); + ///////////////////////////// + // Determine syntax errors in typings + ///////////////////////////// var SyntaxChecking = (function () { function SyntaxChecking(fileHandler, out) { this.fileHandler = fileHandler; @@ -808,7 +845,7 @@ var DefinitelyTyped; var list = []; for (var i = 0; i < this.files.length; i++) { - if (this.files[i].hasError) { + if (this.files[i].execResult.exitCode) { list.push(this.files[i]); } } @@ -820,7 +857,7 @@ var DefinitelyTyped; var list = []; for (var i = 0; i < this.files.length; i++) { - if (!this.files[i].hasError) { + if (!this.files[i].execResult.exitCode) { list.push(this.files[i]); } } @@ -845,7 +882,7 @@ var DefinitelyTyped; for (var i = 0; i < this.getFailedFiles().length; i++) { var errorFile = this.getFailedFiles()[i]; - this.out.printErrorFile(errorFile.formatName(this.fileHandler.path)); + this.out.printErrorFile(errorFile.formatName()); } } }; @@ -853,29 +890,26 @@ var DefinitelyTyped; SyntaxChecking.prototype.run = function (it, file, len, maxLen, callback) { var _this = this; if (!endsWith(file.toUpperCase(), '-TESTS.TS') && endsWith(file.toUpperCase(), '.TS') && file.indexOf('../_infrastructure') < 0) { - new Test(file).run(function (o) { - var failed = false; - - if (o.exitCode === 1) { - _this.out.printFailure(); - failed = true; + new Test(file).run(function (execResult) { + if (execResult.exitCode === 1) { + _this.out.printFailureCharacter(); len++; } else { - _this.out.printSuccess(); + _this.out.printSuccessCharacter(); len++; } - _this.files.push(new File(file, failed)); + _this.files.push(new File(_this.fileHandler.path, file, execResult)); if (len > maxLen) { len = 0; - _this.out.breack(); + _this.out.printBreak(); } if (it.hasNext()) { _this.run(it, it.next(), len, maxLen, callback); } else { - _this.out.breack(); + _this.out.printBreak(); _this.timer.end(); _this.printFailedFiles(); _this.printStats(); @@ -886,7 +920,7 @@ var DefinitelyTyped; } else if (it.hasNext()) { this.run(it, it.next(), len, maxLen, callback); } else { - this.out.breack(); + this.out.printBreak(); this.timer.end(); this.printStats(); this.printFailedFiles(); @@ -912,6 +946,9 @@ var DefinitelyTyped; return SyntaxChecking; })(); + ///////////////////////////// + // Determines errors in typing tests + ///////////////////////////// var TestEval = (function () { function TestEval(fileHandler, out) { this.fileHandler = fileHandler; @@ -923,7 +960,7 @@ var DefinitelyTyped; var list = []; for (var i = 0; i < this.files.length; i++) { - if (this.files[i].hasError) { + if (this.files[i].execResult.exitCode) { list.push(this.files[i]); } } @@ -935,7 +972,7 @@ var DefinitelyTyped; var list = []; for (var i = 0; i < this.files.length; i++) { - if (!this.files[i].hasError) { + if (!this.files[i].execResult.exitCode) { list.push(this.files[i]); } } @@ -960,7 +997,7 @@ var DefinitelyTyped; for (var i = 0; i < this.getFailedFiles().length; i++) { var errorFile = this.getFailedFiles()[i]; - this.out.printErrorFile(errorFile.formatName(this.fileHandler.path)); + this.out.printErrorFile(errorFile.formatName()); } } }; @@ -968,29 +1005,26 @@ var DefinitelyTyped; TestEval.prototype.run = function (it, file, len, maxLen, callback) { var _this = this; if (endsWith(file.toUpperCase(), '-TESTS.TS')) { - new Test(file).run(function (o) { - var failed = false; - - if (o.exitCode === 1) { - _this.out.printFailure(); - failed = true; + new Test(file).run(function (execResult) { + if (execResult.exitCode === 1) { + _this.out.printFailureCharacter(); len++; } else { - _this.out.printSuccess(); + _this.out.printSuccessCharacter(); len++; } - _this.files.push(new File(file, failed)); + _this.files.push(new File(_this.fileHandler.path, file, execResult)); if (len > maxLen) { len = 0; - _this.out.breack(); + _this.out.printBreak(); } if (it.hasNext()) { _this.run(it, it.next(), len, maxLen, callback); } else { - _this.out.breack(); + _this.out.printBreak(); _this.timer.end(); _this.printFailedFiles(); _this.printStats(); @@ -1001,7 +1035,7 @@ var DefinitelyTyped; } else if (it.hasNext()) { this.run(it, it.next(), len, maxLen, callback); } else { - this.out.breack(); + this.out.printBreak(); this.timer.end(); this.printFailedFiles(); this.printStats(); @@ -1027,6 +1061,9 @@ var DefinitelyTyped; return TestEval; })(); + ///////////////////////////////// + // The main class to kick things off + ///////////////////////////////// var TestRunner = (function () { function TestRunner(dtPath) { this.dtPath = dtPath; @@ -1065,19 +1102,41 @@ var DefinitelyTyped; return count; }; + TestRunner.prototype.printErrorsDetected = function () { + var _this = this; + this.out.printErrorsHeader(); + + var printErrorsForFileIfFound = function (file) { + if (file.execResult.exitCode) + _this.out.printErrorsForFile(file); + }; + + // sc errors: + this.sc.files.forEach(printErrorsForFileIfFound); + this.out.printBoldDiv(); + + // te errors: + this.te.files.forEach(printErrorsForFileIfFound); + this.out.printBoldDiv(); + }; + TestRunner.prototype.run = function () { var _this = this; var timer = new Timer(); timer.start(); this.out.printHeader(); - this.out.printSyntaxChecking(); + // Run syntax tests + this.out.printSyntaxCheckingHeader(); this.sc.start(function (syntaxFailedCount, syntaxTotal) { - _this.out.printTypingTests(); + // Now run typing tests + _this.out.printTypingTestsHeader(); _this.te.start(function (testFailedCount, testTotal) { - var total = _this.printTypingsWithoutTest(); + // Get the tests without any typing and simultaneously print their names + var totalTypingsWithoutTest = _this.printTypingsWithoutTest(); + // End total timer and print final messages timer.end(); _this.out.printDiv(); @@ -1087,11 +1146,12 @@ var DefinitelyTyped; _this.out.printElapsedTime(timer.asString, timer.time); _this.out.printSyntaxErrorCount(syntaxFailedCount, syntaxTotal); _this.out.printTestErrorCount(testFailedCount, testTotal); - _this.out.printWithoutTestCount(total, _this.fh.allTypings().length); + _this.out.printWithoutTestCount(totalTypingsWithoutTest, _this.fh.allTypings().length); _this.out.printDiv(); if (syntaxFailedCount > 0 || testFailedCount > 0) { + _this.printErrorsDetected(); process.exit(1); } }); diff --git a/_infrastructure/tests/runner.ts b/_infrastructure/tests/runner.ts index 68e5f36ba..68682f536 100644 --- a/_infrastructure/tests/runner.ts +++ b/_infrastructure/tests/runner.ts @@ -1,562 +1,626 @@ -/// +/// + +/// /// -module DefinitelyTyped { - - export module TestManager { - - var path = require('path'); - - function endsWith(str, suffix) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; - } - - class Iterator { - index: number = -1; - - constructor(public list: any[]){} - - public next() { - this.index++; - return this.list[this.index]; - } - - public hasNext() { - return this.list[1 + this.index] != null; - } - } - - class Tsc { - public static run(tsfile: string, callback: Function) { - var command = 'node ./_infrastructure/tests/typescript/tsc.js --module commonjs '; - if (IO.fileExists(tsfile + '.tscparams')) { - command += '@' + tsfile + '.tscparams'; - } else { - command += '--noImplicitAny'; - } - Exec.exec(command, [tsfile], (ExecResult) => { - callback(ExecResult); - }); - } - } - - class Test { - constructor(public tsfile: string) {} - - public run(callback: Function) { - Tsc.run(this.tsfile , callback); - } - } - - class Typing { - public fileHandler: FileHandler; - - constructor(public name: string, baseDir: string) { - this.fileHandler = new FileHandler(baseDir + '/' + name + '/', /.\.ts/g); - } - } - - class FileHandler { - public files: string[] = []; - public typings: Typing[] = []; - - constructor(public path: string, pattern: any) { - this.files = IO.dir(path, pattern, { recursive: true }).sort(); - } - - public allTS(): string[] { - return this.files; - } - - public allTests(): string[] { - var tests = []; - - for(var i = 0; i < this.files.length; i++) { - if (endsWith(this.files[i].toUpperCase(), '-TESTS.TS')) { - tests.push(this.files[i]); - } - } - - return tests; - } - - public allTypings(): string[] { - var typings = {}; - - for(var i = 0; i < this.files.length; i++) { - var file = this.files[i]; - var firName = path.dirname(file.substr(this.path.length + 1)).replace('\\', '/'); - var dir = firName.split('/')[0]; - - if(!typings[dir]) typings[dir] = true; - } - - var list = []; - for(var attr in typings) { - list.push(attr); - } - - return list; - } - } - - class Timer { - public startTime; - public time = 0; - public asString: string; - - private static prettyDate(date1, date2): string { - var diff = ((date2 - date1) / 1000), - day_diff = Math.floor(diff / 86400); - - if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ) - return; - - return (day_diff == 0 && ( - diff < 60 && (diff + " seconds") || - diff < 120 && "1 minute" || - diff < 3600 && Math.floor( diff / 60 ) + " minutes" || - diff < 7200 && "1 hour" || - diff < 86400 && Math.floor( diff / 3600 ) + " hours") || - day_diff == 1 && "Yesterday" || - day_diff < 7 && day_diff + " days" || - day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks"); - } - - public start() { - this.time = 0; - this.startTime = this.now(); - } - - private now() { - return Date.now(); - } - - public end() { - this.time = (this.now() - this.startTime) / 1000; - this.asString = Timer.prettyDate(this.startTime, this.now()); - } - } - - class Print { - constructor(public version: string, public typings: number, public tsFiles: number) { } - - public out(s) { - process.stdout.write(s); - } - - public printHeader() { - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.3.0\33[0m\n'); - this.out('=============================================================================\n'); - this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); - this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); - this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); - } - - public printSyntaxChecking() { - this.out('============================ \33[34m\33[1mSyntax checking\33[0m ================================\n'); - } - - public printTypingTests() { - this.out('============================= \33[34m\33[1mTyping tests\33[0m ==================================\n'); - } - - public printSuccess() { - this.out('\33[36m\33[1m.\33[0m'); - } - - public printFailure() { - this.out('x'); - } - - public printDiv() { - this.out('-----------------------------------------------------------------------------\n'); - } - - public printfilesWithSintaxErrorMessage() { - this.out(' \33[36m\33[1mFiles with syntax error\33[0m\n'); - } - - public printFailedTestMessage() { - this.out(' \33[36m\33[1mFailed tests\33[0m\n'); - } - - public printTypingsWithoutTestsMessage() { - this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); - } - - public printTotalMessage() { - this.out(' \33[36m\33[1mTotal\33[0m\n'); - } - - public printErrorFile(file) { - this.out(' - ' + file + '\n'); - } - - public printTypingsWithoutTest(file) { - this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); - } - - public breack() { - this.out('\n'); - } - - public printSuccessCount(current: number, total: number) { - this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printFailedCount(current: number, total: number) { - this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printElapsedTime(time, s) { - this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); - } - - public printSyntaxErrorCount(current: number, total: number) { - this.out(' \33[36m\33[1mSyntax error :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printTestErrorCount(current: number, total: number) { - this.out(' \33[36m\33[1mFailed tests :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - - public printWithoutTestCount(current: number, total: number) { - this.out(' \33[36m\33[1mWithout tests :\33[0m \33[33m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); - } - } - - class File { - - constructor(public name: string, public hasError: boolean) {} - - public formatName(baseDir: string): string { - var dirName = path.dirname(this.name.substr(baseDir.length + 1)).replace('\\', '/'); - var dir = dirName.split('/')[0]; - var file = path.basename(this.name, '.ts'); - var ext = path.extname(this.name); - - return dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + '\33[36m\33[1m' + file + '\33[0m' + ext; - } - } - - class SyntaxChecking { - - private timer: Timer; - - public files: File[] = []; - - private getFailedFiles(): File[] { - var list: File[] = []; - - for(var i = 0; i < this.files.length; i++) { - if(this.files[i].hasError) { - list.push(this.files[i]); - } - } - - return list; - } - - private getSuccessFiles(): File[] { - var list: File[] = []; - - for(var i = 0; i < this.files.length; i++) { - if(!this.files[i].hasError) { - list.push(this.files[i]); - } - } - - return list; - } - - constructor(public fileHandler: FileHandler, public out: Print) { - this.timer = new Timer(); - } - - private printStats() { - this.out.printDiv(); - this.out.printElapsedTime(this.timer.asString, this.timer.time); - this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); - this.out.printFailedCount(this.getFailedFiles().length, this.files.length); - } - - private printFailedFiles() { - if (this.getFailedFiles().length > 0) { - this.out.printDiv(); - - this.out.printfilesWithSintaxErrorMessage(); - - this.out.printDiv(); - - for(var i = 0; i < this.getFailedFiles().length; i++) { - var errorFile = this.getFailedFiles()[i]; - this.out.printErrorFile(errorFile.formatName(this.fileHandler.path)); - } - } - } - - private run(it, file, len, maxLen, callback: Function) { - if (!endsWith(file.toUpperCase(), '-TESTS.TS') && endsWith(file.toUpperCase(), '.TS') && file.indexOf('../_infrastructure') < 0) { - new Test(file).run((o) => { - var failed = false; - - if(o.exitCode === 1) { - this.out.printFailure(); - failed = true; - len++; - } else { - this.out.printSuccess(); - len++; - } - - this.files.push(new File(file, failed)); - - if(len > maxLen) { - len = 0; - this.out.breack(); - } - - if (it.hasNext()) { - this.run(it, it.next(), len, maxLen, callback); - } else { - this.out.breack(); - this.timer.end(); - this.printFailedFiles(); - this.printStats(); - - callback(this.getFailedFiles().length, this.files.length); - } - }); - } else if (it.hasNext()) { - this.run(it, it.next(), len, maxLen, callback); - } else { - this.out.breack(); - this.timer.end(); - this.printStats(); - this.printFailedFiles(); - - callback(this.getFailedFiles().length, this.files.length); - } - } - - public start(callback: Function) { - this.timer.start(); - - var tsFiles = this.fileHandler.allTS(); - - var it = new Iterator(tsFiles); - - var len = 0; - var maxLen = 76; - - if (it.hasNext()) { - this.run(it, it.next(), len, maxLen, callback); - } - } - } - - class TestEval { - - private timer: Timer; - - public files: File[] = []; - - private getFailedFiles(): File[] { - var list: File[] = []; - - for(var i = 0; i < this.files.length; i++) { - if(this.files[i].hasError) { - list.push(this.files[i]); - } - } - - return list; - } - - private getSuccessFiles(): File[] { - var list: File[] = []; - - for(var i = 0; i < this.files.length; i++) { - if(!this.files[i].hasError) { - list.push(this.files[i]); - } - } - - return list; - } - - constructor(public fileHandler: FileHandler, public out: Print) { - this.timer = new Timer(); - } - - private printStats() { - this.out.printDiv(); - this.out.printElapsedTime(this.timer.asString, this.timer.time); - this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); - this.out.printFailedCount(this.getFailedFiles().length, this.files.length); - } - - private printFailedFiles() { - if (this.getFailedFiles().length > 0) { - this.out.printDiv(); - - this.out.printFailedTestMessage(); - - this.out.printDiv(); - - for(var i = 0; i < this.getFailedFiles().length; i++) { - var errorFile = this.getFailedFiles()[i]; - this.out.printErrorFile(errorFile.formatName(this.fileHandler.path)); - } - } - } - - private run(it, file, len, maxLen, callback: Function) { - if (endsWith(file.toUpperCase(), '-TESTS.TS')) { - new Test(file).run((o) => { - var failed = false; - - if(o.exitCode === 1) { - this.out.printFailure(); - failed = true; - len++; - } else { - this.out.printSuccess(); - len++; - } - - this.files.push(new File(file, failed)); - - if(len > maxLen) { - len = 0; - this.out.breack(); - } - - if (it.hasNext()) { - this.run(it, it.next(), len, maxLen, callback); - } else { - this.out.breack(); - this.timer.end(); - this.printFailedFiles(); - this.printStats(); - - callback(this.getFailedFiles().length, this.files.length); - } - }); - } else if (it.hasNext()) { - this.run(it, it.next(), len, maxLen, callback); - } else { - this.out.breack(); - this.timer.end(); - this.printFailedFiles(); - this.printStats(); - - callback(this.getFailedFiles().length, this.files.length); - } - } - - public start(callback: Function) { - this.timer.start(); - - var tsFiles = this.fileHandler.allTS(); - - var it = new Iterator(tsFiles); - - var len = 0; - var maxLen = 76; - - if (it.hasNext()) { - this.run(it, it.next(), len, maxLen, callback); - } - } - } - - export class TestRunner { - private fh: FileHandler; - private out: Print; - private sc: SyntaxChecking; - private te: TestEval; - private typings: Typing[] = []; - - private printTypingsWithoutTest() { - var count = 0; - - if (this.typings.length > 0) { - this.out.printDiv(); - - this.out.printTypingsWithoutTestsMessage(); - - this.out.printDiv(); - - for(var i = 0; i < this.typings.length; i++) { - var typing = this.typings[i]; - if(typing.fileHandler.allTests().length == 0) { - if (typing.name != '_infrastructure' - && typing.name != '_ReSharper.DefinitelyTyped' - && typing.name != 'obj' - && typing.name != 'bin' - && typing.name != 'Properties') { - this.out.printTypingsWithoutTest(typing.name); - count++; - } - } - } - } - - return count; - } - - constructor(public dtPath: string) { - this.fh = new FileHandler(dtPath, /.\.ts/g); - this.out = new Print('0.9.1.1', this.fh.allTypings().length, this.fh.allTS().length); - this.sc = new SyntaxChecking(this.fh, this.out); - this.te = new TestEval(this.fh, this.out); - - var tpgs = this.fh.allTypings(); - for(var i = 0; i < tpgs.length; i++) { - this.typings.push(new Typing(tpgs[i], this.dtPath)); - } - } - - public run() { - var timer = new Timer(); - timer.start(); - - this.out.printHeader(); - this.out.printSyntaxChecking(); - - this.sc.start((syntaxFailedCount, syntaxTotal) => { - this.out.printTypingTests(); - this.te.start((testFailedCount, testTotal) => { - var total = this.printTypingsWithoutTest(); - - timer.end(); - - this.out.printDiv(); - this.out.printTotalMessage(); - this.out.printDiv(); - - this.out.printElapsedTime(timer.asString, timer.time); - this.out.printSyntaxErrorCount(syntaxFailedCount, syntaxTotal); - this.out.printTestErrorCount(testFailedCount, testTotal); - this.out.printWithoutTestCount(total, this.fh.allTypings().length); - - this.out.printDiv(); - - if (syntaxFailedCount > 0 || testFailedCount > 0) { - process.exit(1); - } - }); - }); - } - } - } +module DefinitelyTyped.TestManager { + + var path = require('path'); + + function endsWith(str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + } + + class Iterator { + index: number = -1; + + constructor(public list: any[]) { } + + public next() { + this.index++; + return this.list[this.index]; + } + + public hasNext() { + return this.list[1 + this.index] != null; + } + } + + interface TscCallback { + (result: ExecResult): void; + } + + class Tsc { + public static run(tsfile: string, callback: TscCallback) { + var command = 'node ./_infrastructure/tests/typescript/tsc.js --module commonjs '; + if (IO.fileExists(tsfile + '.tscparams')) { + command += '@' + tsfile + '.tscparams'; + } else { + command += '--noImplicitAny'; + } + Exec.exec(command, [tsfile], (ExecResult) => { + callback(ExecResult); + }); + } + } + + class Test { + constructor(public tsfile: string) { } + + public run(callback: TscCallback) { + Tsc.run(this.tsfile, callback); + } + } + + class Typing { + public fileHandler: FileHandler; + + constructor(public name: string, baseDir: string) { + this.fileHandler = new FileHandler(baseDir + '/' + name + '/', /.\.ts/g); + } + } + + ///////////////////////////////// + // Given a document root + ts file pattern this class returns: + // all the TS files OR just tests OR just definition files + ///////////////////////////////// + class FileHandler { + public files: string[] = []; + public typings: Typing[] = []; + + constructor(public path: string, pattern: any) { + this.files = IO.dir(path, pattern, { recursive: true }).sort(); + } + + public allTS(): string[] { + return this.files; + } + + public allTests(): string[] { + var tests = []; + + for (var i = 0; i < this.files.length; i++) { + if (endsWith(this.files[i].toUpperCase(), '-TESTS.TS')) { + tests.push(this.files[i]); + } + } + + return tests; + } + + public allTypings(): string[] { + var typings = {}; + + for (var i = 0; i < this.files.length; i++) { + var file = this.files[i]; + var firName = path.dirname(file.substr(this.path.length + 1)).replace('\\', '/'); + var dir = firName.split('/')[0]; + + if (!typings[dir]) typings[dir] = true; + } + + var list = []; + for (var attr in typings) { + list.push(attr); + } + + return list; + } + } + + ///////////////////////////////// + // Timer.start starts a timer + // Timer.end stops the timer and sets asString to the pretty print value + ///////////////////////////////// + class Timer { + public startTime; + public time = 0; + public asString: string; + + private static prettyDate(date1, date2): string { + var diff = ((date2 - date1) / 1000), + day_diff = Math.floor(diff / 86400); + + if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) + return; + + return (day_diff == 0 && ( + diff < 60 && (diff + " seconds") || + diff < 120 && "1 minute" || + diff < 3600 && Math.floor(diff / 60) + " minutes" || + diff < 7200 && "1 hour" || + diff < 86400 && Math.floor(diff / 3600) + " hours") || + day_diff == 1 && "Yesterday" || + day_diff < 7 && day_diff + " days" || + day_diff < 31 && Math.ceil(day_diff / 7) + " weeks"); + } + + public start() { + this.time = 0; + this.startTime = this.now(); + } + + private now() { + return Date.now(); + } + + public end() { + this.time = (this.now() - this.startTime) / 1000; + this.asString = Timer.prettyDate(this.startTime, this.now()); + } + } + + ///////////////////////////////// + // All the common things that we pring are functions of this class + ///////////////////////////////// + class Print { + constructor(public version: string, public typings: number, public tsFiles: number) { } + + public out(s) { + process.stdout.write(s); + } + + public printHeader() { + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.3.0\33[0m\n'); + this.out('=============================================================================\n'); + this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n'); + this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n'); + this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n'); + } + + public printSyntaxCheckingHeader() { + this.out('============================ \33[34m\33[1mSyntax checking\33[0m ================================\n'); + } + + public printTypingTestsHeader() { + this.out('============================= \33[34m\33[1mTyping tests\33[0m ==================================\n'); + } + + public printSuccessCharacter() { + this.out('\33[36m\33[1m.\33[0m'); + } + + public printFailureCharacter() { + this.out('x'); + } + + public printDiv() { + this.out('-----------------------------------------------------------------------------\n'); + } + + public printBoldDiv() { + this.out('=============================================================================\n'); + } + + public printErrorsHeader() { + this.out('=============================================================================\n'); + this.out(' \33[34m\33[1mErrors in files\33[0m \n'); + this.out('=============================================================================\n'); + } + + public printErrorsForFile(file: File) { + this.out('----------------- For file:' + file.formatName() ); + this.printBreak(); + this.out(file.execResult.stderr); + this.printBreak(); + } + + public printfilesWithSintaxErrorMessage() { + this.out(' \33[36m\33[1mFiles with syntax error\33[0m\n'); + } + + public printFailedTestMessage() { + this.out(' \33[36m\33[1mFailed tests\33[0m\n'); + } + + public printTypingsWithoutTestsMessage() { + this.out(' \33[36m\33[1mTyping without tests\33[0m\n'); + } + + public printTotalMessage() { + this.out(' \33[36m\33[1mTotal\33[0m\n'); + } + + public printErrorFile(file: string) { + this.out(' - ' + file + '\n'); + } + + public printTypingsWithoutTest(file) { + this.out(' - \33[33m\33[1m' + file + '\33[0m\n'); + } + + public printBreak() { + this.out('\n'); + } + + public printSuccessCount(current: number, total: number) { + this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printFailedCount(current: number, total: number) { + this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printElapsedTime(time, s) { + this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n'); + } + + public printSyntaxErrorCount(current: number, total: number) { + this.out(' \33[36m\33[1mSyntax error :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printTestErrorCount(current: number, total: number) { + this.out(' \33[36m\33[1mFailed tests :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + + public printWithoutTestCount(current: number, total: number) { + this.out(' \33[36m\33[1mWithout tests :\33[0m \33[33m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n'); + } + } + + ///////////////////////////// + // Represents the results of a test file execution + ///////////////////////////// + class File { + static baseDir: string; + + constructor(public baseDir: string, public filePathWithName: string, public execResult: ExecResult) { } + + // From '/complete/path/to/file' to 'specfolder/specfile.d.ts' + public formatName(): string { + var dirName = path.dirname(this.filePathWithName.substr(this.baseDir.length + 1)).replace('\\', '/'); + var dir = dirName.split('/')[0]; + var file = path.basename(this.filePathWithName, '.ts'); + var ext = path.extname(this.filePathWithName); + + return dir + ((dirName.split('/').length > 1) ? '/-/' : '/') + '\33[36m\33[1m' + file + '\33[0m' + ext; + } + } + + + ///////////////////////////// + // Determine syntax errors in typings + ///////////////////////////// + class SyntaxChecking { + + private timer: Timer; + + public files: File[] = []; + + private getFailedFiles(): File[] { + var list: File[] = []; + + for (var i = 0; i < this.files.length; i++) { + if (this.files[i].execResult.exitCode) { + list.push(this.files[i]); + } + } + + return list; + } + + private getSuccessFiles(): File[] { + var list: File[] = []; + + for (var i = 0; i < this.files.length; i++) { + if (!this.files[i].execResult.exitCode) { + list.push(this.files[i]); + } + } + + return list; + } + + constructor(public fileHandler: FileHandler, public out: Print) { + this.timer = new Timer(); + } + + private printStats() { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + } + + private printFailedFiles() { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printfilesWithSintaxErrorMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName()); + } + } + } + + private run(it, file, len, maxLen, callback: Function) { + if (!endsWith(file.toUpperCase(), '-TESTS.TS') && endsWith(file.toUpperCase(), '.TS') && file.indexOf('../_infrastructure') < 0) { + new Test(file).run((execResult) => { + + if (execResult.exitCode === 1) { + this.out.printFailureCharacter(); + len++; + } else { + this.out.printSuccessCharacter(); + len++; + } + + this.files.push(new File(this.fileHandler.path, file, execResult)); + + if (len > maxLen) { + len = 0; + this.out.printBreak(); + } + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.printBreak(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.printBreak(); + this.timer.end(); + this.printStats(); + this.printFailedFiles(); + + callback(this.getFailedFiles().length, this.files.length); + } + } + + public start(callback: Function) { + this.timer.start(); + + var tsFiles = this.fileHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + } + } + + ///////////////////////////// + // Determines errors in typing tests + ///////////////////////////// + class TestEval { + + private timer: Timer; + + public files: File[] = []; + + private getFailedFiles(): File[] { + var list: File[] = []; + + for (var i = 0; i < this.files.length; i++) { + if (this.files[i].execResult.exitCode) { + list.push(this.files[i]); + } + } + + return list; + } + + private getSuccessFiles(): File[] { + var list: File[] = []; + + for (var i = 0; i < this.files.length; i++) { + if (!this.files[i].execResult.exitCode) { + list.push(this.files[i]); + } + } + + return list; + } + + constructor(public fileHandler: FileHandler, public out: Print) { + this.timer = new Timer(); + } + + private printStats() { + this.out.printDiv(); + this.out.printElapsedTime(this.timer.asString, this.timer.time); + this.out.printSuccessCount(this.getSuccessFiles().length, this.files.length); + this.out.printFailedCount(this.getFailedFiles().length, this.files.length); + } + + private printFailedFiles() { + if (this.getFailedFiles().length > 0) { + this.out.printDiv(); + + this.out.printFailedTestMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.getFailedFiles().length; i++) { + var errorFile = this.getFailedFiles()[i]; + this.out.printErrorFile(errorFile.formatName()); + } + } + } + + private run(it, file, len, maxLen, callback: Function) { + if (endsWith(file.toUpperCase(), '-TESTS.TS')) { + new Test(file).run((execResult) => { + + if (execResult.exitCode === 1) { + this.out.printFailureCharacter(); + len++; + } else { + this.out.printSuccessCharacter(); + len++; + } + + this.files.push(new File(this.fileHandler.path, file, execResult)); + + if (len > maxLen) { + len = 0; + this.out.printBreak(); + } + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.printBreak(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + }); + } else if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } else { + this.out.printBreak(); + this.timer.end(); + this.printFailedFiles(); + this.printStats(); + + callback(this.getFailedFiles().length, this.files.length); + } + } + + public start(callback: Function) { + this.timer.start(); + + var tsFiles = this.fileHandler.allTS(); + + var it = new Iterator(tsFiles); + + var len = 0; + var maxLen = 76; + + if (it.hasNext()) { + this.run(it, it.next(), len, maxLen, callback); + } + } + } + + ///////////////////////////////// + // The main class to kick things off + ///////////////////////////////// + export class TestRunner { + private fh: FileHandler; + private out: Print; + private sc: SyntaxChecking; + private te: TestEval; + private typings: Typing[] = []; + + private printTypingsWithoutTest() { + var count = 0; + + if (this.typings.length > 0) { + this.out.printDiv(); + + this.out.printTypingsWithoutTestsMessage(); + + this.out.printDiv(); + + for (var i = 0; i < this.typings.length; i++) { + var typing = this.typings[i]; + if (typing.fileHandler.allTests().length == 0) { + if (typing.name != '_infrastructure' + && typing.name != '_ReSharper.DefinitelyTyped' + && typing.name != 'obj' + && typing.name != 'bin' + && typing.name != 'Properties') { + this.out.printTypingsWithoutTest(typing.name); + count++; + } + } + } + } + + return count; + } + + private printErrorsDetected() { + this.out.printErrorsHeader(); + + var printErrorsForFileIfFound = (file: File) => { + if (file.execResult.exitCode) + this.out.printErrorsForFile(file); + }; + + // sc errors: + this.sc.files.forEach(printErrorsForFileIfFound); + this.out.printBoldDiv(); + + // te errors: + this.te.files.forEach(printErrorsForFileIfFound); + this.out.printBoldDiv(); + } + + constructor(public dtPath: string) { + this.fh = new FileHandler(dtPath, /.\.ts/g); + this.out = new Print('0.9.1.1', this.fh.allTypings().length, this.fh.allTS().length); + this.sc = new SyntaxChecking(this.fh, this.out); + this.te = new TestEval(this.fh, this.out); + + var tpgs = this.fh.allTypings(); + for (var i = 0; i < tpgs.length; i++) { + this.typings.push(new Typing(tpgs[i], this.dtPath)); + } + } + + public run() { + var timer = new Timer(); + timer.start(); + + this.out.printHeader(); + + // Run syntax tests + this.out.printSyntaxCheckingHeader(); + this.sc.start((syntaxFailedCount, syntaxTotal) => { + + // Now run typing tests + this.out.printTypingTestsHeader(); + this.te.start((testFailedCount, testTotal) => { + + // Get the tests without any typing and simultaneously print their names + var totalTypingsWithoutTest = this.printTypingsWithoutTest(); + + // End total timer and print final messages + timer.end(); + + this.out.printDiv(); + this.out.printTotalMessage(); + this.out.printDiv(); + + this.out.printElapsedTime(timer.asString, timer.time); + this.out.printSyntaxErrorCount(syntaxFailedCount, syntaxTotal); + this.out.printTestErrorCount(testFailedCount, testTotal); + this.out.printWithoutTestCount(totalTypingsWithoutTest, this.fh.allTypings().length); + + this.out.printDiv(); + + if (syntaxFailedCount > 0 || testFailedCount > 0) { + this.printErrorsDetected(); + process.exit(1); + } + }); + }); + } + } } -declare var __dirname: any; - var dtPath = __dirname + '/../..'; var runner = new DefinitelyTyped.TestManager.TestRunner(dtPath); diff --git a/_infrastructure/tests/src/io.ts b/_infrastructure/tests/src/io.ts index 6fce75489..2c7a81f4f 100644 --- a/_infrastructure/tests/src/io.ts +++ b/_infrastructure/tests/src/io.ts @@ -83,22 +83,12 @@ declare class Enumerator { public item(): any; constructor (o: any); } -declare function setTimeout(callback: () =>void , ms?: number); -//declare var require: any; -declare module process { - export var argv: string[]; - export var platform: string; - export function on(event: string, handler: (any) => void ): void; - export module stdout { - export function write(str: string); + +// Missing in node definitions, but called in code below. +interface NodeProcess { + mainModule: { + filename: string; } - export module stderr { - export function write(str: string); - } - export module mainModule { - export var filename: string; - } - export function exit(exitCode?: number); } var IO = (function() { diff --git a/angularjs/README.md b/angularjs/README.md index 1692d947c..806a605d5 100644 --- a/angularjs/README.md +++ b/angularjs/README.md @@ -35,6 +35,7 @@ To avoid cluttering the list of suggestions as you type in your IDE, all interfa * `ng.cookies` for **ngCookies** * `ng.mock` for **ngMock** * `ng.resource` for **ngResource** +* `ng.route` for **ngRoute** * `ng.sanitize` for **ngSanitize** **ngMockE2E** does not define a new namespace, but rather modifies some of **ng**'s interfaces. diff --git a/angularjs/angular-1.0-tests.ts b/angularjs/angular-1.0-tests.ts new file mode 100644 index 000000000..ff3c87f77 --- /dev/null +++ b/angularjs/angular-1.0-tests.ts @@ -0,0 +1,219 @@ +/// + +// issue: https://github.com/borisyankov/DefinitelyTyped/issues/369 +https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js +/** + * @license HTTP Auth Interceptor Module for AngularJS + * (c) 2012 Witold Szczerba + * License: MIT + */ +angular.module('http-auth-interceptor', []) + + .provider('authService', function () { + /** + * Holds all the requests which failed due to 401 response, + * so they can be re-requested in future, once login is completed. + */ + var buffer = []; + + /** + * Required by HTTP interceptor. + * Function is attached to provider to be invisible for regular users of this service. + */ + this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred) { + buffer.push({ + config: config, + deferred: deferred + }); + } + + this.$get = ['$rootScope', '$injector', function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { + var $http: ng.IHttpService; //initialized later because of circular dependency problem + function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { + $http = $http || $injector.get('$http'); + $http(config).then(function (response) { + deferred.resolve(response); + }); + } + function retryAll() { + for (var i = 0; i < buffer.length; ++i) { + retry(buffer[i].config, buffer[i].deferred); + } + buffer = []; + } + + return { + loginConfirmed: function () { + $rootScope.$broadcast('event:auth-loginConfirmed'); + retryAll(); + } + } + }] + }) + +/** + * $http interceptor. + * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'. + */ + .config(['$httpProvider', 'authServiceProvider', function ($httpProvider: ng.IHttpProvider, authServiceProvider) { + + var interceptor = ['$rootScope', '$q', function ($rootScope: ng.IScope, $q: ng.IQService) { + function success(response: ng.IHttpPromiseCallbackArg) { + return response; + } + + function error(response: ng.IHttpPromiseCallbackArg) { + if (response.status === 401) { + var deferred = $q.defer(); + authServiceProvider.pushToBuffer(response.config, deferred); + $rootScope.$broadcast('event:auth-loginRequired'); + return deferred.promise; + } + // otherwise + return $q.reject(response); + } + + return function (promise: ng.IHttpPromise) { + return promise.then(success, error); + } + + }]; + $httpProvider.responseInterceptors.push(interceptor); + }]); + + +module HttpAndRegularPromiseTests { + interface Person { + firstName: string; + lastName: string; + } + + interface ExpectedResponse extends Person { } + + interface SomeControllerScope extends ng.IScope { + person: Person; + theAnswer: number; + letters: string[]; + } + + var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => { + $http.get("http://somewhere/some/resource") + .success((data: ExpectedResponse) => { + $scope.person = data; + }); + + $http.get("http://somewhere/some/resource") + .then((response: ng.IHttpPromiseCallbackArg) => { + // typing lost, so something like + // var i: number = response.data + // would type check + $scope.person = response.data; + }); + + $http.get("http://somewhere/some/resource") + .then((response: ng.IHttpPromiseCallbackArg) => { + // typing lost, so something like + // var i: number = response.data + // would NOT type check + $scope.person = response.data; + }); + + var aPromise: ng.IPromise = $q.when({ firstName: "Jack", lastName: "Sparrow" }); + aPromise.then((person: Person) => { + $scope.person = person; + }); + + var bPromise: ng.IPromise = $q.when(42); + bPromise.then((answer: number) => { + $scope.theAnswer = answer; + }); + + var cPromise: ng.IPromise = $q.when(["a", "b", "c"]); + cPromise.then((letters: string[]) => { + $scope.letters = letters; + }); + } + + // Test that we can pass around a type-checked success/error Promise Callback + var anotherController: Function = ($scope: SomeControllerScope, $http: + ng.IHttpService, $q: ng.IQService) => { + + var buildFooData: Function = () => 42; + + var doFoo: Function = (callback: ng.IHttpPromiseCallback) => { + $http.get('/foo', buildFooData()) + .success(callback); + } + + doFoo((data) => console.log(data)); + } +} + +// Test for AngularJS Syntax + +module My.Namespace { + export var x; // need to export something for module to kick in +} + +// IModule Registering Test +var mod = angular.module('tests', []); +mod.controller('name', function ($scope: ng.IScope) { }) +mod.controller('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.controller(My.Namespace); +mod.directive('name', function ($scope: ng.IScope) { }) +mod.directive('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.directive(My.Namespace); +mod.factory('name', function ($scope: ng.IScope) { }) +mod.factory('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.factory(My.Namespace); +mod.filter('name', function ($scope: ng.IScope) { }) +mod.filter('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.filter(My.Namespace); +mod.provider('name', function ($scope: ng.IScope) { }) +mod.provider('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.provider(My.Namespace); +mod.service('name', function ($scope: ng.IScope) { }) +mod.service('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.service(My.Namespace); +mod.constant('name', 23); +mod.constant('name', "23"); +mod.constant(My.Namespace); +mod.value('name', 23); +mod.value('name', "23"); +mod.value(My.Namespace); + +// Promise signature tests +var foo: ng.IPromise; +foo.then((x) => { + // x is inferred to be a number + return "asdf"; +}).then((x) => { + // x is inferred to be string + x.length; + return 123; +}).then((x) => { + // x is infered to be a number + x.toFixed(); + return; +}).then((x) => { + // x is infered to be void + // Typescript will prevent you to actually use x as a local variable + // Try object: + return { a: 123 }; +}).then((x) => { + // Object is inferred here + x.a = 123; + //Try a promise + var y: ng.IPromise; + return y; +}).then((x) => { + // x is infered to be a number, which is the resolved value of a promise + x.toFixed(); +}); + + +// angular.element() tests +var element = angular.element("div.myApp"); +var scope: ng.IScope = element.scope(); + + diff --git a/angularjs/angular-1.0-tests.ts.tscparams b/angularjs/angular-1.0-tests.ts.tscparams new file mode 100644 index 000000000..e16c76dff --- /dev/null +++ b/angularjs/angular-1.0-tests.ts.tscparams @@ -0,0 +1 @@ +"" diff --git a/angularjs/angular-1.0.d.ts b/angularjs/angular-1.0.d.ts new file mode 100755 index 000000000..ecb7bd2c9 --- /dev/null +++ b/angularjs/angular-1.0.d.ts @@ -0,0 +1,760 @@ +// Type definitions for Angular JS 1.0 +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare var angular: ng.IAngularStatic; + +// Support for painless dependency injection +interface Function { + $inject:string[]; +} + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng { + + // All service providers extend this interface + interface IServiceProvider { + $get(): any; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + bootstrap(element: string, modules?: any[]): auto.IInjectorService; + bootstrap(element: JQuery, modules?: any[]): auto.IInjectorService; + bootstrap(element: Element, modules?: any[]): auto.IInjectorService; + bootstrap(element: Document, modules?: any[]): auto.IInjectorService; + copy(source: any, destination?: any): any; + element: IAugmentedJQueryStatic; + equals(value1: any, value2: any): boolean; + extend(destination: any, ...sources: any[]): any; + forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + fromJson(json: string): any; + identity(arg?: any): any; + injector(modules?: any[]): auto.IInjectorService; + isArray(value: any): boolean; + isDate(value: any): boolean; + isDefined(value: any): boolean; + isElement(value: any): boolean; + isFunction(value: any): boolean; + isNumber(value: any): boolean; + isObject(value: any): boolean; + isString(value: any): boolean; + isUndefined(value: any): boolean; + lowercase(str: string): string; + /** construct your angular application + official docs: Interface for configuring angular modules. + see: http://docs.angularjs.org/api/angular.Module + */ + module( + /** name of your module you want to create */ + name: string, + /** name of modules yours depends on */ + requires?: string[], + configFunction?: any): IModule; + noop(...args: any[]): void; + toJson(obj: any, pretty?: boolean): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codename: string; + }; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + animation(name: string, animationFactory: Function): IModule; + animation(name: string, inlineAnnotadedFunction: any[]): IModule; + animation(object: Object): IModule; + /** configure existing services. + Use this method to register work which needs to be performed on module loading + */ + config(configFn: Function): IModule; + /** configure existing services. + Use this method to register work which needs to be performed on module loading + */ + config(inlineAnnotadedFunction: any[]): IModule; + constant(name: string, value: any): IModule; + constant(object: Object): IModule; + controller(name: string, controllerConstructor: Function): IModule; + controller(name: string, inlineAnnotadedConstructor: any[]): IModule; + controller(object : Object): IModule; + directive(name: string, directiveFactory: (...params:any[])=> IDirective): IModule; + directive(name: string, inlineAnnotadedFunction: any[]): IModule; + directive(object: Object): IModule; + factory(name: string, serviceFactoryFunction: Function): IModule; + factory(name: string, inlineAnnotadedFunction: any[]): IModule; + factory(object: Object): IModule; + filter(name: string, filterFactoryFunction: Function): IModule; + filter(name: string, inlineAnnotadedFunction: any[]): IModule; + filter(object: Object): IModule; + provider(name: string, serviceProviderConstructor: Function): IModule; + provider(name: string, inlineAnnotadedConstructor: any[]): IModule; + provider(object: Object): IModule; + run(initializationFunction: Function): IModule; + run(inlineAnnotadedFunction: any[]): IModule; + service(name: string, serviceConstructor: Function): IModule; + service(name: string, inlineAnnotadedConstructor: any[]): IModule; + service(object: Object): IModule; + value(name: string, value: any): IModule; + value(object: Object): IModule; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + interface IAttributes { + $set(name: string, value: any): void; + $observe(name: string, fn:(value?:any)=>any):void; + $attr: any; + } + + /////////////////////////////////////////////////////////////////////////// + // FormController + // see http://docs.angularjs.org/api/ng.directive:form.FormController + /////////////////////////////////////////////////////////////////////////// + interface IFormController { + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + $error: any; + $setDirty(): void; + $setPristine(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + interface INgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: boolean): void; + $setViewValue(value: string): void; + + // XXX Not sure about the types here. Documentation states it's a string, but + // I've seen it receiving other types throughout the code. + // Falling back to any for now. + $viewValue: any; + + // XXX Same as avove + $modelValue: any; + + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; + $error: any; + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // Scope + // see http://docs.angularjs.org/api/ng.$rootScope.Scope + /////////////////////////////////////////////////////////////////////////// + interface IScope { + $apply(): any; + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + $emit(name: string, ...args: any[]): IAngularEvent; + + // Documentation says exp is optional, but actual implementaton counts on it + $eval(expression: string): any; + $eval(expression: (scope: IScope) => any): any; + + // Documentation says exp is optional, but actual implementaton counts on it + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: boolean): IScope; + + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; + + $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + + $watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + + $parent: IScope; + + $id: number; + + // Hidden members + $$isolateBindings: any; + $$phase: any; + } + + interface IAngularEvent { + targetScope: IScope; + currentScope: IScope; + name: string; + preventDefault: Function; + defaultPrevented: boolean; + + // Available only events that were $emit-ted + stopPropagation?: Function; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window {} + + /////////////////////////////////////////////////////////////////////////// + // BrowserService + // TODO undocumented, so we need to get it from the source code + /////////////////////////////////////////////////////////////////////////// + interface IBrowserService {} + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (func: Function, delay?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // FilterService + // see http://docs.angularjs.org/api/ng.$filter + // see http://docs.angularjs.org/api/ng.$filterProvider + /////////////////////////////////////////////////////////////////////////// + interface IFilterService { + (name: string): Function; + } + + interface IFilterProvider extends IServiceProvider { + register(name: string, filterFactory: Function): IServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + interface ILocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; + DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; + pluralCat: (num: any) => string; + } + + interface ILocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: ILocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + interface ILocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + interface ILocaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + debug: ILogCall; + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; + } + + // We define this as separete interface so we can reopen it later for + // the ngMock module. + interface ILogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + /////////////////////////////////////////////////////////////////////////// + interface IParseService { + (expression: string): ICompiledExpression; + } + + interface ICompiledExpression { + (context: any, locals?: any): any; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /////////////////////////////////////////////////////////////////////////// + // LocationService + // see http://docs.angularjs.org/api/ng.$location + // see http://docs.angularjs.org/api/ng.$locationProvider + // see http://docs.angularjs.org/guide/dev_guide.services.$location + /////////////////////////////////////////////////////////////////////////// + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + path(): string; + path(newPath: string): ILocationService; + port(): number; + protocol(): string; + replace(): ILocationService; + search(): any; + search(parametersMap: any): ILocationService; + search(parameter: string, parameterValue: any): ILocationService; + url(): string; + url(url: string): ILocationService; + } + + interface ILocationProvider extends IServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): ILocationProvider; + html5Mode(): boolean; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: boolean): ILocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + interface IDocumentService extends Document {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + interface IRootElementService extends JQuery {} + + /////////////////////////////////////////////////////////////////////////// + // QService + // see http://docs.angularjs.org/api/ng.$q + /////////////////////////////////////////////////////////////////////////// + interface IQService { + all(promises: IPromise[]): IPromise; + defer(): IDeferred; + reject(reason?: any): IPromise; + when(value: T): IPromise; + } + + interface IPromise { + then(successCallback: (promiseValue: T) => IHttpPromise, errorCallback?: (reason: any) => any): IPromise; + then(successCallback: (promiseValue: T) => IPromise, errorCallback?: (reason: any) => any): IPromise; + then(successCallback: (promiseValue: T) => TResult, errorCallback?: (reason: any) => TResult): IPromise; + } + + interface IDeferred { + resolve(value?: T): void; + reject(reason?: any): void; + promise: IPromise; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CacheFactoryService + // see http://docs.angularjs.org/api/ng.$cacheFactory + /////////////////////////////////////////////////////////////////////////// + interface ICacheFactoryService { + // Lets not foce the optionsMap to have the capacity member. Even though + // it's the ONLY option considered by the implementation today, a consumer + // might find it useful to associate some other options to the cache object. + //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; + (cacheId: string, optionsMap?: { capacity: number; }): ICacheObject; + + // Methods bellow are not documented + info(): any; + get (cacheId: string): ICacheObject; + } + + interface ICacheObject { + info(): { + id: string; + size: number; + + // Not garanteed to have, since it's a non-mandatory option + //capacity: number; + }; + put(key: string, value?: any): void; + get (key: string): any; + remove(key: string): void; + removeAll(): void; + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + interface ICompileService { + (element: string, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: JQuery, transclude?: ITemplateLinkingFunction, maxPriority?: number): ITemplateLinkingFunction; + } + + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + } + + interface ITemplateLinkingFunction { + // Let's hint but not force cloneAttachFn's signature + (scope: IScope, cloneAttachFn?: (clonedElement?: JQuery, scope?: IScope) => any): JQuery; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: Function, locals?: any): any; + (controllerName: string, locals?: any): any; + } + + interface IControllerProvider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotadedConstructor: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpService + // see http://docs.angularjs.org/api/ng.$http + /////////////////////////////////////////////////////////////////////////// + interface IHttpService { + // At least moethod and url must be provided... + (config: IRequestConfig): IHttpPromise; + get (url: string, RequestConfig?: any): IHttpPromise; + delete (url: string, RequestConfig?: any): IHttpPromise; + head(url: string, RequestConfig?: any): IHttpPromise; + jsonp(url: string, RequestConfig?: any): IHttpPromise; + post(url: string, data: any, RequestConfig?: any): IHttpPromise; + put(url: string, data: any, RequestConfig?: any): IHttpPromise; + defaults: IRequestConfig; + + // For debugging, BUT it is documented as public, so... + pendingRequests: any[]; + } + + // This is just for hinting. + // Some opetions might not be available depending on the request. + // see http://docs.angularjs.org/api/ng.$http#Usage for options explanations + interface IRequestConfig { + method: string; + url: string; + params?: any; + + // XXX it has it's own structure... perhaps we should define it in the future + headers?: any; + + cache?: any; + timeout?: number; + withCredentials?: boolean; + + // These accept multiple types, so let's defile them as any + data?: any; + transformRequest?: any; + transformResponse?: any; + } + + interface IHttpPromiseCallback { + (data: T, status: number, headers: (headerName: string) => string, config: IRequestConfig): void; + } + + interface IHttpPromiseCallbackArg { + data?: T; + status?: number; + headers?: (headerName: string) => string; + config?: IRequestConfig; + } + + interface IHttpPromise extends IPromise { + success(callback: IHttpPromiseCallback): IHttpPromise; + error(callback: IHttpPromiseCallback): IHttpPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + then(successCallback: (response: IHttpPromiseCallbackArg) => IPromise, errorCallback?: (response: IHttpPromiseCallbackArg) => any): IPromise; + } + + interface IHttpProvider extends IServiceProvider { + defaults: IRequestConfig; + interceptors: any[]; + responseInterceptors: any[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + interface IInterpolateService { + (text: string, mustHaveExpression?: boolean): IInterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + interface IInterpolationFunction { + (context: any): string; + } + + interface IInterpolateProvider extends IServiceProvider { + startSymbol(): string; + startSymbol(value: string): IInterpolateProvider; + endSymbol(): string; + endSymbol(value: string): IInterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // RouteParamsService + // see http://docs.angularjs.org/api/ng.$routeParams + /////////////////////////////////////////////////////////////////////////// + interface IRouteParamsService {} + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + interface ITemplateCacheService extends ICacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // RootScopeService + // see http://docs.angularjs.org/api/ng.$rootScope + /////////////////////////////////////////////////////////////////////////// + interface IRootScopeService extends IScope {} + + /////////////////////////////////////////////////////////////////////////// + // RouteService + // see http://docs.angularjs.org/api/ng.$route + // see http://docs.angularjs.org/api/ng.$routeProvider + /////////////////////////////////////////////////////////////////////////// + interface IRouteService { + reload(): void; + routes: any; + + // May not always be available. For instance, current will not be available + // to a controller that was not initialized as a result of a route maching. + current?: ICurrentRoute; + } + + // see http://docs.angularjs.org/api/ng.$routeProvider#when for options explanations + interface IRoute { + controller?: any; + name?: string; + template?: string; + templateUrl?: any; + resolve?: any; + redirectTo?: any; + reloadOnSearch?: boolean; + } + + // see http://docs.angularjs.org/api/ng.$route#current + interface ICurrentRoute extends IRoute { + locals: { + $scope: IScope; + $template: string; + }; + + params: any; + } + + interface IRouteProvider extends IServiceProvider { + otherwise(params: any): IRouteProvider; + when(path: string, route: IRoute): IRouteProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // Directive + // see http://docs.angularjs.org/api/ng.$compileProvider#directive + // and http://docs.angularjs.org/guide/directive + /////////////////////////////////////////////////////////////////////////// + + interface IDirective{ + priority?: number; + template?: any; + templateUrl?: any; + replace?: boolean; + transclude?: any; + restrict?: string; + scope?: any; + link?: Function; + compile?: Function; + controller?: any; + } + + /////////////////////////////////////////////////////////////////////////// + // angular.element + // when calling angular.element, angular returns a jQuery object, + // augmented with additional methods like e.g. scope. + // see: http://docs.angularjs.org/api/angular.element + /////////////////////////////////////////////////////////////////////////// + interface IAugmentedJQueryStatic extends JQueryStatic { + (selector: string, context?: any): IAugmentedJQuery; + (element: Element): IAugmentedJQuery; + (object: {}): IAugmentedJQuery; + (elementArray: Element[]): IAugmentedJQuery; + (object: JQuery): IAugmentedJQuery; + (func: Function): IAugmentedJQuery; + (array: any[]): IAugmentedJQuery; + (): IAugmentedJQuery; + } + + interface IAugmentedJQuery extends JQuery { + // TODO: events, how to define? + //$destroy + + find(selector: string): IAugmentedJQuery; + find(element: any): IAugmentedJQuery; + find(obj: JQuery): IAugmentedJQuery; + + controller(name: string): any; + injector(): any; + scope(): IScope; + + inheritedData(key: string, value: any): JQuery; + inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key?: string): any; + + + } + + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function): string[]; + annotate(inlineAnnotadedFunction: any[]): string[]; + get (name: string): any; + instantiate(typeConstructor: Function, locals?: any): any; + invoke(func: Function, context?: any, locals?: any): any; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + interface IProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // constant(name: string, value: any): any; + constant(name: string, value: any): void; + + decorator(name: string, decorator: Function): void; + decorator(name: string, decoratorInline: any[]): void; + factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; + provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; + service(name: string, constructor: Function): ng.IServiceProvider; + value(name: string, value: any): ng.IServiceProvider; + } + + } + +} diff --git a/angularjs/angular-cookies-1.0.d.ts b/angularjs/angular-cookies-1.0.d.ts new file mode 100644 index 000000000..4dc2e038e --- /dev/null +++ b/angularjs/angular-cookies-1.0.d.ts @@ -0,0 +1,30 @@ +/// Type definitions for Angular JS 1.0 (ngCookies module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngCookies module (angular-cookies.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng.cookies { + + /////////////////////////////////////////////////////////////////////////// + // CookieService + // see http://docs.angularjs.org/api/ngCookies.$cookies + /////////////////////////////////////////////////////////////////////////// + interface ICookiesService {} + + /////////////////////////////////////////////////////////////////////////// + // CookieStoreService + // see http://docs.angularjs.org/api/ngCookies.$cookieStore + /////////////////////////////////////////////////////////////////////////// + interface ICookieStoreService { + get(key: string): any; + put(key: string, value: any): void; + remove(key: string): void; + } + +} diff --git a/angularjs/angular-cookies.d.ts b/angularjs/angular-cookies.d.ts index 4dc2e038e..60eebbacb 100644 --- a/angularjs/angular-cookies.d.ts +++ b/angularjs/angular-cookies.d.ts @@ -1,4 +1,4 @@ -/// Type definitions for Angular JS 1.0 (ngCookies module) +/// Type definitions for Angular JS 1.2 (ngCookies module) // Project: http://angularjs.org // Definitions by: Diego Vilar // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/angularjs/angular-mocks-1.0.d.ts b/angularjs/angular-mocks-1.0.d.ts new file mode 100644 index 000000000..4d8decbf8 --- /dev/null +++ b/angularjs/angular-mocks-1.0.d.ts @@ -0,0 +1,150 @@ +// Type definitions for Angular JS 1.0 (ngMock, ngMockE2E module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +/////////////////////////////////////////////////////////////////////////////// +// functions attached to global object (window) +/////////////////////////////////////////////////////////////////////////////// +declare var module: (...modules: any[]) => any; +declare var inject: (...fns: Function[]) => any; + +/////////////////////////////////////////////////////////////////////////////// +// ngMock module (angular-mocks.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng { + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // We reopen it to add the MockStatic definition + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + mock: IMockStatic; + } + + interface IMockStatic { + // see http://docs.angularjs.org/api/angular.mock.debug + debug(obj: any): string; + + // see http://docs.angularjs.org/api/angular.mock.inject + inject(...fns: Function[]): any; + + // see http://docs.angularjs.org/api/angular.mock.module + module(...modules: any[]): any; + + // see http://docs.angularjs.org/api/angular.mock.TzDate + TzDate(offset: number, timestamp: number): Date; + TzDate(offset: number, timestamp: string): Date; + } + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ngMock.$exceptionHandler + // see http://docs.angularjs.org/api/ngMock.$exceptionHandlerProvider + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerProvider extends IServiceProvider { + mode(mode: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ngMock.$timeout + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + flush(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ngMock.$log + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + assertEmpty(): void; + reset(): void; + } + + interface LogCall { + logs: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ngMock.$httpBackend + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + flush(count?: number): void; + resetExpectations(): void; + verifyNoOutstandingExpectation(): void; + verifyNoOutstandingRequest(): void; + + expect(method: string, url: string, data?: any, headers?: any): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: any, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: string, data?: any, headers?: any): mock.IRequestHandler; + expect(method: RegExp, url: RegExp, data?: any, headers?: any): mock.IRequestHandler; + + when(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + when(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + + expectDELETE(url: string, headers?: any): mock.IRequestHandler; + expectDELETE(url: RegExp, headers?: any): mock.IRequestHandler; + expectGET(url: string, headers?: any): mock.IRequestHandler; + expectGET(url: RegExp, headers?: any): mock.IRequestHandler; + expectHEAD(url: string, headers?: any): mock.IRequestHandler; + expectHEAD(url: RegExp, headers?: any): mock.IRequestHandler; + expectJSONP(url: string): mock.IRequestHandler; + expectJSONP(url: RegExp): mock.IRequestHandler; + expectPATCH(url: string, data?: any, headers?: any): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: any, headers?: any): mock.IRequestHandler; + expectPOST(url: string, data?: any, headers?: any): mock.IRequestHandler; + expectPOST(url: RegExp, data?: any, headers?: any): mock.IRequestHandler; + expectPUT(url: string, data?: any, headers?: any): mock.IRequestHandler; + expectPUT(url: RegExp, data?: any, headers?: any): mock.IRequestHandler; + + whenDELETE(url: string, headers?: any): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: any): mock.IRequestHandler; + whenGET(url: string, headers?: any): mock.IRequestHandler; + whenGET(url: RegExp, headers?: any): mock.IRequestHandler; + whenHEAD(url: string, headers?: any): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: any): mock.IRequestHandler; + whenJSONP(url: string): mock.IRequestHandler; + whenJSONP(url: RegExp): mock.IRequestHandler; + whenPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPOST(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPUT(url: string, data?: string, headers?: any): mock.IRequestHandler; + whenPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; + whenPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; + whenPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; + } + + export module mock { + + // returned interface by the the mocked HttpBackendService expect/when methods + interface IRequestHandler { + respond(func: Function): void; + respond(status: number, data?: any, headers?: any): void; + respond(data: any, headers?: any): void; + + // Available wehn ngMockE2E is loaded + passThrough(): void; + } + + } + +} diff --git a/angularjs/angular-mocks-tests.ts b/angularjs/angular-mocks-tests.ts new file mode 100644 index 000000000..b43580f36 --- /dev/null +++ b/angularjs/angular-mocks-tests.ts @@ -0,0 +1,288 @@ +/// + +/////////////////////////////////////// +// IAngularStatic +/////////////////////////////////////// +var angular: ng.IAngularStatic; +var mock: ng.IMockStatic; + +mock = angular.mock; + + +/////////////////////////////////////// +// IMockStatic +/////////////////////////////////////// +var date: Date; + +mock.dump({ key: 'value' }); + +mock.inject( + function () { return 1; }, + function () { return 2; } + ); + +mock.module('module1', 'module2'); +mock.module( + function () { return 1; }, + function () { return 2; } + ); +mock.module({ module1: function () { return 1; } }); + +date = mock.TzDate(-7, '2013-1-1T15:00:00Z'); +date = mock.TzDate(-8, 12345678); + + +/////////////////////////////////////// +// IExceptionHandlerProvider +/////////////////////////////////////// +var exceptionHandlerProvider: ng.IExceptionHandlerProvider; + +exceptionHandlerProvider.mode('log'); + + +/////////////////////////////////////// +// IExceptionHandlerProvider +/////////////////////////////////////// +var timeoutService: ng.ITimeoutService; + +timeoutService.flush(); +timeoutService.flush(1234); +timeoutService.flushNext(); +timeoutService.flushNext(1234); +timeoutService.verifyNoPendingTasks(); + + +/////////////////////////////////////// +// ILogService, ILogCall +/////////////////////////////////////// +var logService: ng.ILogService; +var logCall: ng.ILogCall; +var logs: string[]; + +logService.assertEmpty(); +logService.reset(); + +logCall = logService.debug; +logCall = logService.error; +logCall = logService.info; +logCall = logService.log; +logCall = logService.warn; + +logs = logCall.logs; + + +/////////////////////////////////////// +// IHttpBackendService +/////////////////////////////////////// +var httpBackendService: ng.IHttpBackendService; +var requestHandler: ng.mock.IRequestHandler; + +httpBackendService.flush(); +httpBackendService.flush(1234); +httpBackendService.resetExpectations(); +httpBackendService.verifyNoOutstandingExpectation(); +httpBackendService.verifyNoOutstandingRequest(); + +requestHandler = httpBackendService.expect('GET', 'http://test.local'); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data'); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data'); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); + +requestHandler = httpBackendService.expectDELETE('http://test.local'); +requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectGET('http://test.local'); +requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectHEAD('http://test.local'); +requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectJSONP('http://test.local'); +requestHandler = httpBackendService.expectJSONP(/test.local/); + +requestHandler = httpBackendService.expectPATCH('http://test.local'); +requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data'); +requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/); +requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/); +requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data'); +requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/); +requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.expectPOST('http://test.local'); +requestHandler = httpBackendService.expectPOST('http://test.local', 'response data'); +requestHandler = httpBackendService.expectPOST('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', /response data/); +requestHandler = httpBackendService.expectPOST('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/); +requestHandler = httpBackendService.expectPOST(/test.local/, 'response data'); +requestHandler = httpBackendService.expectPOST(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/, /response data/); +requestHandler = httpBackendService.expectPOST(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.expectPUT('http://test.local'); +requestHandler = httpBackendService.expectPUT('http://test.local', 'response data'); +requestHandler = httpBackendService.expectPUT('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', /response data/); +requestHandler = httpBackendService.expectPUT('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/); +requestHandler = httpBackendService.expectPUT(/test.local/, 'response data'); +requestHandler = httpBackendService.expectPUT(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/, /response data/); +requestHandler = httpBackendService.expectPUT(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.when('GET', 'http://test.local'); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data'); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/); +requestHandler = httpBackendService.when('GET', /test.local/, 'response data'); +requestHandler = httpBackendService.when('GET', /test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/, /response data/); +requestHandler = httpBackendService.when('GET', /test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); + +requestHandler = httpBackendService.whenDELETE('http://test.local'); +requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenGET('http://test.local'); +requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenHEAD('http://test.local'); +requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenJSONP('http://test.local'); +requestHandler = httpBackendService.whenJSONP(/test.local/); + +requestHandler = httpBackendService.whenPATCH('http://test.local'); +requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data'); +requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/); +requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/); +requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data'); +requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/); +requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.whenPOST('http://test.local'); +requestHandler = httpBackendService.whenPOST('http://test.local', 'response data'); +requestHandler = httpBackendService.whenPOST('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', /response data/); +requestHandler = httpBackendService.whenPOST('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/); +requestHandler = httpBackendService.whenPOST(/test.local/, 'response data'); +requestHandler = httpBackendService.whenPOST(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/, /response data/); +requestHandler = httpBackendService.whenPOST(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.whenPUT('http://test.local'); +requestHandler = httpBackendService.whenPUT('http://test.local', 'response data'); +requestHandler = httpBackendService.whenPUT('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', /response data/); +requestHandler = httpBackendService.whenPUT('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/); +requestHandler = httpBackendService.whenPUT(/test.local/, 'response data'); +requestHandler = httpBackendService.whenPUT(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/, /response data/); +requestHandler = httpBackendService.whenPUT(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' }); + + +/////////////////////////////////////// +// IRequestHandler +/////////////////////////////////////// +requestHandler.passThrough(); +requestHandler.respond(function () { }); +requestHandler.respond({ key: 'value' }); +requestHandler.respond({ key: 'value' }, { header: 'value' }); +requestHandler.respond(404); +requestHandler.respond(404, { key: 'value' }); +requestHandler.respond(404, { key: 'value' }, { header: 'value' }); diff --git a/angularjs/angular-mocks-tests.ts.tscparams b/angularjs/angular-mocks-tests.ts.tscparams new file mode 100644 index 000000000..e16c76dff --- /dev/null +++ b/angularjs/angular-mocks-tests.ts.tscparams @@ -0,0 +1 @@ +"" diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 4d8decbf8..a607422dd 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -1,9 +1,8 @@ -// Type definitions for Angular JS 1.0 (ngMock, ngMockE2E module) +// Type definitions for Angular JS 1.2 (ngMock, ngMockE2E module) // Project: http://angularjs.org // Definitions by: Diego Vilar // Definitions: https://github.com/borisyankov/DefinitelyTyped - /// /////////////////////////////////////////////////////////////////////////////// @@ -26,14 +25,16 @@ declare module ng { } interface IMockStatic { - // see http://docs.angularjs.org/api/angular.mock.debug - debug(obj: any): string; - + // see http://docs.angularjs.org/api/angular.mock.dump + dump(obj: any): string; + // see http://docs.angularjs.org/api/angular.mock.inject inject(...fns: Function[]): any; - + // see http://docs.angularjs.org/api/angular.mock.module - module(...modules: any[]): any; + module(...modules: string[]): any; + module(...modules: Function[]): any; + module(modules: Object): any; // see http://docs.angularjs.org/api/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; @@ -55,7 +56,9 @@ declare module ng { // Augments the original service /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { - flush(): void; + flush(delay?: number): void; + flushNext(expectedDelay?: number): void; + verifyNoPendingTasks(): void; } /////////////////////////////////////////////////////////////////////////// @@ -68,7 +71,7 @@ declare module ng { reset(): void; } - interface LogCall { + interface ILogCall { logs: string[]; } @@ -82,62 +85,127 @@ declare module ng { verifyNoOutstandingExpectation(): void; verifyNoOutstandingRequest(): void; - expect(method: string, url: string, data?: any, headers?: any): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: any, headers?: any): mock.IRequestHandler; - expect(method: RegExp, url: string, data?: any, headers?: any): mock.IRequestHandler; - expect(method: RegExp, url: RegExp, data?: any, headers?: any): mock.IRequestHandler; - - when(method: string, url: string, data?: string, headers?: any): mock.IRequestHandler; - when(method: string, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; - when(method: string, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; - when(method: string, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; - when(method: RegExp, url: string, data?: string, headers?: any): mock.IRequestHandler; - when(method: RegExp, url: RegExp, data?: string, headers?: any): mock.IRequestHandler; - when(method: RegExp, url: string, data?: RegExp, headers?: any): mock.IRequestHandler; - when(method: RegExp, url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; - - expectDELETE(url: string, headers?: any): mock.IRequestHandler; - expectDELETE(url: RegExp, headers?: any): mock.IRequestHandler; - expectGET(url: string, headers?: any): mock.IRequestHandler; - expectGET(url: RegExp, headers?: any): mock.IRequestHandler; - expectHEAD(url: string, headers?: any): mock.IRequestHandler; - expectHEAD(url: RegExp, headers?: any): mock.IRequestHandler; + expect(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expect(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + expect(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + + expectDELETE(url: string, headers?: Object): mock.IRequestHandler; + expectDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; + expectGET(url: string, headers?: Object): mock.IRequestHandler; + expectGET(url: RegExp, headers?: Object): mock.IRequestHandler; + expectHEAD(url: string, headers?: Object): mock.IRequestHandler; + expectHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; expectJSONP(url: string): mock.IRequestHandler; expectJSONP(url: RegExp): mock.IRequestHandler; - expectPATCH(url: string, data?: any, headers?: any): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: any, headers?: any): mock.IRequestHandler; - expectPOST(url: string, data?: any, headers?: any): mock.IRequestHandler; - expectPOST(url: RegExp, data?: any, headers?: any): mock.IRequestHandler; - expectPUT(url: string, data?: any, headers?: any): mock.IRequestHandler; - expectPUT(url: RegExp, data?: any, headers?: any): mock.IRequestHandler; - whenDELETE(url: string, headers?: any): mock.IRequestHandler; - whenDELETE(url: RegExp, headers?: any): mock.IRequestHandler; - whenGET(url: string, headers?: any): mock.IRequestHandler; - whenGET(url: RegExp, headers?: any): mock.IRequestHandler; - whenHEAD(url: string, headers?: any): mock.IRequestHandler; - whenHEAD(url: RegExp, headers?: any): mock.IRequestHandler; + expectPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + expectPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + expectPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + expectPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + when(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; + when(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; + when(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + when(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenDELETE(url: string, headers?: Object): mock.IRequestHandler; + whenDELETE(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; + whenDELETE(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenGET(url: string, headers?: Object): mock.IRequestHandler; + whenGET(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenGET(url: RegExp, headers?: Object): mock.IRequestHandler; + whenGET(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + + whenHEAD(url: string, headers?: Object): mock.IRequestHandler; + whenHEAD(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; + whenHEAD(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + whenJSONP(url: string): mock.IRequestHandler; whenJSONP(url: RegExp): mock.IRequestHandler; - whenPATCH(url: string, data?: string, headers?: any): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; - whenPATCH(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; - whenPOST(url: string, data?: string, headers?: any): mock.IRequestHandler; - whenPOST(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; - whenPOST(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; - whenPOST(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; - whenPUT(url: string, data?: string, headers?: any): mock.IRequestHandler; - whenPUT(url: RegExp, data?: string, headers?: any): mock.IRequestHandler; - whenPUT(url: string, data?: RegExp, headers?: any): mock.IRequestHandler; - whenPUT(url: RegExp, data?: RegExp, headers?: any): mock.IRequestHandler; - } + + whenPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + whenPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + + whenPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; + whenPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + } export module mock { - + // returned interface by the the mocked HttpBackendService expect/when methods interface IRequestHandler { - respond(func: Function): void; + respond(func: Function): void; respond(status: number, data?: any, headers?: any): void; respond(data: any, headers?: any): void; @@ -145,6 +213,6 @@ declare module ng { passThrough(): void; } - } + } } diff --git a/angularjs/angular-mocks.d.ts.tscparams b/angularjs/angular-mocks.d.ts.tscparams new file mode 100644 index 000000000..e16c76dff --- /dev/null +++ b/angularjs/angular-mocks.d.ts.tscparams @@ -0,0 +1 @@ +"" diff --git a/angularjs/angular-resource-1.0.d.ts b/angularjs/angular-resource-1.0.d.ts new file mode 100644 index 000000000..c66bb341d --- /dev/null +++ b/angularjs/angular-resource-1.0.d.ts @@ -0,0 +1,82 @@ +// Type definitions for Angular JS 1.0 (ngResource module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +/////////////////////////////////////////////////////////////////////////////// +// ngResource module (angular-resource.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng.resource { + + /////////////////////////////////////////////////////////////////////////// + // ResourceService + // see http://docs.angularjs.org/api/ngResource.$resource + // Most part of the following definitions were achieved by analyzing the + // actual implementation, since the documentation doesn't seem to cover + // that deeply. + /////////////////////////////////////////////////////////////////////////// + interface IResourceService { + (url: string, paramDefaults?: any, + /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } + where deleteDescriptor : IActionDescriptor */ + actionDescriptors?: any): IResourceClass; + } + + // Just a reference to facilitate describing new actions + interface IActionDescriptor { + method: string; + isArray?: boolean; + params?: any; + headers?: any; + } + + // Baseclass for everyresource with default actions. + // If you define your new actions for the resource, you will need + // to extend this interface and typecast the ResourceClass to it. + interface IResourceClass { + get: IActionCall; + save: IActionCall; + query: IActionCall; + remove: IActionCall; + delete: IActionCall; + } + + // In case of passing the first argument as anything but a function, + // it's gonna be considered data if the action method is POST, PUT or + // PATCH (in other words, methods with body). Otherwise, it's going + // to be considered as parameters to the request. + interface IActionCall { + (): IResource; + (dataOrParams: any): IResource; + (dataOrParams: any, success: Function): IResource; + (success: Function, error?: Function): IResource; + (params: any, data: any, success?: Function, error?: Function): IResource; + } + + interface IResource { + $save: IActionCall; + $remove: IActionCall; + $delete: IActionCall; + + // No documented, but they are there, just as any custom action will be + $query: IActionCall; + $get: IActionCall; + } + + /** when creating a resource factory via IModule.factory */ + interface IResourceServiceFactoryFunction { + ($resource: ng.resource.IResourceService): ng.resource.IResourceClass; + } +} + +/** extensions to base ng based on using angular-resource */ +declare module ng { + + interface IModule { + /** creating a resource service factory */ + factory(name: string, resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction): IModule; + } +} diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 494288365..f74f3eb44 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular JS 1.0 (ngResource module) +// Type definitions for Angular JS 1.2 (ngResource module) // Project: http://angularjs.org // Definitions by: Diego Vilar // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -19,10 +19,10 @@ declare module ng.resource { // that deeply. /////////////////////////////////////////////////////////////////////////// interface IResourceService { - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actionDescriptors?: any): IResourceClass; + (url: string, paramDefaults?: any, + /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } + where deleteDescriptor : IActionDescriptor */ + actionDescriptors?: any): IResourceClass; } // Just a reference to facilitate describing new actions diff --git a/angularjs/angular-route-tests.ts b/angularjs/angular-route-tests.ts new file mode 100644 index 000000000..2ebe16a21 --- /dev/null +++ b/angularjs/angular-route-tests.ts @@ -0,0 +1,14 @@ +/// + +/** + * @license HTTP Auth Interceptor Module for AngularJS + * (c) 2013 Jonathan Park @ Daptiv Solutions Inc + * License: MIT + */ + +declare var $routeProvider: ng.route.IRouteProvider; +$routeProvider + .when('/projects/:projectId/dashboard',{ + controller: '' + }) + .otherwise({redirectTo: '/'}); diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts new file mode 100644 index 000000000..b8d1db50b --- /dev/null +++ b/angularjs/angular-route.d.ts @@ -0,0 +1,64 @@ +// Type definitions for Angular JS 1.2 (ngRoute module) +// Project: http://angularjs.org +// Definitions by: Jonathan Park +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +/////////////////////////////////////////////////////////////////////////////// +// ngRoute module (angular-route.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng.route { + + /////////////////////////////////////////////////////////////////////////// + // RouteParamsService + // see http://docs.angularjs.org/api/ngRoute.$routeParams + /////////////////////////////////////////////////////////////////////////// + interface IRouteParamsService {} + + /////////////////////////////////////////////////////////////////////////// + // RouteService + // see http://docs.angularjs.org/api/ngRoute.$route + // see http://docs.angularjs.org/api/ngRoute.$routeProvider + /////////////////////////////////////////////////////////////////////////// + interface IRouteService { + reload(): void; + routes: any; + + // May not always be available. For instance, current will not be available + // to a controller that was not initialized as a result of a route maching. + current?: ICurrentRoute; + } + + // see http://docs.angularjs.org/api/ngRoute.$routeProvider#when for options explanations + interface IRoute { + controller?: any; + controllerAs?: any; + name?: string; + template?: string; + templateUrl?: any; + resolve?: any; + redirectTo?: any; + reloadOnSearch?: boolean; + } + + // see http://docs.angularjs.org/api/ng.$route#current + interface ICurrentRoute extends IRoute { + locals: { + $scope: IScope; + $template: string; + }; + + params: any; + } + + interface IRouteProvider extends IServiceProvider { + otherwise(params: any): IRouteProvider; + /** + * This is a description + * + */ + when(path: string, route: IRoute): IRouteProvider; + } +} diff --git a/angularjs/angular-sanitize-1.0.d.ts b/angularjs/angular-sanitize-1.0.d.ts new file mode 100644 index 000000000..56a3bc2ae --- /dev/null +++ b/angularjs/angular-sanitize-1.0.d.ts @@ -0,0 +1,22 @@ +// Type definitions for Angular JS 1.0 (ngSanitize module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +/////////////////////////////////////////////////////////////////////////////// +// ngSanitize module (angular-sanitize.js) +/////////////////////////////////////////////////////////////////////////////// +declare module ng.sanitize { + + /////////////////////////////////////////////////////////////////////////// + // SanitizeService + // see http://docs.angularjs.org/api/ngSanitize.$sanitize + /////////////////////////////////////////////////////////////////////////// + interface ISanitizeService { + (html: string): string; + } + +} diff --git a/angularjs/angular-sanitize.d.ts b/angularjs/angular-sanitize.d.ts index 56a3bc2ae..43576ae3b 100644 --- a/angularjs/angular-sanitize.d.ts +++ b/angularjs/angular-sanitize.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular JS 1.0 (ngSanitize module) +// Type definitions for Angular JS 1.2 (ngSanitize module) // Project: http://angularjs.org // Definitions by: Diego Vilar // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/angularjs/angular-scenario-1.0.d.ts b/angularjs/angular-scenario-1.0.d.ts new file mode 100644 index 000000000..8dd605f7d --- /dev/null +++ b/angularjs/angular-scenario-1.0.d.ts @@ -0,0 +1,155 @@ +// Type definitions for Angular Scenario Testing +// Project: [http://angularjs.org] +// Definitions by: [RomanoLindano] +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module angularScenario { + export interface AngularModel { + scenario: any; + } + + export interface RunFunction { + (functionToRun: any): any; + } + export interface RunFunctionWithDescription { + (description: string, functionToRun: any): any; + } + + export interface PauseFunction { + (): any; + } + + export interface SleepFunction { + (seconds: number): any; + } + + export interface Future { + } + + export interface testWindow { + href(): Future; + path(): Future; + search(): Future; + hash(): Future; + } + + export interface testLocation { + url(): Future; + path(): Future; + search(): Future; + hash(): Future; + } + + export interface Browser { + navigateTo(url: string): void; + navigateTo(urlDescription: string, urlFunction: () => string): void; + reload(): void; + window(): testWindow; + location(): testLocation; + } + + export interface Matchers { + toEqual(value: any): void; + toBe(value: any): void; + toBeDefined(): void; + toBeTruthy(): void; + toBeFalsy(): void; + toMatch(regularExpression: any): void; + toBeNull(): void; + toContain(value: any): void; + toBeLessThan(value: any): void; + toBeGreaterThan(value: any): void; + } + + export interface CustomMatchers extends Matchers{ + } + + export interface Expect extends CustomMatchers { + not(): angularScenario.CustomMatchers; + } + + export interface UsingFunction { + (selector: string, selectorDescription?: string): void; + } + + export interface BindingFunction { + (bracketBindingExpression: string): Future; + } + + export interface Input { + enter(value: any); + check(): any; + select(radioButtonValue: any): any; + val(): Future; + } + + export interface Repeater { + count(): Future; + row(index: number): Future; + column(ngBindingExpression: string): Future; + } + + export interface Select { + option(value: any): any; + option(...listOfValues: any[]): any; + } + + export interface Element { + count(): Future; + click(): any; + query(callback: (selectedDOMElements: any[], callbackWhenDone: (objNull: any, futureValue: any) => any) =>any): any; + val(): Future; + text(): Future; + html(): Future; + height(): Future; + innerHeight(): Future; + outerHeight(): Future; + width(): Future; + innerWidth(): Future; + outerWidth(): Future; + position(): Future; + scrollLeft(): Future; + scrollTop(): Future; + offset(): Future; + + val(value: any): void; + text(value: any): void; + html(value: any): void; + height(value: any): void; + innerHeight(value: any): void; + outerHeight(value: any): void; + width(value: any): void; + innerWidth(value: any): void; + outerWidth(value: any): void; + position(value: any): void; + scrollLeft(value: any): void; + scrollTop(value: any): void; + offset(value: any): void; + + attr(key: any): Future; + prop(key: any): Future; + css(key: any): Future; + + attr(key: any, value: any): void; + prop(key: any, value: any): void; + css(key: any, value: any): void; + } +} + +declare var describe: angularScenario.RunFunctionWithDescription; +declare var xdescribe: angularScenario.RunFunctionWithDescription; +declare var beforeEach: angularScenario.RunFunction; +declare var afterEach: angularScenario.RunFunction; +declare var it: angularScenario.RunFunctionWithDescription; +declare var xit: angularScenario.RunFunctionWithDescription; +declare var pause: angularScenario.PauseFunction; +declare var sleep: angularScenario.SleepFunction; +declare function browser(): angularScenario.Browser; +declare function expect(expectation: angularScenario.Future): angularScenario.Expect; +declare var using: angularScenario.UsingFunction; +declare var binding: angularScenario.BindingFunction; +declare function input(ngModelBinding: string): angularScenario.Input; +declare function repeater(selector: string, repeaterDescription?: string): angularScenario.Repeater; +declare function select(ngModelBinding: string): angularScenario.Select; +declare function element(selector: string, elementDescription?: string): angularScenario.Element; +declare var angular: angularScenario.AngularModel; diff --git a/angularjs/angular-scenario-1.0.d.ts.tscparams b/angularjs/angular-scenario-1.0.d.ts.tscparams new file mode 100644 index 000000000..e16c76dff --- /dev/null +++ b/angularjs/angular-scenario-1.0.d.ts.tscparams @@ -0,0 +1 @@ +"" diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 6a6892f57..bcfe31d16 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -182,6 +182,7 @@ mod.value('name', 23); mod.value('name', "23"); mod.value(My.Namespace); + // Promise signature tests var foo: ng.IPromise; foo.then((x) => { @@ -217,3 +218,17 @@ var element = angular.element("div.myApp"); var scope: ng.IScope = element.scope(); + +function test_IAttributes(attributes: ng.IAttributes){ + return attributes; +} + +test_IAttributes({ + $addClass: function (classVal){}, + $removeClass: function(classVal){}, + $set: function(key, value){}, + $observe: function(name, fn){ + return fn; + }, + $attr: {} +}); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 145696286..921cbafc9 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -81,11 +81,11 @@ declare module ng { animation(name: string, animationFactory: Function): IModule; animation(name: string, inlineAnnotadedFunction: any[]): IModule; animation(object: Object): IModule; - /** configure existing services. + /** configure existing services. Use this method to register work which needs to be performed on module loading */ config(configFn: Function): IModule; - /** configure existing services. + /** configure existing services. Use this method to register work which needs to be performed on module loading */ config(inlineAnnotadedFunction: any[]): IModule; @@ -94,9 +94,9 @@ declare module ng { controller(name: string, controllerConstructor: Function): IModule; controller(name: string, inlineAnnotadedConstructor: any[]): IModule; controller(object : Object): IModule; - directive(name: string, directiveFactory: (...params:any[])=> IDirective): IModule; + directive(name: string, directiveFactory: Function): IModule; directive(name: string, inlineAnnotadedFunction: any[]): IModule; - directive(object: Object): IModule; + directive(object: Object): IModule; factory(name: string, serviceFactoryFunction: Function): IModule; factory(name: string, inlineAnnotadedFunction: any[]): IModule; factory(object: Object): IModule; @@ -124,9 +124,33 @@ declare module ng { // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes /////////////////////////////////////////////////////////////////////////// interface IAttributes { - $set(name: string, value: any): void; - $observe(name: string, fn:(value?:any)=>any):void; - $attr: any; + // this is necessary to be able to access the scoped attributes. it's not very elegant + // because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way + // this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 + [name: string]: any; + + // Adds the CSS class value specified by the classVal parameter to the + // element. If animations are enabled then an animation will be triggered + // for the class addition. + $addClass(classVal: string): void; + + // Removes the CSS class value specified by the classVal parameter from the + // element. If animations are enabled then an animation will be triggered for + // the class removal. + $removeClass(classVal: string): void; + + // Set DOM element attribute value. + $set(key: string, value: any): void; + + // Observes an interpolated attribute. + // The observer function will be invoked once during the next $digest + // following compilation. The observer is then invoked whenever the + // interpolated value changes. + $observe(name: string, fn:(value?:any)=>any): Function; + + // A map of DOM element attribute names to the normalized name. This is needed + // to do reverse lookup from normalized name back to actual name. + $attr: Object; } /////////////////////////////////////////////////////////////////////////// @@ -139,6 +163,8 @@ declare module ng { $valid: boolean; $invalid: boolean; $error: any; + $addControl(control: ng.INgModelController): void; + $removeControl(control: ng.INgModelController): void; $setDirty(): void; $setPristine(): void; } @@ -189,8 +215,8 @@ declare module ng { $emit(name: string, ...args: any[]): IAngularEvent; // Documentation says exp is optional, but actual implementaton counts on it - $eval(expression: string): any; - $eval(expression: (scope: IScope) => any): any; + $eval(expression: string, args?: Object): any; + $eval(expression: (scope: IScope) => any, args?: Object): any; // Documentation says exp is optional, but actual implementaton counts on it $evalAsync(expression: string): void; @@ -212,7 +238,7 @@ declare module ng { $parent: IScope; $id: number; - + // Hidden members $$isolateBindings: any; $$phase: any; @@ -250,6 +276,15 @@ declare module ng { cancel(promise: IPromise): boolean; } + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ng.$interval + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + (func: Function, delay: number, count?: number, invokeApply?: boolean): IPromise; + cancel(promise: IPromise): boolean; + } + /////////////////////////////////////////////////////////////////////////// // FilterService // see http://docs.angularjs.org/api/ng.$filter @@ -602,12 +637,6 @@ declare module ng { endSymbol(value: string): IInterpolateProvider; } - /////////////////////////////////////////////////////////////////////////// - // RouteParamsService - // see http://docs.angularjs.org/api/ng.$routeParams - /////////////////////////////////////////////////////////////////////////// - interface IRouteParamsService {} - /////////////////////////////////////////////////////////////////////////// // TemplateCacheService // see http://docs.angularjs.org/api/ng.$templateCache @@ -621,45 +650,58 @@ declare module ng { interface IRootScopeService extends IScope {} /////////////////////////////////////////////////////////////////////////// - // RouteService - // see http://docs.angularjs.org/api/ng.$route - // see http://docs.angularjs.org/api/ng.$routeProvider + // SCEService + // see http://docs.angularjs.org/api/ng.$sce /////////////////////////////////////////////////////////////////////////// - interface IRouteService { - reload(): void; - routes: any; + interface ISCEService { + getTrusted(type: string, mayBeTrusted: any): any; + getTrustedCss(value: any): any; + getTrustedHtml(value: any): any; + getTrustedJs(value: any): any; + getTrustedResourceUrl(value: any): any; + getTrustedUrl(value: any): any; + parse(type: string, expression: string): (context: any, locals: any) => any; + parseAsCss(expression: string): (context: any, locals: any) => any; + parseAsHtml(expression: string): (context: any, locals: any) => any; + parseAsJs(expression: string): (context: any, locals: any) => any; + parseAsResourceUrl(expression: string): (context: any, locals: any) => any; + parseAsUrl(expression: string): (context: any, locals: any) => any; + trustAs(type: string, value: any): any; + trustAsHtml(value: any): any; + trustAsJs(value: any): any; + trustAsResourceUrl(value: any): any; + trustAsUrl(value: any): any; + isEnabled(): boolean; + } - // May not always be available. For instance, current will not be available - // to a controller that was not initialized as a result of a route maching. - current?: ICurrentRoute; + /////////////////////////////////////////////////////////////////////////// + // SCEProvider + // see http://docs.angularjs.org/api/ng.$sceProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEProvider extends IServiceProvider { + enabled(value: boolean): void; } - // see http://docs.angularjs.org/api/ng.$routeProvider#when for options explanations - interface IRoute { - controller?: any; - name?: string; - template?: string; - templateUrl?: any; - resolve?: any; - redirectTo?: any; - reloadOnSearch?: boolean; + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateService + // see http://docs.angularjs.org/api/ng.$sceDelegate + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateService { + getTrusted(type: string, mayBeTrusted: any): any; + trustAs(type: string, value: any): any; + valueOf(value: any): any; } - // see http://docs.angularjs.org/api/ng.$route#current - interface ICurrentRoute extends IRoute { - locals: { - $scope: IScope; - $template: string; - }; - - params: any; + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateProvider + // see http://docs.angularjs.org/api/ng.$sceDelegateProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateProvider extends IServiceProvider { + resourceUrlBlacklist(blacklist: any[]): void; + resourceUrlWhitelist(whitelist: any[]): void; } - - interface IRouteProvider extends IServiceProvider { - otherwise(params: any): IRouteProvider; - when(path: string, route: IRoute): IRouteProvider; - } - + /////////////////////////////////////////////////////////////////////////// // Directive // see http://docs.angularjs.org/api/ng.$compileProvider#directive @@ -667,16 +709,29 @@ declare module ng { /////////////////////////////////////////////////////////////////////////// interface IDirective{ + compile?: + (templateElement: any, + templateAttributes: IAttributes, + transclude: (scope: IScope, cloneLinkingFn: Function) => void + ) => any; + controller?: any; + controllerAs?: string; + link?: + (scope: IScope, + instanceElement: any, + instanceAttributes: IAttributes, + controller: any + ) => void; + name?: string; priority?: number; - template?: any; - templateUrl?: any; replace?: boolean; - transclude?: any; + require?: any; restrict?: string; scope?: any; - link?: Function; - compile?: Function; - controller?: any; + template?: any; + templateUrl?: any; + terminal?: boolean; + transclude?: any; } /////////////////////////////////////////////////////////////////////////// diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index e2579c407..3902d8ffd 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -67,16 +67,16 @@ declare module Backbone { } class Events { - on(eventName: any, callback?: (...args: any[]) => void , context?: any): any; - off(eventName?: string, callback?: (...args: any[]) => void , context?: any): any; + on(eventName: any, callback?: Function, context?: any): any; + off(eventName?: string, callback?: Function, context?: any): any; trigger(eventName: string, ...args: any[]): any; - bind(eventName: string, callback: (...args: any[]) => void , context?: any): any; - unbind(eventName?: string, callback?: (...args: any[]) => void , context?: any): any; + bind(eventName: string, callback: Function, context?: any): any; + unbind(eventName?: string, callback?: Function, context?: any): any; - once(events: string, callback: (...args: any[]) => void , context?: any): any; - listenTo(object: any, events: string, callback: (...args: any[]) => void ): any; - listenToOnce(object: any, events: string, callback: (...args: any[]) => void ): any; - stopListening(object?: any, events?: string, callback?: (...args: any[]) => void ): any; + once(events: string, callback: Function, context?: any): any; + listenTo(object: any, events: string, callback: Function): any; + listenToOnce(object: any, events: string, callback: Function): any; + stopListening(object?: any, events?: string, callback?: Function): any; } class ModelBase extends Events { @@ -248,7 +248,7 @@ declare module Backbone { constructor(options?: RouterOptions); initialize(options?: RouterOptions); - route(route: string, name: string, callback?: (...parameter: any[]) => void ); + route(route: string, name: string, callback?: Function); navigate(fragment: string, options?: NavigateOptions); navigate(fragment: string, trigger?: boolean); @@ -269,7 +269,7 @@ declare module Backbone { getHash(window?: Window): string; getFragment(fragment?: string, forcePushState?: boolean): string; stop(): void; - route(route: string, callback: (...args: any[]) => void ); + route(route: string, callback: Function); checkUrl(e?: any): void; loadUrl(fragmentOverride: string): boolean; navigate(fragment: string, options?: any); @@ -339,4 +339,3 @@ declare module Backbone { function setDomLibrary(jQueryNew); } - diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap.datepicker/bootstrap.datepicker.d.ts index 9be7bccc2..4cf27ef19 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap.datepicker/bootstrap.datepicker.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bootstrap.datepicker +// Type definitions for bootstrap.datepicker // Project: https://github.com/eternicode/bootstrap-datepicker // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -24,4 +24,10 @@ interface JQuery { datepicker(methodName: string): JQuery; datepicker(methodName: string, params: any): JQuery; datepicker(options: DatepickerOptions): JQuery; -} \ No newline at end of file + + off(events?: "changeDate", selector?: any, handler?: (eventObject: any) => any): JQuery; + + on(events: "changeDate", selector?: string, data?: any, handler?: (eventObject: any) => any): JQuery; + on(events: "changeDate", selector?: string, handler?: (eventObject: any) => any): JQuery; + on(events: "changeDate", handler?: (eventObject: any) => any): JQuery; +} diff --git a/browser-harness/browser-harness.d.ts b/browser-harness/browser-harness.d.ts index 3b8cf08be..8c410b94a 100644 --- a/browser-harness/browser-harness.d.ts +++ b/browser-harness/browser-harness.d.ts @@ -9,25 +9,25 @@ declare module "browser-harness" { import events = require("events"); interface HarnessEvents extends events.NodeEventEmitter { - once(event: string, listener: (driver: Driver) => void); - once(event: 'ready', listener: (driver: Driver) => void); + once(event: string, listener: (driver: Driver) => void): events.NodeEventEmitter; + once(event: 'ready', listener: (driver: Driver) => void): events.NodeEventEmitter; - on(event: string, listener: (driver: Driver) => void); - on(event: 'ready', listener: (driver: Driver) => void); + on(event: string, listener: (driver: Driver) => void): events.NodeEventEmitter; + on(event: 'ready', listener: (driver: Driver) => void): events.NodeEventEmitter; } interface DriverEvents extends events.NodeEventEmitter { - once(event: string, listener: (text: string) => void); - once(event: 'console.log', listener: (text: string) => void); - once(event: 'console.warn', listener: (text: string) => void); - once(event: 'console.error', listener: (text: string) => void); - once(event: 'window.onerror', listener: (text: string) => void); + once(event: string, listener: (text: string) => void): events.NodeEventEmitter; + once(event: 'console.log', listener: (text: string) => void): events.NodeEventEmitter; + once(event: 'console.warn', listener: (text: string) => void): events.NodeEventEmitter; + once(event: 'console.error', listener: (text: string) => void): events.NodeEventEmitter; + once(event: 'window.onerror', listener: (text: string) => void): events.NodeEventEmitter; - on(event: string, listener: (text: string) => void); - on(event: 'console.log', listener: (text: string) => void); - on(event: 'console.warn', listener: (text: string) => void); - on(event: 'console.error', listener: (text: string) => void); - on(event: 'window.onerror', listener: (text: string) => void); + on(event: string, listener: (text: string) => void): events.NodeEventEmitter; + on(event: 'console.log', listener: (text: string) => void): events.NodeEventEmitter; + on(event: 'console.warn', listener: (text: string) => void): events.NodeEventEmitter; + on(event: 'console.error', listener: (text: string) => void): events.NodeEventEmitter; + on(event: 'window.onerror', listener: (text: string) => void): events.NodeEventEmitter; } export interface Driver { diff --git a/casperjs/casperjs.d.ts b/casperjs/casperjs.d.ts index 4be7b40c4..de43c548b 100644 --- a/casperjs/casperjs.d.ts +++ b/casperjs/casperjs.d.ts @@ -5,39 +5,50 @@ /// -interface Casper { +interface CasperModule { + create(options: CasperOptions): Casper; + selectXPath(expression: string): Object +} - constructor (options: CasperOptions); +interface EventEmitter { + removeAllFilters(filter: string): Casper; + setFilter(filter: string, cb: Function): boolean; +} + +interface Casper extends EventEmitter { + test: Tester; + + constructor (options: CasperOptions): Casper; // Properties __utils__: ClientUtils; // Methods - back(); - base64encode(url: string, method?: string, data?: any); - click(selector: string); - clickLabel(label: string, tag?: string); - capture(targetFilePath: string, clipRect: ClipRect); - captureBase64(format: string); - captureBase64(format: string, area: string); - captureBase64(format: string, area: ClipRect); - captureBase64(format: string, area: any); - captureSelector(targetFile: string, selector: string); - clear(); - debugHTML(selector?: string, outer?: boolean); - debugPage(); - die(message: string, status?: number); - download(url: string, target?: string, method?: string, data?: any); - each(array: Array, fn: (self, link) => void); - echo(message: string, style?: string); - evaluate(fn: Function, ...args: any[]); - evaluateOrDie(fn: Function, message?: string); - exit(status?: number); - exists(selector: string); - fetchText(selector: string); - forward(); - log(message: string, level?: string, space?: string); - fill(selector: string, values: any, submit?: boolean); + back(): Casper; + base64encode(url: string, method?: string, data?: any): string; + click(selector: string): boolean; + clickLabel(label: string, tag?: string): boolean; + capture(targetFilePath: string, clipRect: ClipRect): Casper; + captureBase64(format: string): string; + captureBase64(format: string, area: string): string; + captureBase64(format: string, area: ClipRect): string; + captureBase64(format: string, area: any): string; + captureSelector(targetFile: string, selector: string): Casper; + clear(): Casper; + debugHTML(selector?: string, outer?: boolean): Casper; + debugPage(): Casper; + die(message: string, status?: number): Casper; + download(url: string, target?: string, method?: string, data?: any): Casper; + each(array: T[], fn: (self: Casper, item: T, index: number) => void): Casper; + echo(message: string, style?: string): Casper; + evaluate(fn: () => T, ...args: any[]): T + evaluateOrDie(fn: () => any, message?: string, status?: number): Casper; + exit(status?: number): Casper; + exists(selector: string): boolean; + fetchText(selector: string): string; + forward(): Casper; + log(message: string, level?: string, space?: string): Casper; + fill(selector: string, values: any, submit?: boolean): void; getCurrentUrl(): string; getElementAttribute(selector: string, attribute: string): string; getElementBounds(selector: string): ElementBounds; @@ -48,44 +59,44 @@ interface Casper { getHTML(selector?: string, outer?: boolean): string; getPageContent(): string; getTitle(): string; - mouseEvent(type: string, selector: string); + mouseEvent(type: string, selector: string): boolean; open(location: string, settings: OpenSettings): Casper; - reload(then?: (response: HttpResponse) => void); - repeat(times: number, then: Function); - resourceExists(test: Function); - resourceExists(test: string); - run(onComplete: Function, time?: number); - sendKeys(selector: string, keys: string, options?: any); - setHttpAuth(username: string, password: string); + reload(then?: (response: HttpResponse) => void): Casper; + repeat(times: number, then: Function): Casper; + resourceExists(test: Function): boolean; + resourceExists(test: string): boolean; + run(onComplete: Function, time?: number): Casper; + sendKeys(selector: string, keys: string, options?: any): Casper; + setHttpAuth(username: string, password: string): Casper; start(url?: string, then?: (response: HttpResponse) => void): Casper; status(asString: boolean): any; - then(fn: (self?: Casper) => void); - thenClick(selector: string); - thenEvaluate(fn: Function, ...args: any[]); - thenOpen(location: string, then?: (response: HttpResponse) => void); - thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void); - thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]); - toString(); - userAgent(agent: string); - viewport(width: number, height: number); - visible(selector: string); - wait(timeout: number, then?: Function); - waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number); - waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number); - waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number); - waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number); - waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number); - waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number); - waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number); - waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number); - waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number); - waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number); - warn(message: string); - withFrame(frameInfo: string, then: Function); - withFrame(frameInfo: number, then: Function); - withPopup(popupInfo: string, step: Function); - withPopup(popupInfo: RegExp, step: Function); - zoom(factor: number); + then(fn: (self?: Casper) => void): Casper; + thenClick(selector: string): Casper; + thenEvaluate(fn: () => any, ...args: any[]): Casper; + thenOpen(location: string, then?: (response: HttpResponse) => void): Casper; + thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper; + thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]): Casper; + toString(): string; + userAgent(agent: string): string; + viewport(width: number, height: number): Casper; + visible(selector: string): boolean; + wait(timeout: number, then?: Function): Casper; + waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + warn(message: string): Casper; + withFrame(frameInfo: string, then: Function): Casper; + withFrame(frameInfo: number, then: Function): Casper; + withPopup(popupInfo: string, step: Function): Casper; + withPopup(popupInfo: RegExp, step: Function): Casper; + zoom(factor: number): Casper; } interface HttpResponse { @@ -127,96 +138,105 @@ interface ElementInfo { } interface CasperOptions { - clientScripts: Array; - exitOnError: boolean; - httpStatusHandlers: any; - logLevel: string; - onAlert: Function; - onDie: Function; - onError: Function; - onLoadError: Function; - onPageInitialized: Function; - onResourceReceived: Function; - onResourceRequested: Function; - onStepComplete: Function; - onStepTimeout: Function; - onTimeout: Function; - onWaitTimeout: Function; - page: WebPage; - pageSettings: any; - remoteScripts: Array; - safeLogs: boolean; - stepTimeout: number; - timeout: number; - verbose: boolean; - viewportSize: any; - waitTimeout: number; + clientScripts?: Array; + exitOnError?: boolean; + httpStatusHandlers?: any; + logLevel?: string; + onAlert?: Function; + onDie?: Function; + onError?: Function; + onLoadError?: Function; + onPageInitialized?: Function; + onResourceReceived?: Function; + onResourceRequested?: Function; + onStepComplete?: Function; + onStepTimeout?: Function; + onTimeout?: Function; + onWaitTimeout?: Function; + page?: WebPage; + pageSettings?: any; + remoteScripts?: Array; + safeLogs?: boolean; + stepTimeout?: number; + timeout?: number; + verbose?: boolean; + viewportSize?: any; + waitTimeout?: number; } interface ClientUtils { - echo(message: string); - encode(contents: string); - exists(selector: string); - findAll(selector: string); - findOne(selector: string); - getBase64(url: string, method?: string, data?: any); - getBinary(url: string, method?: string, data?: any); - getDocumentHeight(); - getElementBounds(selector: string); - getElementsBounds(selector: string); - getElementByXPath(expression: string, scope?: HTMLElement); - getElementsByXPath(expression: string, scope?: HTMLElement); - getFieldValue(inputName: string); - getFormValues(selector: string); - mouseEvent(type: string, selector: string); - removeElementsByXPath(expression: string); - sendAJAX(url: string, method?: string, data?: any, async?: boolean); - visible(selector: string); + echo(message: string): void; + encode(contents: string): void; + exists(selector: string): void; + findAll(selector: string): void; + findOne(selector: string): void; + getBase64(url: string, method?: string, data?: any): void; + getBinary(url: string, method?: string, data?: any): void; + getDocumentHeight(): void; + getElementBounds(selector: string): void; + getElementsBounds(selector: string): void; + getElementByXPath(expression: string, scope?: HTMLElement): void; + getElementsByXPath(expression: string, scope?: HTMLElement): void; + getFieldValue(inputName: string): void; + getFormValues(selector: string): void; + mouseEvent(type: string, selector: string): void; + removeElementsByXPath(expression: string): void; + sendAJAX(url: string, method?: string, data?: any, async?: boolean): void; + visible(selector: string): void; } interface Colorizer { - colorize(text: string, styleName: string); - format(text: string, style: any); + colorize(text: string, styleName: string): void; + format(text: string, style: any): void; } interface Tester { - assert(condition: boolean, message?: string); - assertDoesntExist(selector: string, message?: string); - assertEquals(testValue: any, expected: any, message?: string); - assertEval(fn: Function, message: string, arguments: any); - assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any); - assertExists(selector: string, message?: string); - assertFalsy(subject: any, message?: string); - assertField(inputName: string, expected: string, message?: string); - assertHttpStatus(status: number, message?: string); - assertMatch(subject: any, pattern: RegExp, message?: string); - assertNot(subject: any, message?: string); - assertNotEquals(testValue: any, expected: any, message?: string); - assertNotVisible(selector: string, message?: string); - assertRaises(fn: Function, args: Array, message?: string); - assertSelectorDoesntHaveText(selector: string, text: string, message?: string); - assertSelectorExists(selector: string, message?: string); - assertSelectorHasText(selector: string, text: string, message?: string); - assertResourceExists(testFx: Function, message?: string); - assertTextExists(expected: string, message?: string); - assertTextDoesntExist(unexpected: string, message: string); - assertTitle(expected: string, message?: string); - assertTitleMatch(pattern: RegExp, message?: string); - assertTruthy(subject: any, message?: string); - assertType(input: any, type: string, message?: string); - assertUrlMatch(pattern: RegExp, message?: string); - assertVisible(selector: string, message?: string); - colorize(message: string, style: string); - comment(message: string); - done(expected?: number); - error(message: string); - fail(message: string); - formatMessage(message: string, style: string); + assert(condition: boolean, message?: string): any; + assertDoesntExist(selector: string, message?: string): any; + assertElementCount(selctor: string, expected: number, message?: string): any; + assertEquals(testValue: any, expected: any, message?: string): any; + assertEval(fn: Function, message: string, arguments: any): any; + assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any): any; + assertExists(selector: string, message?: string): any; + assertFalsy(subject: any, message?: string): any; + assertField(inputName: string, expected: string, message?: string): any; + assertHttpStatus(status: number, message?: string): any; + assertMatch(subject: any, pattern: RegExp, message?: string): any; + assertNot(subject: any, message?: string): any; + assertNotEquals(testValue: any, expected: any, message?: string): any; + assertNotVisible(selector: string, message?: string): any; + assertRaises(fn: Function, args: Array, message?: string): any; + assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any; + assertSelectorExists(selector: string, message?: string): any; + assertSelectorHasText(selector: string, text: string, message?: string): any; + assertResourceExists(testFx: Function, message?: string): any; + assertTextExists(expected: string, message?: string): any; + assertTextDoesntExist(unexpected: string, message: string): any; + assertTitle(expected: string, message?: string): any; + assertTitleMatch(pattern: RegExp, message?: string): any; + assertTruthy(subject: any, message?: string): any; + assertType(input: any, type: string, message?: string): any; + assertUrlMatch(pattern: string, message?: string): any; + assertUrlMatch(pattern: RegExp, message?: string): any; + assertVisible(selector: string, message?: string): any; + + /* since 1.1 */ + begin(description: string, planned: number, suite: Function): any; + begin(description: string, suite: Function): any; + begin(description: string, planned: number, config: Object): any; + begin(description: string, config: Object): any; + + colorize(message: string, style: string): any; + comment(message: string): any; + done(expected?: number): any; + error(message: string): any; + fail(message: string): any; + formatMessage(message: string, style: string): any; getFailures(): Cases; getPasses(): Cases; - info(message: string); - pass(message: string); - renderResults(exit: boolean, status: number, save: string); + info(message: string): any; + pass(message: string): any; + renderResults(exit: boolean, status: number, save: string): any; } interface Cases { @@ -238,30 +258,30 @@ interface CaseValues { } interface Utils { - betterTypeOf(input: any); - dump(value: any); - fileExt(file: string); - fillBlanks(text: string, pad: number); - format(f: string, ...args: any[]); - getPropertyPath(obj: any, path: string); - inherits(ctor: any, superCtor: any); - isArray(value: any); - isCasperObject(value: any); - isClipRect(value: any); - isFalsy(subject: any); - isFunction(value: any); - isJsFile(file: string); - isNull(value: any); - isNumber(value: any); - isObject(value: any); - isRegExp(value: any); - isString(value: any); - isTruthy(subject: any); - isType(what: any, type: string); - isUndefined(value: any); - isWebPage(what: any); - mergeObjects(origin: any, add: any); - node(name: string, attributes: any); - serialize(value: any); - unique(array: Array); + betterTypeOf(input: any): any; + dump(value: any): any; + fileExt(file: string): any; + fillBlanks(text: string, pad: number): any; + format(f: string, ...args: any[]): any; + getPropertyPath(obj: any, path: string): any; + inherits(ctor: any, superCtor: any): any; + isArray(value: any): any; + isCasperObject(value: any): any; + isClipRect(value: any): any; + isFalsy(subject: any): any; + isFunction(value: any): any; + isJsFile(file: string): any; + isNull(value: any): any; + isNumber(value: any): any; + isObject(value: any): any; + isRegExp(value: any): any; + isString(value: any): any; + isTruthy(subject: any): any; + isType(what: any, type: string): any; + isUndefined(value: any): any; + isWebPage(what: any): any; + mergeObjects(origin: any, add: any): any; + node(name: string, attributes: any): any; + serialize(value: any): any; + unique(array: Array): any; } diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index 8a09c3f42..b559c515d 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -688,6 +688,12 @@ function _throw() { }, "blah: expected [Function] to throw error including 'hello' but got 'testing'"); } +function use(){ + chai.use(function (_chai, utils) { + _chai.can.use.any(); + }); +} + function respondTo() { function Foo() {}; var bar = {}; diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 9d649a17c..9fc93a667 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -8,6 +8,9 @@ declare module chai { function expect(target: any): Expect; + // Provides a way to extend the internals of Chai + function use(fn: (chai: any, utils: any) => void); + interface ExpectStatic { (target: any): Expect; } diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 8b77c9617..8c9ec22dd 100644 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -830,44 +830,11 @@ declare module chrome.events { // Extension //////////////////// declare module chrome.extension { - interface MessageSender { - id: string; - tab?: chrome.tabs.Tab; - } - - interface Port { - postMessage: Function; - sender?: MessageSender; - onDisconnect: chrome.events.Event; - onMessage: chrome.events.Event; - name: string; - } - interface FetchProperties { windowId?: number; type?: string; } - interface ConnectInfo { - name?: string; - } - - interface ExtensionMessageEvent extends chrome.events.Event { - addListener(callback: (message: any, sender: MessageSender, sendResponse: Function) => void): void; - } - - interface ExtensionMessageExternalEvent extends chrome.events.Event { - addListener(callback: (message: any, sender: MessageSender, sendResponse: Function) => void): void; - } - - interface ExtensionConnectEvent extends chrome.events.Event { - addListener(callback: (port: Port) => void): void; - } - - interface ExtensionConnectExternalEvent extends chrome.events.Event { - addListener(callback: (port: Port) => void): void; - } - var inIncognitoContext: boolean; var lastError: Object; @@ -876,15 +843,7 @@ declare module chrome.extension { export function setUpdateUrlData(data: string): void; export function getViews(fetchProperties?: FetchProperties): Window[]; export function isAllowedFileSchemeAccess(callback: (isAllowedAccess: boolean) => void): void; - export function sendMessage(message: any, responseCallback?: (response: any) => void): void; - export function sendMessage(extensionId: string, message: any, responseCallback?: (response: any) => void): void; - export function connect(extensionId?: string, connectInfo?: ConnectInfo): Port; export function isAllowedIncognitoAccess(callback: (isAllowedAccess) => void): void; - - var onMessage: ExtensionMessageEvent; - var onMessageExternal: ExtensionMessageExternalEvent; - var onConnect: ExtensionConnectEvent; - var onConnectExternal: ExtensionConnectExternalEvent; } //////////////////// @@ -1461,11 +1420,62 @@ declare module chrome.runtime { var lastError: Object; var id: string; + interface ConnectInfo { + name?: string; + } + interface InstalledDetails { reason: string; previousVersion?: string; } + interface MessageOptions { + includeTlsChannelId?: boolean; + } + + interface MessageSender { + id: string; + tab?: chrome.tabs.Tab; + } + + interface PlatformInfo { + os: string; + arch: string; + nacl_arch: string; + } + + interface Port { + postMessage: Function; + sender?: MessageSender; + onDisconnect: chrome.events.Event; + onMessage: chrome.events.Event; + name: string; + } + + interface UpdateAvailableDetails { + version: string; + } + + interface UpdateCheckDetails { + version: string; + } + + interface ExtensionMessageEvent extends chrome.events.Event { + addListener(callback: (message: any, sender: MessageSender, sendResponse: Function) => void): void; + } + + interface ExtensionMessageExternalEvent extends chrome.events.Event { + addListener(callback: (message: any, sender: MessageSender, sendResponse: Function) => void): void; + } + + interface ExtensionConnectEvent extends chrome.events.Event { + addListener(callback: (port: Port) => void): void; + } + + interface ExtensionConnectExternalEvent extends chrome.events.Event { + addListener(callback: (port: Port) => void): void; + } + interface RuntimeSuspendEvent extends chrome.events.Event { addListener(callback: Function): void; } @@ -1484,18 +1494,43 @@ declare module chrome.runtime { interface RuntimeMessageEvent extends chrome.events.Event { addListener(callback: Function): void; } + + interface RuntimeRestartRequiredEvent extends chrome.events.Event { + addListener(callback: (reason: string) => void): void; + } + + interface RuntimeUpdateAvailableEvent extends chrome.events.Event { + addListener(callback: (details: UpdateAvailableDetails) => void): void; + } + export function connect(connectInfo?: ConnectInfo): Port; + export function connect(extensionId: string, connectInfo?: ConnectInfo): Port; + export function connectNative(application: string): Port; export function getBackgroundPage(callback: (backgroundPage?: Window) => void): void; export function getManifest(): Object; + export function getPackageDirectoryEntry(callback: (directoryEntry: any) => void): void; + export function getPlatformInfo(callback: (platformInfo: PlatformInfo) => void): void; export function getURL(path: string): string; - + export function reload(): void; + export function requestUpdateCheck(callback: (status: string, details?: UpdateCheckDetails) => void): void; + export function restart(): void; + export function sendMessage(message: any, responseCallback?: (response: any) => void): void; + export function sendMessage(message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + export function sendMessage(extensionId: string, message: any, responseCallback?: (response: any) => void): void; + export function sendMessage(extensionId: string, message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + export function sendNativeMessage(application: string, message: any, responseCallback?: (response: any) => void ): void; + export function setUninstallUrl(url: string): void; + + var onConnect: ExtensionConnectEvent; + var onConnectExternal: ExtensionConnectExternalEvent; var onSuspend: RuntimeSuspendEvent; var onStartup: RuntimeStartupEvent; var onInstalled: RuntimeInstalledEvent; var onSuspendCanceled: RuntimeSuspendCanceledEvent; var onMessage: RuntimeMessageEvent; var onMessageExternal: RuntimeMessageEvent; - var sendMessage:(req:any, cb:(resp:any)=>void)=>void; + var onRestartRequired: RuntimeRestartRequiredEvent; + var onUpdateAvailable: RuntimeUpdateAvailableEvent; } @@ -1718,6 +1753,7 @@ declare module chrome.tabs { } interface TabRemoveInfo { + windowId: number; isWindowClosing: boolean; } diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index 89417e3e5..c2567f62c 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -1,5 +1,5 @@ /** - * Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. + * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ @@ -116,7 +116,7 @@ declare module 'durandal/system' { * @param {object} extension* Uses to extend the target object. */ export function extend(obj: any, ...extensions: any[]): any; - + /** * Uses a setTimeout to wait the specified milliseconds. * @param {number} milliseconds The number of milliseconds to wait. @@ -226,7 +226,7 @@ declare module 'durandal/viewEngine' { * @returns {boolean} True if the url is a view url, false otherwise. */ export function isViewUrl(url: string):boolean; - + /** * Converts a view url into a view id. * @param {string} url The url to convert. @@ -285,62 +285,8 @@ declare module 'durandal/viewEngine' { * @requires system */ declare module 'durandal/events' { - import ts = require('durandal/typescript'); - - /** - * Creates an object with eventing capabilities. - * @class Events - */ - class Events { - constructor(); - - /** - * Creates a subscription or registers a callback for the specified event. - * @param {string} events One or more events, separated by white space. - * @returns {Subscription} A subscription is returned. - */ - on(events: string): ts.EventSubscription; - - /** - * Creates a subscription or registers a callback for the specified event. - * @param {string} events One or more events, separated by white space. - * @param {function} [callback] The callback function to invoke when the event is triggered. - * @param {object} [context] An object to use as `this` when invoking the `callback`. - * @returns {Events} The events object is returned for chaining. - */ - on(events: string, callback: Function, context?: any): Events; - - /** - * Removes the callbacks for the specified events. - * @param {string} [events] One or more events, separated by white space to turn off. If no events are specified, then the callbacks will be removed. - * @param {function} [callback] The callback function to remove. If `callback` is not provided, all callbacks for the specified events will be removed. - * @param {object} [context] The object that was used as `this`. Callbacks with this context will be removed. - * @chainable - */ - off(events: string, callback: Function, context?: any): Events; - - /** - * Triggers the specified events. - * @param {string} [events] One or more events, separated by white space to trigger. - * @chainable - */ - trigger(events: string, ...eventArgs: any[]): Events; - - /** - * Creates a function that will trigger the specified events when called. Simplifies proxying jQuery (or other) events through to the events object. - * @param {string} events One or more events, separated by white space to trigger by invoking the returned function. - * @returns {function} Calling the function will invoke the previously specified events on the events object. - */ - proxy(events: string): Function; - - /** - * Adds eventing capabilities to the specified object. - * @param {object} targetObject The object to add eventing capabilities to. - */ - static includeIn(targetObject: any): void; - } - - export = Events; + var theModule: DurandalEventModule; + export = theModule; } /** @@ -389,7 +335,7 @@ declare module 'durandal/binder' { * @param {object} [obj] The data to bind to, causing the creation of a child binding context if present. */ export function bindContext(bindingContext: KnockoutBindingContext, view: HTMLElement, obj?: any): BindingInstruction; - + /** * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context. * @param {object} obj The data to bind to. @@ -407,136 +353,12 @@ declare module 'durandal/binder' { * @requires knockout */ declare module 'durandal/activator' { - interface ActivatorSettings { - /** - * The default value passed to an object's deactivate function as its close parameter. - * @default true - */ - closeOnDeactivate: boolean; - - /** - * Lower-cased words which represent a truthy value. - * @default ['yes', 'ok', 'true'] - */ - affirmations: string[]; - - /** - * Interprets the response of a `canActivate` or `canDeactivate` call using the known affirmative values in the `affirmations` array. - * @param {object} value - * @returns {boolean} - */ - interpretResponse(value: any): boolean; - - /** - * Determines whether or not the current item and the new item are the same. - * @param {object} currentItem - * @param {object} newItem - * @param {object} currentActivationData - * @param {object} newActivationData - * @returns {boolean} - */ - areSameItem(currentItem: any, newItem: any, currentActivationData: any, newActivationData: any): boolean; - - /** - * Called immediately before the new item is activated. - * @param {object} newItem - */ - beforeActivate(newItem: any): any; - - /** - * Called immediately after the old item is deactivated. - * @param {object} oldItem The previous item. - * @param {boolean} close Whether or not the previous item was closed. - * @param {function} setter The activate item setter function. - */ - afterDeactivate(oldItem: any, close: boolean, setter: Function): void; - } - - interface Activator extends KnockoutComputed { - /** - * The settings for this activator. - */ - settings: ActivatorSettings; - - /** - * An observable which indicates whether or not the activator is currently in the process of activating an instance. - * @returns {boolean} - */ - isActivating: KnockoutObservable; - - /** - * Determines whether or not the specified item can be deactivated. - * @param {object} item The item to check. - * @param {boolean} close Whether or not to check if close is possible. - * @returns {promise} - */ - canDeactivateItem(item: T, close: boolean): JQueryPromise; - - /** - * Deactivates the specified item. - * @param {object} item The item to deactivate. - * @param {boolean} close Whether or not to close the item. - * @returns {promise} - */ - deactivateItem(item: T, close: boolean): JQueryPromise; - - /** - * Determines whether or not the specified item can be activated. - * @param {object} item The item to check. - * @param {object} activationData Data associated with the activation. - * @returns {promise} - */ - canActivateItem(newItem: T, activationData?: any): JQueryPromise; - - /** - * Activates the specified item. - * @param {object} newItem The item to activate. - * @param {object} newActivationData Data associated with the activation. - * @returns {promise} - */ - activateItem(newItem: T, activationData?: any): JQueryPromise; - - /** - * Determines whether or not the activator, in its current state, can be activated. - * @returns {promise} - */ - canActivate(): JQueryPromise; - - /** - * Activates the activator, in its current state. - * @returns {promise} - */ - activate(): JQueryPromise; - - /** - * Determines whether or not the activator, in its current state, can be deactivated. - * @returns {promise} - */ - canDeactivate(close: boolean): JQueryPromise; - - /** - * Deactivates the activator, in its current state. - * @returns {promise} - */ - deactivate(close: boolean): JQueryPromise; - - /** - * Adds canActivate, activate, canDeactivate and deactivate functions to the provided model which pass through to the corresponding functions on the activator. - */ - includeIn(includeIn: any): void; - - /** - * Sets up a collection representing a pool of objects which the activator will activate. See below for details. Activators without an item bool always close their values on deactivate. Activators with an items pool only deactivate, but do not close them. - */ - forItems(items): Activator; - } - /** * The default settings used by activators. * @property {ActivatorSettings} defaults */ - export var defaults: ActivatorSettings; - + export var defaults: DurandalActivatorSettings; + /** * Creates a new activator. * @method create @@ -544,7 +366,7 @@ declare module 'durandal/activator' { * @param {ActivatorSettings} [settings] Per activator overrides of the default activator settings. * @returns {Activator} The created activator. */ - export function create(initialActiveItem?: T, settings?: ActivatorSettings): Activator; + export function create(initialActiveItem?: T, settings?: DurandalActivatorSettings): DurandalActivator; /** * Determines whether or not the provided object is an activator or not. @@ -568,7 +390,7 @@ declare module 'durandal/viewLocator' { * @param {string} [areasPath] Partial views are mapped to the "views" folder if not specified. Use this parameter to change their location. */ export function useConvention(modulesPath?: string, viewsPath?: string, areasPath?: string): void; - + /** * Maps an object instance to a view instance. * @param {object} obj The object to locate the view for. @@ -577,7 +399,7 @@ declare module 'durandal/viewLocator' { * @returns {Promise} A promise of the view. */ export function locateViewForObject(obj: any, area:string, elementsToSearch?: HTMLElement[]): JQueryPromise; - + /** * Converts a module id into a view id. By default the ids are the same. * @param {string} moduleId The module id. @@ -599,7 +421,7 @@ declare module 'durandal/viewLocator' { * @returns {string} The translated view id. */ export function translateViewIdToArea(viewId: string, area: string): string; - + /** * Locates the specified view. * @param {string|DOMElement} view A view. It will be immediately returned. @@ -608,7 +430,7 @@ declare module 'durandal/viewLocator' { * @returns {Promise} A promise of the view. */ export function locateView(view: HTMLElement, area?: string, elementsToSearch?: HTMLElement[]): JQueryPromise; - + /** * Locates the specified view. * @param {string|DOMElement} viewUrlOrId A view url or view id to locate. @@ -725,100 +547,8 @@ declare module 'durandal/composition' { * @requires jquery */ declare module 'durandal/app' { - import Events = require('durandal/events'); - import ts = require('durandal/typescript'); - - /** - * The title of your application. - */ - export var title: string; - - /** - * Shows a dialog via the dialog plugin. - * @param {object|string} obj The object (or moduleId) to display as a dialog. - * @param {object} [activationData] The data that should be passed to the object upon activation. - * @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified. - * @returns {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing. - */ - export function showDialog(obj: any, activationData?: any, context?: string):JQueryPromise; - - /** - * Shows a message box via the dialog plugin. - * @param {string} message The message to display in the dialog. - * @param {string} [title] The title message. - * @param {string[]} [options] The options to provide to the user. - * @returns {Promise} A promise that resolves when the message box is closed and returns the selected option. - */ - export function showMessage(message: string, title?: string, options?: string[]): JQueryPromise; - - /** - * Configures one or more plugins to be loaded and installed into the application. - * @method configurePlugins - * @param {object} config Keys are plugin names. Values can be truthy, to simply install the plugin, or a configuration object to pass to the plugin. - * @param {string} [baseUrl] The base url to load the plugins from. - */ - export function configurePlugins(config: Object, baseUrl?: string): void; - - /** - * Starts the application. - * @returns {promise} - */ - export function start(): JQueryPromise; - - /** - * Sets the root module/view for the application. - * @param {string} root The root view or module. - * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root. - * @param {string} [applicationHost] The application host element id. By default the id 'applicationHost' will be used. - */ - export function setRoot(root: any, transition?: string, applicationHost?: string): void; - - /** - * Sets the root module/view for the application. - * @param {string} root The root view or module. - * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root. - * @param {string} [applicationHost] The application host element. By default the id 'applicationHost' will be used. - */ - export function setRoot(root: any, transition?: string, applicationHost?: HTMLElement): void; - - /** - * Creates a subscription or registers a callback for the specified event. - * @param {string} events One or more events, separated by white space. - * @returns {Subscription} A subscription is returned. - */ - export function on(events: string): ts.EventSubscription; - - /** - * Creates a subscription or registers a callback for the specified event. - * @param {string} events One or more events, separated by white space. - * @param {function} [callback] The callback function to invoke when the event is triggered. - * @param {object} [context] An object to use as `this` when invoking the `callback`. - * @returns {Events} The events object is returned for chaining. - */ - export function on(events: string, callback: Function, context?: any): Events; - - /** - * Removes the callbacks for the specified events. - * @param {string} [events] One or more events, separated by white space to turn off. If no events are specified, then the callbacks will be removed. - * @param {function} [callback] The callback function to remove. If `callback` is not provided, all callbacks for the specified events will be removed. - * @param {object} [context] The object that was used as `this`. Callbacks with this context will be removed. - * @chainable - */ - export function off(events: string, callback: Function, context?: any): Events; - - /** - * Triggers the specified events. - * @param {string} [events] One or more events, separated by white space to trigger. - * @chainable - */ - export function trigger(events: string, ...eventArgs:any[]): Events; - - /** - * Creates a function that will trigger the specified events when called. Simplifies proxying jQuery (or other) events through to the events object. - * @param {string} events One or more events, separated by white space to trigger by invoking the returned function. - * @returns {function} Calling the function will invoke the previously specified events on the events object. - */ - export function proxy(events: string): Function; + var theModule: DurandalAppModule; + export = theModule; } /** @@ -832,7 +562,6 @@ declare module 'durandal/app' { * @requires knockout */ declare module 'plugins/dialog' { - import activator = require('durandal/activator'); import composition = require('durandal/composition'); /** @@ -907,7 +636,7 @@ declare module 'plugins/dialog' { interface Dialog { owner: any; context: DialogContext; - activator: activator.Activator; + activator: DurandalActivator; close(): JQueryPromise; settings: composition.CompositionContext; } @@ -947,7 +676,7 @@ declare module 'plugins/dialog' { * @param {DialogContext} dialogContext The context to add. */ export function addContext(name: string, modalContext: DialogContext): void; - + /** * Gets the dialog model that is associated with the specified object. * @param {object} obj The object for whom to retrieve the dialog. @@ -958,9 +687,9 @@ declare module 'plugins/dialog' { /** * Closes the dialog associated with the specified object. * @param {object} obj The object whose dialog should be closed. - * @param {object} result* The results to return back to the dialog caller after closing. + * @param {object} results* The results to return back to the dialog caller after closing. */ - export function close(obj: any, ...result: any[]): void; + export function close(obj: any, ...results: any[]): void; /** * Shows a dialog. @@ -993,41 +722,6 @@ declare module 'plugins/dialog' { * @requires jquery */ declare module 'plugins/history' { - interface HistoryOptions { - /** - * The function that will be called back when the fragment changes. - */ - routeHandler: (fragment: string) => void; - - /** - * The url root used to extract the fragment when using push state. - */ - root?: string; - - /** - * Use hash change when present. - * @default true - */ - hashChange?: boolean; - - /** - * Use push state when present. - * @default false - */ - pushState?: boolean; - - /** - * Prevents loading of the current url when activating history. - * @default false - */ - silent?: boolean; - } - - interface NavigationOptions { - trigger: boolean; - replace: boolean; - } - /** * The setTimeout interval used when the browser does not support hash change events. * @default 50 @@ -1059,7 +753,7 @@ declare module 'plugins/history' { * @param {HistoryOptions} options. * @returns {boolean|undefined} Returns true/false from loading the url unless the silent option was selected. */ - export function activate(options: HistoryOptions): boolean; + export function activate(options: DurandalHistoryOptions): boolean; /** * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers. @@ -1102,7 +796,7 @@ declare module 'plugins/history' { * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. * @return {boolean} Returns true/false from loading the url. */ - export function navigate(fragment: string, options: NavigationOptions): boolean; + export function navigate(fragment: string, options: DurandalNavigationOptions): boolean; /** * Navigates back in the browser history. @@ -1121,7 +815,7 @@ declare module 'plugins/http' { * @default callback */ export var callbackParam: string; - + /** * Makes an HTTP GET request. * @param {string} url The url to send the get request to. @@ -1138,7 +832,7 @@ declare module 'plugins/http' { * @returns {Promise} A promise of the response data. */ export function jsonp(url: string, query?: Object, callbackParam?: string): JQueryPromise; - + /** * Makes an HTTP POST request. * @param {string} url The url to send the post request to. @@ -1395,324 +1089,571 @@ declare module 'plugins/widget' { * @requires jquery */ declare module 'plugins/router' { - import activator = require('durandal/activator'); - import Events = require('durandal/events'); - import ts = require('durandal/typescript'); - - var RootRouter: ts.RootRouter; - - export = RootRouter; + var theModule: DurandalRootRouter; + export = theModule; } -/** - * Interface definitions used by other modules which were not possible to define within those modules due to TypeScript limitations. - */ -declare module 'durandal/typescript' { - import activator = require('durandal/activator'); - import history = require('plugins/history'); +interface DurandalEventSubscription { + /** + * Attaches a callback to the event subscription. + * @param {function} callback The callback function to invoke when the event is triggered. + * @param {object} [context] An object to use as `this` when invoking the `callback`. + * @chainable + */ + then(thenCallback: Function, context?: any): DurandalEventSubscription; /** - * Represents an event subscription. - * @class - */ - export interface EventSubscription { - /** - * Attaches a callback to the event subscription. - * @param {function} callback The callback function to invoke when the event is triggered. - * @param {object} [context] An object to use as `this` when invoking the `callback`. - * @chainable - */ - then(thenCallback: Function, context?: any): EventSubscription; + * Attaches a callback to the event subscription. + * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, the previous callback will be re-activated. + * @param {object} [context] An object to use as `this` when invoking the `callback`. + * @chainable + */ + on(thenCallback: Function, context?: any): DurandalEventSubscription; - /** - * Attaches a callback to the event subscription. - * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, the previous callback will be re-activated. - * @param {object} [context] An object to use as `this` when invoking the `callback`. - * @chainable - */ - on(thenCallback: Function, context?: any): EventSubscription; - - /** - * Cancels the subscription. - * @chainable - */ - off(): EventSubscription; - } - - export interface RouteConfiguration { - title?: string; - moduleId?: string; - hash?: string; - routePattern?: RegExp; - isActive?: KnockoutComputed; - } - - export interface RouteInstruction { - fragment: string; - queryString: string; - config: RouteConfiguration; - params: any[]; - queryParams: Object; - } - - export interface RelativeRouteSettings { - moduleId?: string; - route?: string; - fromParent?: boolean; - } - - export interface Router { - /** - * The route handlers that are registered. Each handler consists of a `routePattern` and a `callback`. - */ - handlers: { routePattern: RegExp; callback: (fragment: string) => void; }[]; - - /** - * The route configs that are registered. - */ - routes: RouteConfiguration[]; - - /** - * The active item/screen based on the current navigation state. - */ - activeItem: activator.Activator; - - /** - * The route configurations that have been designated as displayable in a nav ui (nav:true). - */ - navigationModel: KnockoutObservableArray; - - /** - * Indicates that the router (or a child router) is currently in the process of navigating. - */ - isNavigating: KnockoutComputed; - - /** - * An observable surfacing the active routing instruction that is currently being processed or has recently finished processing. - * The instruction object has `config`, `fragment`, `queryString`, `params` and `queryParams` properties. - */ - activeInstruction: KnockoutObservable; - - /** - * Parses a query string into an object. - * @param {string} queryString The query string to parse. - * @returns {object} An object keyed according to the query string parameters. - */ - parseQueryString(queryString: string): Object; - - /** - * Add a route to be tested when the url fragment changes. - * @param {RegEx} routePattern The route pattern to test against. - * @param {function} callback The callback to execute when the route pattern is matched. - */ - route(routePattern: RegExp, callback: (fragment: string) => void ): void; - - /** - * Attempt to load the specified URL fragment. If a route succeeds with a match, returns `true`. If no defined routes matches the fragment, returns `false`. - * @param {string} fragment The URL fragment to find a match for. - * @returns {boolean} True if a match was found, false otherwise. - */ - loadUrl(fragment: string): boolean; - - /** - * Updates the document title based on the activated module instance, the routing instruction and the app.title. - * @param {object} instance The activated module. - * @param {object} instruction The routing instruction associated with the action. It has a `config` property that references the original route mapping config. - */ - updateDocumentTitle(instance: Object, instruction: RouteInstruction): void; - - /** - * Save a fragment into the hash history, or replace the URL state if the - * 'replace' option is passed. You are responsible for properly URL-encoding - * the fragment in advance. - * The options object can contain `trigger: false` if you wish to not have the - * route callback be fired, or `replace: true`, if - * you wish to modify the current URL without adding an entry to the history. - * @param {string} fragment The url fragment to navigate to. - * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. - * @return {boolean} Returns true/false from loading the url. - */ - navigate(fragment: string, trigger?: boolean): boolean; - - /** - * Save a fragment into the hash history, or replace the URL state if the - * 'replace' option is passed. You are responsible for properly URL-encoding - * the fragment in advance. - * The options object can contain `trigger: false` if you wish to not have the - * route callback be fired, or `replace: true`, if - * you wish to modify the current URL without adding an entry to the history. - * @param {string} fragment The url fragment to navigate to. - * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. - * @return {boolean} Returns true/false from loading the url. - */ - navigate(fragment: string, options: history.NavigationOptions): boolean; - - /** - * Navigates back in the browser history. - */ - navigateBack(): void; - - /** - * Converts a route to a hash suitable for binding to a link's href. - * @param {string} route - * @returns {string} The hash. - */ - convertRouteToHash(route: string): string; - - /** - * Converts a route to a module id. This is only called if no module id is supplied as part of the route mapping. - * @param {string} route - * @returns {string} The module id. - */ - convertRouteToModuleId(route: string): string; - - /** - * Converts a route to a displayable title. This is only called if no title is specified as part of the route mapping. - * @method convertRouteToTitle - * @param {string} route - * @returns {string} The title. - */ - convertRouteToTitle(route: string): string; - - /** - * Maps route patterns to modules. - * @param {string} route A route. - * @chainable - */ - map(route: string): Router; - - /** - * Maps route patterns to modules. - * @param {string} route A route pattern. - * @param {string} moduleId The module id to map the route to. - * @chainable - */ - map(route: string, moduleId: string): Router; - - /** - * Maps route patterns to modules. - * @param {RegExp} route A route pattern. - * @param {string} moduleId The module id to map the route to. - * @chainable - */ - map(route: RegExp, moduleId: string): Router; - - /** - * Maps route patterns to modules. - * @param {string} route A route pattern. - * @param {RouteConfiguration} config The route's configuration. - * @chainable - */ - map(route: string, config: RouteConfiguration): Router; - - /** - * Maps route patterns to modules. - * @method map - * @param {RegExp} route A route pattern. - * @param {RouteConfiguration} config The route's configuration. - * @chainable - */ - map(route: RegExp, config: RouteConfiguration): Router; - - /** - * Maps route patterns to modules. - * @param {RouteConfiguration} config The route's configuration. - * @chainable - */ - map(config: RouteConfiguration): Router; - - /** - * Maps route patterns to modules. - * @param {RouteConfiguration[]} configs An array of route configurations. - * @chainable - */ - map(configs: RouteConfiguration[]): Router; - - /** - * Builds an observable array designed to bind a navigation UI to. The model will exist in the `navigationModel` property. - * @param {number} defaultOrder The default order to use for navigation visible routes that don't specify an order. The defualt is 100. - * @chainable - */ - buildNavigationModel(defaultOrder?: number): Router; - - /** - * Configures the router to map unknown routes to modules at the same path. - * @chainable - */ - mapUnknownRoutes(): Router; - - /** - * Configures the router use the specified module id for all unknown routes. - * @param {string} notFoundModuleId Represents the module id to route all unknown routes to. - * @param {string} [replaceRoute] Optionally provide a route to replace the url with. - * @chainable - */ - mapUnknownRoutes(notFoundModuleId: string, replaceRoute?: string): Router; - - /** - * Configures how the router will handle unknown routes. - * @param {function} callback Called back with the route instruction containing the route info. The function can then modify the instruction by adding a moduleId and the router will take over from there. - * @chainable - */ - mapUnknownRoutes(callback: (instruction: RouteInstruction) => void ): Router; - - /** - * Configures how the router will handle unknown routes. - * @param {RouteConfiguration} config The route configuration to use for unknown routes. - * @chainable - */ - mapUnknownRoutes(config: RouteConfiguration): Router; - - /** - * Resets the router by removing handlers, routes, event handlers and previously configured options. - * @chainable - */ - reset(): Router; - - /** - * Makes all configured routes and/or module ids relative to a certain base url. - * @param {string} settings The value is used as the base for routes and module ids. - * @chainable - */ - makeRelative(settings: string): Router; - - /** - * Makes all configured routes and/or module ids relative to a certain base url. - * @param {RelativeRouteSettings} settings If an object, you can specify `route` and `moduleId` separately. In place of specifying route, you can set `fromParent:true` to make routes automatically relative to the parent router's active route. - * @chainable - */ - makeRelative(settings: RelativeRouteSettings): Router; - - /** - * Creates a child router. - * @returns {Router} The child router. - */ - createChildRouter(): Router; - - /** - * Inspects routes and modules before activation. Can be used to protect access by cancelling navigation or redirecting. - * @param {object} instance The module instance that is about to be activated by the router. - * @param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties. - * @returns {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types. - */ - guardRoute?:(instance:Object, instruction:RouteInstruction) => any; - } - - export interface RootRouter extends Router { - /** - * Activates the router and the underlying history tracking mechanism. - * @returns {Promise} A promise that resolves when the router is ready. - */ - activate(options?: history.HistoryOptions): JQueryPromise; - - /** - * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers. - */ - deactivate(): void; - - /** - * Installs the router's custom ko binding handler. - */ - install(): void; - } + /** + * Cancels the subscription. + * @chainable + */ + off(): DurandalEventSubscription; } + +interface DurandalEventSupport { + /** + * Creates a subscription or registers a callback for the specified event. + * @param {string} events One or more events, separated by white space. + * @returns {Subscription} A subscription is returned. + */ + on(events: string): DurandalEventSubscription; + + /** + * Creates a subscription or registers a callback for the specified event. + * @param {string} events One or more events, separated by white space. + * @param {function} [callback] The callback function to invoke when the event is triggered. + * @param {object} [context] An object to use as `this` when invoking the `callback`. + * @returns {Events} The events object is returned for chaining. + */ + on(events: string, callback: Function, context?: any): T; + + /** + * Removes the callbacks for the specified events. + * @param {string} [events] One or more events, separated by white space to turn off. If no events are specified, then the callbacks will be removed. + * @param {function} [callback] The callback function to remove. If `callback` is not provided, all callbacks for the specified events will be removed. + * @param {object} [context] The object that was used as `this`. Callbacks with this context will be removed. + * @chainable + */ + off(events: string, callback: Function, context?: any): T; + + /** + * Triggers the specified events. + * @param {string} [events] One or more events, separated by white space to trigger. + * @chainable + */ + trigger(events: string, ...eventArgs: any[]): T; + + /** + * Creates a function that will trigger the specified events when called. Simplifies proxying jQuery (or other) events through to the events object. + * @param {string} events One or more events, separated by white space to trigger by invoking the returned function. + * @returns {function} Calling the function will invoke the previously specified events on the events object. + */ + proxy(events: string): Function; +} + +interface DurandalEventModule { + new (): DurandalEventSupport; + includeIn(targetObject: any): void; +} + +interface DurandalAppModule extends DurandalEventSupport { + /** + * The title of your application. + */ + title: string; + + /** + * Shows a dialog via the dialog plugin. + * @param {object|string} obj The object (or moduleId) to display as a dialog. + * @param {object} [activationData] The data that should be passed to the object upon activation. + * @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified. + * @returns {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing. + */ + showDialog(obj: any, activationData?: any, context?: string): JQueryPromise; + + /** + * Shows a message box via the dialog plugin. + * @param {string} message The message to display in the dialog. + * @param {string} [title] The title message. + * @param {string[]} [options] The options to provide to the user. + * @returns {Promise} A promise that resolves when the message box is closed and returns the selected option. + */ + showMessage(message: string, title?: string, options?: string[]): JQueryPromise; + + /** + * Configures one or more plugins to be loaded and installed into the application. + * @method configurePlugins + * @param {object} config Keys are plugin names. Values can be truthy, to simply install the plugin, or a configuration object to pass to the plugin. + * @param {string} [baseUrl] The base url to load the plugins from. + */ + configurePlugins(config: Object, baseUrl?: string): void; + + /** + * Starts the application. + * @returns {promise} + */ + start(): JQueryPromise; + + /** + * Sets the root module/view for the application. + * @param {string} root The root view or module. + * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root. + * @param {string} [applicationHost] The application host element id. By default the id 'applicationHost' will be used. + */ + setRoot(root: any, transition?: string, applicationHost?: string): void; + + /** + * Sets the root module/view for the application. + * @param {string} root The root view or module. + * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root. + * @param {string} [applicationHost] The application host element. By default the id 'applicationHost' will be used. + */ + setRoot(root: any, transition?: string, applicationHost?: HTMLElement): void; +} + +interface DurandalActivatorSettings { + /** + * The default value passed to an object's deactivate function as its close parameter. + * @default true + */ + closeOnDeactivate: boolean; + + /** + * Lower-cased words which represent a truthy value. + * @default ['yes', 'ok', 'true'] + */ + affirmations: string[]; + + /** + * Interprets the response of a `canActivate` or `canDeactivate` call using the known affirmative values in the `affirmations` array. + * @param {object} value + * @returns {boolean} + */ + interpretResponse(value: any): boolean; + + /** + * Determines whether or not the current item and the new item are the same. + * @param {object} currentItem + * @param {object} newItem + * @param {object} currentActivationData + * @param {object} newActivationData + * @returns {boolean} + */ + areSameItem(currentItem: any, newItem: any, currentActivationData: any, newActivationData: any): boolean; + + /** + * Called immediately before the new item is activated. + * @param {object} newItem + */ + beforeActivate(newItem: any): any; + + /** + * Called immediately after the old item is deactivated. + * @param {object} oldItem The previous item. + * @param {boolean} close Whether or not the previous item was closed. + * @param {function} setter The activate item setter function. + */ + afterDeactivate(oldItem: any, close: boolean, setter: Function): void; +} + +interface DurandalActivator extends KnockoutComputed { + /** + * The settings for this activator. + */ + settings: DurandalActivatorSettings; + + /** + * An observable which indicates whether or not the activator is currently in the process of activating an instance. + * @returns {boolean} + */ + isActivating: KnockoutObservable; + + /** + * Determines whether or not the specified item can be deactivated. + * @param {object} item The item to check. + * @param {boolean} close Whether or not to check if close is possible. + * @returns {promise} + */ + canDeactivateItem(item: T, close: boolean): JQueryPromise; + + /** + * Deactivates the specified item. + * @param {object} item The item to deactivate. + * @param {boolean} close Whether or not to close the item. + * @returns {promise} + */ + deactivateItem(item: T, close: boolean): JQueryPromise; + + /** + * Determines whether or not the specified item can be activated. + * @param {object} item The item to check. + * @param {object} activationData Data associated with the activation. + * @returns {promise} + */ + canActivateItem(newItem: T, activationData?: any): JQueryPromise; + + /** + * Activates the specified item. + * @param {object} newItem The item to activate. + * @param {object} newActivationData Data associated with the activation. + * @returns {promise} + */ + activateItem(newItem: T, activationData?: any): JQueryPromise; + + /** + * Determines whether or not the activator, in its current state, can be activated. + * @returns {promise} + */ + canActivate(): JQueryPromise; + + /** + * Activates the activator, in its current state. + * @returns {promise} + */ + activate(): JQueryPromise; + + /** + * Determines whether or not the activator, in its current state, can be deactivated. + * @returns {promise} + */ + canDeactivate(close: boolean): JQueryPromise; + + /** + * Deactivates the activator, in its current state. + * @returns {promise} + */ + deactivate(close: boolean): JQueryPromise; + + /** + * Adds canActivate, activate, canDeactivate and deactivate functions to the provided model which pass through to the corresponding functions on the activator. + */ + includeIn(includeIn: any): void; + + /** + * Sets up a collection representing a pool of objects which the activator will activate. See below for details. Activators without an item bool always close their values on deactivate. Activators with an items pool only deactivate, but do not close them. + */ + forItems(items): DurandalActivator; +} + +interface DurandalHistoryOptions { + /** + * The function that will be called back when the fragment changes. + */ + routeHandler: (fragment: string) => void; + + /** + * The url root used to extract the fragment when using push state. + */ + root?: string; + + /** + * Use hash change when present. + * @default true + */ + hashChange?: boolean; + + /** + * Use push state when present. + * @default false + */ + pushState?: boolean; + + /** + * Prevents loading of the current url when activating history. + * @default false + */ + silent?: boolean; +} + +interface DurandalNavigationOptions { + trigger: boolean; + replace: boolean; +} + +interface DurandalRouteConfiguration { + title?: string; + moduleId?: string; + hash?: string; + route?: string; + routePattern?: RegExp; + isActive?: KnockoutComputed; + nav:any; +} + +interface DurandalRouteInstruction { + fragment: string; + queryString: string; + config: DurandalRouteConfiguration; + params: any[]; + queryParams: Object; +} + +interface DurandalRelativeRouteSettings { + moduleId?: string; + route?: string; + fromParent?: boolean; +} + +interface DurandalRouterBase extends DurandalEventSupport { + /** + * The route handlers that are registered. Each handler consists of a `routePattern` and a `callback`. + */ + handlers: { routePattern: RegExp; callback: (fragment: string) => void; }[]; + + /** + * The route configs that are registered. + */ + routes: DurandalRouteConfiguration[]; + + /** + * The active item/screen based on the current navigation state. + */ + activeItem: DurandalActivator; + + /** + * The route configurations that have been designated as displayable in a nav ui (nav:true). + */ + navigationModel: KnockoutObservableArray; + + /** + * Indicates that the router (or a child router) is currently in the process of navigating. + */ + isNavigating: KnockoutComputed; + + /** + * An observable surfacing the active routing instruction that is currently being processed or has recently finished processing. + * The instruction object has `config`, `fragment`, `queryString`, `params` and `queryParams` properties. + */ + activeInstruction: KnockoutObservable; + + /** + * Parses a query string into an object. + * @param {string} queryString The query string to parse. + * @returns {object} An object keyed according to the query string parameters. + */ + parseQueryString(queryString: string): Object; + + /** + * Add a route to be tested when the url fragment changes. + * @param {RegEx} routePattern The route pattern to test against. + * @param {function} callback The callback to execute when the route pattern is matched. + */ + route(routePattern: RegExp, callback: (fragment: string) => void): void; + + /** + * Attempt to load the specified URL fragment. If a route succeeds with a match, returns `true`. If no defined routes matches the fragment, returns `false`. + * @param {string} fragment The URL fragment to find a match for. + * @returns {boolean} True if a match was found, false otherwise. + */ + loadUrl(fragment: string): boolean; + + /** + * Updates the document title based on the activated module instance, the routing instruction and the app.title. + * @param {object} instance The activated module. + * @param {object} instruction The routing instruction associated with the action. It has a `config` property that references the original route mapping config. + */ + updateDocumentTitle(instance: Object, instruction: DurandalRouteInstruction): void; + + /** + * Save a fragment into the hash history, or replace the URL state if the + * 'replace' option is passed. You are responsible for properly URL-encoding + * the fragment in advance. + * The options object can contain `trigger: false` if you wish to not have the + * route callback be fired, or `replace: true`, if + * you wish to modify the current URL without adding an entry to the history. + * @param {string} fragment The url fragment to navigate to. + * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. + * @return {boolean} Returns true/false from loading the url. + */ + navigate(fragment: string, trigger?: boolean): boolean; + + /** + * Save a fragment into the hash history, or replace the URL state if the + * 'replace' option is passed. You are responsible for properly URL-encoding + * the fragment in advance. + * The options object can contain `trigger: false` if you wish to not have the + * route callback be fired, or `replace: true`, if + * you wish to modify the current URL without adding an entry to the history. + * @param {string} fragment The url fragment to navigate to. + * @param {object|boolean} options An options object with optional trigger and replace flags. You can also pass a boolean directly to set the trigger option. Trigger is `true` by default. + * @return {boolean} Returns true/false from loading the url. + */ + navigate(fragment: string, options: DurandalNavigationOptions): boolean; + + /** + * Navigates back in the browser history. + */ + navigateBack(): void; + + /** + * Converts a route to a hash suitable for binding to a link's href. + * @param {string} route + * @returns {string} The hash. + */ + convertRouteToHash(route: string): string; + + /** + * Converts a route to a module id. This is only called if no module id is supplied as part of the route mapping. + * @param {string} route + * @returns {string} The module id. + */ + convertRouteToModuleId(route: string): string; + + /** + * Converts a route to a displayable title. This is only called if no title is specified as part of the route mapping. + * @method convertRouteToTitle + * @param {string} route + * @returns {string} The title. + */ + convertRouteToTitle(route: string): string; + + /** + * Maps route patterns to modules. + * @param {string} route A route. + * @chainable + */ + map(route: string): T; + + /** + * Maps route patterns to modules. + * @param {string} route A route pattern. + * @param {string} moduleId The module id to map the route to. + * @chainable + */ + map(route: string, moduleId: string): T; + + /** + * Maps route patterns to modules. + * @param {RegExp} route A route pattern. + * @param {string} moduleId The module id to map the route to. + * @chainable + */ + map(route: RegExp, moduleId: string): T; + + /** + * Maps route patterns to modules. + * @param {string} route A route pattern. + * @param {RouteConfiguration} config The route's configuration. + * @chainable + */ + map(route: string, config: DurandalRouteConfiguration): T; + + /** + * Maps route patterns to modules. + * @method map + * @param {RegExp} route A route pattern. + * @param {RouteConfiguration} config The route's configuration. + * @chainable + */ + map(route: RegExp, config: DurandalRouteConfiguration): T; + + /** + * Maps route patterns to modules. + * @param {RouteConfiguration} config The route's configuration. + * @chainable + */ + map(config: DurandalRouteConfiguration): T; + + /** + * Maps route patterns to modules. + * @param {RouteConfiguration[]} configs An array of route configurations. + * @chainable + */ + map(configs: DurandalRouteConfiguration[]): T; + + /** + * Builds an observable array designed to bind a navigation UI to. The model will exist in the `navigationModel` property. + * @param {number} defaultOrder The default order to use for navigation visible routes that don't specify an order. The defualt is 100. + * @chainable + */ + buildNavigationModel(defaultOrder?: number): T; + + /** + * Configures the router to map unknown routes to modules at the same path. + * @chainable + */ + mapUnknownRoutes(): T; + + /** + * Configures the router use the specified module id for all unknown routes. + * @param {string} notFoundModuleId Represents the module id to route all unknown routes to. + * @param {string} [replaceRoute] Optionally provide a route to replace the url with. + * @chainable + */ + mapUnknownRoutes(notFoundModuleId: string, replaceRoute?: string): T; + + /** + * Configures how the router will handle unknown routes. + * @param {function} callback Called back with the route instruction containing the route info. The function can then modify the instruction by adding a moduleId and the router will take over from there. + * @chainable + */ + mapUnknownRoutes(callback: (instruction: DurandalRouteInstruction) => void): T; + + /** + * Configures how the router will handle unknown routes. + * @param {RouteConfiguration} config The route configuration to use for unknown routes. + * @chainable + */ + mapUnknownRoutes(config: DurandalRouteConfiguration): T; + + /** + * Resets the router by removing handlers, routes, event handlers and previously configured options. + * @chainable + */ + reset(): T; + + /** + * Makes all configured routes and/or module ids relative to a certain base url. + * @param {string} settings The value is used as the base for routes and module ids. + * @chainable + */ + makeRelative(settings: string): T; + + /** + * Makes all configured routes and/or module ids relative to a certain base url. + * @param {RelativeRouteSettings} settings If an object, you can specify `route` and `moduleId` separately. In place of specifying route, you can set `fromParent:true` to make routes automatically relative to the parent router's active route. + * @chainable + */ + makeRelative(settings: DurandalRelativeRouteSettings): T; + + /** + * Creates a child router. + * @returns {Router} The child router. + */ + createChildRouter(): T; + + /** + * Inspects routes and modules before activation. Can be used to protect access by cancelling navigation or redirecting. + * @param {object} instance The module instance that is about to be activated by the router. + * @param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties. + * @returns {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types. + */ + guardRoute?: (instance: Object, instruction: DurandalRouteInstruction) => any; +} + +interface DurandalRouter extends DurandalRouterBase { } + +interface DurandalRootRouter extends DurandalRouterBase { + /** + * Activates the router and the underlying history tracking mechanism. + * @returns {Promise} A promise that resolves when the router is ready. + */ + activate(options?: DurandalHistoryOptions): JQueryPromise; + + /** + * Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers. + */ + deactivate(): void; + + /** + * Installs the router's custom ko binding handler. + */ + install(): void; +} \ No newline at end of file diff --git a/ember/ember.d.ts b/ember/ember.d.ts index 2ef232644..574bb3b9f 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -2728,13 +2728,13 @@ declare module Ember { (target: any, method: Function): void; begin(): void; cancel(timer: any): void; - debounce(target: any, method: Function, wait: number, immediate: boolean): void; - debounce(target: any, method: string, wait: number, immediate: boolean): void; + debounce(target: any, method: Function, ...args: any[]): void; + debounce(target: any, method: string, ...args: any[]): void; end(): void; join(target: any, method: Function, ...any): any; join(target: any, method: string, ...any): any; - later(target: any, method: Function, wait: boolean): string; - later(target: any, method: string, wait: boolean): string; + later(target: any, method: Function, ...args: any[]): string; + later(target: any, method: string, ...args: any[]): string; next(target: any, method: Function, ...any): number; next(target: any, method: string, ...any): number; once(target: any, method: Function, ...any): number; @@ -2744,8 +2744,8 @@ declare module Ember { scheduleOnce(queue: string, target: any, method: Function, ...any): void; scheduleOnce(queue: string, target: any, method: string, ...any): void; sync(): void; - throttle(target: any, method: Function, spacing: number): void; - throttle(target: any, method: string, spacing: number): void; + throttle(target: any, method: Function, ...args: any[]): void; + throttle(target: any, method: string, ...args: any[]): void; queues: any[]; }; function runLoadHooks(name: string, object: any): void; diff --git a/flight/flight-tests.ts b/flight/flight-tests.ts new file mode 100644 index 000000000..1bfe68d3a --- /dev/null +++ b/flight/flight-tests.ts @@ -0,0 +1,49 @@ +/// +declare var el: Element; +declare var els: Element[]; +declare var mixinFn: Function; + +function TestComponent() { + var self: Flight.Component = this; + + self.defaultAttrs({ + fooSelector: '.bar' + }); + + this.onClick = function (ev: JQueryEventObject, data: Flight.EventData) { + var el: HTMLElement = data.el; + self.select('fooSelector').addClass('bar'); + }; + + self.around('initialize', function () { }); + self.before('initialize', function () { }); + self.after("initialize", function () { + + var $node: JQuery = self.$node; + var node: Element = self.node; + + self.on(el, 'click', {}); + self.on(els, 'click', function () { }); + self.on(document, 'click', this.onClick); + self.on('click', function () { }); + self.on('click', { + fooSelector: this.onClick + }); + + self.off('click', function () { }); + self.off(document, 'click'); + self.off(el, 'click') + self.off(els, 'click'); + + self.teardown(); + }); +} + +flight.component(TestComponent, mixinFn).attachTo(el); +flight.component(TestComponent, mixinFn).attachTo($(els)); +flight.component(TestComponent, mixinFn).attachTo('.test'); +flight.component(TestComponent, mixinFn).attachTo('.test', { + some: 'data' +}); + +flight.component.teardownAll(); diff --git a/flight/flight.d.ts b/flight/flight.d.ts new file mode 100644 index 000000000..a00f6d958 --- /dev/null +++ b/flight/flight.d.ts @@ -0,0 +1,238 @@ +/// + +// Type definitions for Flight 1.1.1 +// Project: http://flightjs.github.com/flight/ +// Definitions by: Jonathan Hedrén +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Flight { + + export interface Base { + + /** + * Most Components and Mixins need to define attributes. In Flight, + * default values are assigned by passing an object to the defaultAttrs + * function. + */ + defaultAttrs(obj: Object): void; + + /** + * The select method takes an attr key as its argument. The value of the + * attr must be a CSS Selector. The method will return all matching + * elements within the component's node. + * + * This is a handy alternative to jQuery's this.$node.find() and prevents + * accidental access to elements outside of the component's node. + * + * @param attr + */ + select(attr: string): JQuery; + + /** + * This method is attached to the prototype of every Component; it accepts + * the component's node and an options object as arguments. The core + * implementation, which is called every time an instance is created, will + * assign the node to the instance and override the default attrs with the + * options object. + * + * Components and Mixins will typically augment the core implementation by + * supplying a function as an argument to the after method (see the advice + * API for more information). This is a good place to set up event + * listeners that bind to callbacks. + */ + initialize(node: any, options: Object): void; + + /** + * This allows a component instance to listen to an event and register a + * callback to be invoked. Flight will automatically bind the context + * (this) of the callback to the component instance. + * + * @param selector Optional. Specify the DOM node(s) that should listen + * for the event. Defaults to the component instance's node value. + * + * @param eventType The event type to listen for. + * + * @param handler Either a function (callback) to be invoked, or a map of + * targets and callbacks. + */ + on(eventType: string, handler: Function): void; + on(eventType: string, handler: Object): void; + on(selector: string, eventType: string, handler: Function): void; + on(selector: Document, eventType: string, handler: Function): void; + on(selector: Element, eventType: string, handler: Function): void; + on(selector: Element[], eventType: string, handler: Function): void; + on(selector: string, eventType: string, handler: Object): void; + on(selector: Document, eventType: string, handler: Object): void; + on(selector: Element, eventType: string, handler: Object): void; + on(selector: Element[], eventType: string, handler: Object): void; + + /** + * If we no longer want a component instance to listen to an event we can + * use the off method to unsubscribe. + * + * @param selector Optional. The DOM node(s) listening for the event. + * Defaults to the component instance's node value. + * + * @param eventType The event type being listened to. + * + * @param handler Optional. The function (callback) to detach from the + * component instance. Defaults to the detaching all callbacks for the event. + */ + off(eventType: string, handler?: Function): void; + off(selector: string, eventType: string, handler?: Function): void; + off(selector: Document, eventType: string, handler?: Function): void; + off(selector: Element, eventType: string, handler?: Function): void; + off(selector: Element[], eventType: string, handler?: Function): void; + off(selector: string, eventType: Object, handler?: Function): void; + off(selector: Document, eventType: Object, handler?: Function): void; + off(selector: Element, eventType: Object, handler?: Function): void; + off(selector: Element[], eventType: Object, handler?: Function): void; + off(selector: string, eventType: string, handler?: Object): void; + off(selector: Document, eventType: string, handler?: Object): void; + off(selector: Element, eventType: string, handler?: Object): void; + off(selector: Element[], eventType: string, handler?: Object): void; + off(selector: string, eventType: Object, handler?: Object): void; + off(selector: Document, eventType: Object, handler?: Object): void; + off(selector: Element, eventType: Object, handler?: Object): void; + off(selector: Element[], eventType: Object, handler?: Object): void; + + /** + * Trigger an event. + * + * @param selector Optional. The DOM node(s) that the event will be + * dispatched to. Defaults to the component instance's node value. + * + * @param eventType String. The event type to be triggered. + * + * You can also specify a default function that will be called by the + * component, providing that nothing in the event's bubble chain invokes + * preventDefault. Default functions in custom events are analagous to the + * default actions of native events. + * + * To define a default function, make the eventType argument an object + * that specifies the event's type and a defaultBehavior property. A + * common use case is defining default behavior for keyboard events. + * + * @param eventPayload This is the payload of data that accompanies the event. + */ + trigger(eventType: string): void; + trigger(selector: string, eventType: string, eventPayload?: Object): void; + trigger(selector: Document, eventType: string, eventPayload?: Object): void; + trigger(selector: Element, eventType: string, eventPayload?: Object): void; + trigger(selector: Element[], eventType: string, eventPayload?: Object): void; + trigger(eventType: Object): void; + trigger(selector: string, eventType: Object, eventPayload?: Object): void; + trigger(selector: Document, eventType: Object, eventPayload?: Object): void; + trigger(selector: Element, eventType: Object, eventPayload?: Object): void; + trigger(selector: Element[], eventType: Object, eventPayload?: Object): void; + + /** + * Remove a component instance and its event bindings. + * + * It's a good idea to teardown components after each unit test - and + * teardown is also good for unbinding event listeners when, for example, + * the user navigates away from a page. + * + */ + teardown(): void; + } + + export interface Advice extends Base { + /** + * Run the customFunc function after the existingFunc function. + * + * @param existingFuncName The name of the existing function (existingFunc) + * you want to augment. + * + * customFunc The function to be invoked after existingFunc. + */ + after(method: string, fn: Function): void; + + /** + * Run the existingFunc function in the middle of the customFunc function. + * It's similar to underscore's _wrap function). + * + * @param existingFuncName The name of the existing function (existingFunc) + * you want to augment. + * + * customFunc The function to wrap around existingFunc. The existingFunc + * function will be passed to customFunc as an argument. + * + * The existing function is passed to the custom function as an argument so + * that it can be referenced. If the custom function does not call the + * existing function then it will replace that function instead of + * surrounding it. + */ + around(method: string, fn: Function): void; + + /** + * Run the customFunc function before the existingFunc function. + * + * @param existingFuncName The name of the existing function (existingFunc) + * you want to augment. + * + * @param customFunc The function to be invoked before existingFunc. + */ + before(method: string, fn: Function): void; + } + + export interface Component extends Base, Advice { + node: Element; + $node: JQuery; + } + + + export interface AdviceStatic { + withAdvice(): Function; + } + + export interface ComponentStatic { + (...fns: Function[]): ComponentStatic; + attachTo(selector: string, options?: Object): void; + attachTo(selector: Element, options?: Object): void; + attachTo(selector: JQuery, options?: Object): void; + teardownAll(): void; + } + + export interface ComposeStatic { + mixin(base: Object, mixins: Function[]): void; + } + + export interface DebugStatic { + events: { + logAll(): void; + logByAction(action: string): void; + logByName(name: string): void; + logNone(): void; + } + } + + export interface UtilsStatic { + compose(fn1: Function, fn2: Function, ...fns: Function[]): Function; + countThen(num: number, base: Function): Function; + debounce(func: Function, wait: number, immediate: boolean): Function; + delegate(rules: Object): void; + isDomObj(obj: Object): boolean; + isEnumerable(obj: Object, property: string): boolean; + merge(obj1: Object, obj2: Object, deepClone?: boolean): Object; + merge(obj1: Object, obj2: Object, ...args: any[]): Object; + push(base: Object, extra: Object, protect?: boolean): void; + throttle(func: Function, wait: number): Function; + toArray(obj: Object, from?: number): Array; + uniqueArray(array: Array): Array; + } + + export interface EventData { + el: HTMLElement; + } + + export interface FlightStatic { + advice: AdviceStatic; + component: ComponentStatic; + compose: ComposeStatic; + utils: UtilsStatic; + } +} + +declare var DEBUG: Flight.DebugStatic; +declare var flight: Flight.FlightStatic; \ No newline at end of file diff --git a/flot/jquery.flot.d.ts b/flot/jquery.flot.d.ts index fc484aae5..542810545 100644 --- a/flot/jquery.flot.d.ts +++ b/flot/jquery.flot.d.ts @@ -72,7 +72,7 @@ declare module jquery.flot { } interface seriesOptions { - color?: number; + color?: any; // color or number label?: string; lines?: linesOptions; bars?: barsOptions; diff --git a/globalize/globalize-tests.ts b/globalize/globalize-tests.ts index 577330424..5174f90f9 100644 --- a/globalize/globalize-tests.ts +++ b/globalize/globalize-tests.ts @@ -22,10 +22,14 @@ Globalize.addCultureInfo("fr", { messages: { "translate": "traduire" } }); console.log(Globalize.localize("translate", "fr")); Globalize.parseInt("1,234.56"); -Globalize.parseInt("1.234,56"); +Globalize.parseInt("1.234,56", 10); +Globalize.parseInt("1.234,56", 10, "de"); Globalize.parseFloat("1,234.56"); -Globalize.parseFloat("1.234,56"); +Globalize.parseFloat("1.234,56", 10); +Globalize.parseFloat("1.234,56", 10, "de"); Globalize.parseDate("1/2/2003"); +Globalize.parseDate("15 Jun 2012", "dd MMM yyyy"); +Globalize.parseDate("15 Jun 2012", ["dd MMM yyyy"]); Globalize.culture("fr"); Globalize.parseDate("1/2/2003"); diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index dd2876bc8..da17957f1 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -107,14 +107,16 @@ interface GlobalizeStatic { culture(cultureSelector: string): GlobalizeCulture; culture(cultureSelector: string[]): GlobalizeCulture; - addCultureInfo(cultureName, baseCultureName, info? ); + addCultureInfo(cultureName: string, baseCultureName, info?); findClosestCulture(cultureSelector: string); - format(value, format, cultureSelector? ); - localize(key, cultureSelector?); + format(value: number, format: string, cultureSelector?: string); + format(value: Date, format: string, cultureSelector?: string); + localize(key: string, cultureSelector?: string); - parseDate(value: string, formats? , cultureSelector?: string): Date; - parseInt(value: string, radix? , cultureSelector?: string): number; - parseFloat(value: string, radix? , cultureSelector?: string): number; + parseDate(value: string, format?: string, cultureSelector?: string): Date; + parseDate(value: string, formats?: string[], cultureSelector?: string): Date; + parseInt(value: string, radix?: number, cultureSelector?: string): number; + parseFloat(value: string, radix?: number, cultureSelector?: string): number; } declare var Globalize: GlobalizeStatic; diff --git a/google.visualization/google.visualization-tests.ts b/google.visualization/google.visualization-tests.ts new file mode 100644 index 000000000..0f0082816 --- /dev/null +++ b/google.visualization/google.visualization-tests.ts @@ -0,0 +1,41 @@ +/// + +function test_arrayToDataTable() { + var array = [ + ['City', 'Population', 'Area'], + ['Rome', 2761477, 1285.31], + ['Milan', 1324110, 181.76], + ['Naples', 959574, 117.27], + ['Turin', 907563, 130.17], + ['Palermo', 655875, 158.9], + ['Genoa', 607906, 243.60], + ['Bologna', 380181, 140.7], + ['Florence', 371282, 102.41], + ['Fiumicino', 67370, 213.44], + ['Anzio', 52192, 43.43], + ['Ciampino', 38262, 11], + ]; + + var dataTable = google.visualization.arrayToDataTable(array); +} + +function test_ctorDataTable() { + var dataTable = new google.visualization.DataTable(); + return dataTable; +} + +function test_dataTableAddColumn() { + var dataTable = test_ctorDataTable(); + dataTable.addColumn('string', 'First Column'); + dataTable.addColumn('number', 'Second Column'); +} + +function test_dataTableAddRow() { + var dataTable = test_ctorDataTable(); + dataTable.addRow(['row1', 6]); + dataTable.addRow(['row2', -1]); + dataTable.addRow(['row3', 0]); +} + + + diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts new file mode 100644 index 000000000..511d65a23 --- /dev/null +++ b/google.visualization/google.visualization.d.ts @@ -0,0 +1,369 @@ +declare module google { + + function load(visualization: string, version: string, packages: any): void; + function setOnLoadCallback(handler: Function): void; + function setOnLoadCallback(handler: () => void): void; + + //https://developers.google.com/chart/interactive/docs/reference + module visualization { + //#region DataTable + + // https://developers.google.com/chart/interactive/docs/reference#DataTable + export class DataTable { + constructor(data?: any, version?: any); + addColumn(type: string, label?: string, id?: string): number; + addColumn(descriptionObject: DataTableColumnDescription): number; + addRow(cellObject: DataObjectCell): number; + addRow(cellArray?: any[]): number; + addRows(count: number): number; + addRows(array: DataObjectCell[][]): number; + addRows(array: any[]): number; + getFilteredRows(filters: DataTableCellFilter[]): number[]; + getFormattedValue(rowIndex: number, columnIndex: number): string; + getNumberOfColumns(): number; + getNumberOfRows(): number; + removeRow(rowIndex: number): void; + removeRows(rowIndex: number, numberOfRows: number): void; + setColumnLabel(columnIndex: number, label: string): void; + } + + export interface DataTableColumnDescription { + type?: string; + label?: string; + id?: string; + role?: string; + pattern?: string; + } + + export interface DataObject { + cols: DataObjectColumn[]; + rows: DataObjectRow[]; + p: any; + } + + export interface DataObjectColumn { + type: string; + id?: string; + label?: string; + pattern?: string; + p?: any; + } + + export interface DataObjectRow { + c: DataObjectCell[]; + p?: any; + } + + export interface DataTableCellFilter { + column: number; + } + + export interface DataObjectCell { + v?: any; + f?: string; + p?: any; + } + + export interface DataTableCellValueFilter extends DataTableCellFilter { + value: any; + } + + export interface DataTableCellRangeFilter extends DataTableCellFilter { + minValue?: any; + maxValue?: any; + } + + function arrayToDataTable(data: any[]): DataTable; + + //#endregion + //#region DataView + + // https://developers.google.com/chart/interactive/docs/reference#DataView + export class DataView { + constructor(data: DataTable); + constructor(data: DataView); + setColumns(columnIndexes: number[]): void; + } + + //#endregion + //#region GeoChart + + //https://google-developers.appspot.com/chart/interactive/docs/gallery/geochart + export class GeoChart { + constructor(element: Element); + + // https://developers.google.com/chart/interactive/docs/gallery/geochart?hl=fr&csw=1#Methods + draw(data: DataTable, options: GeoChartOptions): void; + getSelection(): GeoChartSelection[]; + setSelection(selection: VisualizationSelectionArray[]): void; + clearChart(): void; + } + + // https://developers.google.com/chart/interactive/docs/gallery/geochart?hl=fr&csw=1#Configuration_Options + export interface GeoChartOptions { + backgroundColor?: any; + colorAxis?: GeoChartColorAxis; + datalessRegionColor?: string; + displayMode?: string; + enableRegionInteractivity?: boolean; + height?: number; + keepAspectRatio?: boolean; + legend?: GeoChartLegend; + region?: string; + magnifyingGlass?: GeoChartMagnifyingGlass; + markerOpacity?: number; + resolution?: string; + sizeAxis?: GeoChartAxis; + tooltip?: GeoChartTooltip; + width?: number; + } + export interface GeoChartAxis { + maxSize?: number; + maxValue?: number; + minSize?: number; + minValue?: number; + } + export interface GeoChartColorAxis extends GeoChartAxis { + minValue?: number; + maxValue?: number; + values?: number[]; + colors?: string[]; + } + export interface GeoChartTextStyle { + color?: string; + fontName?: string; + fontSize?: number; + bold?: boolean; + italic?: boolean; + } + export interface GeoChartLegend { + numberFormat?: string; + textStyle?: GeoChartTextStyle; + } + export interface GeoChartMagnifyingGlass { + enable?: boolean; + zoomFactor?: number; + } + export interface GeoChartTooltip { + textStyle?: GeoChartTextStyle; + trigger?: string; + } + export interface GeoChartRegionClickEvent { + region: string; + } + export interface GeoChartSelection { + row: number; + } + + //#endregion + //#region Common + + export interface ChartArea { + top: any; + left: any; + width: any; + height: any; + } + + export interface ChartTextStyle { + color?: string; + fontName?: string; + fontSize?: number; + bold?: boolean; + italic?: boolean; + } + + export interface ChartLegend { + alignment?: string; + maxLines?: number; + position?: string; + textStyle?: ChartTextStyle; + } + + // https://google-developers.appspot.com/chart/interactive/docs/animation + export interface TransitionAnimation { + duration?: number; + easing?: string; // linear, in, out, inAndOut + } + + export interface ChartAxis { + baseline?: number; // This option is only supported for a continuous axis. https://google-developers.appspot.com/chart/interactive/docs/customizing_axes#Terminology + baselineColor?: string; // google's documentation on this is wrong, specifies it as a number. The color of the baseline for the horizontal axis. Can be any HTML color string, for example: 'red' or '#00cc00' + direction?: number; // The direction in which the values along the horizontal axis grow. Specify -1 to reverse the order of the values. + format?: string; // icu pattern set http://icu-project.org/apiref/icu4c/classDecimalFormat.html#_details + gridlines?: ChartGridlines; + logScale?: boolean; + textPosition?: string; + textStyle?: ChartTextStyle; + ticks?: any[]; + title?: string; + titleTextStyle?: ChartTextStyle; + allowContainerBoundaryTextCufoff?: boolean; + slantedText?: boolean; + slantedTextAngle?: number; + maxAlternation?: number; + maxTextLines?: number; + minTextSpacing?: number; + showTextEvery?: number; + maxValue?: number; + minValue?: number; + viewWindowMode?: string; + viewWindow?: ChartViewWindow; + } + + export interface ChartGridlines { + color?: string; + count?: number; + minorGridlines?: ChartMinorGridlines; + } + + export interface ChartMinorGridlines { + color?: string; + count?: number; + } + + export interface ChartViewWindow { + max?: number; + min?: number; + } + + export interface ChartTooltip { + isHtml?: boolean; + showColorCode?: boolean; + textStyle?: ChartTextStyle; + trigger?: string; + } + + export interface ChartBoundingBox { + left: number; + top: number; + width: number; + height: number; + } + + export interface ChartLayoutInterface { + getBoundingBox(id: string): ChartBoundingBox; + getChartAreaBoundingBox(): ChartBoundingBox; + getHAxisValue(position: number, axisIndex?: number): number; + getVAxisValue(position: number, axisIndex?: number): number; + getXLocation(position: number, axisIndex?: number): number; + getYLocation(position: number, axisIndex?: number): number; + } + + export interface VisualizationSelectionArray { + column?: number; + row?: number; + } + + //#endregion + //#region ColumnChart + + // https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart + export class ColumnChart { + constructor(element: Element); + + // https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart#Methods + draw(data: DataTable, options?: ColumnChartOptions): void; + draw(data: DataView, options?: ColumnChartOptions): void; + getChartLayoutInterface(): ChartLayoutInterface; + getSelection(): any[]; + setSelection(selection: any[]): void; + clearChart(): void; + } + + // https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart#Configuration_Options + export interface ColumnChartOptions { + aggregationTarget?: string; + animation?: TransitionAnimation; + axisTitlesPosition?: string; // in, out, none + backgroundColor?: any; + bar?: ColumnChartBarOptions; + chartArea?: ChartArea; + colors?: string[]; + enableInteractivity?: boolean; + focusTarget?: string; + fontSize?: number; + fontName?: string; + hAxis?: ChartAxis; + height?: number; + isStacked?: boolean; + legend?: ChartLegend; + reverseCategories?: boolean; + selectionMode?: string // single / multiple + series?: any; + theme?: string; + title?: string; + titlePosition?: string; + titleTextStyle?: ChartTextStyle; + tooltip?: ChartTooltip; + vAxes?: any; + vAxis?: ChartAxis; + width?: number; + } + + export interface ColumnChartBarOptions { + groupWidth: any; + } + + //#endregion + //#region LineChart + + // https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart + export class LineChart { + constructor(element: Element); + + // https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#Methods + draw(data: DataTable, options: any): void; + draw(data: DataView, options: any): void; + getChartLayoutInterface(): ChartLayoutInterface; + getSelection(): any[]; + setSelection(selection: any[]): void; + clearChart(): void; + } + + // https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#Configuration_Options + export interface LineChartOptions { + aggregationTarget?: string; + animation?: TransitionAnimation; + axisTitlesPosition?: string; + backgroundColor?: any; + chartArea?: ChartArea; + colors?: string[]; + curveType?: string; + enableInteractivity?: boolean; + focusTarget?: string; + fontSize?: number; + fontName?: string; + hAxis?: ChartAxis; + height?: number; + interpolateNulls?: boolean; + legend?: ChartLegend; + lineWidth?: number; + pointSize?: number; + reverseCategories?: boolean; + selectionMode?: string // single / multiple + series?: any; + theme?: string; + title?: string; + titlePosition?: string; + titleTextStyle?: ChartTextStyle; + tooltip?: ChartTooltip; + vAxes?: any; + vAxis?: ChartAxis; + width?: number; + } + + //#endregion + //#region Events + + module events { + function addListener(visualization: any, eventName: string, callback: Function): any; + function addListener(visualization: any, eventName: string, callback: (...args: any[]) => void): any; + function removeListener(listener: any): void; + function removeAllListeners(visualization: any): void; + function trigger(visualization: any, eventName: string, args?: any): void; + } + + //#endregion + } +} \ No newline at end of file diff --git a/greasemonkey/greasemonkey-tests.ts b/greasemonkey/greasemonkey-tests.ts new file mode 100644 index 000000000..914c8f4e3 --- /dev/null +++ b/greasemonkey/greasemonkey-tests.ts @@ -0,0 +1,220 @@ +/// + +//////////////// +// Global variable +//////////////// + +var title: string = unsafeWindow.document.title; + +var scriptDescription: string = GM_info.script.description; +var scriptExcludes: string[] = GM_info.script.excludes; +var scriptIncludes: string[] = GM_info.script.includes; +var scriptMatches: string[] = GM_info.script.matches; +var scriptName: string = GM_info.script.name; +var scriptNamespace: string = GM_info.script.namespace; +var scriptResouces: Object = GM_info.script.resources; +var scriptRunAt: string = GM_info.script['run-at']; +var scriptUnwrap: boolean = GM_info.script.unwrap; +var scriptVersion: string = GM_info.script.version; +var scriptMetsStr: string = GM_info.scriptMetaStr; +var scriptWillUpdate: boolean = GM_info.scriptWillUpdate; +var gmVersion: string = GM_info.version; + +//////////////// +// Values +//////////////// + +GM_setValue('a', 'foobar'); +GM_setValue('b', 123); +GM_setValue('c', true); +GM_setValue('d', null); +// NG: GM_setValue('x', new Date()); + +var a: string = GM_getValue('a', 'foobar'); +var b: number = GM_getValue('b', 123); +var c: boolean = GM_getValue('c', true); +var d: any = GM_getValue('d', null); +var e: string = GM_getValue('e'); +var f: number = GM_getValue('f'); +var g: boolean = GM_getValue('g'); +// NG: var x: string = GM_getValue('x', 123); + +GM_deleteValue('d'); + +GM_listValues().forEach((name: string) => { + console.log(name + ":", GM_getValue(name)); +}); + +//////////////// +// Resources +//////////////// + +var prototypeSource: string = GM_getResourceText('prototype'); +var prototypeURL: string = GM_getResourceURL('prototype'); + +//////////////// +// Utilities +//////////////// + +GM_addStyle("body { color: white; background-color: black; } img { border: 0; }"); + +GM_log("Hello, World!"); + +GM_openInTab("http://www.example.com/"); + +GM_registerMenuCommand("Hello, world (simple)", helloSimple); +GM_registerMenuCommand("Hello, world!", hello, "h"); +// NG (Old Style): GM_registerMenuCommand("Hello, world! (again)", hello2, "e", "shift alt", "w"); +function helloSimple() {} +function hello() {} + +GM_setClipboard('http://www.example.com/short-url-code'); + +//////////////// +// XMLHttpRequest +//////////////// + +//// Examples from Greasemonkey Wiki + +// Bare Minimum + +GM_xmlhttpRequest({ + method: "GET", + url: "http://www.example.com/", + onload: function(response) { + alert(response.responseText); + } +}); + +// GET request + +GM_xmlhttpRequest({ + method: "GET", + url: "http://www.example.net/", + headers: { + "User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used. + "Accept": "text/xml" // If not specified, browser defaults will be used. + }, + onload: function(response) { + var responseXML = response.responseXML; + // Inject responseXML into existing Object (only appropriate for XML content). + if (!response.responseXML) { + responseXML = new DOMParser() + .parseFromString(response.responseText, "text/xml"); + } + + GM_log([ + response.status, + response.statusText, + response.readyState, + response.responseHeaders, + response.responseText, + response.finalUrl, + responseXML + ].join("\n")); + } +}); + +// POST request + +GM_xmlhttpRequest({ + method: "POST", + url: "http://www.example.net/login", + data: "username=johndoe&password=xyz123", + headers: { + "Content-Type": "application/x-www-form-urlencoded" + }, + onload: function(response) { + if (response.responseText.indexOf("Logged in as") > -1) { + location.href = "http://www.example.net/dashboard"; + } + } +}); + +// HEAD request + +GM_xmlhttpRequest({ + url: "http://www.example.com", + method: "HEAD", + onload: function(response) { + GM_log(response.responseHeaders); + } +}); + +//// Checkk all options + +var result = GM_xmlhttpRequest({ + binary: false, + context: {}, + data: 'foo=1&bar=2', + headers: { 'User-Agent': 'greasemonkey' }, + method: 'POST', + onabort: (response: GMXMLHttpRequestResponse) => { }, + onerror: (response: GMXMLHttpRequestResponse) => { }, + onload: (response: GMXMLHttpRequestResponse) => { }, + onprogress: (response: GMXMLHttpRequestProgressResponse) => { }, + onreadystatechange: (response: GMXMLHttpRequestResponse) => { }, + ontimeout: (response: GMXMLHttpRequestResponse) => { }, + overrideMimeType: 'text/plain', + password: 'abc123', + synchronous: false, + timeout: 10, + upload: { + onabort: (response: GMXMLHttpRequestResponse) => { }, + onerror: (response: GMXMLHttpRequestResponse) => { }, + onload: (response: GMXMLHttpRequestResponse) => { }, + onprogress: (response: GMXMLHttpRequestProgressResponse) => { } + }, + url: 'http://example.com/', + user: 'guest' +}); + +//// Check responses + +GM_xmlhttpRequest({ + method: 'GET', + url: 'http://example.com/', + onload: (response: GMXMLHttpRequestResponse) => { + var readyState: number = response.readyState; + var responseHeaders: string = response.responseHeaders; + var responseText: string = response.responseText; + var status: number = response.status; + var statusText: string = response.statusText; + var context: any = response.context; + var finalUrl: string = response.finalUrl; + // NG: var loaded: number = response.loaded; + }, + onprogress: (response: GMXMLHttpRequestProgressResponse) => { + var status: number = response.status; + var lengthComputable: boolean = response.lengthComputable; + var loaded: number = response.loaded; + var total: number = response.total; + } +}); + +//// Synchronous + +var syncResult: GMXMLHttpRequestSyncResult = GM_xmlhttpRequest({ + method: 'GET', + url: 'http://example.com/', + synchronous: true +}); + +syncResult.abort(); +var finalUrl: string = syncResult.finalUrl; +var readyState: number = syncResult.readyState; +var responseHeaders: string = syncResult.responseHeaders; +var responseText: string = syncResult.responseText; +var status: number = syncResult.status; +var statusText: string = syncResult.statusText; + +//// Asynchronous + +var asyncResult: GMXMLHttpRequestAsyncResult = GM_xmlhttpRequest({ + method: 'GET', + url: 'http://example.com/', + synchronous: false +}); + +asyncResult.abort(); +// NG: var status: number = asyncResult.status; diff --git a/greasemonkey/greasemonkey.d.ts b/greasemonkey/greasemonkey.d.ts new file mode 100644 index 000000000..27abcfa7f --- /dev/null +++ b/greasemonkey/greasemonkey.d.ts @@ -0,0 +1,235 @@ +// Type definitions for Greasemonkey +// Project: http://www.greasespot.net/ +// Definitions by: Kota Saito +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// This definition is based on the API reference of Greasemonkey. +// http://wiki.greasespot.net/Greasemonkey_Manual:API + +//////////////// +// Global variable +//////////////// + +/** + * Window object of the content page where the user script is running on. + * @see {@link http://wiki.greasespot.net/UnsafeWindow} + */ +declare var unsafeWindow: Window; + +/** + * Meta data about the running user script. + * @see {@link http://wiki.greasespot.net/GM_info} + */ +declare var GM_info: { + script: { + description: string; + excludes: string[]; + includes: string[]; + matches: string[]; + name: string; + namespace: string; + resources: Object; + "run-at": string; + unwrap: boolean; + version: string; + }; + scriptMetaStr: string; + scriptWillUpdate: boolean; + version: string; +}; + +//////////////// +// Values +//////////////// + +/** + * Deletes an existing name / value pair from the script storage. + * @param name a name of the pair to delete. + * @see {@link http://wiki.greasespot.net/GM_deleteValue} + */ +declare function GM_deleteValue(name: string): void; + +/** + * Retrieves a value from the script storage. + * @param name a name to retrieve. + * @param defaultValue a value to be returned when the name does not exist. + * @returns a retrieved value, or passed default value, or undefined. + * @see {@link http://wiki.greasespot.net/GM_getValue} + */ +declare function GM_getValue(name: string, defaultValue?: any): any; +declare function GM_getValue(name: string, defaultValue?: string): string; +declare function GM_getValue(name: string, defaultValue?: number): number; +declare function GM_getValue(name: string, defaultValue?: boolean): boolean; + +/** + * Retrieves an array of names stored in the script storage. + * @returns an array of names in the storage. + * @see {@link http://wiki.greasespot.net/GM_listValues} + */ +declare function GM_listValues(): string[]; + +/** + * Stores a name / value pair to the script storage. + * @param name a name of the pair. + * @param value a value to be stored. + * @see {@link http://wiki.greasespot.net/GM_setValue} + */ +declare function GM_setValue(name: string, value: string): void; +declare function GM_setValue(name: string, value: boolean): void; +declare function GM_setValue(name: string, value: number): void; + +//////////////// +// Resources +//////////////// + +/** + * Gets a content of a resouce defined by {@link http://wiki.greasespot.net/Metadata_Block#.40resource|@resource}. + * @param resourceName a name of the resource to get. + * @returns the content of the resource. + * @see {@link http://wiki.greasespot.net/GM_getResourceText} + */ +declare function GM_getResourceText(resourceName: string): string; + +/** + * Gets a URL of a resource defined by {@link http://wiki.greasespot.net/Metadata_Block#.40resource|@resource}. + * @param resourceName a name of the resource. + * @returns a URL that returns the content of the resource. + * @see {@link http://wiki.greasespot.net/GM_getResourceURL} + */ +declare function GM_getResourceURL(resourceName: string): string; + +//////////////// +// Utilities +//////////////// + +/** + * Adds CSS to the content page. + * @param css a CSS string. It can have multiple style definitions. + * @see {@link http://wiki.greasespot.net/GM_addStyle} + */ +declare function GM_addStyle(css: string): void; + +/** + * Writes a message as a log to the console with the script identifier. + * @param message a message to be written. + * @see {@link http://wiki.greasespot.net/GM_log} + */ +declare function GM_log(message: any): void; + +/** + * Opens a URL in a new tab. + * @param url a URL to open. + * @returns window object of the opened tab. + * @see {@link http://wiki.greasespot.net/GM_openInTab} + */ +declare function GM_openInTab(url: string): Window; + +/** + * Registers an item as a submenu of User Script Commands. + * @param caption a caption of the menu item. + * @param commandFunc a function to be invoked when the item has been selected. + * @param accessKey a single character that can be used to select the item by keyboard. + * It should be a letter in the caption. + * @see {@link http://wiki.greasespot.net/GM_registerMenuCommand} + */ +declare function GM_registerMenuCommand(caption: string, commandFunc: Function, accessKey?: string): void; + +/** + * Sets a text to the clipboard of the opeating system. + * @param text a text to be set to the clipboard. + * @see {@link http://wiki.greasespot.net/GM_setClipboard} + */ +declare function GM_setClipboard(text: string): void; + +//////////////// +// XMLHttpRequest +//////////////// + +/** + * Request options for {@link GM_xmlhttpRequest}. + * @see {@link http://wiki.greasespot.net/GM_xmlhttpRequest#Arguments} + */ +interface GMXMLHttpRequestOptions { + binary?: boolean; + context?: any; + data?: string; + headers?: Object; + method: string; + onabort?: (response: GMXMLHttpRequestResponse) => any; + onerror?: (response: GMXMLHttpRequestResponse) => any; + onload?: (response: GMXMLHttpRequestResponse) => any; + onprogress?: (response: GMXMLHttpRequestProgressResponse) => any; + onreadystatechange?: (response: GMXMLHttpRequestResponse) => any; + ontimeout?: (response: GMXMLHttpRequestResponse) => any; + overrideMimeType?: string; + password?: string; + synchronous?: boolean; + timeout?: number; + upload?: { + onabort?: (response: GMXMLHttpRequestResponse) => any; + onerror?: (response: GMXMLHttpRequestResponse) => any; + onload?: (response: GMXMLHttpRequestResponse) => any; + onprogress?: (response: GMXMLHttpRequestProgressResponse) => any; + }; + url: string; + user?: string; +} + +/** + * Response object for general events of {@link GM_xmlhttpRequest}. + * @see {@link http://wiki.greasespot.net/GM_xmlhttpRequest#Response_Object} + */ +interface GMXMLHttpRequestResponse { + readyState: number; + responseHeaders: string; + responseText: string; + status: number; + statusText: string; + context: any; + finalUrl: string; +} + +/** + * Response object for onprogress event of {@link GM_xmlhttpRequest}. + */ +interface GMXMLHttpRequestProgressResponse extends GMXMLHttpRequestResponse { + lengthComputable: boolean; + loaded: number; + total: number; +} + +/** + * Returned object by {@link GM_xmlhttpRequest} in asynchronous mode. + */ +interface GMXMLHttpRequestAsyncResult { + abort(): void; +} + +/** + * Returned object by {@link GM_xmlhttpRequest} in synchronouse mode. + */ +interface GMXMLHttpRequestSyncResult { + abort(): void; + finalUrl: string; + readyState: number; + responseHeaders: string; + responseText: string; + status: number; + statusText: string; +} + +/** + * Returned object by {@link GM_xmlhttpRequest}. + * @see {@link http://wiki.greasespot.net/GM_xmlhttpRequest#Returns} + */ +interface GMXMLHttpRequestResult extends GMXMLHttpRequestAsyncResult, GMXMLHttpRequestSyncResult { +} + +/** + * Sends a HTTP request to a URL. + * @param options options and callbacks for HTTP request. + * @returns an object which can abort the request. + * If the request is sent in the synchronous mode, it also contains the response information. + * @see {@link http://wiki.greasespot.net/GM_setClipboard} + */ +declare function GM_xmlhttpRequest(options: GMXMLHttpRequestOptions): GMXMLHttpRequestResult; diff --git a/gruntjs/gruntjs-tests.ts b/gruntjs/gruntjs-tests.ts index abd1c90ed..9097fa7df 100644 --- a/gruntjs/gruntjs-tests.ts +++ b/gruntjs/gruntjs-tests.ts @@ -4,7 +4,7 @@ // http://gruntjs.com/getting-started#an-example-gruntfile // exports should work same as module.exports -exports = function (grunt) { +exports = (grunt: IGrunt) => { // Project configuration. grunt.initConfig({ @@ -26,4 +26,16 @@ exports = function (grunt) { // Default task(s). grunt.registerTask('default', ['uglify']); + + // util methods + var testOneArg = (a: number) => a * 2; + var asyncedOneArg = grunt.util.callbackify(testOneArg); + asyncedOneArg(1, (result: number) => { + console.log(result); + }); + var testTwoArgs = (a: number, b: string) => "it works with " + a + " " + b; + var asyncedTwoArgs = grunt.util.callbackify(testTwoArgs); + asyncedTwoArgs(2, "values", (result: string) => { + console.log(result); + }); }; \ No newline at end of file diff --git a/gruntjs/gruntjs.d.ts b/gruntjs/gruntjs.d.ts index 463721da9..0b3d6ee2e 100644 --- a/gruntjs/gruntjs.d.ts +++ b/gruntjs/gruntjs.d.ts @@ -1,220 +1,1302 @@ -// Type definitions for Grunt JS -// Project: http://gruntjs.com/ -// Definitions by: Basarat Ali Syed -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Type definitions for Grunt 0.4.x +// Project: http://gruntjs.com +// Definitions by: Jeff May +// Definitions: https://github.com/jeffmay/DefinitelyTyped +/// -//////////////// -/// To add plugins update the IGruntConfig using open ended interface syntax -//////////////// -interface IGruntConfig { - pkg?: any; +/** + * {@link http://github.com/marak/colors.js/} + */ +interface String { + yellow: string; + cyan: string; + white: string; + magenta: string; + green: string; + red: string; + grey: string; + blue: string; } -//////////////// -/// Sample grunt plugin definition: -/// uglify : https://github.com/gruntjs/grunt-contrib-uglify -//////////////// -interface IGruntUglifyConfig { - mangle?: boolean; - compress?: boolean; - beautify?: boolean; - report?: any; // false / 'min' / 'gzip' - sourceMap?: any; // String / Function - sourceMapRoot?: string; - sourceMapIn?: string; - sourceMappingURL?: any; // String / Function - sourceMapPrefix?: number; - wrap?: string; - exportAll?: boolean; - preserveComments?: any; // boolean / string / function - banner?: string; -} -interface IGruntConfig { - uglify?: { - options?: IGruntUglifyConfig; - build?: { - src: string; - dest: string; - }; +declare module node { - }; + /** + * {@link http://npmjs.org/doc/json.html} + */ + interface NodePackage { + name: string + version: string + description?: string + keywords?: string[] + homepage?: string + } } +/** + * {@link http://github.com/isaacs/minimatch} + */ +declare module minimatch { + /** + * A minimal matching utility options. + * + * This is the matching library used internally by npm. + * Eventually, it will replace the C binding in node-glob. + * It works by converting glob expressions into JavaScript RegExp objects. + */ + interface IMinimatchOptions { + /* + All options are false by default. + */ + /** + * Dump a ton of stuff to stderr. + */ + debug?: boolean -//////////////// -// Main Grunt object -// http://gruntjs.com/api/grunt -//////////////// -interface IGrunt { - // Config - config: IGruntConfigObject; - initConfig(config?: IGruntConfig): void; + /** + * Do not expand {a,b} and {1..3} brace sets. + */ + nobrace?: boolean + /** + * Disable ** matching against multiple folder names. + */ + noglobstar?: boolean - // Tasks - task: any; - // Creating - registerTask: Function; - registerMultiTask: Function; - renameTask: Function; - // Loading - loadTasks: Function; - loadNpmTasks: Function; + /** + * Allow patterns to match filenames starting with a period, + * even if the pattern does not explicitly have a period in that spot. + */ + // Note that by default, a/**\/b will not match a/.d/b, unless dot is set. + dot?: boolean - // Errors - warn: Function; - fatal: Function; + /** + * Disable "extglob" style patterns like +(a|b). + */ + noext?: boolean - // Misc: - package: any; - version: any; + /** + * Perform a case-insensitive match. + */ + nocase?: boolean - // File - file: IGruntFileObject; + /** + * When a match is not found by minimatch.match, return a list containing the pattern itself. + * When set, an empty list is returned if there are no matches. + */ + nonull?: boolean - // Event - event: any; - // Fail - fail: any; - // Log - log: any; - // Options - option: any; - // Template - template: any; - // Util - util: any; + /** + * If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. + * For example, a?b would match the path /xyz/123/acb, but not /xyz/acb/123. + */ + matchBase?: boolean + + /** + * Suppress the behavior of treating # at the start of a pattern as a comment. + */ + nocomment?: boolean + + /** + * Suppress the behavior of treating a leading ! character as negation. + */ + nonegate?: boolean + + /** + * Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) + */ + flipNegate?: boolean + } } -//////////////// -/// Grunt Config object -/// http://gruntjs.com/api/grunt.config#accessing-config-data -//////////////// -interface IGruntConfigObject { - (...param: any[]): any; - init: (config?: IGruntConfig) => void; - get: Function; - process: Function; - getRaw: Function; - set: Function; - escape: (propString: string) => void; - requires: Function; +/* GRUNT CONFIGURATION + *********************/ + +declare module grunt { + + module config { + + /** + * {@link http://gruntjs.com/sample-gruntfile} + */ + interface IProjectConfig extends IConfigOptionFormat { + pkg: string + } + + /** + * @see IProjectConfig + */ + interface IConfigOptionFormat { + [plugin: string]: IConfigPluginFormat + } + + /** + * A map of plugin task names to config objects. + */ + interface IConfigPluginFormat { + [task: string]: grunt.task.ITaskOptions + } + + /** + * {@link http://gruntjs.com/api/grunt.config} + */ + interface ConfigModule { + /** + * Get or set a value from the project's Grunt configuration. + * This method serves as an alias to other methods; + * if two arguments are passed, grunt.config.set is called, + * otherwise grunt.config.get is called. + */ + (prop: string, value: any): any + (prop: string): any + + /** + * Initialize a configuration object for the current project. + * The specified configObject is used by tasks and can be accessed using the grunt.config method. + * Nearly every project's Gruntfile will call this method. + */ + init(config: IProjectConfig): void + + /** + * Get a value from the project's Grunt configuration. + * If prop is specified, that property's value is returned, or null if that property is not defined. + * If prop isn't specified, a copy of the entire config object is returned. + * Templates strings will be recursively processed using the grunt.config.process method. + * + * @note Although this accepts a generic type, you may still get the wrong typed value. + */ + get(prop: string): T + get(): ConfigModule + + /** + * Process a value, recursively expanding <% %> templates (via the grunt.template.process method) + * in the context of the Grunt config, as they are encountered. + * this method is called automatically by grunt.config.get but not by grunt.config.getRaw. + * + * If any retrieved value is entirely a single '<%= foo %>' or '<%= foo.bar %>' template string, + * and the specified foo or foo.bar property is a non-string (and not null or undefined) value, + * it will be expanded to the actual value. That, combined with grunt's task system automatically + * flattening arrays, can be extremely useful. + */ + process(value: string): T + + /** + * Get a raw value from the project's Grunt configuration, without processing <% %> template strings. + * If prop is specified, that property's value is returned, or null if that property is not defined. + * If prop isn't specified, a copy of the entire config object is returned. + */ + getRaw(prop: string): T + + /** + * Set a value into the project's Grunt configuration. + * @note any specified <% %> template strings will only be processed when config data is retrieved. + */ + set(prop: string, value: T): T + + /** + * Escape '.' dots in the given propString. This should be used for property names that contain dots. + */ + escape(propString: string): string + + /** + * Fail the current task if one or more required config properties is missing, null or undefined. + * One or more string or array config properties may be specified. + */ + requires(prop: string, ...andProps: string[]): void + requires(prop: string[], ...andProps: string[][]): void + } + } + + module event { + /** + * {@link http://github.com/hij1nx/EventEmitter2} + */ + interface EventModule { + + /** + * Adds a listener to the end of the listeners array for the specified event. + */ + addListener(event: string, listener: Function): EventModule + on(event: string, listener: Function): EventModule + + /** + * Adds a listener that will be fired when any event is emitted. + */ + onAny(listener: Function): EventModule + + /** + * Removes the listener that will be fired when any event is emitted. + */ + offAny(listener: Function): EventModule + + /** + * Adds a one time listener for the event. + * The listener is invoked only the first time the event is fired, after which it is removed. + */ + once(event: string, listener: Function): EventModule + + /** + * Adds a listener that will execute n times for the event before being removed. + * The listener is invoked only the first time the event is fired, after which it is removed. + */ + many(event: string, timesToListen: number, listener: Function): EventModule + + /** + * Remove a listener from the listener array for the specified event. + * Caution: changes array indices in the listener array behind the listener. + */ + removeListener(event: string, listener: Function): EventModule + off(event: string, listener: Function): EventModule + + /** + * Removes all listeners, or those of the specified event. + */ + removeAllListeners(event: string): EventModule + + /** + * By default EventEmitters will print a warning if more than 10 listeners are added to it. + * This is a useful default which helps finding memory leaks. Obviously not all Emitters + * should be limited to 10. This function allows that to be increased. + * + * Set to zero for unlimited. + */ + setMaxListener(n: number): void + + /** + * Returns an array of listeners for the specified event. + * This array can be manipulated, e.g. to remove listeners. + */ + listeners(event: string): Function[] + + /** + * Returns an array of listeners that are listening for any event that is specified. + * This array can be manipulated, e.g. to remove listeners. + */ + listenersAny(): Function[] + + /** + * Execute each of the listeners that may be listening for the specified event name + * in order with the list of arguments. + */ + emit(event: string, ...args: any[]): any + } + } + + module fail { + + enum ErrorCode { + NoError = 0, + Fatal = 1, + MissingGruntfile = 2, + Task = 3, + Template = 4, + Autocomplete = 5, + Warning = 6, + } + + interface FailModule { + + /** + * Display a warning and abort Grunt immediately. + * Grunt will continue processing tasks if the --force command-line option was specified. + */ + warn(error: string, errorCode?: ErrorCode): void + warn(error: Error, errorCode?: ErrorCode): void + + /** + * Display a warning and abort Grunt immediately. + */ + fatal(error: string, errorCode?: ErrorCode): void + fatal(error: Error, errorCode?: ErrorCode): void + } + } + + module file { + + /** + * {@link http://gruntjs.com/api/grunt.file#grunt.file.defaultencoding} + */ + interface IFileEncodedOption { + encoding: string + } + + /** + * {@link http://gruntjs.com/api/grunt.file#grunt.file.copy} + * + * @see IFileWriteBufferOption + * @see IFileWriteStringOption + */ + interface IFileWriteOptions { + /** + * These optional globbing patterns will be matched against the filepath + * (not the filename) using grunt.file.isMatch. If any specified globbing + * pattern matches, the file won't be processed via the `process` function. + * If `true` is specified, processing will be prevented. + */ + // noProcess?: string[] + // noProcess?: boolean + noProcess?: any + } + + /** + * @see IFileWriteOptions + */ + interface IFileWriteBufferOption extends grunt.file.IFileWriteOptions { + /** + * The source file contents and file path are passed into this function, + * whose return value will be used as the destination file's contents. If + * this function returns `false`, the file copy will be aborted. + */ + process?: (buffer: NodeBuffer) => boolean + } + + /** + * @see IFileWriteOptions + */ + interface IFileWriteStringOption extends grunt.file.IFileWriteOptions { + /** + * The source file contents and file path are passed into this function, + * whose return value will be used as the destination file's contents. If + * this function returns `false`, the file copy will be aborted. + */ + process?: (file: string) => boolean + } + + /** + * {@link http://gruntjs.com/api/grunt.file} + */ + interface FileModule { + + /** + * Set this property to change the default encoding used by all grunt.file methods. + * Defaults to 'utf8'. + * + * If you do have to change this value, it's recommended that you change + * it as early as possible inside your Gruntfile. + */ + defaultEncoding: string + + /** + * Read and return a file's contents. + * Returns a string, unless options.encoding is null in which case it returns a Buffer. + */ + read(filepath: string): string + read(filepath: string, options: IFileEncodedOption): NodeBuffer + + /** + * Read a file's contents, parsing the data as JSON and returning the result. + * @see FileModule.read for a list of supported options. + */ + readJSON(filepath: string): any + readJSON(filepath: string, options: IFileEncodedOption): NodeBuffer + + /** + * Read a file's contents, parsing the data as YAML and returning the result. + * @see FileModule.read for a list of supported options. + */ + readYAML(filepath: string): any + readYAML(filepath: string, options: IFileEncodedOption): NodeBuffer + + /** + * Write the specified contents to a file, creating intermediate directories if necessary. + * Strings will be encoded using the specified character encoding, Buffers will be written to disk as-specified. + * + * @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 + + /** + * Copy a source file to a destination path, creating intermediate directories if necessary. + */ + copy(srcpath: string, destpath: string): void + copy(srcpath: string, destpath: string, options: IFileWriteStringOption): void + copy(srcpath: string, destpath: string, options: IFileWriteBufferOption): void + + /** + * Delete the specified filepath. Will delete files and folders recursively. + * + * @return true if the files could be deleted, otherwise false. + */ + delete(filepath: string, options?: { force?: boolean }): boolean + + /** + * Works like mkdir -p. Create a directory along with any intermediate directories. + * If mode isn't specified, it defaults to 0777 & (~process.umask()). + */ + mkdir(dirpath: string, mode?: string): void + + /** + * Recurse into a directory, executing callback for each file. + * + * Callback args: + * abspath - The full path to the current file, + * which is nothing more than the rootdir + subdir + filename arguments, joined. + * rootdir - The root director, as originally specified. + * subdir - The current file's directory, relative to rootdir. + * filename - The filename of the current file, without any directory parts. + */ + recurse( + rootdir: string, + callback: (abspath: string, rootdir: string, subdir: string, filename: string) => void + ): void + + /** + * Return a unique array of all file or directory paths that match the given globbing pattern(s). + * This method accepts either comma separated globbing patterns or an array of globbing patterns. + * Paths matching patterns that begin with ! will be excluded from the returned array. + * Patterns are processed in order, so inclusion and exclusion order is significant. + * + * File paths are relative to the Gruntfile unless the current working directory is changed with + * grunt.file.setBase or the --base command-line option. + */ + expand(patterns: string[]): string[] + expand(options: IFilesConfig, patterns: string[]): string[] + + /** + * Returns an array of src-dest file mapping objects. + * For each source file matched by a specified pattern, join that file path to the specified dest. + * This file path may be flattened or renamed, depending on the options specified. + * + * @see FileModule.expand method documentation for an explanation of how the patterns + * and options arguments may be specified. + */ + expandMapping(patterns: string[], dest: string, options: IExpandedFilesConfig): IFilesMap + + /** + * Match one or more globbing patterns against one or more file paths. + * Returns a uniqued array of all file paths that match any of the specified globbing patterns. + * Both the patterns and filepaths argument can be a single string or array of strings. + * Paths matching patterns that begin with ! will be excluded from the returned array. + * Patterns are processed in order, so inclusion and exclusion order is significant. + */ + match(pattern: string, filepath: string): string[] + match(pattern: string, filepaths: string[]): string[] + match(patterns: string[], filepath: string): string[] + match(patterns: string[], filepaths: string[]): string[] + match(options: minimatch.IMinimatchOptions, pattern: string, filepath: string): string[] + match(options: minimatch.IMinimatchOptions, pattern: string, filepaths: string[]): string[] + match(options: minimatch.IMinimatchOptions, patterns: string[], filepath: string): string[] + match(options: minimatch.IMinimatchOptions, patterns: string[], filepaths: string[]): string[] + + /** + * This method contains the same signature and logic as the grunt.file.match method, + * but simply returns true if any files were matched, otherwise false. + * + * @see FileModule.match + */ + isMatch(pattern: string, filepath: string): boolean + isMatch(pattern: string, filepaths: string[]): boolean + isMatch(patterns: string[], filepath: string): boolean + isMatch(patterns: string[], filepaths: string[]): boolean + isMatch(options: minimatch.IMinimatchOptions, pattern: string, filepath: string): boolean + isMatch(options: minimatch.IMinimatchOptions, pattern: string, filepaths: string[]): boolean + isMatch(options: minimatch.IMinimatchOptions, patterns: string[], filepath: string): boolean + isMatch(options: minimatch.IMinimatchOptions, patterns: string[], filepaths: string[]): boolean + + + /* + * Like the Node.js path.join method, the methods below will + * join all arguments together and normalize the resulting path. + */ + + /** + * Does the given path exist? + */ + exists(path: string, ...append: string[]): boolean + + /** + * Is the given path a symbolic link? + */ + isLink(path: string, ...append: string[]): boolean + + /** + * Is the given path a symbolic link? + */ + isDir(path: string, ...append: string[]): boolean + + /** + * Is the given path a file? + */ + isFile(path: string, ...append: string[]): boolean + + /** + * Is a given file path absolute? + */ + isPathAbsolute(path: string, ...append: string[]): boolean + + /** + * Do all the specified paths refer to the same path? + */ + arePathsEquivalent(path: string, ...append: string[]): boolean + + /** + * Are all descendant path(s) contained within the specified ancestor path? + */ + doesPathContain(ancestorPath: string, decendantPaths: string[]): boolean + + /** + * Is a given file path the current working directory (CWD)? + */ + isPathCwd(path: string, ...append: string[]): boolean + + /** + * Change grunt's current working directory (CWD). + * By default, all file paths are relative to the Gruntfile. + * This works just like the --base command-line option. + */ + setBase(path: string, ...append: string[]): void + + // External libraries + // TODO: Create declarations + glob: any + minimatch: any + findup: any + } + + /** + * A convenience type. + * + * {@link http://gruntjs.com/configuring-tasks#files} + */ + interface IFilesArray extends Array {} + + /** + * {@link http://gruntjs.com/configuring-tasks#files} + */ + interface IFilesConfig extends minimatch.IMinimatchOptions { + + /** + * Pattern(s) to match, relative to the {@link IExpandedFilesConfig.cwd}. + */ + src: string[] + + /** + * Destination path prefix. + */ + dest?: string + + /** + * Process a dynamic src-dest file mapping, + * @see {@link http://gruntjs.com/configuring-tasks#building-the-files-object-dynamically for more information. + */ + expand?: boolean // = false + + /** + * Either a valid fs.Stats method name: + * - isFile + * - isDirectory + * - isBlockDevice + * - isCharacterDevice + * - isSymbolicLink + * - isFIFO + * - isSocket + * + * or a function that is passed the matched src filepath and returns true or false. + * + * string + * (src: string) => boolean + */ + // filter?: string + // filter?: (src: string) => boolean + filter?: any + } + + /** + * These are valid for compact-format + */ + interface IExpandedFilesConfig extends IFilesConfig { + + /** + * Enables the following options + */ + expand: boolean // = true + + /** + * All {@link IExpandedFilesConfig.src} matches are relative to (but don't include) this path. + */ + cwd?: boolean + + /** + * Replace any existing extension with this value in generated {@link IExpandedFilesConfig.dest} paths. + */ + ext?: boolean + + /** + * Remove all path parts from generated {@link IExpandedFilesConfig.dest} paths. + */ + flatten?: boolean + + /** + * This function is called for each matched src file, (after extension renaming and flattening). + * The {@link IExpandedFilesConfig.dest} and matched {@link IExpandedFilesConfig.src} path are passed in, + * and this function must return a new dest value. + * If the same dest is returned more than once, each src which used it will be added to an array of sources for it. + */ + rename?: boolean + } + + /** + * @see {@link http://gruntjs.com/configuring-tasks#files-object-format} + */ + interface IFilesMap { + /** + * A map of sources to a destination. + */ + [dest: string]: string[] + } + } + + module log { + + /** + * Grunt output should look consistent, and maybe even pretty. + * As such, there is a plethora of logging methods, and a few useful patterns. + * All of the methods that actually log something are chainable. + */ + interface CommonLogging { + + /** + * Log the specified msg string, with no trailing newline. + */ + write(msg: string): T + + /** + * Log the specified msg string, with trailing newline. + */ + writeln(msg: string): T + + /** + * If msg string is omitted, logs ERROR in red, + * otherwise logs >> msg, with trailing newline. + */ + error(msg: string): T + + /** + * Log an error with grunt.log.error, wrapping text to 80 columns using grunt.log.wraptext. + */ + errorlns(msg: string): T + + /** + * If msg string is omitted, logs OK in green, otherwise logs >> msg, with trailing newline. + */ + ok(msg: string): T + + /** + * Log an ok message with grunt.log.ok, wrapping text to 80 columns using grunt.log.wraptext. + */ + oklns(msg: string): T + + /** + * Log the specified msg string in bold, with trailing newline. + */ + subhead(msg: string): T + + /** + * Log a list of obj properties (good for debugging flags). + */ + writeflags(obj: any): T + } + + /** + * @note all methods available under grunt.verbose work exactly like grunt.log methods, + * but only log if the --verbose command-line option was specified. + */ + interface VerboseLogModule extends CommonLogging { + or: NotVerboseLogModule + } + + /** + * @note all methods available under grunt.verbose work exactly like grunt.log methods, + * but only log if the --verbose command-line option was not specified. + */ + interface NotVerboseLogModule extends CommonLogging { + or: VerboseLogModule + } + + /** + * {@link http://gruntjs.com/api/grunt.log} + */ + interface LogModule extends CommonLogging { + verbose: VerboseLogModule + notverbose: NotVerboseLogModule + } + } + + module option { + + /** + * {@link http://gruntjs.com/api/grunt.option} + */ + interface OptionModule { + + /** + * Gets or sets an option. + * Boolean options can be negated by prepending no- onto the key. For example: + * + * grunt.option('staging', false); + * var isDev = grunt.option('no-staging'); + * assert(isDev === true) + */ + (key: string, value: T): void + (key: string): T + + /** + * Initialize grunt.option. + * If initObject is omitted option will be initialized to an empty object + * otherwise will be set to initObject. + */ + init(initObject?: any): void + + /** + * Returns the options as an array of command line parameters. + */ + flags: grunt.IFlag[] + } + + } + + module task { + + interface TaskFunction extends ITask { + (...args: any[]): boolean + } + + /** + * {@link http://gruntjs.com/api/grunt.task} + */ + interface CommonTaskModule { + + /** + * If a task list is specified, the new task will be an alias for one or more other tasks. + * Whenever this "alias task" is run, every specified task in taskList will be run, in the order specified. + * The taskList argument must be an array of tasks. + */ + registerTask(taskName: string, taskList: string[]): void + + /** + * If a description and taskFunction are passed, the specified function will be executed + * whenever the task is run. + * + * In addition, the specified description will be shown when grunt --help is run. + * Task-specific properties and methods are available inside the task function as properties + * of the this object. The task function can return false to indicate that the task has failed. + * + * @note taskFunction.apply(scope: grunt.task.IMultiTask, args: any[]) + */ + registerTask(taskName: string, description: string, taskFunction: TaskFunction): void + + /** + * Register a "multi task." A multi task is a task that implicitly iterates over all of its + * named sub-properties (AKA targets) if no target was specified. + * In addition to the default properties and methods, extra multi task-specific properties + * are available inside the task function as properties of the this object. + * + * @note taskFunction.apply(scope: grunt.task.IMultiTask, args: any[]) + */ + registerMultiTask(taskName: string, taskFunction: grunt.task.ITask): void + registerMultiTask(taskName: string, taskDescription: string, taskFunction: TaskFunction): void + } + + /** + * {@link http://gruntjs.com/api/grunt.task#queueing-tasks} + */ + interface TaskModule extends CommonTaskModule { + /** + * Enqueue one or more tasks. + * Every specified task in taskList will be run immediately after the current task completes, + * in the order specified. The task list can be an array of tasks or individual task arguments. + */ + run(tasks: string[]): void + run(task: string, ...thenTasks: string[]): void + + /** + * Empty the task queue completely. Unless additional tasks are enqueued, no more tasks will be run. + */ + clearQueue(): void + + /** + * Normalizes a task target configuration object into an array of src-dest file mappings. + * This method is used internally by the multi task system this.files / grunt.task.current.files property. + */ + normalizeMultiTaskFiles(data: grunt.config.IProjectConfig, targetname?: string): grunt.file.IFilesMap + } + + interface AsyncResultCatcher { + /** + * Either false or an Error object may be passed to the done function + * to instruct Grunt that the task has failed. + */ + done(success: boolean): void; + done(error: Error): void; + done(result: any): void; + } + + /** + * @link http://gruntjs.com/inside-tasks + * + * Grunt version 0.4.x + */ + interface ITask { + + /** + * If a task is asynchronous, this method must be invoked to instruct Grunt to wait. + * It returns a handle to a "done" function that should be called when the task has completed. + * + * // Tell Grunt this task is asynchronous. + * var done = this.async(); + * // Your async code. + * setTimeout(function() { + * // Let's simulate an error, sometimes. + * var success = Math.random() > 0.5; + * // All done! + * done(success); + * }, 1000); + */ + async(): AsyncResultCatcher + + /** + * If one task depends on the successful completion of another task (or tasks), + * this method can be used to force Grunt to abort if the other task didn't run, + * or if the other task failed. + * + * @param tasks an array of task names or individual task names, as arguments. + * @note that this won't actually run the specified task(s), + * it will just fail the current task if they haven't already run successfully. + */ + requires(tasks: string[]): void + requires(tasks: string, ...otherTasks: string[]): void + requires(tasks: string[], ...otherTasks: string[][]): void + + /** + * Fail the current task if one or more required config properties is missing. + * One or more string or array config properties may be specified. + * this.requiresConfig(prop [, prop [, ...]]) + */ + requiresConfig(prop: string, ...andProps: string[]): void + + /** + * The name of the task, as defined in grunt.registerTask. + * For example, if a "sample" task was run as grunt sample or grunt sample:foo, + * inside the task function, this.name would be "sample". + */ + name: string + + /** + * The name of the task, including any colon-separated arguments or flags specified on the command-line. + * For example, if a "sample" task was run as grunt sample:foo, + * inside the task function, this.nameArgs would be "sample:foo". + */ + nameArgs: string + + /** + * An array of arguments passed to the task. + * For example, if a "sample" task was run as grunt sample:foo:bar, + * inside the task function, this.args would be ["foo", "bar"]. + */ + args: string[] + + /** + * An object generated from the arguments passed to the task. + * For example, if a "sample" task was run as grunt sample:foo:bar, + * inside the task function, this.flags would be {foo: true, bar: true}. + */ + flags: grunt.IFlag[] + + /** + * The number of grunt.log.error calls that occurred during this task. + * This can be used to fail a task if errors were logged during the task. + */ + errorCount: number + + /** + * Returns an options object. + * Properties of the optional defaultsObj argument will be overridden by any task-level options + * object properties, which will be further overridden in multi tasks by any target-level + * options object properties. + */ + // options(defaultsObj: T): ITaskOptions + // options(defaultsObj: T): T + options(defaultsObj: any): any + } + + /** + * {@link http://gruntjs.com/inside-tasks#inside-multi-tasks} + */ + interface IMultiTask extends ITask { + /** + * In a multi task, this property contains the name of the target currently being iterated over. + * For example, if a "sample" multi task was run as grunt sample:foo with the config data + * {sample: {foo: "bar"}}, inside the task function, this.target would be "foo". + */ + target: string + + /** + * In a multi task, all files specified using any Grunt-supported file formats and options, + * globbing patterns or dynamic mappings will automatically be normalized into a single format: + * the Files Array file format. + * + * What this means is that tasks don't need to contain a ton of boilerplate for explicitly + * handling custom file formats, globbing patterns, mapping source files to destination files + * or filtering out files or directories. A task user can just specify files per the Configuring + * tasks guide, and Grunt will handle all the details. + * + * Your task should iterate over the this.files array, utilizing the src and dest properties of + * each object in that array. The this.files property will always be an array. + * The src property will also always be an array, in case your task cares about multiple source + * files per destination file. + * + * @note it's possible that nonexistent files might be included in src values, + * so you may want to explicitly test that source files exist before using them. + */ + files: grunt.file.IFilesArray + + /** + * In a multi task, all src files files specified via any file format are reduced to a single array. + * If your task is "read only" and doesn't care about destination filepaths, + * use this array instead of this.files. + */ + filesSrc: string[] + + /** + * In a multi task, this is the actual data stored in the Grunt config object for the given target. + * For example, if a "sample" multi task was run as grunt sample:foo with the config data + * {sample: {foo: "bar"}}, inside the task function, this.data would be "bar". + * + * @note It is recommended that this.options this.files and this.filesSrc are used instead of this.data, + * as their values are normalized. + */ + data: T + } + + /** + * {@link http://gruntjs.com/configuring-tasks} + * + * A TaskConfig can be either be a full config or a compacted files config. + * @see ITaskCompactOptions + */ + interface ITaskOptions { + + options?: any + + // files?: grunt.file.IFilesArray + // files?: grunt.file.IFilesMap + files?: any + } + + /** + * @see ITaskOptions + */ + interface ITaskCompactOptions extends grunt.task.ITaskOptions, grunt.file.IFilesConfig {} + } + + module template { + + interface TemplateModule { + + /** + * Process a Lo-Dash template string. + * + * The template argument will be processed recursively until there are no more templates to process. + * + * The default data object is the entire config object, but if options.data is set, that object will + * be used instead. The default template delimiters are <% %> but if options.delimiters is set to a + * custom delimiter name, those template delimiters will be used instead. + * + * Inside templates, the grunt object is exposed so that you can do things like: + * <%= grunt.template.today('yyyy') %> + * + * @note if the data object already has a grunt property, the grunt API will not be accessible in templates. + */ + process(template: string): (options: any) => string + process(template: string, options: any): string + + /** + * Set the Lo-Dash template delimiters to a predefined set in case you grunt.util._.template + * needs to be called manually. + * + * The config delimiters <% %> are included by default. + */ + setDelimiters(name: string): void + + /** + * Add a named set of Lo-Dash template delimiters. + * + * You probably won't need to use this method, because the built-in delimiters should be sufficient, + * but you could always add {% %} or [% %] style delimiters. + */ + addDelimiters(name: string, opener: string, closer: string): void + + /** + * Format a date using the dateformat library. + * {@link http://github.com/felixge/node-dateformat} + * + * @note if you don't include the mask argument, dateFormat.masks.default is used + */ + date(date?: Date, format?: string): string + date(date?: number, format?: string): string + date(date?: string, format?: string): string + + /** + * Format today's date using the dateformat library using the current date and time. + * {@link http://github.com/felixge/node-dateformat} + * + * @note if you don't include the mask argument, dateFormat.masks.default is used + */ + today(format?: string): string + } + } + + module util { + + /** + * {@link http://gruntjs.com/api/grunt.util} + */ + interface UtilModule { + + /** + * Return the "kind" of a value. Like typeof but returns the internal [Class](Class/) value. + * Possible results are "number", "string", "boolean", "function", "regexp", "array", "date", + * "error", "null", "undefined" and the catch-all "object". + */ + kindOf(value: any): string + + /** + * Return a new Error instance (that can be thrown) with the appropriate message. + * If an Error object is specified instead of message that object will be returned. + * Also, if an Error object is specified for origError and Grunt was run with the --debug 9 option, + * the original Error stack will be dumped. + */ + error(message: string, origError?: Error): Error + error(error: Error, origError?: Error): Error + error(error: any, origError?: Error): Error + + /** + * The linefeed character, normalized for the current operating system. + * (\r\n on Windows, \n otherwise) + */ + linefeed: string + + /** + * Given a string, return a new string with all the linefeeds normalized for the current operating system. + * (\r\n on Windows, \n otherwise) + */ + normalizelf(str: string): string + + /** + * Recurse through nested objects and arrays, executing callbackFunction for each non-object value. + * If continueFunction returns false, a given object or value will be skipped. + */ + recurse(object: any, callbackFunction: (value: any) => void, continueFunction: (objOrValue: any) => boolean): void + + /** + * Return string str repeated n times. + */ + repeat(n: number, str: string): string + + /** + * Given str of "a/b", If n is 1, return "a" otherwise "b". + * You can specify a custom separator if '/' doesn't work for you. + */ + pluralize(n: number, str: string, separator?: string): string + + /** + * Spawn a child process, keeping track of its stdout, stderr and exit code. + * The method returns a reference to the spawned child. + * When the child exits, the done function is called. + * + * @param done a function with arguments: + * error - If the exit code was non-zero and a fallback wasn't specified, + * an Error object, otherwise null. + * result - The result object is an + * code - The numeric exit code. + */ + spawn(options: ISpawnOptions, done: (error: Error, result: ISpawnResult, code: number) => void): ISpawnedChild + + /** + * Given an array or array-like object, return an array. + * Great for converting arguments objects into arrays. + */ + toArray(arrayLikeObject: any): T[] + + /** + * Normalizes both "returns a value" and "passes result to a callback" functions to always + * pass a result to the specified callback. If the original function returns a value, + * that value will now be passed to the callback, which is specified as the last argument, + * after all other predefined arguments. If the original function passed a value to a callback, + * it will continue to do so. + */ + callbackify(syncOrAsyncFunction: () => R): + (callback: (result: R) => void) => void + callbackify(syncOrAsyncFunction: (a: A) => R): + (a: A, callback: (result: R) => void) => void + callbackify(syncOrAsyncFunction: (a: A, b: B) => R): + (a: A, b: B, callback: (result: R) => void) => void + callbackify(syncOrAsyncFunction: (a: A, b: B, c: C) => R): + (a: A, b: B, c: C, callback: (result: R) => void) => void + callbackify(syncOrAsyncFunction: (a: A, b: B, c: C, d: D) => R): + (a: A, b: B, c: C, d: D, callback: (result: R) => void) => void + + // Internal libraries + namespace: any + task: any + } + + /** + * {@link http://gruntjs.com/api/grunt.util#grunt.util.spawn} + */ + interface ISpawnOptions { + + /** + * The command to execute. It should be in the system path. + */ + cmd: string + + /** + * If specified, the same grunt bin that is currently running will be + * spawned as the child command, instead of the "cmd" option. + * Defaults to false. + */ + grunt?: boolean + + /** + * An array of arguments to pass to the command. + */ + args?: string[] + + /** + * Additional options for the Node.js child_process spawn method. + */ + opts?: ISpawnOptions + + /** + * If this value is set and an error occurs, it will be used as the value + * and null will be passed as the error value. + */ + fallback?: any + } + + /** + * @note When result is coerced to a string, the value is stdout if the exit code + * was zero, the fallback if the exit code was non-zero and a fallback was + * specified, or stderr if the exit code was non-zero and a fallback was + * not specified. + */ + interface ISpawnResult { + stdout: string + stderr: string + code: number + } + + /** + * {@link http://github.com/snbartell/node-spawn} + */ + interface ISpawnedChild { + /** + * Start the cmd with the options provided. + */ + start(): void + + /** + * Convenience function. Overrides options. restarts to 0. + * Runs command exactly once no matter the options passed into the constructor. + */ + once(): void + + /** + * Convenience function. Overrides options.restarts to -1. + * Runs command indefinitely no matter the options passed into the constructor. + */ + forever(): void + + /** + * Shut down the child and don't let it restart. + */ + kill(): void + } + } + + /* + * Common interfaces + */ + + interface IFlag { + [flag: string]: boolean + } + + /* + * Grunt module mixins. + */ + + interface IConfigComponents extends grunt.config.ConfigModule { + /** + * An alias + * @see grunt.config.ConfigModule.init + */ + initConfig(config: grunt.config.IProjectConfig): void + } + + 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 + * specifying the path to that plugin's "tasks" subdirectory. + */ + loadTasks(tasksPath: string): void + + /** + * Load tasks from the specified Grunt plugin. + * This plugin must be installed locally via npm, and must be relative to the Gruntfile. + * Grunt plugins can be created by using the grunt-init gruntplugin template: grunt init:gruntplugin. + */ + loadNpmTasks(pluginName: string): void + } } -//////////////// -// Grunt File object -// http://gruntjs.com/api/grunt.file -//////////////// -interface IGruntFileObjectOptionsSimple { - encoding?: string; +/* GRUNT MODULE + **************/ + +/** + * The main Grunt module. + * + * {@link http://gruntjs.com/api/grunt} + */ +interface IGrunt extends grunt.IConfigComponents, grunt.fail.FailModule, grunt.ITaskComponents { + + config: grunt.config.ConfigModule + + event: grunt.event.EventModule + + fail: grunt.fail.FailModule + + file: grunt.file.FileModule + + log: grunt.log.LogModule + + option: grunt.option.OptionModule + + task: grunt.task.TaskModule + + template: grunt.template.TemplateModule + + util: grunt.util.UtilModule + + /** + * The current Grunt package.json metadata, as an object. + */ + package: node.NodePackage + + /** + * The current Grunt version, as a string. This is just a shortcut to the grunt.package.version property. + */ + version: string } -interface IGruntFileObjectOptions extends IGruntFileObjectOptionsSimple { - process?: Function; - noProcess?: any; -} -interface IGruntFileObject { - - // Character encoding - defaultEncoding: string; - - // Reading and writing - read(filepath: string, options?: IGruntFileObjectOptionsSimple): string; - readJSON(filepath: string, options?: IGruntFileObjectOptionsSimple): any; - readYAML(filepath: string, options?: IGruntFileObjectOptionsSimple): any; - write(filepath: string, contents: any, options?: IGruntFileObjectOptionsSimple): void; - copy(srcpath: string, destpath: string, options?: IGruntFileObjectOptions): void; - delete(filepath: string, options?: { force?: boolean; }): void; - - // Directories - mkdir(dirpath: string, mode?: number): void; - recurse(rootdir: string, callback: (abspath: string, rootdir: string, subdir: string, filename: string) => void): void; - - // Globbing patterns - expand(...patterns: string[]): string[]; - expand(options: Object, ...patterns: string[]): string[]; - expandMapping(patterns: string[], dest: string, options?: Object): any[]; - - match(patterns: string[], filepaths: string[]): string[]; - match(patterns: string[], filepaths: string): string[]; - match(patterns: string, filepaths: string[]): string[]; - match(patterns: string, filepaths: string): string[]; - match(options: Object, patterns: string[], filepaths: string[]): string[]; - match(options: Object, patterns: string[], filepaths: string): string[]; - match(options: Object, patterns: string, filepaths: string[]): string[]; - match(options: Object, patterns: string, filepaths: string): string[]; - - isMatch(patterns: string[], filepaths: string[]): boolean; - isMatch(patterns: string[], filepaths: string): boolean; - isMatch(patterns: string, filepaths: string[]): boolean; - isMatch(patterns: string, filepaths: string): boolean; - isMatch(options: Object, patterns: string[], filepaths: string[]): boolean; - isMatch(options: Object, patterns: string[], filepaths: string): boolean; - isMatch(options: Object, patterns: string, filepaths: string[]): boolean; - isMatch(options: Object, patterns: string, filepaths: string): boolean; - - // file types - exists(...paths: string[]): boolean; - isLink(...paths: string[]): boolean; - isDir(...paths: string[]): boolean; - isFile(...paths: string[]): boolean; - - // paths - isPathAbsolute(...paths: string[]): boolean; - arePathsEquivalent(...paths: string[]): boolean; - doesPathContain(ancestorPath: string, ...descendantPaths: string[]): boolean; - isPathCwd(...paths: string[]): boolean; - isPathInCwd(...paths: string[]): boolean; - setBase(...paths: string[]): void; - - // External libraries - glob: any; - minimatch: any; - findup: any; -} - -//////////////// -// 'this' when executing within a task -// http://gruntjs.com/api/inside-tasks -//////////////// -interface IGruntTaskThis { - async(): (err:any) => void; - requires(...taskNames: string[]): void; - requiresConfig(...props: string[]): void; - name: string; - nameArgs: string; - args: string[]; - flags: any; - errorCount: number; - options(defaults?: Object): any; -} - -//////////////// -// 'this' when executing within a multitask -// http://gruntjs.com/api/inside-tasks -//////////////// -interface IGruntMultiTaskThis extends IGruntTaskThis { - target: string; - files: IGruntFileArray[]; - filesSrc: string[]; - data: any; -} - -//////////////// -// Files array format -// http://gruntjs.com/configuring-tasks#files-array-format -//////////////// -interface IGruntFileArray { - src: string[]; - dest: string; - nonull?: boolean; - filter?: any; -} - -//////////////// -/// Globally called export function module.exports -//////////////// - -declare var exports: (grunt: IGrunt) => void; diff --git a/ix.js/ix-tests.ts b/ix.js/ix-tests.ts new file mode 100644 index 000000000..6953621ca --- /dev/null +++ b/ix.js/ix-tests.ts @@ -0,0 +1,116 @@ +/// + +var ec_ns = (a: number, b: string) => a.toString() == b; //equality comparer on number,string +var ec_ss = (a: string, b: string) => a == b; //equality comparer on string,string +var ec_nn = (a: number, b: number) => a === b; //equality comparer on number,number +var c_nn = (a: number, b: number) => a - b; //comparer on number,number + +// static + +Ix.Enumerable.throw(new Error("error")); +Ix.Enumerable.throwException(new Error("error")); + +var ax = Ix.Enumerable.generate(-100, a => a < 100, a=> a + 10, a=> a * 2); + +Ix.Enumerable.defer(() => ax); + +Ix.Enumerable.using(() => ax.getEnumerator(), e => Ix.Enumerable.return(e.getCurrent())); + +Ix.Enumerable.catch(ax, ax, ax); +Ix.Enumerable.catchException(ax, ax, ax); +Ix.Enumerable.catch(); +Ix.Enumerable.catchException(); + +Ix.Enumerable.onErrorResumeNext(ax, ax, ax); +Ix.Enumerable.onErrorResumeNext(); + +Ix.Enumerable.while(x => x.count() > 0, ax); +Ix.Enumerable.whileDo(x => x.count() > 0, ax); + +Ix.Enumerable.if(() => true, ax, ax); +Ix.Enumerable.ifThen(() => true, ax, ax); +Ix.Enumerable.if(() => true, ax); +Ix.Enumerable.ifThen(() => true, ax); + +Ix.Enumerable.doWhile(ax, x => x.count() > 0); + +Ix.Enumerable.case(() => 42, { 42: ax }, ax); +Ix.Enumerable.switchCase(() => 42, { 42: ax }, ax); +Ix.Enumerable.case(() => 42, { 42: ax }); +Ix.Enumerable.switchCase(() => 42, { 42: ax }); +Ix.Enumerable.case(() => "42", { "42": ax }, ax); +Ix.Enumerable.switchCase(() => "42", { "42": ax }, ax); +Ix.Enumerable.case(() => "42", { "42": ax }); +Ix.Enumerable.switchCase(() => "42", { "42": ax }); + +Ix.Enumerable.for(ax, a => ax); +Ix.Enumerable.forIn(ax, a => ax); + +// instance + +var bx: Ix.Enumerable; + +ax.isEmpty(); + +bx.minBy(b => b.length, c_nn); +bx.minBy(b => b.length); +bx.maxBy(b => b.length, c_nn); +bx.maxBy(b => b.length); + +ax.share(ax => bx); +ax.share(); + +ax.publish(ax => bx); +ax.publish(); + +ax.memoize(); + +ax.do({ onNext: (a: number) => console.log(a), onError: err => console.log(err), onCompleted: () => console.log("completed") }); +ax.do(a => console.log(a), err => console.log(err), () => console.log("completed")); +ax.do(a => console.log(a), err => console.log(err)); +ax.do((a: number) => console.log(a)); +ax.doAction({ onNext: (a: number) => console.log(a), onError: err => console.log(err), onCompleted: () => console.log("completed") }); +ax.doAction(a => console.log(a), err => console.log(err), () => console.log("completed")); +ax.doAction(a => console.log(a), err => console.log(err)); +ax.doAction((a: number) => console.log(a)); + +ax.bufferWithCount(10, 20); +ax.bufferWithCount(10); + +ax.ignoreElements(); + +bx.distinctBy(b => b.length, ec_nn); +bx.distinctBy(b => b.length); + +bx.distinctUntilChanged(b => b.length, ec_nn); +bx.distinctUntilChanged(b => b.length); +bx.distinctUntilChanged(); +bx.distinctUntilChanged(false, ec_ss); + +ax.expand(a => ax); + +ax.startWith(10, 20); + +ax.scan(0, (acc, a) => acc + a); +ax.scan((acc, a) => acc + a); + +ax.takeLast(10); +ax.skipLast(10); + +ax.repeat(10); +ax.repeat(); + +ax.catch(ax, ax, ax); +ax.catchException(ax, ax, ax); +ax.catch(ax); +ax.catchException(ax); +ax.catch(err => ax); +ax.catchException(err => ax); + +ax.finally(() => { }); +ax.finallyDo(() => { }); + +ax.onErrorResumeNext(ax); + +ax.retry(10); +ax.retry(); diff --git a/ix.js/ix.d.ts b/ix.js/ix.d.ts new file mode 100644 index 000000000..614a950fb --- /dev/null +++ b/ix.js/ix.d.ts @@ -0,0 +1,112 @@ +// Type definitions for IxJS 1.0.6 / ix.js +// Project: https://github.com/Reactive-Extensions/IxJS +// Definitions by: Igor Oleinikov + +/// + +declare module Ix { + + export interface Observer { + onNext? (value: T): void; + onError? (error: Error): void; + onCompleted? (): void; + } + + export interface Enumerable { + isEmpty(): boolean; + + minBy(keySelector: (item: T) => TKey, comparer: Comparer): Enumerable; + minBy(keySelector: (item: T) => number): Enumerable; + maxBy(keySelector: (item: T) => TKey, comparer: Comparer): Enumerable; + maxBy(keySelector: (item: T) => number): Enumerable; + + share(selector: (source: Enumerable) => Enumerable): Enumerable; + share(): Enumerable; + + publish(selector: (source: Enumerable) => Enumerable): Enumerable; + publish(): Enumerable; + + memoize(): Enumerable; + + do(onNext: (value: T) => void, onError?: (error: Error) => void, onCompleted?: () => void): Enumerable; + doAction(onNext: (value: T) => void, onError?: (error: Error) => void, onCompleted?: () => void): Enumerable; + do(onbserver: Observer): Enumerable; + doAction(onbserver: Observer): Enumerable; + + bufferWithCount(count: number, skip?: number): Enumerable; + + ignoreElements(): Enumerable; + + distinctBy(keySelector: (item: T) => TKey, comparer?: EqualityComparer): Enumerable; + + distinctUntilChanged(keySelector: (item: T) => TKey, comparer?: EqualityComparer): Enumerable; + distinctUntilChanged(): Enumerable; + // if need to set comparer without keySelector + distinctUntilChanged(_: boolean, comparer: EqualityComparer): Enumerable; + + expand(selector: (item: T) => Enumerable): Enumerable; + + startWith(...values: T[]): Enumerable; + + scan(seed: TSeed, accumulate: (acc: TAccumulator, item: T) => TAccumulator): Enumerable; + scan(accumulate: (acc: T, item: T) => T): Enumerable; + + takeLast(count: number): Enumerable; + skipLast(count: number): Enumerable; + + repeat(count?: number): Enumerable; + + catch(handler: (error: Error) => Enumerable): Enumerable; + catchException(handler: (error: Error) => Enumerable): Enumerable; + catch(second: Enumerable, ...other: Enumerable[]): Enumerable; + catchException(second: Enumerable, ...other: Enumerable[]): Enumerable; + + // todo: Enumerable>.catch(): Enumerable + //catch>(): Enumerable; + + finally(finallyAction: () => void): Enumerable; + finallyDo(finallyAction: () => void): Enumerable; + + onErrorResumeNext(second: Enumerable): Enumerable; + + retry(retryCount?: number): Enumerable; + } + + export interface EnumerableStatic { + throw(error: Error): Enumerable; + throwException(error: Error): Enumerable; + + defer(enumerableFactory: () => Enumerable): Enumerable; + + generate( + initialState: TState, + condition: Predicate, + iterate: (state: TState) => TState, + resultSelector: (state: TState) => TResult): Enumerable; + + using( + resourceFactory: () => TResource, + enumerableFactory: (resource: TResource) => Enumerable): Enumerable; + + catch(...sources: Enumerable[]): Enumerable; + catchException(...sources: Enumerable[]): Enumerable; + + onErrorResumeNext(...sources: Enumerable[]): Enumerable; + + while(condition: EnumerablePredicate>, source: Enumerable): Enumerable; + whileDo(condition: EnumerablePredicate>, source: Enumerable): Enumerable; + + if(condition: () => boolean, thenSource: Enumerable, elseSource?: Enumerable): Enumerable; + ifThen(condition: () => boolean, thenSource: Enumerable, elseSource?: Enumerable): Enumerable; + + doWhile(source: Enumerable, condition: EnumerablePredicate>): Enumerable; + + case(selector: () => number, sources: { [key: number]: Enumerable; }, defaultSource?: Enumerable): Enumerable; + case(selector: () => string, sources: { [key: string]: Enumerable; }, defaultSource?: Enumerable): Enumerable; + switchCase(selector: () => number, sources: { [key: number]: Enumerable; }, defaultSource?: Enumerable): Enumerable; + switchCase(selector: () => string, sources: { [key: string]: Enumerable; }, defaultSource?: Enumerable): Enumerable; + + for(source: Enumerable, resultSelector: EnumerableFunc): Enumerable; + forIn(source: Enumerable, resultSelector: EnumerableFunc): Enumerable; + } +} diff --git a/ix.js/l2o-tests.ts b/ix.js/l2o-tests.ts new file mode 100644 index 000000000..2399d4e9f --- /dev/null +++ b/ix.js/l2o-tests.ts @@ -0,0 +1,221 @@ +/// + +var ec_ns = (a: number, b: string) => a.toString() == b; //equality comparer on number,string +var ec_nn = (a: number, b: number) => a === b; //equality comparer on number,number +var c_nn = (a: number, b: number) => a - b; //comparer on number,number + +// static + +var ax = Ix.Enumerable.fromArray([0, 2, 7, 3, 4, 5]); + +var bx = Ix.Enumerable.create(() => { + var current = "."; + return Ix.Enumerator.create( + () => { current += "."; return true; }, + () => current, + () => { }); +}); + +Ix.Enumerator.create(() => true, () => 1); // without dispose method + +var cx = Ix.Enumerable.empty(); + +var dx = Ix.Enumerable.concat(ax, cx); + +var ex = Ix.Enumerable.return(42); +var fx = Ix.Enumerable.returnValue("42"); + +var gx = Ix.Enumerable.range(-100, 200); + +Ix.Enumerable.repeat(42, 42); +Ix.Enumerable.repeat(42); // infinite + +Ix.Enumerable.sequenceEqual(ax, fx, ec_ns); +Ix.Enumerable.sequenceEqual(ax, ex); // default comparer on same type + +// instance + +ax.getEnumerator(); + +ax.aggregate("", (acc, i) => acc + i, acc=> acc.length); +ax.aggregate("", (acc, i) => acc + i); +ax.aggregate((acc, i) => acc + i); + +ax.reduce((acc, i) => acc + i, 100); +ax.reduce((acc, i) => acc + i); + +ax.all(item => true); +ax.all(item => true, bx); +ax.every(item => true); +ax.every(item => true, bx); + +ax.any(); +ax.any(item => true); +ax.any(item => true, bx); +ax.some(); +ax.some(item => true); +ax.some(item => true, bx); + +ax.average(); +bx.average(item => item.length); +ax.min(); +bx.min(item => item.length); +ax.max(); +bx.max(item => item.length); +ax.sum(); +bx.sum(item => item.length); + +ax.concat(ax, cx, dx, ex, gx); + +ax.contains(10); +ax.contains("10", ec_ns); + +ax.count(); +ax.count(item=>false); +ax.count(item=> false, {}); + +cx.defaultIfEmpty(); +cx.defaultIfEmpty(10); + +dx.distinct(); +dx.distinct((d1, d2) => d1 === d2); + +ax.elementAt(2); +ax.elementAtOrDefault(2); + +//ax.except(bx, ec_ns); // bug https://typescript.codeplex.com/workitem/1841 +bx.except(fx); + +ax.first(); +ax.firstOrDefault(); +ax.last(); +ax.lastOrDefault(); +ax.single(); +ax.singleOrDefault(); + +ax.forEach(a => console.log(a)); +ax.forEach(a => console.log(a), cx); + +//bx.groupBy(b => b.length); // spec 3.5.2, waiting for restriction on generative recursion removal +bx.groupBy(b => b.length, b => "[" + b + "]"); +bx.groupBy(b => b.length, b => "[" + b + "]", (l, values) => l + values.count()); +bx.groupBy(b => b.length, false, (l, values) => l + values.count()); +bx.groupBy(b => b.length, b => "[" + b + "]", (l, values) => l + values.count(), ec_nn); +bx.groupBy(b => b.length, b => "[" + b + "]", false, (x, y) => x == y); +bx.groupBy(b => b.length, false, (l, values) => l + values.count(), ec_nn); +//bx.groupBy(b => b.length, false, false, ec_nn); // spec 3.5.2, waiting for restriction on generative recursion removal + +ax.groupJoin(bx, a => a, b => b, (a, b) => [a, b], ec_ns); +ax.groupJoin(bx, a => a, b => b.length, (a, b) => [a, b]); + +ax.join(bx, a => a, b => b, (a, b) => [a, b], ec_ns); +ax.join(bx, a => a, b => b.length, (a, b) => [a, b]); + +//ax.intersect(bx, ec_ns); // bug https://typescript.codeplex.com/workitem/1841 +ax.intersect(cx); +ax.union(cx); + +ax.orderBy(a=> -a).thenBy(a => a); +ax.orderBy(a=> -a, c_nn).thenBy(a => a, c_nn); +ax.orderByDescending(a=> -a).thenByDescending(a => a); +ax.orderByDescending(a=> -a, c_nn).thenByDescending(a => a, c_nn); + +ax.reverse(); + +ax.select(a=> a.toString()); +ax.select(a=> a.toString(), {}); +ax.map(a=> a.toString()); +ax.map(a=> a.toString(), {}); + +ax.selectMany(a=> bx); +ax.selectMany(a=> bx, (a, b) => [a, b]); + +ax.sequenceEqual(fx, ec_ns); +ax.sequenceEqual(ax, ec_nn); +ax.sequenceEqual(cx); + +ax.skip(10); +ax.skipWhile(a => a > 10); +ax.take(10); +ax.takeWhile(a => a > 10); + +ax.toArray(); + +bx.toDictionary(b => b.length, b => 10, ec_nn); +//bx.toDictionary(b => b.length, false, ec_nn); // spec 3.5.2, waiting for restriction on generative recursion removal +bx.toDictionary(b => b.length, b => 10); +//bx.toDictionary(b => b.length); // spec 3.5.2, waiting for restriction on generative recursion removal + +bx.toLookup(b => b.length, b => 10, ec_nn); +//bx.toLookup(b => b.length, false, ec_nn); // spec 3.5.2, waiting for restriction on generative recursion removal +bx.toLookup(b => b.length, b => 10); +//bx.toLookup(b => b.length); // spec 3.5.2, waiting for restriction on generative recursion removal + +ax.where(a=> a > 10, {}); +ax.where(a=> a > 10); +ax.filter(a=> a > 10, {}); +ax.filter(a=> a > 10); + +ax.zip(bx, (a: number, b: string) => [a, b]); +ax.zip(bx, (a, b) => [a, b]); + +// Disposable + +{ + var d: Ix.Disposable; + + d.dispose(); +} + +// Enumerator + +{ + var e: Ix.Enumerator; + + try { + while (e.moveNext()) { var c = e.getCurrent(); } + } + finally { + e.dispose(); + } +} + +// Dictionary + +{ + var dic = new Ix.Dictionary(0, ec_nn); + + var key = dic.toEnumerable().first().key; + var value = dic.toEnumerable().first().value; + + dic.add(1, "1"); + dic.remove(1); + dic.clear(); + dic.length(); + dic.tryGetValue(1); + dic.get(1); + dic.set(1, "1"); + dic.getValues(); + dic.has(1); +} + +// KeyValuePair + +{ + var kv: Ix.KeyValuePair; + var key = kv.key; + var value = kv.value; +} + +// Lookup + +{ + var lookup: Ix.Lookup; + + var key = lookup.toEnumerable().first().key; + lookup.toEnumerable().first().first(); + + lookup.has(1); + lookup.length(); + lookup.get(1).first(); +} \ No newline at end of file diff --git a/ix.js/l2o.d.ts b/ix.js/l2o.d.ts new file mode 100644 index 000000000..c3f3c415e --- /dev/null +++ b/ix.js/l2o.d.ts @@ -0,0 +1,256 @@ +// Type definitions for IxJS 1.0.6 / l2o.js +// Project: https://github.com/Reactive-Extensions/IxJS +// Definitions by: Igor Oleinikov + +declare module Ix { + export interface Disposable { + dispose(): void; + } + + export interface Enumerator extends Disposable { + moveNext(): boolean; + getCurrent(): T; + } + + export interface EnumeratorStatic { + new (moveNext: () => boolean, getCurrent: () => T, dispose: () => void): Enumerator; + create(moveNext: () => boolean, getCurrent: () => T, dispose?: () => void): Enumerator; + } + + var Enumerator: EnumeratorStatic; + + export interface EnumerableFunc { + (item: T, index: number, self: Enumerable): TResult; + } + export interface EnumerablePredicate extends EnumerableFunc { } + export interface Predicate { + (item: T): boolean; + } + export interface EqualityComparer { + (item1: TFirst, item2: TSecond): boolean; + } + export interface Comparer { + (item1: TFirst, item2: TSecond): number; + } + + export interface Enumerable { + // base functions + getEnumerator(): Enumerator; + + // "extension" functions + + aggregate(seed: TAccumulate, func: (accumulate: TAccumulate, current: T, index: number, self: Enumerable) => TAccumulate, resultSelector: (accumulate: TAccumulate) => TResult): TResult; + aggregate(seed: TAccumulate, func: (accumulate: TAccumulate, current: T, index: number, self: Enumerable) => TAccumulate): TAccumulate; + aggregate(func: (accumulate: T, current: T, index: number, self: Enumerable) => T): T; + + reduce(func: (accumulate: T, current: T, index: number, self: Enumerable) => T): T; + reduce(func: (accumulate: TAccumulate, current: T, index: number, self: Enumerable) => TAccumulate, seed: TAccumulate): TAccumulate; + + all(predicate: EnumerablePredicate, thisArg?: any): boolean; + every(predicate: EnumerablePredicate, thisArg?: any): boolean; // alias + + any(predicate?: EnumerablePredicate, thisArg?: any): boolean; + some(predicate?: EnumerablePredicate, thisArg?: any): boolean; // alias + + average(selector?: EnumerableFunc): number; + max(selector?: EnumerableFunc): number; + min(selector?: EnumerableFunc): number; + sum(selector?: EnumerableFunc): number; + + concat(...sources: Enumerable[]): Enumerable; + + contains(value: TValue, comparer: EqualityComparer): boolean; + contains(value: T): boolean; + + count(predicate?: EnumerablePredicate, thisArg?: any): number; + + defaultIfEmpty(defaultValue?: T): Enumerable; + + distinct(comparer?: EqualityComparer): Enumerable; + + elementAt(index: number): T; + elementAtOrDefault(index: number): T; + + except(second: Enumerable, comparer: EqualityComparer): Enumerable; + except(second: Enumerable): Enumerable; + + first(predicate?: Predicate): T; + firstOrDefault(predicate?: Predicate): T; + last(predicate?: Predicate): T; + lastOrDefault(predicate?: Predicate): T; + single(predicate?: Predicate): T; + singleOrDefault(predicate?: Predicate): T; + + forEach(action: EnumerableFunc, thisArg?: any): void; + + groupBy( + keySelector: (item: T) => TKey, + elementSelector: (item: T) => TElement, + resultSelector: (key: TKey, values: Enumerable) => TResult, + comparer?: EqualityComparer): Enumerable; + groupBy( + keySelector: (item: T) => TKey, + elementSelector: (item: T) => TElement): Grouping; + // spec 3.5.2, waiting for restriction on generative recursion removal + /*groupBy( + keySelector: (item: T) => TKey): Grouping;*/ + + // if need to set comparer without resultSelector + groupBy( + keySelector: (item: T) => TKey, + elementSelector: (item: T) => TElement, + _: boolean, + comparer: EqualityComparer): Grouping; + // if need to set resultSelector without elementSelector + groupBy( + keySelector: (item: T) => TKey, + _: boolean, + resultSelector: (key: TKey, values: Enumerable) => TResult, + comparer?: EqualityComparer): Enumerable; + // if need to set comparer without elementSelector and resultSelector + // spec 3.5.2, waiting for restriction on generative recursion removal + /*groupBy( + keySelector: (item: T) => TKey, + _: boolean, + __: boolean, + comparer: EqualityComparer): Grouping;*/ + + groupJoin( + inner: Enumerable, + outerKeySelector: (item: T) => TOuterKey, + innerKeySelector: (item: TInner) => TInnerKey, + resultSelector: (outer: T, innerSequence: Enumerable) => TResult, + comparer: EqualityComparer): Enumerable; + groupJoin( + inner: Enumerable, + outerKeySelector: (item: T) => TKey, + innerKeySelector: (item: TInner) => TKey, + resultSelector: (outer: T, innerSequence: Enumerable) => TResult): Enumerable; + + join( + inner: Enumerable, + outerKeySelector: (item: T) => TOuterKey, + innerKeySelector: (item: TInner) => TInnerKey, + resultSelector: (outer: T, inner: TInner) => TResult, + comparer: EqualityComparer): Enumerable; + join( + inner: Enumerable, + outerKeySelector: (item: T) => TKey, + innerKeySelector: (item: TInner) => TKey, + resultSelector: (outer: T, inner: TInner) => TResult): Enumerable; + + intersect(second: Enumerable, comparer: EqualityComparer): Enumerable; + intersect(second: Enumerable): Enumerable; + union(second: Enumerable, comparer?: EqualityComparer): Enumerable; + + orderBy(keySelector: (item: T) => TKey, comparer?: Comparer): OrderedEnumerable; + orderByDescending(keySelector: (item: T) => TKey, comparer?: Comparer): OrderedEnumerable; + + reverse(): Enumerable; + + select(selector: EnumerableFunc, thisArg?: any): Enumerable; + map(selector: EnumerableFunc, thisArg?: any): Enumerable; + + selectMany(collectionSelector: (item: T, index: number) => Enumerable, + resultSelector: (outer: T, inner: TCollection) => TResult): Enumerable; + selectMany(collectionSelector: (item: T, index: number) => Enumerable): Enumerable; + + sequenceEqual(second: Enumerable, comparer: EqualityComparer): boolean; + sequenceEqual(second: Enumerable): boolean; + + skip(count: number): Enumerable; + skipWhile(selector: EnumerablePredicate, thisArg?: any): Enumerable; + take(count: number): Enumerable; + takeWhile(selector: EnumerablePredicate, thisArg?: any): Enumerable; + + toArray(): T[]; + + toDictionary( + keySelector: (item: T) => TKey, + elementSelector: (item: T) => TValue, + comparer?: EqualityComparer): Dictionary; + // spec 3.5.2, waiting for restriction on generative recursion removal + /*toDictionary( + keySelector: (item: T) => TKey): Dictionary;*/ + // if need to set comparer without elementSelector + // spec 3.5.2, waiting for restriction on generative recursion removal + /*toDictionary( + keySelector: (item: T) => TKey, + _: boolean, + comparer: EqualityComparer): Dictionary;*/ + + toLookup( + keySelector: (item: T) => TKey, + elementSelector: (item: T) => TValue, + comparer?: EqualityComparer): Lookup; + // spec 3.5.2, waiting for restriction on generative recursion removal + /*toLookup( + keySelector: (item: T) => TKey): Lookup;*/ + // if need to set comparer without elementSelector + // spec 3.5.2, waiting for restriction on generative recursion removal + /*toLookup( + keySelector: (item: T) => TKey, + _: boolean, + comparer: EqualityComparer): Lookup;*/ + + where(selector: EnumerablePredicate, thisArg?: any): Enumerable; + filter(selector: EnumerablePredicate, thisArg?: any): Enumerable; + + zip(right: Enumerable, selector: (left: T, right: TRight) => TResult): Enumerable; + } + + export interface Grouping extends Enumerable { + key: TKey; + } + + export interface OrderedEnumerable extends Enumerable { + thenBy(keySelector: (item: T) => TKey, comparer?: Comparer): OrderedEnumerable; + thenByDescending(keySelector: (item: T) => TKey, comparer?: Comparer): OrderedEnumerable; + } + + class Dictionary { + constructor(capacity?: number, comparer?: EqualityComparer); + + toEnumerable(): Enumerable>; + + add(key: TKey, value: TValue): void; + remove(key: TKey): boolean; + clear(): void; + length(): number; + tryGetValue(key: TKey): TValue; + get(key: TKey): TValue; + set(key: TKey, value: TValue): void; + getValues(): TValue[]; + has(key: TKey): boolean; + } + + export interface KeyValuePair { + key: TKey; + value: TValue; + } + + export interface Lookup { + toEnumerable(): Enumerable>; + has(key: TKey): boolean; + length(): number; + get(key: TKey): Enumerable; + } + + export interface EnumerableStatic { + new (getEnumerator: () => Enumerator): Enumerable; + create(getEnumerator: () => Enumerator): Enumerable; + + concat(...sources: Enumerable[]): Enumerable; + empty(): Enumerable; + fromArray(array: T[]): Enumerable; + return(value: T): Enumerable; + returnValue(value: T): Enumerable; // alias for ; + repeat(value: T, repeatCount?: number): Enumerable; + + sequenceEqual(first: Enumerable, second: Enumerable, comparer: EqualityComparer): boolean; + sequenceEqual(first: Enumerable, second: Enumerable): boolean; + } + + var Enumerable: EnumerableStatic; +} \ No newline at end of file diff --git a/jake/jake.d.ts b/jake/jake.d.ts index f7e7a9e77..14d488bd3 100644 --- a/jake/jake.d.ts +++ b/jake/jake.d.ts @@ -201,14 +201,14 @@ declare module jake{ */ reenable(): void; - addListener(event: string, listener: Function); - on(event: string, listener: Function); - once(event: string, listener: Function): void; - removeListener(event: string, listener: Function): void; - removeAllListeners(event?: string): void; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, arg1?: any, arg2?: any): void; + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, arg1?: any, arg2?: any): boolean; } diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 142d51bcb..2c6e836d2 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -32,6 +32,7 @@ declare module jasmine { function objectContaining(sample: any): ObjectContaining; function createSpy(name: string, originalFn?: Function): Spy; function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; function getEnv(): Env; diff --git a/jquery.base64/jquery.base64-tests.ts b/jquery.base64/jquery.base64-tests.ts new file mode 100644 index 000000000..5f6b6eaa6 --- /dev/null +++ b/jquery.base64/jquery.base64-tests.ts @@ -0,0 +1,8 @@ +/// +/// + +var encoded = $.base64.encode(""); +$.base64.decode(encoded); + +var encodedUTF8 = $.base64.encode("", true); +$.base64.decode(encodedUTF8, true); diff --git a/jquery.base64/jquery.base64.d.ts b/jquery.base64/jquery.base64.d.ts new file mode 100644 index 000000000..9af24ed01 --- /dev/null +++ b/jquery.base64/jquery.base64.d.ts @@ -0,0 +1,15 @@ +// Type definitions for jQuery Plugin - base64 codec +// Project: https://github.com/yatt/jquery.base64/ +// Definitions by: Shinya Mochizuki +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQueryBase64Static { + encode(data: string, isUTF8?: boolean): string; + decode(data: string, isUTF8?: boolean): string; +} + +interface JQueryStatic { + base64: JQueryBase64Static; +} diff --git a/jquery.cleditor/jquery.cleditor-tests.ts b/jquery.cleditor/jquery.cleditor-tests.ts new file mode 100644 index 000000000..b29885150 --- /dev/null +++ b/jquery.cleditor/jquery.cleditor-tests.ts @@ -0,0 +1,42 @@ +/// +/// + +// cribbed from http://premiumsoftware.net/CLEditor/GettingStarted + +$(document).ready(function () { $("#input").cleditor(); }); + +$(document).ready(function() { + $("#input").cleditor({ + width: 500, // width not including margins, borders or padding + height: 250, // height not including margins, borders or padding + controls: // controls to add to the toolbar + "bold italic underline strikethrough subscript superscript | font size " + + "style | color highlight removeformat | bullets numbering | outdent " + + "indent | alignleft center alignright justify | undo redo | " + + "rule image link unlink | cut copy paste pastetext | print source", + colors: // colors in the color popup + "FFF FCC FC9 FF9 FFC 9F9 9FF CFF CCF FCF " + + "CCC F66 F96 FF6 FF3 6F9 3FF 6FF 99F F9F " + + "BBB F00 F90 FC6 FF0 3F3 6CC 3CF 66C C6C " + + "999 C00 F60 FC3 FC0 3C0 0CC 36F 63F C3C " + + "666 900 C60 C93 990 090 399 33F 60C 939 " + + "333 600 930 963 660 060 366 009 339 636 " + + "000 300 630 633 330 030 033 006 309 303", + fonts: // font names in the font popup + "Arial,Arial Black,Comic Sans MS,Courier New,Narrow,Garamond," + + "Georgia,Impact,Sans Serif,Serif,Tahoma,Trebuchet MS,Verdana", + sizes: // sizes in the font size popup + "1,2,3,4,5,6,7", + styles: // styles in the style popup + [["Paragraph", "

"], ["Header 1", "

"], ["Header 2", "

"], + ["Header 3", "

"], ["Header 4","

"], ["Header 5","

"], + ["Header 6","
"]], + useCSS: false, // use CSS to style HTML when possible (not supported in ie) + docType: // Document type contained within the editor + '', + docCSSFile: // CSS file used to style the document contained within the editor + "", + bodyStyle: // style to assign to document body contained within the editor + "margin:4px; font:10pt Arial,Verdana; cursor:text" + }); + }); \ No newline at end of file diff --git a/jquery.cleditor/jquery.cleditor.d.ts b/jquery.cleditor/jquery.cleditor.d.ts new file mode 100644 index 000000000..c273f3227 --- /dev/null +++ b/jquery.cleditor/jquery.cleditor.d.ts @@ -0,0 +1,98 @@ +// Type definitions for jQuery CLEditor Plugin 1.4.3 +// Project: http://premiumsoftware.net/CLEditor +// Definitions by: Jeffery Grajkowski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * An editor is composed of a main div element used to hold a toolbar, + * a text area and an iframe. The toolbar can hold multiple groups + * which in turn hold multiple buttons. + */ +interface CLEditor { + $area: JQuery; + $frame: JQuery; + $main: JQuery; + $toolbar: JQuery; + disabled: boolean; + doc: Document; + options: JQueryCLEditorOptions; + change(handler: Function): CLEditor; + clear(): CLEditor; + disable(disabled: boolean): CLEditor; + execCommand(commands: string, value: any, useCSS?: boolean, button?: any): CLEditor; + focus(): CLEditor; + hidePopups(): CLEditor; + refresh(): CLEditor; + select(): CLEditor; + selectedHTML(): string; + selectedText(): string; + showMessage(message: string, button?: any): CLEditor; + sourceMode(): boolean; + updateFrame(): CLEditor; + updateTextArea(): CLEditor; +} + +interface JQueryCLEditorOptions { + width?: number; + height?: number; + controls?: string; + colors?: string; + fonts?: string; + sizes?: string; + styles?: string[][]; + useCSS?: boolean; + docType?: string; + docCSSFile?: string; + bodyStyle?: string; +} + +interface JQueryCLEditorButtonDefinition { + name: string; + title: string; + css?: any; + image?: string; + stripIndex?: number; + command?: string; + popupName?: string; + popupContent?: string; + getEnabled?: (data: JQueryCLEditorButtonDefinitionEventData) => boolean; + getPressed?: (data: JQueryCLEditorButtonDefinitionEventData) => boolean; + buttonClick?: (event: Event, data: JQueryCLEditorButtonDefinitionEventData) => boolean; + popupClick?: (event: Event, data: JQueryCLEditorButtonDefinitionEventData) => boolean; +} + +interface JQueryCLEditorButtonDefinitionEventData { + editor: CLEditor; + button: HTMLElement; + buttonName: string; + popup: HTMLElement; + popupName: string; + command: string; + value: any; + useCSS: boolean; +} + +/** + * This object contains global properties and methods used to create + * custom plugins and override built in functionality. + */ +interface JQueryCLEditorStatic { + defaultOptions: JQueryCLEditorOptions; + buttons: JQueryCLEditorButtonDefinition[]; + imagesPath: () => string; +} + +interface JQueryStatic { + cleditor: JQueryCLEditorStatic; +} + +interface JQuery { + /** + * If the cleditor object does not exist for a matched textarea element, + * it will be created using the default options combined with the supplied options. + * This is the core method for creating and selecting cleditor objects. + */ + cleditor(options?: JQueryCLEditorOptions): CLEditor; +} diff --git a/jquery.timeago/jquery.timeago.d.ts b/jquery.timeago/jquery.timeago.d.ts index b1a1eab3f..109a7b0a8 100644 --- a/jquery.timeago/jquery.timeago.d.ts +++ b/jquery.timeago/jquery.timeago.d.ts @@ -1,6 +1,6 @@ -// Type definitions for jQuery.timeago.js 1.0.2 +// Type definitions for jQuery.timeago.js 1.0.2 // Project: http://timeago.yarp.com/ -// Definitions by: Franois Guillot +// Definitions by: François Guillot // Definitions: https://github.com/borisyankov/DefinitelyTyped diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 10c5cb979..332ee75da 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -616,6 +616,7 @@ interface JQuery { on(events: string, selector?: string, data?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; on(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + on(events: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; on(eventsMap: { [key: string]: any; }, selector?: any, data?: any): JQuery; one(events: string, selector?: any, data?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 42de3a3af..1a09df7fd 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -73,7 +73,7 @@ declare module JQueryUI { } interface Autocomplete extends Widget, AutocompleteOptions, AutocompleteEvents { - escapeRegex: (string) => string; + escapeRegex: (value: string) => string; } @@ -154,7 +154,7 @@ declare module JQueryUI { interface Datepicker extends Widget, DatepickerOptions { regional: { [languageCod3: string]: any; }; - setDefaults(defaults: DatepickerOptions); + setDefaults(defaults: DatepickerOptions): void; formatDate(format: string, date: Date, settings?: DatepickerFormatDateOptions): string; parseDate(format: string, date: string, settings?: DatepickerFormatDateOptions): Date; iso8601Week(date: Date): void; diff --git a/knockout.deferred.updates/knockout.deferred.updates.d.ts b/knockout.deferred.updates/knockout.deferred.updates.d.ts index 7822c7d95..1371f3263 100644 --- a/knockout.deferred.updates/knockout.deferred.updates.d.ts +++ b/knockout.deferred.updates/knockout.deferred.updates.d.ts @@ -30,7 +30,7 @@ interface KnockoutComputedStatic { deferUpdates: boolean; } -interface KnockoutComputedFunctions { +interface KnockoutSubscription { deferUpdates: boolean; } diff --git a/knockout.es5/knockout.es5-tests.ts b/knockout.es5/knockout.es5-tests.ts index f8faf9529..c51b9bc9d 100644 --- a/knockout.es5/knockout.es5-tests.ts +++ b/knockout.es5/knockout.es5-tests.ts @@ -1,4 +1,4 @@ -/// +/// var empty = {}, obj = { a: 'string', b: 123, c: true, d: empty }, @@ -75,3 +75,12 @@ anOrder.lines.shift(); console.log(someOrderLine.subtotal == someOrderLine.getSubtotal()); // true console.log(anOrder.lines.length); // 1 + +//Array methods +anOrder.lines.remove(someOrderLine); +anOrder.lines.removeAll([someOrderLine]); +anOrder.lines.removeAll(); + +anOrder.lines.destroy(someOrderLine); +anOrder.lines.destroyAll([someOrderLine]); +anOrder.lines.destroyAll(); \ No newline at end of file diff --git a/knockout.es5/knockout.es5.d.ts b/knockout.es5/knockout.es5.d.ts index c546e1beb..868655545 100644 --- a/knockout.es5/knockout.es5.d.ts +++ b/knockout.es5/knockout.es5.d.ts @@ -8,7 +8,22 @@ interface KnockoutStatic { track(obj: any, propertyNames?: Array): any; defineProperty(obj: any, propertyName: string, evaluator: Function): any; - defineProperty(obj: any, propertyName: string, options: { get: () => any; set?: (value: any) => void; }): any; + defineProperty(obj: any, propertyName: string, options: KnockoutDefinePropertyOptions): any; getObservable(obj: any, propertyName: string): KnockoutObservable; valueHasMutated(obj: any, propertyName: string): void; +} + +interface KnockoutDefinePropertyOptions { + get(): any; + set?(value: any): void; +} + +interface Array { + remove(item): T[]; + removeAll(items: T[]): T[]; + removeAll(): T[]; + + destroy(item: T): void; + destroyAll(items: T[]): void; + destroyAll(): void; } \ No newline at end of file diff --git a/knockout.postbox/knockout-postbox.d.ts b/knockout.postbox/knockout-postbox.d.ts index 3e6698851..daa35458a 100644 --- a/knockout.postbox/knockout-postbox.d.ts +++ b/knockout.postbox/knockout-postbox.d.ts @@ -19,6 +19,14 @@ interface KnockoutObservable { syncWith(topic: string, initializeWithLatestValue?: boolean, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservable; } +interface KnockoutObservableArray { + subscribeTo(topic: string, useLastPublishedValueToInitialize?: boolean, transform?: (val: any) => T): KnockoutObservableArray; + unsubscribeFrom(topic: string): KnockoutObservableArray; + publishOn(topic: string, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservableArray; + stopPublishingOn(topic: string): KnockoutObservableArray; + syncWith(topic: string, initializeWithLatestValue?: boolean, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservableArray; +} + interface KnockoutStatic { postbox: KnockoutPostBox; } \ No newline at end of file diff --git a/knockout.rx/knockout.rx-tests.ts b/knockout.rx/knockout.rx-tests.ts new file mode 100644 index 000000000..674e9bb6a --- /dev/null +++ b/knockout.rx/knockout.rx-tests.ts @@ -0,0 +1,12 @@ +/// + +var ax: Rx.IObservable; + +var ao = ax.toKoObservable(); + +ao(100); +ao.getSubscriptionsCount(); + +ao.toObservable(); +ao.toObservable("change"); +ao.toObservable("error"); \ No newline at end of file diff --git a/knockout.rx/knockout.rx-tests.ts.tscparams b/knockout.rx/knockout.rx-tests.ts.tscparams new file mode 100644 index 000000000..e16c76dff --- /dev/null +++ b/knockout.rx/knockout.rx-tests.ts.tscparams @@ -0,0 +1 @@ +"" diff --git a/knockout.rx/knockout.rx.d.ts b/knockout.rx/knockout.rx.d.ts new file mode 100644 index 000000000..4f44153d8 --- /dev/null +++ b/knockout.rx/knockout.rx.d.ts @@ -0,0 +1,26 @@ +// Type definitions for knockout.rx 0.1 +// Project: https://github.com/Igorbek/knockout.rx +// Definitions by: Igor Oleinikov + +/// +/// + +interface KnockoutSubscribableFunctions { + toObservable(event?: string): Rx.IObservable; + toObservable(event: string): Rx.IObservable; +} + +interface KnockoutObservableFunctions { + toObservableWithReplyLatest(): Rx.IObservable; +} + +interface KnockoutComputedFunctions { + toObservableWithReplyLatest(): Rx.IObservable; +} + +declare module Rx { + interface IObservable { + toKoSubscribable(): KnockoutSubscribable; + toKoObservable(initialValue?: T): KnockoutObservable; + } +} diff --git a/knockout.rx/knockout.rx.d.ts.tscparams b/knockout.rx/knockout.rx.d.ts.tscparams new file mode 100644 index 000000000..e16c76dff --- /dev/null +++ b/knockout.rx/knockout.rx.d.ts.tscparams @@ -0,0 +1 @@ +"" diff --git a/knockout.validation/knockout.validation.d.ts b/knockout.validation/knockout.validation.d.ts index 725902e60..2e00c5223 100644 --- a/knockout.validation/knockout.validation.d.ts +++ b/knockout.validation/knockout.validation.d.ts @@ -117,10 +117,10 @@ interface KnockoutValidationStatic { addRule(observable: KnockoutObservable, rule: KnockoutValidationRule): KnockoutObservable; - addAnonymousRule(observable: KnockoutObservableBase, ruleObj: KnockoutValidationAnonymousRuleDefinition): void; + addAnonymousRule(observable: KnockoutObservable, ruleObj: KnockoutValidationAnonymousRuleDefinition): void; insertValidationMessage(element: Element): Element; - parseInputValidationAttributes(element: Element, valueAccessor: () => KnockoutObservableBase): void; + parseInputValidationAttributes(element: Element, valueAccessor: () => KnockoutObservable): void; rules: KnockoutValidationRuleDefinitions; @@ -129,12 +129,12 @@ interface KnockoutValidationStatic { utils: KnockoutValidationUtils; localize(msgTranslations: any): void; - validateObservable(observable: KnockoutObservableBase): boolean; + validateObservable(observable: KnockoutObservable): boolean; } interface KnockoutStatic { validation: KnockoutValidationStatic; - validatedObservable(initialValue: any): KnockoutObservableBase; + validatedObservable(initialValue: any): KnockoutObservable; applyBindingsWithValidation(viewModel: any, rootNode?: any, options?: KnockoutValidationConfiguration): void; } diff --git a/knockout/knockout.amd.d.ts b/knockout/knockout.amd.d.ts index 960a0286d..7eb134612 100644 --- a/knockout/knockout.amd.d.ts +++ b/knockout/knockout.amd.d.ts @@ -24,10 +24,10 @@ declare module 'knockout' { export function isObservable(instance: any): boolean; export function isComputed(instance: any): boolean; export function dataFor(node: any): any; - export function removeNode(node: Element); - export function cleanNode(node: Element); - export function renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any); - export function renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any); + export function removeNode(node: Element): void; + export function cleanNode(node: Element): Element; + export function renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any; + export function renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any; ////////////////////////////////// //// templateSources.js @@ -44,9 +44,10 @@ declare module 'knockout' { //// templateRewriting.js //////////////////////////////////// export var templateRewriting: { - ensureTemplateIsRewritten(template, templateEngine, templateDocument); - memoizeBindingAttributeSyntax(htmlString: string, templateEngine: KnockoutTemplateEngine); - applyMemoizedBindingsToNextSibling(bindings); + ensureTemplateIsRewritten(template: Node, templateEngine: KnockoutTemplateEngine, templateDocument: Document): any; + ensureTemplateIsRewritten(template: string, templateEngine: KnockoutTemplateEngine, templateDocument: Document): any; + memoizeBindingAttributeSyntax(htmlString: string, templateEngine: KnockoutTemplateEngine): any; + applyMemoizedBindingsToNextSibling(bindings: any, nodeName: string): string; }; //////////////////////////////////// //// nativeTemplateEngine.js @@ -61,16 +62,25 @@ declare module 'knockout' { //////////////////////////////////// export var jqueryTmplTemplateEngine: { prototype: KnockoutTemplateEngine; - renderTemplateSource(templateSource, bindingContext, options); + renderTemplateSource(templateSource: Object, bindingContext: KnockoutBindingContext, options: Object): Node[]; createJavaScriptEvaluatorBlock(script: string): string; - addTemplate(templateName, templateMarkup); + addTemplate(templateName: string, templateMarkup: string): void; }; //////////////////////////////////// //// templating.js //////////////////////////////////// - export function setTemplateEngine(templateEngine: KnockoutNativeTemplateEngine); - export function renderTemplate(template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode); - export function renderTemplateForEach(template, arrayOrObservableArray, options, targetNode, parentBindingContext); + export function renderTemplate(template: Function, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; + export function renderTemplate(template: any, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; + export function renderTemplate(template: Function, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; + export function renderTemplate(template: any, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; + export function renderTemplate(template: Function, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; + export function renderTemplate(template: any, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; + export function renderTemplate(template: Function, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; + export function renderTemplate(template: any, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; + export function renderTemplateForEach(template: Function, arrayOrObservableArray: Array, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; + export function renderTemplateForEach(template: any, arrayOrObservableArray: Array, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; + export function renderTemplateForEach(template: Function, arrayOrObservableArray: KnockoutObservable, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; + export function renderTemplateForEach(template: any, arrayOrObservableArray: KnockoutObservable < Array>, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; export var expressionRewriting: { bindingRewriteValidators: any; }; diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 08f7bc88b..442058313 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -4,25 +4,18 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface KnockoutSubscribableFunctions { - extend(source); - dispose(): void; - peek(): any; - valueHasMutated(): void; - - valueWillMutate(): void; +interface KnockoutSubscribableFunctions { + notifySubscribers(valueToWrite: T, event?: string): void; } -interface KnockoutComputedFunctions extends KnockoutSubscribableFunctions { - getDependenciesCount(): number; - getSubscriptionsCount(): number; - hasWriteFunction(): boolean; +interface KnockoutComputedFunctions { } -interface KnockoutObservableFunctions extends KnockoutSubscribableFunctions { +interface KnockoutObservableFunctions { + equalityComparer(a: any, b: any): boolean; } -interface KnockoutObservableArrayFunctions extends KnockoutObservableFunctions { +interface KnockoutObservableArrayFunctions { // General Array functions indexOf(searchElement: T, fromIndex?: number): number; slice(start: number, end?: number): T[]; @@ -34,12 +27,13 @@ interface KnockoutObservableArrayFunctions extends KnockoutObservableFunction unshift(...items: T[]): number; reverse(): T[]; sort(): void; - sort(compareFunction): void; + sort(compareFunction: (left: any, right: any) => number): void; // Ko specific replace(oldItem: T, newItem: T): void; - remove(item): T[]; + remove(item: T): T[]; + remove(removeFunction: (item: T) => boolean): T[]; removeAll(items: T[]): T[]; removeAll(): T[]; @@ -49,18 +43,24 @@ interface KnockoutObservableArrayFunctions extends KnockoutObservableFunction } interface KnockoutSubscribableStatic { - fn: KnockoutSubscribableFunctions; + fn: KnockoutSubscribableFunctions; - new (): KnockoutSubscription; + new (): KnockoutSubscribable; } -interface KnockoutSubscription extends KnockoutSubscribableFunctions { - subscribe(callback: (newValue: any) => void, target?:any, topic?: string): KnockoutSubscription; - notifySubscribers(valueToWrite, topic?: string); +interface KnockoutSubscription { + dispose(): void; +} + +interface KnockoutSubscribable extends KnockoutSubscribableFunctions { + subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription; + subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; + getSubscriptionsCount(): number; } interface KnockoutComputedStatic { - fn: KnockoutComputedFunctions; + fn: KnockoutComputedFunctions; (): KnockoutComputed; (func: () => T, context?: any, options?: any): KnockoutComputed; @@ -68,51 +68,50 @@ interface KnockoutComputedStatic { (options?: any): KnockoutComputed; } -interface KnockoutComputed extends KnockoutComputedFunctions { - (): T; - (value: T): void; +interface KnockoutComputed extends KnockoutSubscribable, KnockoutComputedFunctions { + (): T; + (value: T): void; - subscribe(callback: (newValue: T) => void, target?:any, topic?: string): KnockoutSubscription; - notifySubscribers(valueToWrite: T, topic?: string); + peek(): T; + dispose(): void; + isActive(): boolean; + getDependenciesCount(): number; + extend(requestedExtenders: { [key: string]: any; }): KnockoutComputed; } interface KnockoutObservableArrayStatic { - fn: KnockoutObservableArrayFunctions; (value?: T[]): KnockoutObservableArray; } -interface KnockoutObservableArray extends KnockoutObservableArrayFunctions { - (): T[]; - (value: T[]): void; - - subscribe(callback: (newValue: T[]) => void, target?:any, topic?: string): KnockoutSubscription; - notifySubscribers(valueToWrite: T[], topic?: string); +interface KnockoutObservableArray extends KnockoutObservable, KnockoutObservableArrayFunctions { + extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray; } interface KnockoutObservableStatic { - fn: KnockoutObservableFunctions; + fn: KnockoutObservableFunctions; (value?: T): KnockoutObservable; } -/** use as method to get/set the value */ -interface KnockoutObservableBase extends KnockoutObservableFunctions { - getSubscriptionsCount(): number; -} +interface KnockoutObservable extends KnockoutSubscribable, KnockoutObservableFunctions { + (): T; + (value: T): void; -interface KnockoutObservable extends KnockoutObservableBase { - (): T; - (value: T): void; - - subscribe(callback: (newValue: T) => void, target?:any, topic?: string): KnockoutSubscription; - notifySubscribers(valueToWrite: T, topic?: string); + peek(): T; + valueHasMutated(): void; + valueWillMutate(): void; + extend(requestedExtenders: { [key: string]: any; }): KnockoutObservable; } interface KnockoutComputedDefine { - read(): T; - write(T); + read(): T; + write? (value: T): void; + disposeWhenNodeIsRemoved?: Node; + disposeWhen? (): boolean; + owner?: any; + deferEvaluation?: boolean; } interface KnockoutBindingContext { @@ -123,8 +122,8 @@ interface KnockoutBindingContext { $index?: number; $parentContext?: KnockoutBindingContext; - extend(any): any; - createChildContext(any): any; + extend(properties: any): any; + createChildContext(dataItemOrAccessor: any, dataItemAlias?: any, extendCallback?: Function): any; } interface KnockoutBindingHandler { @@ -168,23 +167,23 @@ interface KnockoutBindingHandlers { } interface KnockoutMemoization { - memoize(callback); - unmemoize(memoId, callbackParams); - unmemoizeDomNodeAndDescendants(domNode, extraCallbackParamsArray); - parseMemoText(memoText); + memoize(callback: () => string): string; + unmemoize(memoId: string, callbackParams: Array): boolean; + unmemoizeDomNodeAndDescendants(domNode: any, extraCallbackParamsArray: Array): boolean; + parseMemoText(memoText: string): string; } interface KnockoutVirtualElement {} interface KnockoutVirtualElements { allowedBindings: { [bindingName: string]: boolean; }; - emptyNode( e: KnockoutVirtualElement ); - firstChild( e: KnockoutVirtualElement ); - insertAfter( container: KnockoutVirtualElement, nodeToInsert: HTMLElement, insertAfter: HTMLElement ); - nextSibling( e: KnockoutVirtualElement ); - prepend( e: KnockoutVirtualElement, toInsert: HTMLElement ); - setDomNodeChildren( e: KnockoutVirtualElement, newChildren: { length: number;[index: number]: HTMLElement; } ); - childNodes( e: KnockoutVirtualElement ): HTMLElement[]; + emptyNode(node: KnockoutVirtualElement ): void; + firstChild(node: KnockoutVirtualElement ): KnockoutVirtualElement; + insertAfter( container: KnockoutVirtualElement, nodeToInsert: HTMLElement, insertAfter: HTMLElement ): void; + nextSibling(node: KnockoutVirtualElement): HTMLElement; + prepend(node: KnockoutVirtualElement, toInsert: HTMLElement ): void; + setDomNodeChildren(node: KnockoutVirtualElement, newChildren: { length: number;[index: number]: HTMLElement; } ): void; + childNodes(node: KnockoutVirtualElement ): HTMLElement[]; } interface KnockoutExtenders { @@ -198,11 +197,11 @@ interface KnockoutUtils { // utils.domManipulation.js ////////////////////////////////// - simpleHtmlParse(html: string); + simpleHtmlParse(html: string): Array; - jQueryHtmlParse(html: string); + jQueryHtmlParse(html: string): Array; - parseHtmlFragment(html: string); + parseHtmlFragment(html: string): Array; setHtml(node: Element, html: string): void; @@ -213,13 +212,13 @@ interface KnockoutUtils { ////////////////////////////////// domData: { - get (node: Element, key: string); + get (node: Element, key: string): any; - set (node: Element, key: string, value: any); + set (node: Element, key: string, value: any): void; - getAll(node: Element, createIfNotFound: boolean); + getAll(node: Element, createIfNotFound: boolean): any; - clear(node: Element); + clear(node: Element): boolean; }; ////////////////////////////////// @@ -227,13 +226,13 @@ interface KnockoutUtils { ////////////////////////////////// domNodeDisposal: { - addDisposeCallback(node: Element, callback: Function); + addDisposeCallback(node: Element, callback: Function): void; - removeDisposeCallback(node: Element, callback: Function); + removeDisposeCallback(node: Element, callback: Function): void; - cleanNode(node: Element); + cleanNode(node: Element): Element; - removeNode(node: Element); + removeNode(node: Element): void; }; ////////////////////////////////// @@ -242,41 +241,29 @@ interface KnockoutUtils { fieldsIncludedWithJsonPost: any[]; + compareArrays(a: T[], b: T[]): Array>; + arrayForEach(array: T[], action: (item: T) => void): void; - arrayForEach(array: any[], action: (any) => void ): void; - - arrayIndexOf(array: any[], item: any): number; + arrayIndexOf(array: T[], item: T): number; arrayFirst(array: T[], predicate: (item: T) => boolean, predicateOwner?: any): T; - arrayFirst(array: any[], predicate: (item) => boolean, predicateOwner?: any): any; - arrayRemoveItem(array: any[], itemToRemove: any): void; arrayGetDistinctValues(array: T[]): T[]; - arrayGetDistinctValues(array: any[]): any[]; - arrayMap(array: T[], mapping: (item: T) => U): U[]; - arrayMap(array: any[], mapping: (item) => any): any[]; - arrayFilter(array: T[], predicate: (item: T) => boolean): T[]; - arrayFilter(array: any[], predicate: (item) => boolean): any[]; - arrayPushAll(array: T[], valuesToPush: T[]): T[]; - arrayPushAll(array: any[], valuesToPush: any[]): any[]; - arrayPushAll(array: KnockoutObservableArray, valuesToPush: T[]): T[]; - arrayPushAll(array: KnockoutObservableArray, valuesToPush: any[]): any[]; + extend(target: Object, source: Object): Object; - extend(target, source); - - emptyDomNode(domNode): void; + emptyDomNode(domNode: HTMLElement): void; moveCleanedNodesToContainerElement(nodes: any[]): HTMLElement; @@ -337,15 +324,21 @@ interface KnockoutUtils { isIe7: boolean; } +interface KnockoutArrayChange { + status: string; + value: T; + index: number; +} + ////////////////////////////////// // templateSources.js ////////////////////////////////// interface KnockoutTemplateSourcesDomElement { - text(valueToWrite?); + text(valueToWrite?: any): any; - data(key, valueToWrite?); + data(key: string, valueToWrite?: any): any; } @@ -367,7 +360,7 @@ interface KnockoutTemplateSources { interface KnockoutNativeTemplateEngine { - renderTemplateSource(templateSource, bindingContext, options?); + renderTemplateSource(templateSource: Object, bindingContext?: KnockoutBindingContext, options?: Object): Array; } ////////////////////////////////// @@ -376,15 +369,15 @@ interface KnockoutNativeTemplateEngine { interface KnockoutTemplateEngine extends KnockoutNativeTemplateEngine { - createJavaScriptEvaluatorBlock(script: string); + createJavaScriptEvaluatorBlock(script: string): string; - makeTemplateSource(template, templateDocument); + makeTemplateSource(template: any, templateDocument?: Document): any; - renderTemplate(template, bindingContext, options, templateDocument); + renderTemplate(template: any, bindingContext: KnockoutBindingContext, options: Object, templateDocument: Document): any; - isTemplateRewritten(template, templateDocument): boolean; + isTemplateRewritten(template: any, templateDocument: Document): boolean; - rewriteTemplate(template, rewriterCallback, templateDocument); + rewriteTemplate(template: any, rewriterCallback: Function, templateDocument: Document): void; } ///////////////////////////////// @@ -413,10 +406,10 @@ interface KnockoutStatic { isWriteableObservable(instance: any): boolean; isComputed(instance: any): boolean; dataFor(node: any): any; - removeNode(node: Element); - cleanNode(node: Element); - renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any); - renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any); + removeNode(node: Element): void; + cleanNode(node: Element): Element; + renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any; + renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any; unwrap(value: any): any; ////////////////////////////////// @@ -442,11 +435,12 @@ interface KnockoutStatic { templateRewriting: { - ensureTemplateIsRewritten(template, templateEngine, templateDocument); + ensureTemplateIsRewritten(template: Node, templateEngine: KnockoutTemplateEngine, templateDocument: Document): any; + ensureTemplateIsRewritten(template: string, templateEngine: KnockoutTemplateEngine, templateDocument: Document): any; - memoizeBindingAttributeSyntax(htmlString: string, templateEngine: KnockoutTemplateEngine); + memoizeBindingAttributeSyntax(htmlString: string, templateEngine: KnockoutTemplateEngine): any; - applyMemoizedBindingsToNextSibling(bindings); + applyMemoizedBindingsToNextSibling(bindings: any, nodeName: string): string; }; ////////////////////////////////// @@ -470,22 +464,32 @@ interface KnockoutStatic { prototype: KnockoutTemplateEngine; - renderTemplateSource(templateSource, bindingContext, options); + renderTemplateSource(templateSource: Object, bindingContext: KnockoutBindingContext, options: Object): Node[]; createJavaScriptEvaluatorBlock(script: string): string; - addTemplate(templateName, templateMarkup); + addTemplate(templateName: string, templateMarkup: string): void; }; ////////////////////////////////// // templating.js ////////////////////////////////// - setTemplateEngine(templateEngine: KnockoutNativeTemplateEngine); + setTemplateEngine(templateEngine: KnockoutNativeTemplateEngine): void; - renderTemplate(template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode); + renderTemplate(template: Function, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; + renderTemplate(template: any, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; + renderTemplate(template: Function, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; + renderTemplate(template: any, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node, renderMode: string): any; + renderTemplate(template: Function, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; + renderTemplate(template: any, dataOrBindingContext: KnockoutBindingContext, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; + renderTemplate(template: Function, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; + renderTemplate(template: any, dataOrBindingContext: any, options: Object, targetNodeOrNodeArray: Node[], renderMode: string): any; - renderTemplateForEach(template, arrayOrObservableArray, options, targetNode, parentBindingContext); + renderTemplateForEach(template: Function, arrayOrObservableArray: Array, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; + renderTemplateForEach(template: any, arrayOrObservableArray: Array, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; + renderTemplateForEach(template: Function, arrayOrObservableArray: KnockoutObservable, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; + renderTemplateForEach(template: any, arrayOrObservableArray: KnockoutObservable, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any; expressionRewriting: { bindingRewriteValidators: any; @@ -501,9 +505,9 @@ interface KnockoutStatic { selectExtensions: { - readValue(element: any); + readValue(element: HTMLElement): any; - writeValue(element: any, value: any); + writeValue(element: HTMLElement, value: any): void; }; } diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 5cdc961bd..6234475b4 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,35 +1,2341 @@ -// Type definitions for Leaflet.js 0.5 +// Type definitions for Leaflet.js 0.6.4 // Project: https://github.com/Leaflet/Leaflet -// Definitions by: Vladimir +// Definitions by: Vladimir Zotov // Definitions: https://github.com/borisyankov/DefinitelyTyped + declare module L { + + export interface AttributionOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomright'. + */ + position?: string; + + /** + * The HTML text shown before the attributions. Pass false to disable. + * Default value: 'Powered by Leaflet'. + */ + prefix?: string; + + } +} + +declare module L { + + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + export function bounds(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + export function bounds(points: Point[]): Bounds; + + export class Bounds { + + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + constructor(topLeft: Point, bottomRight: Point); + + /** + * Creates a Bounds object defined by the points it contains. + */ + constructor(points: Point[]); + + /** + * Extends the bounds to contain the given point. + */ + extend(point: Point): void; + + /** + * Returns the center point of the bounds. + */ + getCenter(): Point; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: Bounds): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(point: Point): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: Bounds): boolean; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + /** + * Returns the size of the given bounds. + */ + getSize(): Point; + + /** + * The top left corner of the rectangle. + */ + min: Point; + + /** + * The bottom right corner of the rectangle. + */ + max: Point; + } +} + +declare module L { + + export class Browser { + + /** + * true for all Internet Explorer versions. + */ + static ie: boolean; + + /** + * true for Internet Explorer 6. + */ + static ie6: boolean; + + /** + * true for Internet Explorer 6. + */ + static ie7: boolean; + + /** + * true for webkit-based browsers like Chrome and Safari (including mobile + * versions). + */ + static webkit: boolean; + + /** + * true for webkit-based browsers that support CSS 3D transformations. + */ + static webkit3d: boolean; + + /** + * true for Android mobile browser. + */ + static android: boolean; + + /** + * true for old Android stock browsers (2 and 3). + */ + static android23: boolean; + + /** + * true for modern mobile browsers (including iOS Safari and different Android + * browsers). + */ + static mobile: boolean; + + /** + * true for mobile webkit-based browsers. + */ + static mobileWebkit: boolean; + + /** + * true for mobile Opera. + */ + static mobileOpera: boolean; + + /** + * true for all browsers on touch devices. + */ + static touch: boolean; + + /** + * true for browsers with Microsoft touch model (e.g. IE10). + */ + static msTouch: boolean; + + /** + * true for devices with Retina screens. + */ + static retina: boolean; + + } +} + + +declare module L { + + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + function circle(latlng: LatLng, radius: number, options?: PathOptions): Circle; + + export class Circle extends Path { + + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + constructor(latlng: LatLng, radius: number, options?: PathOptions); + + /** + * Returns the current geographical position of the circle. + */ + getLatLng(): LatLng; + + /** + * Returns the current radius of a circle. Units are in meters. + */ + getRadius(): number; + + /** + * Sets the position of a circle to a new location. + */ + setLatLng(latlng: LatLng): Circle; + + /** + * Sets the radius of a circle. Units are in meters. + */ + setRadius(radius: number): Circle; + + /** + * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). + */ + toGeoJSON(): any; + + } +} + +declare module L { + + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + function circleMarker(latlng: LatLng, options?: PathOptions): CircleMarker; + + export class CircleMarker extends Circle { + + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + constructor(latlng: LatLng, options?: PathOptions); + + /** + * Sets the position of a circle marker to a new location. + */ + setLatLng(latlng: LatLng): CircleMarker; + + /** + * Sets the radius of a circle marker. Units are in pixels. + */ + setRadius(radius: number): CircleMarker; + + /** + * Returns a GeoJSON representation of the circle marker (GeoJSON Point Feature). + */ + toGeoJSON(): any; + } +} + +declare module L { + + export interface ClassExtendOptions { + /** + * options is a special property that unlike other objects that you pass + * to extend will be merged with the parent one instead of overriding it + * completely, which makes managing configuration of objects and default + * values convenient. + */ + options?: any; + + /** + * includes is a special class property that merges all specified objects + * into the class (such objects are called mixins). A good example of this + * is L.Mixin.Events that event-related methods like on, off and fire + * to the class. + */ + includes?: any; + + /** + * statics is just a convenience property that injects specified object + * properties as the static properties of the class, useful for defining + * constants. + */ + static?: any; + } + + /** + * L.Class powers the OOP facilities of Leaflet and is used to create + * almost all of the Leaflet classes documented. + */ + export class Class { + + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + static extend(options: ClassExtendOptions): any; + + /** + * You can also use the following shortcut when you just need to make + * one additional method call. + */ + static addInitHook(methodName: string, ...args: any[]): void; + } + +} + + + +declare module L { + + export class Control extends Class implements IControl { + + /** + * Creates a control with the given options. + */ + constructor(options?: ControlOptions); + + /** + * Sets the position of the control. See control positions. + */ + setPosition(position: string): Control; + + /** + * Returns the current position of the control. + */ + getPosition(): string; + + /** + * Adds the control to the map. + */ + addTo(map: Map): Control; + + /** + * Removes the control from the map. + */ + removeFrom(map: Map): Control; + + /** + * Returns the HTML container of the control. + */ + getContainer(): HTMLElement; + + // IControl members + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } + + module Control { + + export class Zoom extends L.Control { + + /** + * Creates a zoom control. + */ + constructor(options?: ZoomOptions); + } + + export class Attribution extends L.Control { + + /** + * Creates an attribution control. + */ + constructor(options?: AttributionOptions); + + /** + * Sets the text before the attributions. + */ + setPrefix(prefix: string): Attribution; + + /** + * Adds an attribution text (e.g. 'Vector data © CloudMade'). + */ + addAttribution(text: string): Attribution; + + /** + * Removes an attribution text. + */ + removeAttribution(text: string): Attribution; + + } + + export class Layers extends L.Control implements IEventPowered { + + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + constructor(baseLayers?: any, overlays?: any, options?: LayersOptions); + + /** + * Adds a base layer (radio button entry) with the given name to the control. + */ + addBaseLayer(layer: ILayer, name: string): Layers; + + /** + * Adds an overlay (checkbox entry) with the given name to the control. + */ + addOverlay(layer: ILayer, name: string): Layers; + + /** + * Remove the given layer from the control. + */ + removeLayer(layer: ILayer): Layers; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Layers; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + fire(type: string, data?: any): Layers; addEventListener(eventMap: any, context?: any): Layers; + removeEventListener(eventMap?: any, context?: any): Layers; + clearAllEventListeners(): Layers + on(eventMap: any, context?: any): Layers; + off(eventMap?: any, context?: any): Layers; + } + + export class Scale extends L.Control { + + /** + * Creates an scale control with the given options. + */ + constructor(options?: ScaleOptions); + + } + } + + export class control { + + /** + * Creates a control with the given options. + */ + function (options?: ControlOptions): Control; + + /** + * Creates a zoom control. + */ + static zoom(options?: ZoomOptions): L.Control.Zoom; + + /** + * Creates an attribution control. + */ + static attribution(options?: AttributionOptions): L.Control.Attribution; + + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + static layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; + + /** + * Creates an scale control with the given options. + */ + static scale(options?: ScaleOptions): L.Control.Scale; + } +} + +declare module L { + + export interface ControlOptions { + + /** + * The initial position of the control (one of the map corners). See control + * positions. + * Default value: 'topright'. + */ + position: string; + + } +} + +declare module L { + + export class CRS { + + /** + * The most common CRS for online maps, used by almost all free and commercial + * tile providers. Uses Spherical Mercator projection. Set in by default in + * Map's crs option. + */ + static EPSG3857: ICRS; + + /** + * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. + */ + static EPSG4326: ICRS; + + /** + * Rarely used by some commercial tile providers. Uses Elliptical Mercator + * projection. + */ + static EPSG3395: ICRS; + + /** + * A simple CRS that maps longitude and latitude into x and y directly. May be + * used for maps of flat surfaces (e.g. game maps). Note that the y axis should + * still be inverted (going from bottom to top). + */ + static Simple: ICRS; + + } +} + +declare module L { + + /** + * Creates a div icon instance with the given options. + */ + function divIcon(options: DivIconOptions): DivIcon; + + export class DivIcon extends Icon { + + /** + * Creates a div icon instance with the given options. + */ + constructor(options: DivIconOptions); + } +} + +declare module L { + + export interface DivIconOptions { + + /** + * Size of the icon in pixels. Can be also set through CSS. + */ + iconSize?: Point; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point; + + /** + * A custom class name to assign to the icon. + * + * Default value: 'leaflet-div-icon'. + */ + className?: string; + + /** + * A custom HTML code to put inside the div element. + * + * Default value: ''. + */ + html?: string; + + } +} + +declare module L { + + export class DomEvent { + + /** + * Adds a listener fn to the element's DOM event of the specified type. this keyword + * inside the listener will point to context, or to the element if not specified. + */ + static addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Removes an event listener from the element. + */ + static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void): DomEvent; + + /** + * Stop the given event from propagation to parent elements. Used inside the + * listener functions: + * L.DomEvent.addListener(div, 'click', function + * (e) { + * L.DomEvent.stopPropagation(e); + * }); + */ + static stopPropagation(e: Event): DomEvent; + + /** + * Prevents the default action of the event from happening (such as following + * a link in the href of the a element, or doing a POST request with page reload + * when form is submitted). Use it inside listener functions. + */ + static preventDefault(e: Event): DomEvent; + + /** + * Does stopPropagation and preventDefault at the same time. + */ + static stop(e: Event): DomEvent; + + /** + * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' + * and 'touchstart' events. + */ + static disableClickPropagation(el: HTMLElement): DomEvent; + + /** + * Gets normalized mouse position from a DOM event relative to the container + * or to the whole page if not specified. + */ + static getMousePosition(e: Event, container?: HTMLElement): Point; + + /** + * Gets normalized wheel delta from a mousewheel DOM event. + */ + static getWheelDelta(e: Event): number; + + } +} + +declare module L { + + export class DomUtil { + + /** + * Returns an element with the given id if a string was passed, or just returns + * the element if it was passed directly. + */ + static get(id: string): HTMLElement; + + /** + * Returns the value for a certain style attribute on an element, including + * computed values or values set through CSS. + */ + static getStyle(el: HTMLElement, style: string): string; + + /** + * Returns the offset to the viewport for the requested element. + */ + static getViewportOffset(el: HTMLElement): Point; + + /** + * Creates an element with tagName, sets the className, and optionally appends + * it to container element. + */ + static create(tagName: string, className: string, container?: HTMLElement): HTMLElement; + + /** + * Makes sure text cannot be selected, for example during dragging. + */ + static disableTextSelection(): void; + + /** + * Makes text selection possible again. + */ + static enableTextSelection(): void; + + /** + * Returns true if the element class attribute contains name. + */ + static hasClass(el: HTMLElement, name: string): boolean; + + /** + * Adds name to the element's class attribute. + */ + static addClass(el: HTMLElement, name: string): void; + + /** + * Removes name from the element's class attribute. + */ + static removeClass(el: HTMLElement, name: string): void; + + /** + * Set the opacity of an element (including old IE support). Value must be from + * 0 to 1. + */ + static setOpacity(el: HTMLElement, value: number): void; + + /** + * Goes through the array of style names and returns the first name that is a valid + * style name for an element. If no such name is found, it returns false. Useful + * for vendor-prefixed styles like transform. + */ + static testProp(props: string[]): any; + + /** + * Returns a CSS transform string to move an element by the offset provided in + * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms + * and 2D on other browsers. + */ + static getTranslateString(point: Point): string; + + /** + * Returns a CSS transform string to scale an element (with the given scale origin). + */ + static getScaleString(scale: number, origin: Point): string; + + /** + * Sets the position of an element to coordinates specified by point, using + * CSS translate or top/left positioning depending on the browser (used by + * Leaflet internally to position its layers). Forces top/left positioning + * if disable3D is true. + */ + static setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; + + /** + * Returns the coordinates of an element previously positioned with setPosition. + */ + static getPosition(el: HTMLElement): Point; + + /** + * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). + */ + static TRANSITION: string; + + /** + * Vendor-prefixed transform style name. + */ + static TRANSFORM: string; + + } +} + +declare module L { + + /** + * Creates a Draggable object for moving the given element when you start dragging + * the dragHandle element (equals the element itself by default). + */ + function draggable(element: HTMLElement, dragHandle?: HTMLElement): Draggable; + + export class Draggable extends Class implements IEventPowered { + + /** + * Creates a Draggable object for moving the given element when you start dragging + * the dragHandle element (equals the element itself by default). + */ + constructor(element: HTMLElement, dragHandle?: HTMLElement); + + /** + * Enables the dragging ability. + */ + enable(): void; + + /** + * Disables the dragging ability. + */ + disable(): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Draggable; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + fire(type: string, data?: any): Draggable; + addEventListener(eventMap: any, context?: any): Draggable; + removeEventListener(eventMap?: any, context?: any): Draggable; + clearAllEventListeners(): Draggable + on(eventMap: any, context?: any): Draggable; + off(eventMap?: any, context?: any): Draggable; + } +} + + + +declare module L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function featureGroup(layers?: ILayer[]): FeatureGroup; + + export class FeatureGroup extends LayerGroup implements ILayer, IEventPowered { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + constructor(layers?: ILayer[]); + + /** + * Binds a popup with a particular HTML content to a click on any layer from the + * group that has a bindPopup method. + */ + bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; + + /** + * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates + * of its children). + */ + getBounds(): LatLngBounds; + + /** + * Sets the given path options to each layer of the group that has a setStyle method. + */ + setStyle(style: PathOptions): FeatureGroup; + + /** + * Brings the layer group to the top of all other layers. + */ + bringToFront(): FeatureGroup; + + /** + * Brings the layer group to the bottom of all other layers. + */ + bringToBack(): FeatureGroup; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): FeatureGroup; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + fire(type: string, data?: any): FeatureGroup; + addEventListener(eventMap: any, context?: any): FeatureGroup; + removeEventListener(eventMap?: any, context?: any): FeatureGroup; + clearAllEventListeners(): FeatureGroup + on(eventMap: any, context?: any): FeatureGroup; + off(eventMap?: any, context?: any): FeatureGroup; + } +} + +declare module L { + + export interface FitBoundsOptions extends ZoomPanOptions { + + /** + * Sets the amount of padding in the top left corner of a map container that + * shouldn't be accounted for when setting the view to fit bounds. Useful if + * you have some control overlays on the map like a sidebar and you don't + * want them to obscure objects you're zooming to. + * + * Default value: [0, 0]. + */ + paddingTopLeft?: Point; + + /** + * The same for bottom right corner of the map. + * + * Default value: [0, 0]. + */ + paddingBottomRight?: Point; + + /** + * Equivalent of setting both top left and bottom right padding to the same value. + * + * Default value: [0, 0]. + */ + padding?: Point; + } +} + +declare module L { + + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + export class GeoJSON extends FeatureGroup { + + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + constructor(geojson?: any, options?: GeoJSONOptions); + + /** + * Adds a GeoJSON object to the layer. + */ + addData(data: any): boolean; + + /** + * Changes styles of GeoJSON vector layers with the given style function. + */ + setStyle(style: (featureData: any) => any): GeoJSON; + + /** + * Resets the the given vector layer's style to the original GeoJSON style, + * useful for resetting style after hover events. + */ + resetStyle(layer: Path): GeoJSON; + + /** + * Creates a layer from a given GeoJSON feature. + */ + static geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; + + /** + * Creates a LatLng object from an array of 2 numbers (latitude, longitude) + * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted + * as (longitude, latitude). + */ + static coordsToLatlng(coords: number[], reverse?: boolean): LatLng; + + /** + * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates + * array. levelsDeep specifies the nesting level (0 is for an array of points, + * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to + * true, the numbers will be interpreted as (longitude, latitude). + */ + static coordsToLatlngs(coords: number[], levelsDeep?: number, reverse?: boolean): LatLng[]; + + } +} + +declare module L { + export interface GeoJSONOptions { + /** + * Function that will be used for creating layers for GeoJSON points (if not + * specified, simple markers will be created). + */ + pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; + + /** + * Function that will be used to get style options for vector layers created + * for GeoJSON features. + */ + style?: (featureData: any) => any; + + /** + * Function that will be called on each created feature layer. Useful for attaching + * events and popups to features. + */ + onEachFeature?: (featureData: any, layer: ILayer) => void; + + /** + * Function that will be used to decide whether to show a feature or not. + */ + filter?: (featureData: any, layer: ILayer) => boolean; + + /** + * Function that will be used for converting GeoJSON coordinates to LatLng points + * (if not specified, coords will be assumed to be WGS84 standard[longitude, latitude] + * values in degrees). + */ + coordsToLatLng?: (coords: any[]) => LatLng[]; + } +} + + + + +declare module L { + + /** + * Creates an icon instance with the given options. + */ + function icon(options: IconOptions): Icon; + + export class Icon extends Class { + + /** + * Creates an icon instance with the given options. + */ + constructor(options: IconOptions); + } + + module Icon { + + /** + * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses + * for markers by default. + */ + export class Default extends Icon { + + /** + * Creates an icon instance with default options. + */ + constructor(options: IconOptions); + + static imagePath: string; + } + } +} + +declare module L { + + export interface IconOptions { + + /** + * (required) The URL to the icon image (absolute or relative to your script + * path). + */ + iconUrl?: string; + + /** + * The URL to a retina sized version of the icon image (absolute or relative to + * your script path). Used for Retina screen devices. + */ + iconRetinaUrl?: string; + + /** + * Size of the icon image in pixels. + */ + iconSize?: Point; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point; + + /** + * The URL to the icon shadow image. If not specified, no shadow image will be + * created. + */ + shadowUrl?: string; + + /** + * The URL to the retina sized version of the icon shadow image. If not specified, + * no shadow image will be created. Used for Retina screen devices. + */ + shadowRetinaUrl?: string; + + /** + * Size of the shadow image in pixels. + */ + shadowSize?: Point; + + /** + * The coordinates of the "tip" of the shadow (relative to its top left corner) + * (the same as iconAnchor if not specified). + */ + shadowAnchor?: Point; + + /** + * The coordinates of the point from which popups will "open", relative to the + * icon anchor. + */ + popupAnchor?: Point; + + /** + * A custom class name to assign to both icon and shadow images. Empty by default. + */ + className?: string; + } +} + +declare module L { + + export interface IControl { + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } +} + +declare module L { + + export interface ICRS { + + /** + * Projection that this CRS uses. + */ + projection: IProjection; + + /** + * Transformation that this CRS uses to turn projected coordinates into screen + * coordinates for a particular tile service. + */ + transformation: Transformation; + + /** + * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). + */ + code: string; + + /** + * Projects geographical coordinates on a given zoom into pixel coordinates. + */ + latLngToPoint(latlng: LatLng, zoom: number): Point; + + /** + * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom + * into geographical coordinates. + */ + pointToLatLng(point: Point, zoom: number): LatLng; + + /** + * Projects geographical coordinates into coordinates in units accepted + * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). + */ + project(latlng: LatLng): Point; + + /** + * Returns the scale used when transforming projected coordinates into pixel + * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for + * Mercator-based CRS. + */ + scale(zoom: number): number; + + } +} + +declare module L { + + export interface IEventPowered { + + /** + * Adds a listener function (fn) to a particular event type of the object. You + * can optionally specify the context of the listener (object the this keyword + * will point to). You can also pass several space-separated types (e.g. 'click + * dblclick'). + */ + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * The same as above except the listener will only get fired once and then removed. + */ + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + /** + * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} + */ + addEventListener(eventMap: any, context?: any): T; + + /** + * Removes a previously added listener function. If no function is specified, + * it will remove all the listeners of that particular event from the object. + */ + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Removes a set of type/listener pairs. + */ + removeEventListener(eventMap?: any, context?: any): T; + + /** + * Returns true if a particular event type has some listeners attached to it. + */ + hasEventListeners(type: string): boolean; + + /** + * Fires an event of the specified type. You can optionally provide an data object + * — the first argument of the listener function will contain its properties. + */ + fireEvent(type: string, data?: any): T; + + /** + * Removes all listeners to all events on the object. + */ + clearAllEventListeners(): T; + + /** + * Alias to addEventListener. + */ + on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to addEventListener. + */ + on(eventMap: any, context?: any): T; + + /** + * Alias to addOneTimeEventListener. + */ + once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(eventMap?: any, context?: any): T; + + /** + * Alias to fireEvent. + */ + fire(type: string, data?: any): T; + } +} + +declare module L { + + export interface IHandler { + + /** + * Enables the handler. + */ + enable(): void; + + /** + * Disables the handler. + */ + disable(): void; + + /** + * Returns true if the handler is enabled. + */ + enabled(): boolean; + } +} + +declare module L { + + export interface ILayer { + + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare module L { + + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + + export class ImageOverlay extends Class implements ILayer { + + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + constructor(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions); + + /** + * Adds the overlay to the map. + */ + addTo(map: Map): ImageOverlay; + + /** + * Sets the opacity of the overlay. + */ + setOpacity(opacity: number): ImageOverlay; + + /** + * Brings the layer to the top of all overlays. + */ + bringToFront(): ImageOverlay; + + /** + * Brings the layer to the bottom of all overlays. + */ + bringToBack(): ImageOverlay; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare module L { + + export interface ImageOverlayOptions { + + /** + * The opacity of the image overlay. + */ + opacity?: number; + } +} + +declare module L { + + export interface IProjection { + + /** + * Projects geographical coordinates into a 2D point. + */ + project(latlng: LatLng): Point; + + /** + * The inverse of project. Projects a 2D point into geographical location. + */ + unproject(point: Point): LatLng; + } +} + +declare module L { + + /** + * A constant that represents the Leaflet version in use. + */ + export var version: string; + + /** + * This method restores the L global variale to the original value it had + * before Leaflet inclusion, and returns the real Leaflet namespace. + */ + export function noConflict(): typeof L; +} + +declare module L { + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(coords: number[]): LatLng; + + export class LatLng { + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + constructor(latitude: number, longitude: number); + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + constructor(coords: number[]); + + /** + * Returns the distance (in meters) to the given LatLng calculated using the + * Haversine formula. See description on wikipedia + */ + distanceTo(otherLatlng: LatLng): number; + + /** + * Returns true if the given LatLng point is at the same position (within a small + * margin of error). + */ + equals(otherLatlng: LatLng): boolean; + + /** + * Returns a string representation of the point (for debugging purposes). + */ + toString(): string; + + /** + * Returns a new LatLng object with the longitude wrapped around left and right + * boundaries (-180 to 180 by default). + */ + wrap(left: number, right: number): LatLng; + + /** + * Latitude in degrees. + */ + lat: number; + + /** + * Longitude in degrees. + */ + lng: number; + + /** + * A multiplier for converting degrees into radians. + * + * Value: Math.PI / 180. + */ + static DEG_TO_RAD: number; + + /** + * A multiplier for converting radians into degrees. + * + * Value: 180 / Math.PI. + */ + static RAD_TO_DEG: number; + + /** + * Max margin of error for the equality check. + * + * Value: 1.0E-9. + */ + static MAX_MARGIN: number; + } +} + +declare module L { + + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + function latLngBounds(southWest: LatLng, northEast: LatLng): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + function latLngBounds(latlngs: LatLng[]): LatLngBounds; + + export class LatLngBounds { + + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + constructor(southWest: LatLng, northEast: LatLng); + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + constructor(latlngs: LatLng[]); + + /** + * Extends the bounds to contain the given point. + */ + extend(latlng: LatLng): LatLngBounds; + + /** + * Extends the bounds to contain the given bounds. + */ + extend(latlng: LatLngBounds): LatLngBounds; + + /** + * Returns the south-west point of the bounds. + */ + getSouthWest(): LatLng; + + /** + * Returns the north-east point of the bounds. + */ + getNorthEast(): LatLng; + + /** + * Returns the north-west point of the bounds. + */ + getNorthWest(): LatLng; + + /** + * Returns the south-east point of the bounds. + */ + getSouthEast(): LatLng; + + /** + * Returns the center point of the bounds. + */ + getCenter(): LatLng; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: LatLngBounds): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(latlng: LatLng): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: LatLngBounds): boolean; + + /** + * Returns true if the rectangle is equivalent (within a small margin of error) + * to the given bounds. + */ + equals(otherBounds: LatLngBounds): boolean; + + /** + * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' + * format. Useful for sending requests to web services that return geo data. + */ + toBBoxString(): string; + + /** + * Returns bigger bounds created by extending the current bounds by a given + * percentage in each direction. + */ + pad(bufferRatio: number): LatLngBounds; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + } +} + +declare module L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function layerGroup(layers?: ILayer[]): LayerGroup; + + export class LayerGroup extends Class implements ILayer { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + constructor(layers?: ILayer[]); + + /** + * Adds the group of layers to the map. + */ + addTo(map: Map): LayerGroup; + + /** + * Adds a given layer to the group. + */ + addLayer(layer: ILayer): LayerGroup; + + /** + * Removes a given layer from the group. + */ + removeLayer(layer: ILayer): LayerGroup; + + /** + * Removes a given layer of the given id from the group. + */ + removeLayer(id: string): LayerGroup; + + /** + * Returns true if the given layer is currently added to the group. + */ + hasLayer(layer: ILayer): boolean; + + /** + * Returns the layer with the given id. + */ + getLayer(id: string): ILayer; + + /** + * Returns an array of all the layers added to the group. + */ + getLayers(): ILayer[]; + + /** + * Removes all the layers from the group. + */ + clearLayers(): LayerGroup; + + /** + * Iterates over the layers of the group, optionally specifying context of + * the iterator function. + */ + eachLayer(fn: (layer: ILayer) => void, context?: any): LayerGroup; + + /** + * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). + */ + toGeoJSON(): any; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + + +declare module L { + + export interface LayersOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * + * Default value: 'topright'. + */ + position?: string; + + /** + * If true, the control will be collapsed into an icon and expanded on mouse hover + * or touch. + * + * Default value: true. + */ + collapsed?: boolean; + + /** + * If true, the control will assign zIndexes in increasing order to all of its + * layers so that the order is preserved when switching them on/off. + * + * Default value: true. + */ + autoZIndex?: boolean; + + } +} + +declare module L { + + export interface LeafletErrorEvent extends LeafletEvent { + + /** + * Error message. + */ + message: string; + + /** + * Error code (if applicable). + */ + code: number; + } +} + +declare module L { + + export interface LeafletEvent { + + /** + * The event type (e.g. 'click'). + */ + type: string; + + /** + * The object that fired the event. + */ + target: any; + } +} + +declare module L { + + export interface LeafletGeoJSONEvent extends LeafletEvent { + + /** + * The layer for the GeoJSON feature that is being added to the map. + */ + layer: ILayer; + + /** + * GeoJSON properties of the feature. + */ + properties: any; + + /** + * GeoJSON geometry type of the feature. + */ + geometryType: string; + + /** + * GeoJSON ID of the feature (if present). + */ + id: string; + } +} + +declare module L { + + export interface LeafletLayerEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + } +} + +declare module L { + + export interface LeafletLocationEvent extends LeafletEvent { + + /** + * Detected geographical location of the user. + */ + latlng: LatLng; + + /** + * Geographical bounds of the area user is located in (with respect to the accuracy + * of location). + */ + bounds: LatLngBounds; + + /** + * Accuracy of location in meters. + */ + accuracy: number; + + /** + * Height of the position above the WGS84 ellipsoid in meters. + */ + altitude: number; + + /** + * Accuracy of altitude in meters. + */ + altitudeAccuracy: number; + + /** + * The direction of travel in degrees counting clockwise from true North. + */ + heading: number; + + /** + * Current velocity in meters per second. + */ + speed: number; + + /** + * The time when the position was acquired. + */ + timestamp: number; + + } +} + +declare module L { + + export interface LeafletMouseEvent extends LeafletEvent { + + /** + * The geographical point where the mouse event occured. + */ + latlng: LatLng; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map layer. + */ + layerPoint: Point; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map сontainer. + */ + containerPoint: Point; + + /** + * The original DOM mouse event fired by the browser. + */ + originalEvent: MouseEvent; + } +} + +declare module L { + + export interface LeafletPopupEvent extends LeafletEvent { + + /** + * The popup that was opened or closed. + */ + popup: Popup; + } +} + +declare module L { + + export interface LeafletResizeEvent extends LeafletEvent { + + /** + * The old size before resize event. + */ + oldSize: Point; + + /** + * The new size after the resize event. + */ + newSize: Point; + } +} + +declare module L { + + export interface LeafletTileEvent extends LeafletEvent { + + /** + * The tile element (image). + */ + tile: HTMLElement; + + /** + * The source URL of the tile. + */ + url: string; + } +} + +declare module L { + + export class LineUtil { + + /** + * Dramatically reduces the number of points in a polyline while retaining + * its shape and returns a new array of simplified points. Used for a huge performance + * boost when processing/displaying Leaflet polylines for each zoom level + * and also reducing visual noise. tolerance affects the amount of simplification + * (lesser value means higher quality but slower and with more points). Also + * released as a separated micro-library Simplify.js. + */ + static simplify(points: Point[], tolerance: number): Point[]; + + /** + * Returns the distance between point p and segment p1 to p2. + */ + static pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; + + /** + * Returns the closest point from a point p on a segment p1 to p2. + */ + static closestPointOnSegment(p: Point, p1: Point, p2: Point): number; + + /** + * Clips the segment a to b by rectangular bounds (modifying the segment points + * directly!). Used by Leaflet to only show polyline points that are on the screen + * or near, increasing performance. + */ + static clipSegment(a: Point, b: Point, bounds: Bounds): void; + + } +} + +declare module L { + + export interface LocateOptions { + + /** + * If true, starts continous watching of location changes (instead of detecting + * it once) using W3C watchPosition method. You can later stop watching using + * map.stopLocate() method. + * + * Default value: false. + */ + watch?: boolean; + + /** + * If true, automatically sets the map view to the user location with respect + * to detection accuracy, or to world view if geolocation failed. + * + * Default value: false. + */ + setView?: boolean; + + /** + * The maximum zoom for automatic view setting when using `setView` option. + * + * Default value: Infinity. + */ + maxZoom?: number; + + /** + * Number of millisecond to wait for a response from geolocation before firing + * a locationerror event. + * + * Default value: 10000. + */ + timeout?: number; + + /** + * Maximum age of detected location. If less than this amount of milliseconds + * passed since last geolocation response, locate will return a cached location. + * + * Default value: 0. + */ + maximumAge?: number; + + /** + * Enables high accuracy, see description in the W3C spec. + * + * Default value: false. + */ + enableHighAccuracy?: boolean; + } +} + +declare module L { + + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + */ + function map(id: HTMLElement, options?: MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + */ + function map(id: string, options?: MapOptions): Map; + + export class Map extends Class implements IEventPowered { + + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + * + * @constructor + */ + constructor(id: HTMLElement, options?: MapOptions); + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + * + * @constructor + */ + constructor(id: string, options?: MapOptions); + + // Methods for Modifying Map State + + /** + * Sets the view of the map (geographical center and zoom) with the given + * animation options. + */ + setView(center: LatLng, zoom: number, options?: ZoomPanOptions): Map; + + /** + * Sets the zoom of the map. + */ + setZoom(zoom: number, options?: ZoomOptions): Map; + + /** + * Increases the zoom of the map by delta (1 by default). + */ + zoomIn(delta?: number, options?: ZoomOptions): Map; + + /** + * Decreases the zoom of the map by delta (1 by default). + */ + zoomOut(delta?: number, options?: ZoomOptions): Map; + + /** + * Zooms the map while keeping a specified point on the map stationary + * (e.g. used internally for scroll zoom and double-click zoom). + */ + setZoomAround(latlng: LatLng, zoom: number, options?: ZoomOptions): Map; + + /** + * Sets a map view that contains the given geographical bounds with the maximum + * zoom level possible. + */ + fitBounds(bounds: LatLngBounds, options?: FitBoundsOptions): Map; + + /** + * Sets a map view that mostly contains the whole world with the maximum zoom + * level possible. + */ + fitWorld(options?: FitBoundsOptions): Map; + + /** + * Pans the map to a given center. Makes an animated pan if new center is not more + * than one screen away from the current one. + */ + panTo(latlng: LatLng, options?: PanOptions): Map; + + /** + * Pans the map to the closest view that would lie inside the given bounds (if + * it's not already). + */ + panInsideBounds(bounds: LatLngBounds): Map; + + /** + * Pans the map by a given number of pixels (animated). + */ + panBy(point: Point, options?: PanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + * If options.pan is false, panning will not occur. + */ + invalidateSize(options: ZoomPanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + */ + invalidateSize(animate: boolean): Map; + + /** + * Restricts the map view to the given bounds (see map maxBounds option), + * passing the given animation options through to `setView`, if required. + */ + setMaxBounds(bounds: LatLngBounds, options?: ZoomPanOptions): Map; + + /** + * Tries to locate the user using Geolocation API, firing locationfound event + * with location data on success or locationerror event on failure, and optionally + * sets the map view to the user location with respect to detection accuracy + * (or to the world view if geolocation failed). See Locate options for more + * details. + */ + locate(options?: LocateOptions): Map; + + /** + * Stops watching location previously initiated by map.locate({watch: true}) + * and aborts resetting the map view if map.locate was called with {setView: true}. + */ + stopLocate(): Map; + + /** + * Destroys the map and clears all related event listeners. + */ + remove(): Map; + + // Methods for Getting Map State + + /** + * Returns the geographical center of the map view. + */ + getCenter(): LatLng; + + /** + * Returns the current zoom of the map view. + */ + getZoom(): number; + + /** + * Returns the minimum zoom level of the map. + */ + getMinZoom(): number; + + /** + * Returns the maximum zoom level of the map. + */ + getMaxZoom(): number; + + /** + * Returns the LatLngBounds of the current map view. + */ + getBounds(): LatLngBounds; + + /** + * Returns the maximum zoom level on which the given bounds fit to the map view + * in its entirety. If inside (optional) is set to true, the method instead returns + * the minimum zoom level on which the map view fits into the given bounds in its + * entirety. + */ + getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; + + /** + * Returns the current size of the map container. + */ + getSize(): Point; + + /** + * Returns the bounds of the current map view in projected pixel coordinates + * (sometimes useful in layer and overlay implementations). + */ + getPixelBounds(): Bounds; + + /** + * Returns the projected pixel coordinates of the top left point of the map layer + * (useful in custom layer and overlay implementations). + */ + getPixelOrigin(): Point; + + // Methods for Layers and Controls + + /** + * Adds the given layer to the map. If optional insertAtTheBottom is set to true, + * the layer is inserted under all others (useful when switching base tile layers). + */ + addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; + + /** + * Removes the given layer from the map. + */ + removeLayer(layer: ILayer): Map; + + /** + * Returns true if the given layer is currently added to the map. + */ + hasLayer(layer: ILayer): boolean; + + /** + * Opens the specified popup while closing the previously opened (to make sure + * only one is opened at one time for usability). + */ + openPopup(popup: Popup): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(html: string, latlng: LatLng, options?: PopupOptions): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(el: HTMLElement, latlng: LatLng, options?: PopupOptions): Map; + + /** + * Closes the popup previously opened with openPopup (or the given one). + */ + closePopup(): Map; + + /** + * Adds the given control to the map. + */ + addControl(control: IControl): Map; + + /** + * Removes the given control from the map. + */ + removeControl(control: IControl): Map; + + // Conversion Methods + + /** + * Returns the map layer point that corresponds to the given geographical coordinates + * (useful for placing overlays on the map). + */ + latLngToLayerPoint(latlng: LatLng): Point; + + /** + * Returns the geographical coordinates of a given map layer point. + */ + layerPointToLatLng(point: Point): LatLng; + + /** + * Converts the point relative to the map container to a point relative to the + * map layer. + */ + containerPointToLayerPoint(point: Point): Point; + + /** + * Converts the point relative to the map layer to a point relative to the map + * container. + */ + layerPointToContainerPoint(point: Point): Point; + + /** + * Returns the map container point that corresponds to the given geographical + * coordinates. + */ + latLngToContainerPoint(latlng: LatLng): Point; + + /** + * Returns the geographical coordinates of a given map container point. + */ + containerPointToLatLng(point: Point): LatLng; + + /** + * Projects the given geographical coordinates to absolute pixel coordinates + * for the given zoom level (current zoom level by default). + */ + project(latlng: LatLng, zoom?: number): Point; + + /** + * Projects the given absolute pixel coordinates to geographical coordinates + * for the given zoom level (current zoom level by default). + */ + unproject(point: Point, zoom?: number): LatLng; + + /** + * Returns the pixel coordinates of a mouse click (relative to the top left corner + * of the map) given its event object. + */ + mouseEventToContainerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the pixel coordinates of a mouse click relative to the map layer given + * its event object. + */ + mouseEventToLayerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the geographical coordinates of the point the mouse clicked on given + * the click's event object. + */ + mouseEventToLatLng(event: LeafletMouseEvent): LatLng; + + // Other Methods + + /** + * Returns the container element of the map. + */ + getContainer(): HTMLElement; + + /** + * Returns an object with different map panes (to render overlays in). + */ + getPanes(): MapPanes; + + // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? + /** + * Runs the given callback when the map gets initialized with a place and zoom, + * or immediately if it happened already, optionally passing a function context. + */ + whenReady(fn: (map: Map) => void, context?: any): Map; + + // Properties + + /** + * Map dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + /** + * Touch zoom handler. + */ + touchZoom: IHandler; + + /** + * Double click zoom handler. + */ + doubleClickZoom: IHandler; + + /** + * Scroll wheel zoom handler. + */ + scrollWheelZoom: IHandler; + + /** + * Box (shift-drag with mouse) zoom handler. + */ + boxZoom: IHandler; + + /** + * Keyboard navigation handler. + */ + keyboard: IHandler; + + /** + * Mobile touch hacks (quick tap and touch hold) handler. + */ + tap: IHandler; + + /** + * Zoom control. + */ + zoomControl: Control.Zoom; + + /** + * Attribution control. + */ + attributionControl: Control.Attribution; + + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Map; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; + removeEventListener(eventMap?: any, context?: any): Map; + clearAllEventListeners(): Map + on(eventMap: any, context?: any): Map; + off(eventMap?: any, context?: any): Map; + } +} + +declare module L { + export interface MapOptions { + + // Map State Options + /** * Initial geographical center of the map. */ center?: LatLng; - + /** * Initial map zoom. */ zoom?: number; - + /** * Layers that will be added to the map initially. */ layers?: ILayer[]; - + /** * Minimum zoom level of the map. Overrides any minZoom set on map layers. */ minZoom?: number; - + /** * Maximum zoom level of the map. This overrides any maxZoom set on map layers. */ maxZoom?: number; - + /** * When this option is set, the map restricts the view to the given geographical * bounds, bouncing the user back when he tries to pan outside the view, and also @@ -37,166 +2343,199 @@ declare module L { * on the map size). To set the restriction dynamically, use setMaxBounds method */ maxBounds?: LatLngBounds; - + /** * Coordinate Reference System to use. Don't change this if you're not sure * what it means. + * + * Default value: L.CRS.EPSG3857. */ crs?: ICRS; + + // Interaction Options /** * Whether the map be draggable with mouse/touch or not. + * + * Default value: true. */ dragging?: boolean; - + /** * Whether the map can be zoomed by touch-dragging with two fingers. + * + * Default value: true. */ touchZoom?: boolean; - + /** * Whether the map can be zoomed by using the mouse wheel. + * + * Default value: true. */ scrollWheelZoom?: boolean; - + /** * Whether the map can be zoomed in by double clicking on it. + * + * Default value: true. */ doubleClickZoom?: boolean; /** * Whether the map can be zoomed to a rectangular area specified by dragging * the mouse while pressing shift. + * + * Default value: true. */ boxZoom?: boolean; + /** + * Enables mobile hacks for supporting instant taps (fixing 200ms click delay + * on iOS/Android) and touch holds (fired as contextmenu events). + * + * Default value: true. + */ + tap?: boolean; + + /** + * The max number of pixels a user can shift his finger during touch for it + * to be considered a valid tap. + * + * Default value: 15. + */ + tapTolerance?: number; + /** * Whether the map automatically handles browser window resize to update itself. + * + * Default value: true. */ trackResize?: boolean; - + /** * With this option enabled, the map tracks when you pan to another "copy" of * the world and seamlessly jumps to the original one so that all overlays like * markers and vector layers are still visible. + * + * Default value: false. */ worldCopyJump?: boolean; - + /** * Set it to false if you don't want popups to close when user clicks the map. + * + * Default value: true. */ closePopupOnClick?: boolean; + + // Keyboard Navigation Options /** * Makes the map focusable and allows users to navigate the map with keyboard * arrows and +/- keys. + * + * Default value: true. */ keyboard?: boolean; - + /** * Amount of pixels to pan when pressing an arrow key. + * + * Default value: 80. */ keyboardPanOffset?: number; - + /** * Number of zoom levels to change when pressing + or - key. + * + * Default value: 1. */ keyboardZoomOffset?: number; + + // Panning Inertia Options /** * If enabled, panning of the map will have an inertia effect where the map builds * momentum while dragging and continues moving in the same direction for some * time. Feels especially nice on touch devices. + * + * Default value: true. */ inertia?: boolean; - + /** * The rate with which the inertial movement slows down, in pixels/second2. + * + * Default value: 3000. */ inertiaDeceleration?: number; - + /** * Max speed of the inertial movement, in pixels/second. + * + * Default value: 1500. */ inertiaMaxSpeed?: number; - + /** * Amount of milliseconds that should pass between stopping the movement and - * releasing the mouse or touch to prevent inertial movement. 32 for touch devices - * and 14 for the rest by default. + * releasing the mouse or touch to prevent inertial movement. + * + * Default value: 32 for touch devices and 14 for the rest. */ inertiaThreshold?: number; + + // Control options /** * Whether the zoom control is added to the map by default. + * + * Default value: true. */ zoomControl?: boolean; - + /** * Whether the attribution control is added to the map by default. + * + * Default value: true. */ attributionControl?: boolean; + + // Animation options /** * Whether the tile fade animation is enabled. By default it's enabled in all * browsers that support CSS3 Transitions except Android. */ fadeAnimation?: boolean; - + /** * Whether the tile zoom animation is enabled. By default it's enabled in all * browsers that support CSS3 Transitions except Android. */ zoomAnimation?: boolean; + /** + * Won't animate zoom if the zoom difference exceeds this value. + * + * Default value: 4. + */ + zoomAnimationThreshold?: number; + /** * Whether markers animate their zoom with the zoom animation, if disabled * they will disappear for the length of the animation. By default it's enabled * in all browsers that support CSS3 Transitions except Android. */ markerZoomAnimation?: boolean; - - } - - export interface LocateOptions { - /** - * If true, starts continous watching of location changes (instead of detecting - * it once) using W3C watchPosition method. You can later stop watching using - * map.stopLocate() method. - */ - watch?: boolean; - - /** - * If true, automatically sets the map view to the user location with respect - * to detection accuracy, or to world view if geolocation failed. - */ - setView?: boolean; - - /** - * The maximum zoom for automatic view setting when using `setView` option. - */ - maxZoom?: number; - - /** - * Number of millisecond to wait for a response from geolocation before firing - * a locationerror event. - */ - timeout?: number; - - /** - * Maximum age of detected location. If less than this amount of milliseconds - * passed since last geolocation response, locate will return a cached location. - */ - maximumAge?: number; - - /** - * Enables high accuracy, see description in the W3C spec. - */ - enableHighAccuracy?: boolean; - } +} + +declare module L { export interface MapPanes { + /** * Pane that contains all other map panes. */ @@ -231,978 +2570,403 @@ declare module L { * Pane for popups. */ popupPane: HTMLElement; - } +} + +declare module L { - export class Map implements IEventPowered { - /** - * Instantiates a map object given a div element (or its id) and optionally an - * object literal with map options described below. - */ - constructor(id: HTMLElement, options?: MapOptions); + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + function marker(latlng: LatLng, options?: MarkerOptions): Marker; - /** - * Instantiates a map object given a div element (or its id) and optionally an - * object literal with map options described below. - */ - constructor(id: string, options?: MapOptions); + export class Marker extends Class implements ILayer, IEventPowered { - /** - * Sets the view of the map (geographical center and zoom). If forceReset is - * set to true, the map is reloaded even if it's eligible for pan or zoom animation - * (false by default). - */ - setView(center: LatLng, zoom: number, forceReset?: boolean): Map; - - /** - * Sets the zoom of the map. - */ - setZoom(zoom: number): Map; - - /** - * Increases the zoom of the map by delta (1 by default). - */ - zoomIn(delta?: number): Map; - - /** - * Decreases the zoom of the map by delta (1 by default). - */ - zoomOut(delta?: number): Map; - - /** - * Sets a map view that contains the given geographical bounds with the maximum - * zoom level possible. - */ - fitBounds(bounds: LatLngBounds): Map; - - /** - * Sets a map view that mostly contains the whole world with the maximum zoom - * level possible. - */ - fitWorld(): Map; - - /** - * Pans the map to a given center. Makes an animated pan if new center is not more - * than one screen away from the current one. - */ - panTo(latlng: LatLng): Map; - - /** - * Pans the map to the closest view that would lie inside the given bounds (if - * it's not already). - */ - panInsideBounds(bounds: LatLngBounds): Map; - - /** - * Pans the map by a given number of pixels (animated). - */ - panBy(point: Point): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically. If animate is true, map animates - * the update. - */ - invalidateSize(animate?: boolean): Map; - - /** - * Restricts the map view to the given bounds (see map maxBounds option). - */ - setMaxBounds(bounds: LatLngBounds): Map; - - /** - * Tries to locate the user using Geolocation API, firing locationfound event - * with location data on success or locationerror event on failure, and optionally - * sets the map view to the user location with respect to detection accuracy - * (or to the world view if geolocation failed). See Locate options for more - * details. - */ - locate(options?: LocateOptions): Map; - - /** - * Stops watching location previously initiated by map.locate({watch: true}). - */ - stopLocate(): Map; - - /** - * Returns the geographical center of the map view. - */ - getCenter(): LatLng; - - /** - * Returns the current zoom of the map view. - */ - getZoom(): number; - - /** - * Returns the minimum zoom level of the map. - */ - getMinZoom(): number; - - /** - * Returns the maximum zoom level of the map. - */ - getMaxZoom(): number; - - /** - * Returns the LatLngBounds of the current map view. - */ - getBounds(): LatLngBounds; - - /** - * Returns the maximum zoom level on which the given bounds fit to the map view - * in its entirety. If inside (optional) is set to true, the method instead returns - * the minimum zoom level on which the map view fits into the given bounds in its - * entirety. - */ - getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; - - /** - * Returns the current size of the map container. - */ - getSize(): Point; - - /** - * Returns the bounds of the current map view in projected pixel coordinates - * (sometimes useful in layer and overlay implementations). - */ - getPixelBounds(): Bounds; - - /** - * Returns the projected pixel coordinates of the top left point of the map layer - * (useful in custom layer and overlay implementations). - */ - getPixelOrigin(): Point; - - /** - * Adds the given layer to the map. If optional insertAtTheBottom is set to true, - * the layer is inserted under all others (useful when switching base tile layers). - */ - addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; - - /** - * Removes the given layer from the map. - */ - removeLayer(layer: ILayer): Map; - - /** - * Returns true if the given layer is currently added to the map. - */ - hasLayer(layer: ILayer): boolean; - - /** - * Opens the specified popup while closing the previously opened (to make sure - * only one is opened at one time for usability). - */ - openPopup(popup: Popup): Map; - - /** - * Closes the popup opened with openPopup. - */ - closePopup(): Map; - - /** - * Adds the given control to the map. - */ - addControl(control: IControl): Map; - - /** - * Removes the given control from the map. - */ - removeControl(control: IControl): Map; - - /** - * Returns the map layer point that corresponds to the given geographical coordinates - * (useful for placing overlays on the map). - */ - latLngToLayerPoint(latlng: LatLng): Point; - - /** - * Returns the geographical coordinates of a given map layer point. - */ - layerPointToLatLng(point: Point): LatLng; - - /** - * Converts the point relative to the map container to a point relative to the - * map layer. - */ - containerPointToLayerPoint(point: Point): Point; - - /** - * Converts the point relative to the map layer to a point relative to the map - * container. - */ - layerPointToContainerPoint(point: Point): Point; - - /** - * Returns the map container point that corresponds to the given geographical - * coordinates. - */ - latLngToContainerPoint(latlng: LatLng): Point; - - /** - * Returns the geographical coordinates of a given map container point. - */ - containerPointToLatLng(point: Point): LatLng; - - /** - * Projects the given geographical coordinates to absolute pixel coordinates - * for the given zoom level (current zoom level by default). - */ - project(latlng: LatLng, zoom?: number): Point; - - /** - * Projects the given absolute pixel coordinates to geographical coordinates - * for the given zoom level (current zoom level by default). - */ - unproject(point: Point, zoom?: number): LatLng; - - /** - * Returns the pixel coordinates of a mouse click (relative to the top left corner - * of the map) given its event object. - */ - mouseEventToContainerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the pixel coordinates of a mouse click relative to the map layer given - * its event object. - */ - mouseEventToLayerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the geographical coordinates of the point the mouse clicked on given - * the click's event object. - */ - mouseEventToLatLng(event: LeafletMouseEvent): LatLng; - - /** - * Returns the container element of the map. - */ - getContainer(): HTMLElement; - - /** - * Returns an object with different map panes (to render overlays in). - */ - getPanes(): MapPanes; - - /** - * Runs the given callback when the map gets initialized with a place and zoom, - * or immediately if it happened already, optionally passing a function context. - */ - whenReady(fn: Function, context?: any): Map; - - /** - * Map dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - /** - * Touch zoom handler. - */ - touchZoom: IHandler; - - /** - * Double click zoom handler. - */ - doubleClickZoom: IHandler; - - /** - * Scroll wheel zoom handler. - */ - scrollWheelZoom: IHandler; - - /** - * Box (shift-drag with mouse) zoom handler. - */ - boxZoom: IHandler; - - /** - * Keyboard navigation handler. - */ - keyboard: IHandler; - - /** - * Zoom control. - */ - zoomControl: Zoom; - - /** - * Attribution control. - */ - attributionControl: Attribution; - - //////////// - //// IEventPowered members - //////////// - - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - addEventListener(eventMap: any, context?: any): IEventPowered; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - removeEventListener(eventMap: any, context?: any): IEventPowered; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): IEventPowered; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - on(eventMap: any, context?: any): IEventPowered; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - off(eventMap: any, context?: any): IEventPowered; - fire(type: string, data?: any): IEventPowered; - } - - export interface MarkerOptions { - /** - * Icon class to use for rendering the marker. See Icon documentation for details - * on how to customize the marker icon. Set to new L.Icon.Default() by default. - */ - icon?: Icon; - - /** - * If false, the marker will not emit mouse events and will act as a part of the - * underlying map. - */ - clickable?: boolean; - - /** - * Whether the marker is draggable with mouse/touch or not. - */ - draggable?: boolean; - - /** - * Text for the browser tooltip that appear on marker hover (no tooltip by default). - */ - title?: string; - - /** - * By default, marker images zIndex is set automatically based on its latitude. - * You this option if you want to put the marker on top of all others (or below), - * specifying a high value like 1000 (or high negative value, respectively). - */ - zIndexOffset?: number; - - /** - * The opacity of the marker. - */ - opacity?: number; - - /** - * If true, the marker will get on top of others when you hover the mouse over it. - */ - riseOnHover?: boolean; - - /** - * The z-index offset used for the riseOnHover feature. - */ - riseOffset?: number; - - } - - export class Marker implements ILayer, IEventPowered { /** * Instantiates a Marker object given a geographical point and optionally * an options object. */ constructor(latlng: LatLng, options?: MarkerOptions); - + /** * Adds the marker to the map. */ addTo(map: Map): Marker; - + /** * Returns the current geographical position of the marker. */ getLatLng(): LatLng; - + /** * Changes the marker position to the given point. */ setLatLng(latlng: LatLng): Marker; - + /** * Changes the marker icon. */ setIcon(icon: Icon): Marker; - + /** * Changes the zIndex offset of the marker. */ setZIndexOffset(offset: number): Marker; - + /** * Changes the opacity of the marker. */ setOpacity(opacity: number): Marker; - + /** * Updates the marker position, useful if coordinates of its latLng object * were changed directly. */ update(): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(html: string, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Marker; /** * Binds a popup with a particular HTML content to a click on this marker. You * can also open the bound popup with the Marker openPopup method. */ - bindPopup(htmlContent: string, options?: PopupOptions): Marker; + bindPopup(popup: Popup, options?: PopupOptions): Marker; /** * Unbinds the popup previously bound to the marker with bindPopup. */ unbindPopup(): Marker; - + /** * Opens the popup previously bound by the bindPopup method. */ openPopup(): Marker; - + /** * Closes the bound popup of the marker if it's opened. */ closePopup(): Marker; - //////////// - //// ILayer members - //////////// + /** + * Toggles the popup previously bound by the bindPopup method. + */ + togglePopup(): Marker; + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(html: string, options?: PopupOptions): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). + */ + toGeoJSON(popup: Popup, options?: PopupOptions): any; + + //////////// + //////////// /** * Should contain code that creates DOM elements for the overlay, adds them * to map panes where they should belong and puts listeners on relevant map events. * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; - - //////////// - //// IEventPowered members - //////////// - - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - addEventListener(eventMap: any, context?: any): IEventPowered; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - removeEventListener(eventMap: any, context?: any): IEventPowered; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): IEventPowered; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - on(eventMap: any, context?: any): IEventPowered; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - off(eventMap: any, context?: any): IEventPowered; - fire(type: string, data?: any): IEventPowered; + fireEvent(type: string, data?: any): Marker; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + fire(type: string, data?: any): Marker; + addEventListener(eventMap: any, context?: any): Marker; + removeEventListener(eventMap?: any, context?: any): Marker; + clearAllEventListeners(): Marker + on(eventMap: any, context?: any): Marker; + off(eventMap?: any, context?: any): Marker; } +} + +declare module L { - export interface PopupOptions { - /** - * Max width of the popup. - */ - maxWidth?: number; - - /** - * Min width of the popup. - */ - minWidth?: number; - - /** - * If set, creates a scrollable container of the given height inside a popup - * if its content exceeds it. - */ - maxHeight?: number; - - /** - * Set it to false if you don't want the map to do panning animation to fit the opened - * popup. - */ - autoPan?: boolean; - - /** - * Controls the presense of a close button in the popup. - */ - closeButton?: boolean; - - /** - * The offset of the popup position. Useful to control the anchor of the popup - * when opening it on some overlays. - */ - offset?: Point; - - /** - * The margin between the popup and the edges of the map view after autopanning - * was performed. - */ - autoPanPadding?: Point; - - /** - * Whether to animate the popup on zoom. Disable it if you have problems with - * Flash content inside popups. - */ - zoomAnimation?: boolean; - - } - - export class Popup implements ILayer { - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - constructor(options?: PopupOptions, source?: any); - - /** - * Adds the popup to the map. - */ - addTo(map: Map): Popup; - - /** - * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). - */ - openOn(map: Map): Popup; - - /** - * Sets the geographical point where the popup will open. - */ - setLatLng(latlng: LatLng): Popup; - - /** - * Sets the HTML content of the popup. - */ - setContent(htmlContent: string): Popup; - - //////////// - //// ILayer members - //////////// - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - } - - export interface TileLayerOptions { - /** - * Minimum zoom number. - */ - minZoom?: number; - - /** - * Maximum zoom number. - */ - maxZoom?: number; - - /** - * Tile size (width and height in pixels, assuming tiles are square). - */ - tileSize?: number; - - /** - * Subdomains of the tile service. Can be passed in the form of one string (where - * each letter is a subdomain name) or an array of strings. - */ - subdomains?: any; - - /** - * URL to the tile image to show in place of the tile that failed to load. - */ - errorTileUrl?: string; - - /** - * e.g. "© CloudMade" — the string used by the attribution control, describes - * the layer data. - */ - attribution?: string; - - /** - * If true, inverses Y axis numbering for tiles (turn this on for TMS services). - */ - tms?: boolean; - - /** - * If set to true, the tile coordinates won't be wrapped by world width (-180 - * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this - * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor - * or photo maps). - */ - continuousWorld?: boolean; - - /** - * If set to true, the tiles just won't load outside the world width (-180 to 180 - * longitude) instead of repeating. - */ - noWrap?: boolean; - - /** - * The zoom number used in tile URLs will be offset with this value. - */ - zoomOffset?: number; - - /** - * If set to true, the zoom number used in tile URLs will be reversed (maxZoom - * - zoom instead of zoom) - */ - zoomReverse?: boolean; - - /** - * The opacity of the tile layer. - */ - opacity?: number; - - /** - * The explicit zIndex of the tile layer. Not set by default. - */ - zIndex?: number; - - /** - * If true, all the tiles that are not visible after panning are removed (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - unloadInvisibleTiles?: boolean; - - /** - * If false, new tiles are loaded during panning, otherwise only after it (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - updateWhenIdle?: boolean; - - /** - * If true and user is on a retina display, it will request four tiles of half the - * specified size and a bigger zoom level in place of one to utilize the high resolution. - */ - detectRetina?: boolean; - - /** - * If true, all the tiles that are not visible after panning are placed in a reuse - * queue from which they will be fetched when new tiles become visible (as opposed - * to dynamically creating new ones). This will in theory keep memory usage - * low and eliminate the need for reserving new memory whenever a new tile is - * needed. - */ - reuseTiles?: boolean; - - } - - export class TileLayer implements ILayer, IEventPowered { - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - constructor(urlTemplate: string, options?: TileLayerOptions); - - /** - * Adds the layer to the map. - */ - addTo(map: Map): TileLayer; - - /** - * Brings the tile layer to the top of all tile layers. - */ - bringToFront(): TileLayer; + export interface MarkerOptions { /** - * Brings the tile layer to the bottom of all tile layers. + * Icon class to use for rendering the marker. See Icon documentation for details + * on how to customize the marker icon. + * + * Default value: new L.Icon.Default(). */ - bringToBack(): TileLayer; - - /** - * Changes the opacity of the tile layer. - */ - setOpacity(opacity: number): TileLayer; - - /** - * Sets the zIndex of the tile layer. - */ - setZIndex(zIndex: number): TileLayer; - - /** - * Causes the layer to clear all the tiles and request them again. - */ - redraw(): TileLayer; - - /** - * Updates the layer's URL template and redraws it. - */ - setUrl(urlTemplate: string): TileLayer; - - static WMS: new () => WMS; - - static Canvas: new () => Canvas; - - //////////// - //// ILayer members - //////////// - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////// - //// IEventPowered members - //////////// - - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - addEventListener(eventMap: any, context?: any): IEventPowered; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - removeEventListener(eventMap: any, context?: any): IEventPowered; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): IEventPowered; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - on(eventMap: any, context?: any): IEventPowered; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - off(eventMap: any, context?: any): IEventPowered; - fire(type: string, data?: any): IEventPowered; - } - - export interface WMSOptions { - /** - * (required) Comma-separated list of WMS layers to show. - */ - layers?: string; - - /** - * Comma-separated list of WMS styles. - */ - styles?: string; - - /** - * WMS image format (use 'image/png' for layers with transparency). - */ - format?: string; - - /** - * If true, the WMS service will return images with transparency. - */ - transparent?: boolean; - - /** - * Version of the WMS service to use. - */ - version?: string; - - } - - export class WMS { - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - constructor(baseUrl: string, options: WMSOptions); - - /** - * Merges an object with the new parameters and re-requests tiles on the current - * screen (unless noRedraw was set to true). - */ - setParams(params: WMS, noRedraw?: boolean): WMS; - - } - - export class Canvas { - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - constructor(options?: TileLayerOptions); - - /** - * You need to define this method after creating the instance to draw tiles; - * canvas is the actual canvas tile on which you can draw, tilePoint represents - * the tile numbers, and zoom is the current zoom. - */ - drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; - - /** - * Calling redraw will cause the drawTile method to be called for all tiles. - * May be used for updating dynamic content drawn on the Canvas - */ - redraw(): Canvas; - - } - - export interface ImageOverlayOptions { - /** - * The opacity of the image overlay. - */ - opacity?: number; - - } - - export class ImageOverlay implements ILayer { - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - constructor(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions); - - /** - * Adds the overlay to the map. - */ - addTo(map: Map): ImageOverlay; - - /** - * Sets the opacity of the overlay. - */ - setOpacity(opacity: number): ImageOverlay; - - /** - * Brings the layer to the top of all overlays. - */ - bringToFront(): ImageOverlay; - - /** - * Brings the layer to the bottom of all overlays. - */ - bringToBack(): ImageOverlay; - - //////////// - //// ILayer members - //////////// - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - } - - export interface PathOptions { - /** - * Whether to draw stroke along the path. Set it to false to disable borders on - * polygons or circles. - */ - stroke?: boolean; - - /** - * Stroke color. - */ - color?: string; - - /** - * Stroke width in pixels. - */ - weight?: number; - - /** - * Stroke opacity. - */ - opacity?: number; - - /** - * Whether to fill the path with color. Set it to false to disable filling on polygons - * or circles. - */ - fill?: boolean; - - /** - * Fill color. - */ - fillColor?: string; - - /** - * Fill opacity. - */ - fillOpacity?: number; - - /** - * A string that defines the stroke dash pattern. Doesn't work on canvas-powered - * layers (e.g. Android 2). - */ - dashArray?: string; - + icon?: Icon; + /** - * If false, the vector will not emit mouse events and will act as a part of the + * If false, the marker will not emit mouse events and will act as a part of the * underlying map. + * + * Default value: true. */ clickable?: boolean; + + /** + * Whether the marker is draggable with mouse/touch or not. + * + * Default value: false. + */ + draggable?: boolean; + /** + * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Text for the browser tooltip that appear on marker hover (no tooltip by default). + * + * Default value: ''. + */ + title?: string; + + /** + * By default, marker images zIndex is set automatically based on its latitude. + * You this option if you want to put the marker on top of all others (or below), + * specifying a high value like 1000 (or high negative value, respectively). + * + * Default value: 0. + */ + zIndexOffset?: number; + + /** + * The opacity of the marker. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * If true, the marker will get on top of others when you hover the mouse over it. + * + * Default value: false. + */ + riseOnHover?: boolean; + + /** + * The z-index offset used for the riseOnHover feature. + * + * Default value: 250. + */ + riseOffset?: number; } +} + +declare module L { + + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + + export class MultiPolygon extends FeatureGroup { + + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + constructor(latlngs: LatLng[][], options?: PolylineOptions); + + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolygon; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). + */ + toGeoJSON(): any; + } +} + +declare module L { + + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + + export class MultiPolyline extends FeatureGroup { + + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + constructor(latlngs: LatLng[][], options?: PolylineOptions); + + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolyline; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). + */ + toGeoJSON(): any; + } +} + +declare module L { + + export interface PanOptions { + + /** + * If true, panning will always be animated if possible. If false, it will not + * animate panning, either resetting the map view if panning more than a screen + * away, or just setting a new offset for the map pane (except for `panBy` + * which always does the latter). + */ + animate?: boolean; + + /** + * Duration of animated panning. + * + * Default value: 0.25. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic + * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. + * + * Default value: 0.25. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + * + * Default value: false. + */ + noMoveStart?: boolean; + } +} + +declare module L { + + export class Path extends Class implements ILayer, IEventPowered { - export class Path implements ILayer, IEventPowered { /** * Adds the layer to the map. */ addTo(map: Map): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(html: string, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Path; /** * Binds a popup with a particular HTML content to a click on this path. */ - bindPopup(htmlContent: string, options?: PopupOptions): Path; + bindPopup(popup: Popup, options?: PopupOptions): Path; /** * Unbinds the popup previously bound to the path with bindPopup. */ unbindPopup(): Path; - + /** * Opens the popup previously bound by the bindPopup method in the given point, * or in one of the path's points if not specified. */ openPopup(latlng?: LatLng): Path; - + /** * Closes the path's bound popup if it is opened. */ closePopup(): Path; - + /** * Changes the appearance of a Path based on the options in the Path options object. */ setStyle(object: PathOptions): Path; - + /** * Returns the LatLngBounds of the path. */ getBounds(): LatLngBounds; - + /** * Brings the layer to the top of all path layers. */ bringToFront(): Path; - + /** * Brings the layer to the bottom of all path layers. */ bringToBack(): Path; - + /** * Redraws the layer. Sometimes useful after you changed the coordinates that * the path uses. */ redraw(): Path; - + /** * True if SVG is used for vector rendering (true for most modern browsers). */ static SVG: boolean; - + /** * True if VML is used for vector rendering (IE 6-8). */ static VML: boolean; - + /** * True if Canvas is used for vector rendering (Android 2). You can also force * this by setting global variable L_PREFER_CANVAS to true before the Leaflet @@ -1211,7 +2975,7 @@ declare module L { * a bug that causes removing such layers to be extremely slow. */ static CANVAS: boolean; - + /** * How much to extend the clip area around the map view (relative to its size, * e.g. 0.5 is half the screen in each direction). Smaller values mean that you @@ -1221,503 +2985,124 @@ declare module L { static CLIP_PADDING: number; //////////// - //// ILayer members //////////// - /** * Should contain code that creates DOM elements for the overlay, adds them * to map panes where they should belong and puts listeners on relevant map events. * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; - - //////////// - //// IEventPowered members - //////////// - - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - addEventListener(eventMap: any, context?: any): IEventPowered; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - removeEventListener(eventMap: any, context?: any): IEventPowered; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): IEventPowered; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - on(eventMap: any, context?: any): IEventPowered; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - off(eventMap: any, context?: any): IEventPowered; - fire(type: string, data?: any): IEventPowered; + fireEvent(type: string, data?: any): Path; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + fire(type: string, data?: any): Path; + addEventListener(eventMap: any, context?: any): Path; + removeEventListener(eventMap?: any, context?: any): Path; + clearAllEventListeners(): Path + on(eventMap: any, context?: any): Path; + off(eventMap?: any, context?: any): Path; } +} + +declare module L { - export interface PolylineOptions { - /** - * How much to simplify the polyline on each zoom level. More means better performance - * and smoother look, and less means more accurate representation. - */ - smoothFactor?: number; + export interface PathOptions { /** - * Disabled polyline clipping. + * Whether to draw stroke along the path. Set it to false to disable borders on + * polygons or circles. + * + * Default value: true. */ - noClip?: boolean; - - } - - export class Polyline extends Path { + stroke?: boolean; + /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. + * Stroke color. + * + * Default value: '#03f'. */ - constructor(latlngs: LatLng[], options?: PolylineOptions); - + color?: string; + /** - * Adds a given point to the polyline. + * Stroke width in pixels. + * + * Default value: 5. */ - addLatLng(latlng: LatLng): Polyline; - + weight?: number; + /** - * Replaces all the points in the polyline with the given array of geographical - * points. + * Stroke opacity. + * + * Default value: 0.5. */ - setLatLngs(latlngs: LatLng[]): Polyline; - + opacity?: number; + /** - * Returns an array of the points in the path. + * Whether to fill the path with color. Set it to false to disable filling on polygons + * or circles. */ - getLatLngs(): LatLng[]; - + fill?: boolean; + /** - * Allows adding, removing or replacing points in the polyline. Syntax is the - * same as in Array#splice. Returns the array of removed points (if any). + * Fill color. + * + * Default value: same as color. */ - spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; - + fillColor?: string; + /** - * Returns the LatLngBounds of the polyline. + * Fill opacity. + * + * Default value: 0.2. */ - getBounds(): LatLngBounds; - - } - - export class MultiPolyline extends FeatureGroup { + fillOpacity?: number; + /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. + * A string that defines the stroke dash pattern. Doesn't work on canvas-powered + * layers (e.g. Android 2). */ - constructor(latlngs: LatLng[][], options?: PolylineOptions); - - } - - export class Polygon extends Polyline { + dashArray?: string; + /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. + * If false, the vector will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. */ - constructor(latlngs: LatLng[], options?: PolylineOptions); - - } - - export class MultiPolygon extends FeatureGroup { - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - constructor(latlngs: LatLng[][], options?: PolylineOptions); - - } - - export class Rectangle extends Polygon { - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - constructor(bounds: LatLngBounds, options?: PathOptions); - - /** - * Redraws the rectangle with the passed bounds. - */ - setBounds(bounds: LatLngBounds): Rectangle; - - } - - export class Circle extends Path { - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - constructor(latlng: LatLng, radius: number, options?: PathOptions); - - /** - * Returns the current geographical position of the circle. - */ - getLatLng(): LatLng; - - /** - * Returns the current radius of a circle. Units are in meters. - */ - getRadius(): number; - - /** - * Sets the position of a circle to a new location. - */ - setLatLng(latlng: LatLng): Circle; - - /** - * Sets the radius of a circle. Units are in meters. - */ - setRadius(radius: number): Circle; - - } - - export class CircleMarker extends Circle { - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - constructor(latlng: LatLng, options?: PathOptions); - - /** - * Sets the position of a circle marker to a new location. - */ - setLatLng(latlng: LatLng): CircleMarker; - - /** - * Sets the radius of a circle marker. Units are in pixels. - */ - setRadius(radius: number): CircleMarker; - - } - - export class LayerGroup implements ILayer { - /** - * Create a layer group, optionally given an initial set of layers. - */ - constructor(layers?: ILayer[]); - - /** - * Adds the group of layers to the map. - */ - addTo(map: Map): LayerGroup; - - /** - * Adds a given layer to the group. - */ - addLayer(layer: ILayer): LayerGroup; - - /** - * Removes a given layer from the group. - */ - removeLayer(layer: ILayer): LayerGroup; - - /** - * Removes all the layers from the group. - */ - clearLayers(): LayerGroup; - - /** - * Iterates over the layers of the group, optionally specifying context of - * the iterator function. - */ - eachLayer(fn: (layer: ILayer) => void, context?: any): LayerGroup; - - //////////// - //// ILayer members - //////////// - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - } - - export class FeatureGroup extends LayerGroup implements ILayer, IEventPowered { - /** - * Create a layer group, optionally given an initial set of layers. - */ - constructor(layers?: ILayer[]); - - /** - * Binds a popup with a particular HTML content to a click on any layer from the - * group that has a bindPopup method. - */ - bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; - - /** - * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates - * of its children). - */ - getBounds(): LatLngBounds; - - /** - * Sets the given path options to each layer of the group that has a setStyle method. - */ - setStyle(style: PathOptions): FeatureGroup; - - /** - * Brings the layer group to the top of all other layers. - */ - bringToFront(): FeatureGroup; - - /** - * Brings the layer group to the bottom of all other layers. - */ - bringToBack(): FeatureGroup; - - //////////// - //// ILayer members - //////////// - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////// - //// IEventPowered members - //////////// - - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - addEventListener(eventMap: any, context?: any): IEventPowered; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - removeEventListener(eventMap: any, context?: any): IEventPowered; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): IEventPowered; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - on(eventMap: any, context?: any): IEventPowered; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - off(eventMap: any, context?: any): IEventPowered; - fire(type: string, data?: any): IEventPowered; - } - - export interface GeoJSONOptions { - /** - * Function that will be used for creating layers for GeoJSON points (if not - * specified, simple markers will be created). - */ - pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; - - /** - * Function that will be used to get style options for vector layers created - * for GeoJSON features. - */ - style?: (featureData: any) => any; - - /** - * Function that will be called on each created feature layer. Useful for attaching - * events and popups to features. - */ - onEachFeature?: (featureData: any, layer: ILayer) => void; - - /** - * Function that will be used to decide whether to show a feature or not. - */ - filter?: (featureData: any, layer: ILayer) => boolean; - - } - - export class GeoJSON extends FeatureGroup { - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - constructor(geojson?: any, options?: GeoJSONOptions); - - /** - * Adds a GeoJSON object to the layer. - */ - addData(data: any): boolean; - - /** - * NOTE: A fake signature to allow an overriding overload. - */ - setStyle(style: PathOptions): FeatureGroup; - - /** - * Changes styles of GeoJSON vector layers with the given style function. - */ - setStyle(style: (featureData: any) => any): GeoJSON; - - /** - * Resets the the given vector layer's style to the original GeoJSON style, - * useful for resetting style after hover events. - */ - resetStyle(layer: Path): GeoJSON; - - /** - * Creates a layer from a given GeoJSON feature. - */ - static geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; - - /** - * Creates a LatLng object from an array of 2 numbers (latitude, longitude) - * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted - * as (longitude, latitude). - */ - static coordsToLatlng(coords: number[], reverse?: boolean): LatLng; - - /** - * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates - * array. levelsDeep specifies the nesting level (0 is for an array of points, - * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to - * true, the numbers will be interpreted as (longitude, latitude). - */ - static coordsToLatlngs(coords: number[], levelsDeep?: number, reverse?: boolean): LatLng[]; - - } - - export class LatLng { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - constructor(latitude: number, longitude: number); - - /** - * Returns the distance (in meters) to the given LatLng calculated using the - * Haversine formula. See description on wikipedia - */ - distanceTo(otherLatlng: LatLng): number; - - /** - * Returns true if the given LatLng point is at the same position (within a small - * margin of error). - */ - equals(otherLatlng: LatLng): boolean; - - /** - * Returns a string representation of the point (for debugging purposes). - */ - toString(): string; - - /** - * Returns a new LatLng object with the longitude wrapped around left and right - * boundaries (-180 to 180 by default). - */ - wrap(left: number, right: number): LatLng; - - /** - * Latitude in degrees. - */ - lat: number; - - /** - * Longitude in degrees. - */ - lng: number; - - } - - export class LatLngBounds { - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - constructor(southWest: LatLng, northEast: LatLng); - - /** - * Extends the bounds to contain the given point or bounds. - */ - extend(latlng: LatLng): LatLngBounds; - - /** - * Extends the bounds to contain the given point or bounds. - */ - extend(latlng: LatLngBounds): LatLngBounds; - - /** - * Returns the south-west point of the bounds. - */ - getSouthWest(): LatLng; - - /** - * Returns the north-east point of the bounds. - */ - getNorthEast(): LatLng; - - /** - * Returns the north-west point of the bounds. - */ - getNorthWest(): LatLng; - - /** - * Returns the south-east point of the bounds. - */ - getSouthEast(): LatLng; - - /** - * Returns the center point of the bounds. - */ - getCenter(): LatLng; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: LatLngBounds): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(latlng: LatLng): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: LatLngBounds): boolean; - - /** - * Returns true if the rectangle is equivalent (within a small margin of error) - * to the given bounds. - */ - equals(otherBounds: LatLngBounds): boolean; - - /** - * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' - * format. Useful for sending requests to web services that return geo data. - */ - toBBoxString(): string; - - /** - * Returns bigger bounds created by extending the current bounds by a given - * percentage in each direction. - */ - pad(bufferRatio: number): LatLngBounds; - - /** - * Returns true if the bounds are properly initialized. - */ - isValid(): boolean; + clickable?: boolean; + /** + * Sets the pointer-events attribute on the path if SVG backend is used. + */ + pointerEvents?: boolean; + } +} + +declare module L { + + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + function point(x: number, y: number, round?: boolean): Point; export class Point { + /** * Creates a Point object with the given x and y coordinates. If optional round * is set to true, rounds the x and y values. @@ -1728,48 +3113,48 @@ declare module L { * Returns the result of addition of the current and the given points. */ add(otherPoint: Point): Point; - + /** * Returns the result of subtraction of the given point from the current. */ subtract(otherPoint: Point): Point; - + /** * Returns the result of multiplication of the current point by the given number. */ multiplyBy(number: number): Point; - + /** * Returns the result of division of the current point by the given number. If * optional round is set to true, returns a rounded result. */ divideBy(number: number, round?: boolean): Point; - + /** * Returns the distance between the current and the given points. */ distanceTo(otherPoint: Point): number; - + /** * Returns a copy of the current point. */ clone(): Point; - + /** * Returns a copy of the current point with rounded coordinates. */ round(): Point; - + /** * Returns true if the given point has the same coordinates. */ equals(otherPoint: Point): boolean; - + /** * Returns a string representation of the point for debugging purposes. */ toString(): string; - + /** * The x coordinate. */ @@ -1779,773 +3164,108 @@ declare module L { * The y coordinate. */ y: number; - } +} + +declare module L { - export class Bounds { - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - constructor(topLeft: Point, bottomRight: Point); + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + function polygon(latlngs: LatLng[], options?: PolylineOptions): Polygon; + + export class Polygon extends Polyline { /** - * Extends the bounds to contain the given point. + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. */ - extend(point: Point): void; - - /** - * Returns the center point of the bounds. - */ - getCenter(): Point; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: Bounds): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(point: Point): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: Bounds): boolean; - - /** - * Returns true if the bounds are properly initialized. - */ - isValid(): boolean; - - /** - * Returns the size of the given bounds. - */ - getSize(): Point; - - /** - * The top left corner of the rectangle. - */ - min: Point; - - /** - * The bottom right corner of the rectangle. - */ - max: Point; - + constructor(latlngs: LatLng[], options?: PolylineOptions); } +} + +declare module L { - export interface IconOptions { - /** - * (required) The URL to the icon image (absolute or relative to your script - * path). - */ - iconUrl?: string; + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + function polyline(latlngs: LatLng[], options?: PolylineOptions): Polyline; + + export class Polyline extends Path { /** - * The URL to a retina sized version of the icon image (absolute or relative to - * your script path). Used for Retina screen devices. + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. */ - iconRetinaUrl?: string; + constructor(latlngs: LatLng[], options?: PolylineOptions); + + /** + * Adds a given point to the polyline. + */ + addLatLng(latlng: LatLng): Polyline; + + /** + * Replaces all the points in the polyline with the given array of geographical + * points. + */ + setLatLngs(latlngs: LatLng[]): Polyline; + + /** + * Returns an array of the points in the path. + */ + getLatLngs(): LatLng[]; + + /** + * Allows adding, removing or replacing points in the polyline. Syntax is the + * same as in Array#splice. Returns the array of removed points (if any). + */ + spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; + + /** + * Returns the LatLngBounds of the polyline. + */ + getBounds(): LatLngBounds; /** - * Size of the icon image in pixels. + * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). */ - iconSize?: Point; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point; - - /** - * The URL to the icon shadow image. If not specified, no shadow image will be - * created. - */ - shadowUrl?: string; - - /** - * The URL to the retina sized version of the icon shadow image. If not specified, - * no shadow image will be created. Used for Retina screen devices. - */ - shadowRetinaUrl?: string; - - /** - * Size of the shadow image in pixels. - */ - shadowSize?: Point; - - /** - * The coordinates of the "tip" of the shadow (relative to its top left corner) - * (the same as iconAnchor if not specified). - */ - shadowAnchor?: Point; - - /** - * The coordinates of the point from which popups will "open", relative to the - * icon anchor. - */ - popupAnchor?: Point; - - /** - * A custom class name to assign to both icon and shadow images. Empty by default. - */ - className?: string; - + toGeoJSON(): any; } +} + +declare module L { + + export interface PolylineOptions { - export class Icon { /** - * Creates an icon instance with the given options. + * How much to simplify the polyline on each zoom level. More means better performance + * and smoother look, and less means more accurate representation. + * + * Default value: 1.0. */ - constructor(options: IconOptions); - } - - export module Icon { - export class Default extends Icon { - /** - * Creates an icon instance with default options. - */ - constructor(); - - static imagePath: string; - } - } - - export interface DivIconOptions { + smoothFactor?: number; + /** - * Size of the icon in pixels. Can be also set through CSS. + * Disabled polyline clipping. + * + * Default value: false. */ - iconSize?: Point; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point; - - /** - * A custom class name to assign to the icon. 'leaflet-div-icon' by default. - */ - className?: string; - - /** - * A custom HTML code to put inside the div element, empty by default. - */ - html?: string; - - } - - export class DivIcon extends Icon{ - /** - * Creates a div icon instance with the given options. - */ - constructor(options: DivIconOptions); - - } - - export interface ControlOptions { - /** - * The initial position of the control (one of the map corners). See control - * positions. - */ - position: string; - - } - - export class Control implements IControl { - /** - * Creates a control with the given options. - */ - constructor(options?: ControlOptions); - - /** - * Sets the position of the control. See control positions. - */ - setPosition(position: string): Control; - - /** - * Returns the current position of the control. - */ - getPosition(): string; - - /** - * Adds the control to the map. - */ - addTo(map: Map): Control; - - /** - * Removes the control from the map. - */ - removeFrom(map: Map): Control; - - static Zoom: new () => Zoom; - - static Attribution: new () => Attribution; - - static Layers: new () => Layers; - - static Scale: new () => Scale; - - //////////// - //// IControl members - //////////// - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - - } - - export interface ZoomOptions { - /** - * The position of the control (one of the map corners). See control positions. - */ - position?: string; - - } - - export class Zoom extends Control { - /** - * Creates a zoom control. - */ - constructor(options?: ZoomOptions); - - } - - export interface AttributionOptions { - /** - * The position of the control (one of the map corners). See control positions. - */ - position?: string; - - /** - * The HTML text shown before the attributions. Pass false to disable. - */ - prefix?: string; - - } - - export class Attribution extends Control { - /** - * Creates an attribution control. - */ - constructor(options?: AttributionOptions); - - /** - * Sets the text before the attributions. - */ - setPrefix(prefix: string): Attribution; - - /** - * Adds an attribution text (e.g. 'Vector data © CloudMade'). - */ - addAttribution(text: string): Attribution; - - /** - * Removes an attribution text. - */ - removeAttribution(text: string): Attribution; - - } - - export interface LayersOptions { - /** - * The position of the control (one of the map corners). See control positions. - */ - position?: string; - - /** - * If true, the control will be collapsed into an icon and expanded on mouse hover - * or touch. - */ - collapsed?: boolean; - - /** - * If true, the control will assign zIndexes in increasing order to all of its - * layers so that the order is preserved when switching them on/off. - */ - autoZIndex?: boolean; - - } - - export class Layers extends Control implements IEventPowered { - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - constructor(baseLayers?: any, overlays?: any, options?: LayersOptions); - - /** - * Adds a base layer (radio button entry) with the given name to the control. - */ - addBaseLayer(layer: ILayer, name: string): Layers; - - /** - * Adds an overlay (checkbox entry) with the given name to the control. - */ - addOverlay(layer: ILayer, name: string): Layers; - - /** - * Remove the given layer from the control. - */ - removeLayer(layer: ILayer): Layers; - - //////////// - //// IEventPowered members - //////////// - - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - addEventListener(eventMap: any, context?: any): IEventPowered; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - removeEventListener(eventMap: any, context?: any): IEventPowered; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): IEventPowered; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - on(eventMap: any, context?: any): IEventPowered; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - off(eventMap: any, context?: any): IEventPowered; - fire(type: string, data?: any): IEventPowered; - } - - export interface ScaleOptions { - /** - * The position of the control (one of the map corners). See control positions. - */ - position?: string; - - /** - * Maximum width of the control in pixels. The width is set dynamically to show - * round values (e.g. 100, 200, 500). - */ - maxWidth?: number; - - /** - * Whether to show the metric scale line (m/km). - */ - metric?: boolean; - - /** - * Whether to show the imperial scale line (mi/ft). - */ - imperial?: boolean; - - /** - * If true, the control is updated on moveend, otherwise it's always up-to-date - * (updated on move). - */ - updateWhenIdle?: boolean; - - } - - export class Scale extends Control { - /** - * Creates an scale control with the given options. - */ - constructor(options?: ScaleOptions); - - } - - export interface IEventPowered { - /** - * Adds a listener function (fn) to a particular event type of the object. You - * can optionally specify the context of the listener (object the this keyword - * will point to). You can also pass several space-separated types (e.g. 'click - * dblclick'). - */ - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - - /** - * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} - */ - addEventListener(eventMap: any, context?: any): IEventPowered; - - /** - * Removes a previously added listener function. If no function is specified, - * it will remove all the listeners of that particular event from the object. - */ - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - - /** - * Removes a set of type/listener pairs. - */ - removeEventListener(eventMap: any, context?: any): IEventPowered; - - /** - * Returns true if a particular event type has some listeners attached to it. - */ - hasEventListeners(type: string): boolean; - - /** - * Fires an event of the specified type. You can optionally provide an data object - * — the first argument of the listener function will contain its properties. - */ - fireEvent(type: string, data?: any): IEventPowered; - - /** - * Alias to addEventListener. - */ - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - - /** - * Alias to addEventListener. - */ - on(eventMap: any, context?: any): IEventPowered; - - /** - * Alias to removeEventListener. - */ - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - - /** - * Alias to removeEventListener. - */ - off(eventMap: any, context?: any): IEventPowered; - - /** - * Alias to fireEvent. - */ - fire(type: string, data?: any): IEventPowered; - - } - - export interface LeafletEvent { - /** - * The event type (e.g. 'click'). - */ - type: string; - - /** - * The object that fired the event. - */ - target: any; - - } - - export interface LeafletMouseEvent { - /** - * The geographical point where the mouse event occured. - */ - latlng: LatLng; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map layer. - */ - layerPoint: Point; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map сontainer. - */ - containerPoint: Point; - - /** - * The original DOM mouse event fired by the browser. - */ - originalEvent: MouseEvent; - - } - - export interface LeafletLocationEvent { - /** - * Detected geographical location of the user. - */ - latlng: LatLng; - - /** - * Geographical bounds of the area user is located in (with respect to the accuracy - * of location). - */ - bounds: LatLngBounds; - - /** - * Accuracy of location in meters. - */ - accuracy: number; - - } - - export interface LeafletErrorEvent { - /** - * Error message. - */ - message: string; - - /** - * Error code (if applicable). - */ - code: number; - - } - - export interface LeafletLayerEvent { - /** - * The layer that was added or removed. - */ - layer: ILayer; - - } - - export interface LeafletTileEvent { - /** - * The tile element (image). - */ - tile: HTMLElement; - - /** - * The source URL of the tile. - */ - url: string; - - } - - export interface LeafletGeoJSONEvent { - /** - * The layer for the GeoJSON feature that is being added to the map. - */ - layer: ILayer; - - /** - * GeoJSON properties of the feature. - */ - properties: any; - - /** - * GeoJSON geometry type of the feature. - */ - geometryType: string; - - /** - * GeoJSON ID of the feature (if present). - */ - id: string; - - } - - export interface LeafletPopupEvent { - /** - * The popup that was opened or closed. - */ - popup: Popup; - - } - - export class Class { - } - - export class Browser { - /** - * true for all Internet Explorer versions. - */ - static ie: boolean; - - /** - * true for Internet Explorer 6. - */ - static ie6: boolean; - - /** - * true for Internet Explorer 6. - */ - static ie7: boolean; - - /** - * true for webkit-based browsers like Chrome and Safari (including mobile - * versions). - */ - static webkit: boolean; - - /** - * true for webkit-based browsers that support CSS 3D transformations. - */ - static webkit3d: boolean; - - /** - * true for Android mobile browser. - */ - static android: boolean; - - /** - * true for old Android stock browsers (2 and 3). - */ - static android23: boolean; - - /** - * true for modern mobile browsers (including iOS Safari and different Android - * browsers). - */ - static mobile: boolean; - - /** - * true for mobile webkit-based browsers. - */ - static mobileWebkit: boolean; - - /** - * true for mobile Opera. - */ - static mobileOpera: boolean; - - /** - * true for all browsers on touch devices. - */ - static touch: boolean; - - /** - * true for browsers with Microsoft touch model (e.g. IE10). - */ - static msTouch: boolean; - - /** - * true for devices with Retina screens. - */ - static retina: boolean; - - } - - export class Util { - /** - * Merges the properties of the src object (or multiple objects) into dest object - * and returns the latter. Has an L.extend shortcut. - */ - static extend(dest: any, ...sources: any[]): any; - - /** - * Returns a function which executes function fn with the given scope obj (so - * that this keyword refers to obj inside the function code). Has an L.bind shortcut. - */ - static bind(fn: Function, obj: any): Function; - - /** - * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. - */ - static stamp(obj: any): string; - - /** - * Returns a wrapper around the function fn that makes sure it's called not more - * often than a certain time interval time, but as fast as possible otherwise - * (for example, it is used for checking and requesting new tiles while dragging - * the map), optionally passing the scope (context) in which the function will - * be called. - */ - static limitExecByInterval(fn: Function, time: number, context?: any): Function; - - /** - * Returns a function which always returns false. - */ - static falseFn(): () => boolean; - - /** - * Returns the number num rounded to digits decimals. - */ - static formatNum(num: number, digits: number): number; - - /** - * Trims and splits the string on whitespace and returns the array of parts. - */ - static splitWords(str: string): string[]; - - /** - * Merges the given properties to the options of the obj object, returning the - * resulting options. See Class options. Has an L.setOptions shortcut. - */ - static setOptions(obj: any, options: any): any; - - /** - * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} - * translates to '?a=foo&b=bar'. - */ - static getParamString(obj: any): string; - - /** - * Simple templating facility, creates a string by applying the values of the - * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form - * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. - */ - static template(str: string, data: any): string; - - /** - * Returns true if the given object is an array. - */ - static isArray(obj: any): boolean; - - /** - * Data URI string containing a base64-encoded empty GIF image. Used as a hack - * to free memory from unused images on WebKit-powered mobile devices (by setting - * image src to this string). - */ - static emptyImageUrl: string; - - } - - export class Transformation { - /** - * Creates a transformation object with the given coefficients. - */ - constructor(a: number, b: number, c: number, d: number); - - /** - * Returns a transformed point, optionally multiplied by the given scale. - * Only accepts real L.Point instances, not arrays. - */ - transform(point: Point, scale?: number): Point; - - /** - * Returns the reverse transformation of the given point, optionally divided - * by the given scale. Only accepts real L.Point instances, not arrays. - */ - untransform(point: Point, scale?: number): Point; - - } - - export class LineUtil { - /** - * Dramatically reduces the number of points in a polyline while retaining - * its shape and returns a new array of simplified points. Used for a huge performance - * boost when processing/displaying Leaflet polylines for each zoom level - * and also reducing visual noise. tolerance affects the amount of simplification - * (lesser value means higher quality but slower and with more points). Also - * released as a separated micro-library Simplify.js. - */ - static simplify(points: Point[], tolerance: number): Point[]; - - /** - * Returns the distance between point p and segment p1 to p2. - */ - static pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; - - /** - * Returns the closest point from a point p on a segment p1 to p2. - */ - static closestPointOnSegment(p: Point, p1: Point, p2: Point): number; - - /** - * Clips the segment a to b by rectangular bounds (modifying the segment points - * directly!). Used by Leaflet to only show polyline points that are on the screen - * or near, increasing performance. - */ - static clipSegment(a: Point, b: Point, bounds: Bounds): void; - + noClip?: boolean; } +} + +declare module L { export class PolyUtil { + /** * Clips the polygon geometry defined by the given points by rectangular bounds. * Used by Leaflet to only show polygon points that are on the screen or near, @@ -2553,291 +3273,194 @@ declare module L { * for clipping than polyline, so there's a seperate method for it. */ static clipPolygon(points: Point[], bounds: Bounds): Point[]; - } +} + +declare module L { - export class DomEvent { - /** - * Adds a listener fn to the element's DOM event of the specified type. this keyword - * inside the listener will point to context, or to the element if not specified. - */ - static addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + function popup(options?: PopupOptions, source?: any): Popup; + + export class Popup extends Class implements ILayer { /** - * Removes an event listener from the element. + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. */ - static removeListener(el: HTMLElement, type: string, fn: (e: Event) => void): DomEvent; + constructor(options?: PopupOptions, source?: any); + + /** + * Adds the popup to the map. + */ + addTo(map: Map): Popup; + + /** + * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). + */ + openOn(map: Map): Popup; + + /** + * Sets the geographical point where the popup will open. + */ + setLatLng(latlng: LatLng): Popup; + + /** + * Sets the HTML content of the popup. + */ + setContent(html: string): Popup; /** - * Stop the given event from propagation to parent elements. Used inside the - * listener functions: - * L.DomEvent.addListener(div, 'click', function - * (e) { - * L.DomEvent.stopPropagation(e); - * }); + * Sets the HTML content of the popup. */ - static stopPropagation(e: Event): DomEvent; - - /** - * Prevents the default action of the event from happening (such as following - * a link in the href of the a element, or doing a POST request with page reload - * when form is submitted). Use it inside listener functions. - */ - static preventDefault(e: Event): DomEvent; - - /** - * Does stopPropagation and preventDefault at the same time. - */ - static stop(e: Event): DomEvent; - - /** - * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' - * and 'touchstart' events. - */ - static disableClickPropagation(el: HTMLElement): DomEvent; - - /** - * Gets normalized mouse position from a DOM event relative to the container - * or to the whole page if not specified. - */ - static getMousePosition(e: Event, container?: HTMLElement): Point; - - /** - * Gets normalized wheel delta from a mousewheel DOM event. - */ - static getWheelDelta(e: Event): number; - - } - - export class DomUtil { - /** - * Returns an element with the given id if a string was passed, or just returns - * the element if it was passed directly. - */ - static get(id: string): HTMLElement; - - /** - * Returns the value for a certain style attribute on an element, including - * computed values or values set through CSS. - */ - static getStyle(el: HTMLElement, style: string): string; - - /** - * Returns the offset to the viewport for the requested element. - */ - static getViewportOffset(el: HTMLElement): Point; - - /** - * Creates an element with tagName, sets the className, and optionally appends - * it to container element. - */ - static create(tagName: string, className: string, container?: HTMLElement): HTMLElement; - - /** - * Makes sure text cannot be selected, for example during dragging. - */ - static disableTextSelection(): void; - - /** - * Makes text selection possible again. - */ - static enableTextSelection(): void; - - /** - * Returns true if the element class attribute contains name. - */ - static hasClass(el: HTMLElement, name: string): boolean; - - /** - * Adds name to the element's class attribute. - */ - static addClass(el: HTMLElement, name: string): void; - - /** - * Removes name from the element's class attribute. - */ - static removeClass(el: HTMLElement, name: string): void; - - /** - * Set the opacity of an element (including old IE support). Value must be from - * 0 to 1. - */ - static setOpacity(el: HTMLElement, value: number): void; - - /** - * Goes through the array of style names and returns the first name that is a valid - * style name for an element. If no such name is found, it returns false. Useful - * for vendor-prefixed styles like transform. - */ - static testProp(props: String[]): string; - - /** - * Returns a CSS transform string to move an element by the offset provided in - * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms - * and 2D on other browsers. - */ - static getTranslateString(point: Point): string; - - /** - * Returns a CSS transform string to scale an element (with the given scale origin). - */ - static getScaleString(scale: number, origin: Point): string; - - /** - * Sets the position of an element to coordinates specified by point, using - * CSS translate or top/left positioning depending on the browser (used by - * Leaflet internally to position its layers). Forces top/left positioning - * if disable3D is true. - */ - static setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; - - /** - * Returns the coordinates of an element previously positioned with setPosition. - */ - static getPosition(el: HTMLElement): Point; - - /** - * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). - */ - static TRANSITION: string; - - /** - * Vendor-prefixed transform style name. - */ - static TRANSFORM: string; - - } - - export class PosAnimation implements IEventPowered { - /** - * Creates a PosAnimation object. - */ - constructor(); - - /** - * Run an animation of a given element to a new position, optionally setting - * duration in seconds (0.25 by default) and easing linearity factor (3rd argument - * of the cubic bezier curve, 0.5 by default) - */ - run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; + setContent(el: HTMLElement): Popup; //////////// - //// IEventPowered members //////////// - - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - addEventListener(eventMap: any, context?: any): IEventPowered; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - removeEventListener(eventMap: any, context?: any): IEventPowered; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): IEventPowered; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - on(eventMap: any, context?: any): IEventPowered; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - off(eventMap: any, context?: any): IEventPowered; - fire(type: string, data?: any): IEventPowered; - } - - export class Draggable implements IEventPowered { - /** - * Creates a Draggable object for moving the given element when you start dragging - * the dragHandle element (equals the element itself by default). - */ - constructor(element: HTMLElement, dragHandle?: HTMLElement); - - /** - * Enables the dragging ability. - */ - enable(): void; - - /** - * Disables the dragging ability. - */ - disable(): void; - - //////////// - //// IEventPowered members - //////////// - - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - addEventListener(eventMap: any, context?: any): IEventPowered; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - removeEventListener(eventMap: any, context?: any): IEventPowered; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): IEventPowered; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): IEventPowered; - on(eventMap: any, context?: any): IEventPowered; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): IEventPowered; - off(eventMap: any, context?: any): IEventPowered; - fire(type: string, data?: any): IEventPowered; - } - - export interface IHandler { - /** - * Enables the handler. - */ - enable(): void; - - /** - * Disables the handler. - */ - disable(): void; - - /** - * Returns true if the handler is enabled. - */ - enabled(): boolean; - - } - - export interface ILayer { /** * Should contain code that creates DOM elements for the overlay, adds them * to map panes where they should belong and puts listeners on relevant map events. * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; - } +} + +declare module L { - export interface IControl { - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; + export interface PopupOptions { /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. + * Max width of the popup. + * + * Default value: 300. */ - onRemove(map: Map): void; + maxWidth?: number; + + /** + * Min width of the popup. + * + * Default value: 50. + */ + minWidth?: number; + + /** + * If set, creates a scrollable container of the given height inside a popup + * if its content exceeds it. + */ + maxHeight?: number; + + /** + * Set it to false if you don't want the map to do panning animation to fit the opened + * popup. + * + * Default value: true. + */ + autoPan?: boolean; + + /** + * Controls the presense of a close button in the popup. + * + * Default value: true. + */ + closeButton?: boolean; + + /** + * The offset of the popup position. Useful to control the anchor of the popup + * when opening it on some overlays. + * + * Default value: new Point(0, 6). + */ + offset?: Point; + + /** + * The margin between the popup and the edges of the map view after autopanning + * was performed. + * + * Default value: new Point(5, 5). + */ + autoPanPadding?: Point; + + /** + * Whether to animate the popup on zoom. Disable it if you have problems with + * Flash content inside popups. + * + * Default value: true. + */ + zoomAnimation?: boolean; + /** + * Set it to false if you want to override the default behavior of the popup + * closing when user clicks the map (set globally by the Map closePopupOnClick + * option). + */ + closeOnClick?: boolean; } +} + +declare module L { + + export class PosAnimation extends Class implements IEventPowered { + + /** + * Creates a PosAnimation object. + */ + constructor(); + + /** + * Run an animation of a given element to a new position, optionally setting + * duration in seconds (0.25 by default) and easing linearity factor (3rd argument + * of the cubic bezier curve, 0.5 by default) + */ + run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): PosAnimation; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + fire(type: string, data?: any): PosAnimation; + addEventListener(eventMap: any, context?: any): PosAnimation; + removeEventListener(eventMap?: any, context?: any): PosAnimation; + clearAllEventListeners(): PosAnimation + on(eventMap: any, context?: any): PosAnimation; + off(eventMap?: any, context?: any): PosAnimation; + } +} + +declare module L { export class Projection { + /** * Spherical Mercator projection — the most common projection for online maps, * used by almost all free and commercial tile providers. Assumes that Earth * is a sphere. Used by the EPSG:3857 CRS. */ static SphericalMercator: IProjection; - + /** * Elliptical Mercator projection — more complex than Spherical Mercator. * Takes into account that Earth is a geoid, not a perfect sphere. Used by the * EPSG:3395 CRS. */ static Mercator: IProjection; - + /** * Equirectangular, or Plate Carree projection — the most simple projection, * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. @@ -2845,108 +3468,539 @@ declare module L { * CRS. */ static LonLat: IProjection; - } - - export interface IProjection { - /** - * Projects geographical coordinates into a 2D point. - */ - project(latlng: LatLng): Point; - - /** - * The inverse of project. Projects a 2D point into geographical location. - */ - unproject(point: Point): LatLng; - - } - - export class CRS { - /** - * The most common CRS for online maps, used by almost all free and commercial - * tile providers. Uses Spherical Mercator projection. Set in by default in - * Map's crs option. - */ - static EPSG3857: ICRS; - - /** - * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. - */ - static EPSG4326: ICRS; - - /** - * Rarely used by some commercial tile providers. Uses Elliptical Mercator - * projection. - */ - static EPSG3395: ICRS; - - /** - * A simple CRS that maps longitude and latitude into x and y directly. May be - * used for maps of flat surfaces (e.g. game maps). Note that the y axis should - * still be inverted (going from bottom to top). - */ - static Simple: ICRS; - - } - - export interface ICRS { - /** - * Projection that this CRS uses. - */ - projection: IProjection; - - /** - * Transformation that this CRS uses to turn projected coordinates into screen - * coordinates for a particular tile service. - */ - transformation: Transformation; - - /** - * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). - */ - code: string; - - /** - * Projects geographical coordinates on a given zoom into pixel coordinates. - */ - latLngToPoint(latlng: LatLng, zoom: number): Point; - - /** - * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom - * into geographical coordinates. - */ - pointToLatLng(point: Point, zoom: number): LatLng; - - /** - * Projects geographical coordinates into coordinates in units accepted - * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). - */ - project(latlng: LatLng): Point; - - /** - * Returns the scale used when transforming projected coordinates into pixel - * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for - * Mercator-based CRS. - */ - scale(zoom: number): number; - - } - - /** - * This method restores the L global variale to the original value it had - * before Leaflet inclusion, and returns the real Leaflet namespace. - */ - export var noConflict: () => typeof L; - - /** - * A constant that represents the Leaflet version in use. - */ - export var version: string; } + +declare module L { + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; + + export class Rectangle extends Polygon { + + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + constructor(bounds: LatLngBounds, options?: PathOptions); + + /** + * Redraws the rectangle with the passed bounds. + */ + setBounds(bounds: LatLngBounds): Rectangle; + } +} + + +declare module L { + + export interface ScaleOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomleft'. + */ + position?: string; + + /** + * Maximum width of the control in pixels. The width is set dynamically to show + * round values (e.g. 100, 200, 500). + * Default value: 100. + */ + maxWidth?: number; + + /** + * Whether to show the metric scale line (m/km). + * Default value: true. + */ + metric?: boolean; + + /** + * Whether to show the imperial scale line (mi/ft). + * Default value: true. + */ + imperial?: boolean; + + /** + * If true, the control is updated on moveend, otherwise it's always up-to-date + * (updated on move). + * Default value: false. + */ + updateWhenIdle?: boolean; + } +} + +declare module L { + + export class TileLayer implements ILayer, IEventPowered { + + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + constructor(urlTemplate: string, options?: TileLayerOptions); + + /** + * Adds the layer to the map. + */ + addTo(map: Map): TileLayer; + + /** + * Brings the tile layer to the top of all tile layers. + */ + bringToFront(): TileLayer; + + /** + * Brings the tile layer to the bottom of all tile layers. + */ + bringToBack(): TileLayer; + + /** + * Changes the opacity of the tile layer. + */ + setOpacity(opacity: number): TileLayer; + + /** + * Sets the zIndex of the tile layer. + */ + setZIndex(zIndex: number): TileLayer; + + /** + * Causes the layer to clear all the tiles and request them again. + */ + redraw(): TileLayer; + + /** + * Updates the layer's URL template and redraws it. + */ + setUrl(urlTemplate: string): TileLayer; + + /** + * Returns the HTML element that contains the tiles for this layer. + */ + getContainer(): HTMLElement; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): TileLayer; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + fire(type: string, data?: any): TileLayer; + addEventListener(eventMap: any, context?: any): TileLayer; + removeEventListener(eventMap?: any, context?: any): TileLayer; + clearAllEventListeners(): TileLayer + on(eventMap: any, context?: any): TileLayer; + off(eventMap?: any, context?: any): TileLayer; + } + + module TileLayer { + + export class WMS { + + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + constructor(baseUrl: string, options: WMSOptions); + + /** + * Merges an object with the new parameters and re-requests tiles on the current + * screen (unless noRedraw was set to true). + */ + setParams(params: WMS, noRedraw?: boolean): WMS; + } + + export class Canvas { + + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + constructor(options?: TileLayerOptions); + + /** + * You need to define this method after creating the instance to draw tiles; + * canvas is the actual canvas tile on which you can draw, tilePoint represents + * the tile numbers, and zoom is the current zoom. + */ + drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; + + /** + * Calling redraw will cause the drawTile method to be called for all tiles. + * May be used for updating dynamic content drawn on the Canvas + */ + redraw(): Canvas; + } + } + + export class tileLayer { + + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + function (urlTemplate: string, options?: TileLayerOptions): TileLayer; + + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + static wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; + + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + static canvas(options?: TileLayerOptions): L.TileLayer.Canvas; + } +} + +declare module L { + + export interface TileLayerOptions { + + /** + * Minimum zoom number. + * + * Default value: 0. + */ + minZoom?: number; + + /** + * Maximum zoom number. + * + * Default value: 18. + */ + maxZoom?: number; + + /** + * Tile size (width and height in pixels, assuming tiles are square). + * + * Default value: 256. + */ + tileSize?: number; + + /** + * Subdomains of the tile service. Can be passed in the form of one string (where + * each letter is a subdomain name) or an array of strings. + * + * Default value: 'abc'. + */ + subdomains?: string[]; + + /** + * URL to the tile image to show in place of the tile that failed to load. + * + * Default value: ''. + */ + errorTileUrl?: string; + + /** + * e.g. "© CloudMade" — the string used by the attribution control, describes + * the layer data. + * + * Default value: ''. + */ + attribution?: string; + + /** + * If true, inverses Y axis numbering for tiles (turn this on for TMS services). + * + * Default value: false. + */ + tms?: boolean; + + /** + * If set to true, the tile coordinates won't be wrapped by world width (-180 + * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this + * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor + * or photo maps). + * + * Default value: false. + */ + continuousWorld?: boolean; + + /** + * If set to true, the tiles just won't load outside the world width (-180 to 180 + * longitude) instead of repeating. + * + * Default value: false. + */ + noWrap?: boolean; + + /** + * The zoom number used in tile URLs will be offset with this value. + * + * Default value: 0. + */ + zoomOffset?: number; + + /** + * If set to true, the zoom number used in tile URLs will be reversed (maxZoom + * - zoom instead of zoom) + * + * Default value: false. + */ + zoomReverse?: boolean; + + /** + * The opacity of the tile layer. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * The explicit zIndex of the tile layer. Not set by default. + */ + zIndex?: number; + + /** + * If true, all the tiles that are not visible after panning are removed (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + unloadInvisibleTiles?: boolean; + + /** + * If false, new tiles are loaded during panning, otherwise only after it (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + updateWhenIdle?: boolean; + + /** + * If true and user is on a retina display, it will request four tiles of half the + * specified size and a bigger zoom level in place of one to utilize the high resolution. + * + * Default value: false. + */ + detectRetina?: boolean; + + /** + * If true, all the tiles that are not visible after panning are placed in a reuse + * queue from which they will be fetched when new tiles become visible (as opposed + * to dynamically creating new ones). This will in theory keep memory usage + * low and eliminate the need for reserving new memory whenever a new tile is + * needed. + * + * Default value: false. + */ + reuseTiles?: boolean; + } +} + +declare module L { + + export class Transformation { + + /** + * Creates a transformation object with the given coefficients. + */ + constructor(a: number, b: number, c: number, d: number); + + /** + * Returns a transformed point, optionally multiplied by the given scale. + * Only accepts real L.Point instances, not arrays. + */ + transform(point: Point, scale?: number): Point; + + /** + * Returns the reverse transformation of the given point, optionally divided + * by the given scale. Only accepts real L.Point instances, not arrays. + */ + untransform(point: Point, scale?: number): Point; + } +} + +declare module L { + + export class Util { + + /** + * Merges the properties of the src object (or multiple objects) into dest object + * and returns the latter. Has an L.extend shortcut. + */ + static extend(dest: any, ...sources: any[]): any; + + /** + * Returns a function which executes function fn with the given scope obj (so + * that this keyword refers to obj inside the function code). Has an L.bind shortcut. + */ + static bind(fn: T, obj: any): T; + + /** + * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. + */ + static stamp(obj: any): string; + + /** + * Returns a wrapper around the function fn that makes sure it's called not more + * often than a certain time interval time, but as fast as possible otherwise + * (for example, it is used for checking and requesting new tiles while dragging + * the map), optionally passing the scope (context) in which the function will + * be called. + */ + static limitExecByInterval(fn: T, time: number, context?: any): T; + + /** + * Returns a function which always returns false. + */ + static falseFn(): () => boolean; + + /** + * Returns the number num rounded to digits decimals. + */ + static formatNum(num: number, digits: number): number; + + /** + * Trims and splits the string on whitespace and returns the array of parts. + */ + static splitWords(str: string): string[]; + + /** + * Merges the given properties to the options of the obj object, returning the + * resulting options. See Class options. Has an L.setOptions shortcut. + */ + static setOptions(obj: any, options: any): any; + + /** + * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} + * translates to '?a=foo&b=bar'. + */ + static getParamString(obj: any): string; + + /** + * Simple templating facility, creates a string by applying the values of the + * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form + * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. + */ + static template(str: string, data: any): string; + + /** + * Returns true if the given object is an array. + */ + static isArray(obj: any): boolean; + + /** + * Trims the whitespace from both ends of the string and returns the result. + */ + static trim(str: string): boolean; + + /** + * Data URI string containing a base64-encoded empty GIF image. Used as a hack + * to free memory from unused images on WebKit-powered mobile devices (by setting + * image src to this string). + */ + static emptyImageUrl: string; + } +} + + +declare module L { + + export interface WMSOptions { + + /** + * (required) Comma-separated list of WMS layers to show. + * + * Default value: ''. + */ + layers?: string; + + /** + * Comma-separated list of WMS styles. + * + * Default value: 'image/jpeg'. + */ + styles?: string; + + /** + * WMS image format (use 'image/png' for layers with transparency). + * + * Default value: false. + */ + format?: string; + + /** + * If true, the WMS service will return images with transparency. + * + * Default value: '1.1.1'. + */ + transparent?: boolean; + + /** + * Version of the WMS service to use. + */ + version?: string; + + } +} + + +declare module L { + + export interface ZoomOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * + * Default value: 'topright'. + */ + position?: string; + } +} + +declare module L { + + export interface ZoomPanOptions { + + /** + * If true, the map view will be completely reset (without any animations). + * + * Default value: false. + */ + reset?: boolean; + + /** + * Sets the options for the panning (without the zoom change) if it occurs. + */ + pan?: PanOptions; + + /** + * Sets the options for the zoom change if it occurs. + */ + zoom?: ZoomOptions; + + /** + * An equivalent of passing animate to both zoom and pan options (see below). + */ + animate?: boolean; + } +} + /** - * Forces Leaflet to use the Canvas back-end (if available) for vector layers - * instead of SVG. This can increase performance considerably in some cases + * Forces Leaflet to use the Canvas back-end (if available) for vector layers + * instead of SVG. This can increase performance considerably in some cases * (e.g. many thousands of circle markers on the map). */ declare var L_PREFER_CANVAS: boolean; @@ -2957,7 +4011,8 @@ declare var L_PREFER_CANVAS: boolean; declare var L_NO_TOUCH: boolean; /** - * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning + * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning * (which may cause glitches in some rare environments) even if they're supported. */ declare var L_DISABLE_3D: boolean; + diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts new file mode 100644 index 000000000..400d8664a --- /dev/null +++ b/lodash/lodash-tests.ts @@ -0,0 +1,929 @@ +/// + +declare var $: any, jQuery: any; + +interface IFoodOrganic { + name: string; + organic: boolean; +} + +interface IFoodType { + name: string; + type: string; +} + +interface IFoodCombined { + name: string; + organic: boolean; + type: string; +} + +interface IStoogesQuote { + name: string; + quotes: string[]; +} + +interface IStoogesAge { + name: string; + age: number; +} + +interface IStoogesCombined { + name: string; + age: number; + quotes: string[]; +} + +interface IKey { + dir: string; + code: number; +} + +var foodsOrganic: IFoodOrganic[] = [ + { name: 'banana', organic: true }, + { name: 'beet', organic: false }, +]; +var foodsType: IFoodType[] = [ + { name: 'apple', type: 'fruit' }, + { name: 'banana', type: 'fruit' }, + { name: 'beet', type: 'vegetable' } +]; +var foodsCombined: IFoodCombined[] = [ + { 'name': 'apple', 'organic': false, 'type': 'fruit' }, + { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } +]; + +var stoogesQuotes: IStoogesQuote[] = [ + { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, + { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } +]; +var stoogesAges: IStoogesAge[] = [ + { 'name': 'moe', 'age': 40 }, + { 'name': 'larry', 'age': 50 } +]; + +var stoogesCombined: IStoogesCombined[] = [ + { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, + { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] } +]; + +var keys: IKey[] = [ + { 'dir': 'left', 'code': 97 }, + { 'dir': 'right', 'code': 100 } +]; + +class Dog { + constructor(public name: string) {} + + public bark() { + console.log('Woof, woof!'); + } +} + +var result : any; + +/************* + * Chaining * + *************/ +result = <_.LoDashWrapper>_('test'); +result = <_.LoDashWrapper>_(1); +result = <_.LoDashWrapper>_(true); +result = <_.LoDashArrayWrapper>_(['test1', 'test2']); +result = <_.LoDashObjectWrapper<_.Dictionary>>_({'key1': 'test1', 'key2': 'test2'}); + +result = <_.LoDashWrapper>_.chain('test'); +result = <_.LoDashWrapper>_('test').chain(); +result = <_.LoDashWrapper>_.chain(1); +result = <_.LoDashWrapper>_(1).chain(); +result = <_.LoDashWrapper>_.chain(true); +result = <_.LoDashWrapper>_(true).chain(); +result = <_.LoDashArrayWrapper>_.chain(['test1', 'test2']); +result = <_.LoDashArrayWrapper>_(['test1', 'test2']).chain(); +result = <_.LoDashObjectWrapper<_.Dictionary>>_.chain({'key1': 'test1', 'key2': 'test2'}); +result = <_.LoDashObjectWrapper<_.Dictionary>>_({'key1': 'test1', 'key2': 'test2'}).chain(); + +//Wrapped array shortcut methods +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).concat(5, 6); +result = <_.LoDashWrapper>_([1, 2, 3, 4]).join(','); +result = <_.LoDashWrapper>_([1, 2, 3, 4]).pop(); +_([1, 2, 3, 4]).push(5, 6, 7); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).reverse(); +result = <_.LoDashWrapper>_([1, 2, 3, 4]).shift(); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).slice(1, 2); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).slice(2); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).sort((a, b) => 1); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).splice(1); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).splice(1, 2, 5, 6); +result = <_.LoDashWrapper>_([1, 2, 3, 4]).unshift(5, 6); + +result = _.tap([1, 2, 3, 4], function(array) { console.log(array); }); +result = <_.LoDashWrapper>_('test').tap(function(value) { console.log(value); }); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).tap(function(array) { console.log(array); }); +result = <_.LoDashObjectWrapper<_.Dictionary>>_({'key1': 'test1', 'key2': 'test2'}).tap(function(array) { console.log(array); }); + +result = _('test').toString(); +result = _([1, 2, 3]).toString(); +result = _({'key1': 'test1', 'key2': 'test2'}).toString(); + +result = _('test').valueOf(); +result = _([1, 2, 3]).valueOf(); +result = <_.Dictionary>_({'key1': 'test1', 'key2': 'test2'}).valueOf(); + +result = _('test').value(); +result = _([1, 2, 3]).value(); +result = <_.Dictionary>_({'key1': 'test1', 'key2': 'test2'}).value(); + +// /************* +// * Arrays * +// *************/ +result = _.compact([0, 1, false, 2, '', 3]); + result = <_.LoDashArrayWrapper>_([0, 1, false, 2, '', 3]).compact(); + +result = _.difference([1, 2, 3, 4, 5], [5, 2, 10]); + result = <_.LoDashArrayWrapper>_([1, 2, 3, 4, 5]).difference([5, 2, 10]); + +result = _.rest([1, 2, 3]); +result = _.rest([1, 2, 3], 2); +result = _.rest([1, 2, 3], (num) => num < 3) +result = _.rest(foodsOrganic, 'test'); +result = _.rest(foodsType, { 'type': 'value' }); + +result = _.drop([1, 2, 3]); +result = _.drop([1, 2, 3], 2); +result = _.drop([1, 2, 3], (num) => num < 3) +result = _.drop(foodsOrganic, 'test'); +result = _.drop(foodsType, { 'type': 'value' }); + +result = _.tail([1, 2, 3]) +result = _.tail([1, 2, 3], 2) +result = _.tail([1, 2, 3], (num) => num < 3) +result = _.tail(foodsOrganic, 'test') +result = _.tail(foodsType, { 'type': 'value' }) + +result = _.findIndex(['apple', 'banana', 'beet'], function(f) { + return /^b/.test(f); +}); +result = _.findIndex(['apple', 'banana', 'beet'], 'apple'); +result = _.findIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple'}); + +result = _.findLastIndex(['apple', 'banana', 'beet'], function(f: string) { + return /^b/.test(f); +}); +result = _.findLastIndex(['apple', 'banana', 'beet'], 'apple'); +result = _.findLastIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple'}); + +result = _.first([1, 2, 3]); +result = _.first([1, 2, 3], 2); +result = _.first([1, 2, 3], function(num) { + return num < 3; +}); +result = _.first(foodsOrganic, 'organic'); +result = _.first(foodsType, { 'type': 'fruit' }); + + result = _.head([1, 2, 3]); + result = _.head([1, 2, 3], 2); + result = _.head([1, 2, 3], function(num) { + return num < 3; + }); + result = _.head(foodsOrganic, 'organic'); + result = _.head(foodsType, { 'type': 'fruit' }); + + result = _.take([1, 2, 3]); + result = _.take([1, 2, 3], 2); + result = _.take([1, 2, 3], (num) => num < 3); + result = _.take(foodsOrganic, 'organic'); + result = _.take(foodsType, { 'type': 'fruit' }); + +result = _.flatten([1, [2], [3, [[4]]]]); +result = _.flatten([1, [2], [3, [[4]]]], true); +var result: any +result = _.flatten(stoogesQuotes, 'quotes'); + + result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(); + result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(true); + result = <_.LoDashArrayWrapper>_(stoogesQuotes).flatten('quotes'); + +result = _.indexOf([1, 2, 3, 1, 2, 3], 2); +result = _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); +result = _.indexOf([1, 1, 2, 2, 3, 3], 2, true); + +result = _.initial([1, 2, 3]); +result = _.initial([1, 2, 3], 2); +result = _.initial([1, 2, 3], function(num) { + return num > 1; +}); +result = _.initial(foodsOrganic, 'organic'); +result = _.initial(foodsType, { 'type': 'vegetable' }); + +result = _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); + +result = _.last([1, 2, 3]); +result = _.last([1, 2, 3], 2); +result = _.last([1, 2, 3], function(num) { + return num > 1; +}); +result = _.last(foodsOrganic, 'organic'); +result = _.last(foodsType, { 'type': 'vegetable' }); + +result = _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); +result = _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); + +result = <{[key: string]: any}>_.zipObject(['moe', 'larry'], [30, 40]); + result = <{[key: string]: any}>_.object(['moe', 'larry'], [30, 40]); + +result = _.pull([1, 2, 3, 1, 2, 3], 2, 3); + +result = _.range(10); +result = _.range(1, 11); +result = _.range(0, 30, 5); +result = _.range(0, -10, -1); +result = _.range(1, 4, 0); +result = _.range(0); + +result = _.remove([1, 2, 3, 4, 5, 6], function(num: number) { return num % 2 == 0; }); +result = _.remove(foodsOrganic, 'organic'); +result = _.remove(foodsType, { 'type': 'vegetable'}); + +result = _.sortedIndex([20, 30, 50], 40); +result = _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); +var sortedIndexDict = { + 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } +}; +result = _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + return sortedIndexDict.wordToNumber[word]; +}); +result = _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + return this.wordToNumber[word]; +}, sortedIndexDict); + +result = _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); + +result = _.uniq([1, 2, 1, 3, 1]); +result = _.uniq([1, 1, 2, 2, 3], true); +result = _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { + return letter.toLowerCase(); +}); +result = _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); +result = <{x: number;}[]>_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + + result = _.unique([1, 2, 1, 3, 1]); + result = _.unique([1, 1, 2, 2, 3], true); + result = _.unique(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { + return letter.toLowerCase(); + }); + result = _.unique([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); + result = <{x: number;}[]>_.unique([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + +result = _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); + +result = _.zip(['moe', 'larry'], [30, 40], [true, false]); + result = _.unzip(['moe', 'larry'], [30, 40], [true, false]); + +// /* ************* +// * Collections * +// ************* */ + +result = _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); +result = _.at(['moe', 'larry', 'curly'], 0, 2); + +result = _.contains([1, 2, 3], 1); +result = _.contains([1, 2, 3], 1, 2); +result = _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); +result = _.contains('curly', 'ur'); + + result = _.include([1, 2, 3], 1); + result = _.include([1, 2, 3], 1, 2); + result = _.include({ 'name': 'moe', 'age': 40 }, 'moe'); + result = _.include('curly', 'ur'); + +result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); +result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); +result = <_.Dictionary>_.countBy(['one', 'two', 'three'], 'length'); + + result = <_.LoDashObjectWrapper<_.Dictionary>>_([4.3, 6.1, 6.4]).countBy(function(num) { return Math.floor(num); }); + result = <_.LoDashObjectWrapper<_.Dictionary>>_([4.3, 6.1, 6.4]).countBy(function(num) { return this.floor(num); }, Math); + result = <_.LoDashObjectWrapper<_.Dictionary>>_(['one', 'two', 'three']).countBy('length'); + +result = _.every([true, 1, null, 'yes'], Boolean); +result = _.every(stoogesAges, 'age'); +result = _.every(stoogesAges, { 'age': 50 }); + + result = _.all([true, 1, null, 'yes'], Boolean); + result = _.all(stoogesAges, 'age'); + result = _.all(stoogesAges, { 'age': 50 }); + +result = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); +result = _.filter(foodsCombined, 'organic'); +result = _.filter(foodsCombined, { 'type': 'fruit' }); + + result = _([1, 2, 3, 4, 5, 6]).filter(function(num) { return num % 2 == 0; }); + result = _(foodsCombined).filter('organic'); + result = _(foodsCombined).filter({ 'type': 'fruit' }); + + result = _.select([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + result = _.select(foodsCombined, 'organic'); + result = _.select(foodsCombined, { 'type': 'fruit' }); + + result = _([1, 2, 3, 4, 5, 6]).select(function(num) { return num % 2 == 0; }); + result = _(foodsCombined).select('organic'); + result = _(foodsCombined).select({ 'type': 'fruit' }); + +result = _.find([1, 2, 3, 4], function(num) { + return num % 2 == 0; +}); +result = _.find(foodsCombined, { 'type': 'vegetable' }); +result = _.find(foodsCombined, 'organic'); + + result = _.detect([1, 2, 3, 4], function(num) { + return num % 2 == 0; + }); + result = _.detect(foodsCombined, { 'type': 'vegetable' }); + result = _.detect(foodsCombined, 'organic'); + + result = _.findWhere([1, 2, 3, 4], function(num) { + return num % 2 == 0; + }); + result = _.findWhere(foodsCombined, { 'type': 'vegetable' }); + result = _.findWhere(foodsCombined, 'organic'); + +result = _.findLast([1, 2, 3, 4], function(num) { + return num % 2 == 0; +}); +result = _.findLast(foodsCombined, { 'type': 'vegetable' }); +result = _.findLast(foodsCombined, 'organic'); + +result = _.forEach([1, 2, 3], function(num) { console.log(num); }); +result = <_.Dictionary>_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + + result = _.each([1, 2, 3], function(num) { console.log(num); }); + result = <_.Dictionary>_.each({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + + result = <_.LoDashArrayWrapper>_([1, 2, 3]).forEach(function(num) { console.log(num); }); + result = <_.LoDashObjectWrapper<_.Dictionary>>_({ 'one': 1, 'two': 2, 'three': 3 }).forEach(function(num) { console.log(num); }); + + result = <_.LoDashArrayWrapper>_([1, 2, 3]).each(function(num) { console.log(num); }); + result = <_.LoDashObjectWrapper<_.Dictionary>>_({ 'one': 1, 'two': 2, 'three': 3 }).each(function(num) { console.log(num); }); + +result = _.forEachRight([1, 2, 3], function(num) { console.log(num); }); +result = <_.Dictionary>_.forEachRight({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + + result = _.eachRight([1, 2, 3], function(num) { console.log(num); }); + result = <_.Dictionary>_.eachRight({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + + result = <_.LoDashArrayWrapper>_([1, 2, 3]).forEachRight(function(num) { console.log(num); }); + result = <_.LoDashObjectWrapper<_.Dictionary>>_({ 'one': 1, 'two': 2, 'three': 3 }).forEachRight(function(num) { console.log(num); }); + + result = <_.LoDashArrayWrapper>_([1, 2, 3]).eachRight(function(num) { console.log(num); }); + result = <_.LoDashObjectWrapper<_.Dictionary>>_({ 'one': 1, 'two': 2, 'three': 3 }).eachRight(function(num) { console.log(num); }); + +result = <_.Dictionary>_.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); +result = <_.Dictionary>_.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); +result = <_.Dictionary>_.groupBy(['one', 'two', 'three'], 'length'); + + result = <_.LoDashObjectWrapper<_.Dictionary>>_([4.2, 6.1, 6.4]).groupBy(function(num) { return Math.floor(num); }); + result = <_.LoDashObjectWrapper<_.Dictionary>>_([4.2, 6.1, 6.4]).groupBy(function(num) { return this.floor(num); }, Math); + result = <_.LoDashObjectWrapper<_.Dictionary>>_(['one', 'two', 'three']).groupBy('length'); + +result = <_.Dictionary>_.indexBy(keys, 'dir'); +result = <_.Dictionary>_.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); +result = <_.Dictionary>_.indexBy(keys, function(key) { this.fromCharCode(key.code); }, String); + +result = _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); +result = _.invoke([123, 456], String.prototype.split, ''); + +result = _.map([1, 2, 3], function(num) { return num * 3; }); +result = _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); +result = _.map(stoogesAges, 'name'); + + result = _.collect([1, 2, 3], function(num) { return num * 3; }); + result = _.collect({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); + result = _.collect(stoogesAges, 'name'); + +result = _.max([4, 2, 8, 6]); +result = _.max(stoogesAges, function(stooge) { return stooge.age; }); +result = _.max(stoogesAges, 'age'); + +result = _.min([4, 2, 8, 6]); +result = _.min(stoogesAges, function(stooge) { return stooge.age; }); +result = _.min(stoogesAges, 'age'); + +result = _.pluck(stoogesAges, 'name'); + +result = _.reduce([1, 2, 3], function(sum: number, num: number) { + return sum + num; +}); +result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(r: any, num: number, key: string) { + r[key] = num * 3; + return r; +}, {}); + + result = _.foldl([1, 2, 3], function(sum: number, num: number) { + return sum + num; + }); + result = _.foldl({ 'a': 1, 'b': 2, 'c': 3 }, function(r: any, num: number, key: string) { + r[key] = num * 3; + return r; + }, {}); + + result = _.inject([1, 2, 3], function(sum: number, num: number) { + return sum + num; + }); + result = _.inject({ 'a': 1, 'b': 2, 'c': 3 }, function(r: any, num: number, key: string) { + r[key] = num * 3; + return r; + }, {}); + +result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function(a: number[], b: number[]) { return a.concat(b); }, []); + result = _.foldr([[0, 1], [2, 3], [4, 5]], function(a: number[], b: number[]) { return a.concat(b); }, []); + +result = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); +result = _.reject(foodsCombined, 'organic'); +result = _.reject(foodsCombined, { 'type': 'fruit' }); + +result = _.sample([1, 2, 3, 4]); +result = _.sample([1, 2, 3, 4], 2); + +result = _.shuffle([1, 2, 3, 4, 5, 6]); + +result = _.size([1, 2]); +result = _.size({ 'one': 1, 'two': 2, 'three': 3 }); +result = _.size('curly'); + +result = _.some([null, 0, 'yes', false], Boolean); +result = _.some(foodsCombined, 'organic'); +result = _.some(foodsCombined, { 'type': 'meat' }); + + result = _.any([null, 0, 'yes', false], Boolean); + result = _.any(foodsCombined, 'organic'); + result = _.any(foodsCombined, { 'type': 'meat' }); + +result = _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); +result = _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); +result = _.sortBy(['banana', 'strawberry', 'apple'], 'length'); + +(function(a: any, b: any, c: any, d: any){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4); + +result = _.where(stoogesCombined, { 'age': 40 }); +result = _.where(stoogesCombined, { 'quotes': ['Poifect!'] }); + +/************* + * Functions * + *************/ +var saves = ['profile', 'settings']; +var asyncSave = (obj: any) => obj.done(); +var done: Function; + +done = _.after(saves.length, function() { + console.log('Done saving!'); +}); + +_.forEach(saves, function(type) { + asyncSave({ 'type': type, 'complete': done }); +}); + +done = _(saves.length).after(function() { + console.log('Done saving!'); +}).value(); + +_.forEach(saves, function(type) { + asyncSave({ 'type': type, 'complete': done }); +}); + +var funcBind = function (greeting: string) { return greeting + ' ' + this.name }; +var funcBind2: () => any = _.bind(funcBind, { 'name': 'moe' }, 'hi'); +funcBind2(); + +var funcBind3: () => any = _(funcBind).bind({ 'name': 'moe' }, 'hi').value(); +funcBind3(); + +var view = { + 'label': 'docs', + 'onClick': function() { console.log('clicked ' + this.label); } +}; + +view = _.bindAll(view); +jQuery('#docs').on('click', view.onClick); + +view = _(view).bindAll().value(); +jQuery('#docs').on('click', view.onClick); + +var objectBindKey = { + 'name': 'moe', + 'greet': function(greeting: string) { + return greeting + ' ' + this.name; + } +}; + +var funcBindKey: Function = _.bindKey(objectBindKey, 'greet', 'hi'); +funcBindKey(); + +objectBindKey.greet = function(greeting) { + return greeting + ', ' + this.name + '!'; +}; + +funcBindKey(); + +funcBindKey = _(objectBindKey).bindKey('greet', 'hi').value(); +funcBindKey(); + +var realNameMap = { + 'curly': 'jerome' +}; + +var format = function(name: string) { + name = realNameMap[name.toLowerCase()] || name; + return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); +}; + +var greet = function(formatted: string) { + return 'Hiya ' + formatted + '!'; +}; + +result = _.compose(greet, format); +result = <_.LoDashObjectWrapper>_(greet).compose(format); + +var createCallbackObj = { name: 'Joe' }; +result = <() => any>_.createCallback('name'); +result = <() => boolean>_.createCallback(createCallbackObj); +result = <_.LoDashObjectWrapper<() => any>>_('name').createCallback(); +result = <_.LoDashObjectWrapper<() => boolean>>_(createCallbackObj).createCallback(); + +result = _.curry(function(a, b, c) { + console.log(a + b + c); +}); + +result = <_.LoDashObjectWrapper>_(function(a, b, c) { + console.log(a + b + c); +}).curry(); + +declare var source: any; +result = _.debounce(function() {}, 150); + +jQuery('#postbox').on('click', _.debounce(function() {}, 300, { + 'leading': true, + 'trailing': false +})); + +source.addEventListener('message', _.debounce(function() {}, 250, { + 'maxWait': 1000 +}), false); + +result = <_.LoDashObjectWrapper>_(function() {}).debounce(150); + +jQuery('#postbox').on('click', <_.LoDashObjectWrapper>_(function() {}).debounce(300, { + 'leading': true, + 'trailing': false +})); + +source.addEventListener('message', <_.LoDashObjectWrapper>_(function() {}).debounce(250, { + 'maxWait': 1000 +}), false); + +result = _.defer(function() { console.log('deferred'); }); +result = <_.LoDashWrapper>_(function() { console.log('deferred'); }).defer(); + +var log = _.bind(console.log, console); +result = _.delay(log, 1000, 'logged later'); +result = <_.LoDashWrapper>_(log).delay(1000, 'logged later'); + +var fibonacci = _.memoize(function(n) { + return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); +}); + +var data = { + 'moe': { 'name': 'moe', 'age': 40 }, + 'curly': { 'name': 'curly', 'age': 60 } +}; + +var stooge = _.memoize(function(name: string) { return data[name]; }, _.identity); +stooge('curly'); + +stooge['cache']['curly'].name = 'jerome'; +stooge('curly'); + +var initialize = _.once(function(){ }); +initialize(); +initialize(); + +var greetPartial = function(greeting: string, name: string) { return greeting + ' ' + name; }; +var hi = _.partial(greetPartial, 'hi'); +hi('moe'); + +var defaultsDeep = _.partialRight(_.merge, _.defaults); + +var optionsPartialRight = { + 'variable': 'data', + 'imports': { 'jq': $ } +}; + +defaultsDeep(optionsPartialRight, _.templateSettings); + +var throttled = _.throttle(function () { }, 100); +jQuery(window).on('scroll', throttled); + +jQuery('.interactive').on('click', _.throttle(function() { }, 300000, { + 'trailing': false +})); + +var helloWrap = function(name: string) { return 'hello ' + name; }; +var helloWrap2 = _.wrap(helloWrap, function(func) { + return 'before, ' + func('moe') + ', after'; +}); +helloWrap2(); + +/********** +* Objects * +***********/ +result = _.assign({ 'name': 'moe' }, { 'age': 40 }); +result = _.assign({ 'name': 'moe' }, { 'age': 40 }, function(a: any, b: any) { + return typeof a == 'undefined' ? b : a; +}); + +result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).assign({ 'age': 40 }); +result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).assign({ 'age': 40 }, function(a: any, b: any) { + return typeof a == 'undefined' ? b : a; +}); + + result = _.extend({ 'name': 'moe' }, { 'age': 40 }); + result = _.extend({ 'name': 'moe' }, { 'age': 40 }, function(a: any, b: any) { + return typeof a == 'undefined' ? b : a; + }); + + result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).extend({ 'age': 40 }); + result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).extend({ 'age': 40 }, function(a: any, b: any) { + return typeof a == 'undefined' ? b : a; + }); + +var result = _.clone(stoogesAges); +var result = _.clone(stoogesAges, true); +var result = _.clone(stoogesAges, true, function(value) { + return _.isElement(value) ? value.cloneNode(false) : undefined; +}); + +var result = _.cloneDeep(stoogesAges); +var result = _.cloneDeep(stoogesAges, function(value) { + return _.isElement(value) ? value.cloneNode(false) : undefined; +}); + +var foodDefaults = { 'name': 'apple' }; +result = _.defaults(foodDefaults, { 'name': 'banana', 'type': 'fruit' }); +result = _(foodDefaults).defaults({ 'name': 'banana', 'type': 'fruit' }); + +result = _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) { + return num % 2 == 0; +}); + +result = _.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) { + return num % 2 == 1; +}); + +result = _.forIn(new Dog('Dagny'), function(value, key) { + console.log(key); +}); + + result = <_.LoDashObjectWrapper>_(new Dog('Dagny')).forIn(function(value, key) { + console.log(key); + }); + +result = _.forInRight(new Dog('Dagny'), function(value, key) { + console.log(key); +}); + + result = <_.LoDashObjectWrapper>_(new Dog('Dagny')).forInRight(function(value, key) { + console.log(key); + }); + +result = _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + console.log(key); +}); + + result = <_.LoDashObjectWrapper>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwn(function(num, key) { + console.log(key); + }); + +result = _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + console.log(key); +}); + + result = <_.LoDashObjectWrapper>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwnRight(function(num, key) { + console.log(key); + }); + +result = _.functions(_); + result = _.methods(_); + + result = <_.LoDashArrayWrapper>_(_).functions(); + result = <_.LoDashArrayWrapper>_(_).methods(); + +result = _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); + +result = _.invert({ 'first': 'moe', 'second': 'larry' }); + +(function(...args: any[]) { return _.isArguments(arguments); })(1, 2, 3); + +(function () { return _.isArray(arguments); })(); +result = _.isArray([1, 2, 3]); + +result = _.isBoolean(null); + +result = _.isDate(new Date()); + +result = _.isElement(document.body); + +result = _.isEmpty([1, 2, 3]); +result = _.isEmpty({}); +result = _.isEmpty(''); + +var moe = { 'name': 'moe', 'age': 40 }; +var copy = { 'name': 'moe', 'age': 40 }; + +result = _.isEqual(moe, copy); + +var words = ['hello', 'goodbye']; +var otherWords = ['hi', 'goodbye']; + +result = _.isEqual(words, otherWords, function(a, b) { + var reGreet = /^(?:hello|hi)$/i, + aGreet = _.isString(a) && reGreet.test(a), + bGreet = _.isString(b) && reGreet.test(b); + + return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; +}); + +result = _.isFinite(-101); +result = _.isFinite('10'); +result = _.isFinite(true); +result = _.isFinite(''); +result = _.isFinite(Infinity); + +result = _.isFunction(_); + +result = _.isNaN(NaN); +result = _.isNaN(new Number(NaN)); +result = _.isNaN(undefined); + +result = _.isNull(null); +result = _.isNull(undefined); + +result = _.isNumber(8.4 * 5); + +result = _.isObject({}); +result = _.isObject([1, 2, 3]); +result = _.isObject(1); + +class Stooge { + constructor( + public name: string, + public age: number + ) {} +} + +result = _.isPlainObject(new Stooge('moe', 40)); +result = _.isPlainObject([1, 2, 3]); +result = _.isPlainObject({ 'name': 'moe', 'age': 40 }); + +result = _.isRegExp(/moe/); + +result = _.isString('moe'); + +result = _.isUndefined(void 0); + +result = _.keys({ 'one': 1, 'two': 2, 'three': 3 }); + +var mergeNames = { + 'stooges': [ + { 'name': 'moe' }, + { 'name': 'larry' } + ] +}; + +var mergeAges = { + 'stooges': [ + { 'age': 40 }, + { 'age': 50 } + ] +}; + +result = _.merge(mergeNames, mergeAges); + +var mergeFood = { + 'fruits': ['apple'], + 'vegetables': ['beet'] +}; + +var mergeOtherFood = { + 'fruits': ['banana'], + 'vegetables': ['carrot'] +}; + +result = _.merge(mergeFood, mergeOtherFood, function(a: any, b: any) { + return _.isArray(a) ? a.concat(b) : undefined; +}); + +result = _.omit({ 'name': 'moe', 'age': 40 }, 'age'); +result = _.omit({ 'name': 'moe', 'age': 40 }, ['age']); +result = _.omit({ 'name': 'moe', 'age': 40 }, function(value) { + return typeof value == 'number'; +}); + +result = _.pairs({ 'moe': 30, 'larry': 40 }); + +result = _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name'); +result = _.pick({ 'name': 'moe', '_userid': 'moe1' }, ['name']); +result = _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) { + return key.charAt(0) != '_'; +}); + +result = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(r: any, num: number) { + num *= num; + if (num % 2) { + return r.push(num) < 3; + } +}); +// → [1, 9, 25] + +result = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(r: any, num: number, key: string) { + r[key] = num * 3; +}); + +result = _.values({ 'one': 1, 'two': 2, 'three': 3 }); + +/********** +* Utilities * +***********/ + +result = _.escape('Moe, Larry & Curly'); + +result = <{ name: string }>_.identity({ 'name': 'moe' }); + +_.mixin({ + 'capitalize': function(string) { + return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + } +}); + +var lodash = _.noConflict(); + +result = _.parseInt('08'); + +result = _.random(0, 5); +result = _.random(5); +result = _.random(5, true); +result = _.random(1.2, 5.2); +result = _.random(0, 5, true); + +var object = { + 'cheese': 'crumpets', + 'stuff': function() { + return 'nonsense'; + } +}; + +result = _.result(object, 'cheese'); +result = _.result(object, 'stuff'); + +var tempObject = {}; +result = _.runInContext(tempObject); + +result = <_.TemplateExecutor>_.template('hello <%= name %>'); +result = _.template('<%- value %>', { 'value': '