Merge branch 'borisyankov-definitelytyped-master' into updating-angular-resource

Conflicts:
	angularjs/angular-resource-tests.ts
This commit is contained in:
John Emau
2013-11-11 12:52:38 -08:00
92 changed files with 23920 additions and 4564 deletions
+10 -5
View File
@@ -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/)
+1
View File
@@ -0,0 +1 @@
tsc runner.ts --out runner.js --module commonjs
+106 -46
View File
@@ -552,10 +552,11 @@ else if (typeof require === "function")
else
return null;
})();
/// <reference path='src/exec.ts' />
/// <reference path='src/io.ts' />
var DefinitelyTyped;
(function (DefinitelyTyped) {
/// <reference path='../../node/node.d.ts' />
/// <reference path='src/exec.ts' />
/// <reference path='src/io.ts' />
(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);
}
});
File diff suppressed because it is too large Load Diff
+5 -15
View File
@@ -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() {
+1
View File
@@ -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.
+219
View File
@@ -0,0 +1,219 @@
/// <reference path="angular-1.0.d.ts" />
// 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<any>) {
buffer.push({
config: config,
deferred: deferred
});
}
this.$get = ['$rootScope', '$injector', <any>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<any>) {
$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', <any>function ($httpProvider: ng.IHttpProvider, authServiceProvider) {
var interceptor = ['$rootScope', '$q', <any>function ($rootScope: ng.IScope, $q: ng.IQService) {
function success(response: ng.IHttpPromiseCallbackArg<any>) {
return response;
}
function error(response: ng.IHttpPromiseCallbackArg<any>) {
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<any>) {
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<ExpectedResponse>) => {
// 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<ExpectedResponse>) => {
// typing lost, so something like
// var i: number = response.data
// would NOT type check
$scope.person = response.data;
});
var aPromise: ng.IPromise<Person> = $q.when({ firstName: "Jack", lastName: "Sparrow" });
aPromise.then((person: Person) => {
$scope.person = person;
});
var bPromise: ng.IPromise<number> = $q.when(42);
bPromise.then((answer: number) => {
$scope.theAnswer = answer;
});
var cPromise: ng.IPromise<string[]> = $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<ExpectedResponse>) => {
$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', <any>function ($scope: ng.IScope) { }])
mod.controller(My.Namespace);
mod.directive('name', <any>function ($scope: ng.IScope) { })
mod.directive('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.directive(My.Namespace);
mod.factory('name', function ($scope: ng.IScope) { })
mod.factory('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.factory(My.Namespace);
mod.filter('name', function ($scope: ng.IScope) { })
mod.filter('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.filter(My.Namespace);
mod.provider('name', function ($scope: ng.IScope) { })
mod.provider('name', ['$scope', <any>function ($scope: ng.IScope) { }])
mod.provider(My.Namespace);
mod.service('name', function ($scope: ng.IScope) { })
mod.service('name', ['$scope', <any>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<number>;
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<number>;
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();
+1
View File
@@ -0,0 +1 @@
""
Vendored Executable
+760
View File
@@ -0,0 +1,760 @@
// Type definitions for Angular JS 1.0
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
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<any>;
cancel(promise: IPromise<any>): 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<any>[]): IPromise<any[]>;
defer<T>(): IDeferred<T>;
reject(reason?: any): IPromise<void>;
when<T>(value: T): IPromise<T>;
}
interface IPromise<T> {
then<TResult>(successCallback: (promiseValue: T) => IHttpPromise<TResult>, errorCallback?: (reason: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>, errorCallback?: (reason: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => TResult, errorCallback?: (reason: any) => TResult): IPromise<TResult>;
}
interface IDeferred<T> {
resolve(value?: T): void;
reject(reason?: any): void;
promise: IPromise<T>;
}
///////////////////////////////////////////////////////////////////////////
// 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<any>;
get (url: string, RequestConfig?: any): IHttpPromise<any>;
delete (url: string, RequestConfig?: any): IHttpPromise<any>;
head(url: string, RequestConfig?: any): IHttpPromise<any>;
jsonp(url: string, RequestConfig?: any): IHttpPromise<any>;
post(url: string, data: any, RequestConfig?: any): IHttpPromise<any>;
put(url: string, data: any, RequestConfig?: any): IHttpPromise<any>;
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<T> {
(data: T, status: number, headers: (headerName: string) => string, config: IRequestConfig): void;
}
interface IHttpPromiseCallbackArg<T> {
data?: T;
status?: number;
headers?: (headerName: string) => string;
config?: IRequestConfig;
}
interface IHttpPromise<T> extends IPromise<T> {
success(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;
error(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg<T>) => any): IPromise<TResult>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => IPromise<TResult>, errorCallback?: (response: IHttpPromiseCallbackArg<T>) => any): IPromise<TResult>;
}
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;
}
}
}
+30
View File
@@ -0,0 +1,30 @@
/// Type definitions for Angular JS 1.0 (ngCookies module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// 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;
}
}
+1 -1
View File
@@ -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 <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+150
View File
@@ -0,0 +1,150 @@
// Type definitions for Angular JS 1.0 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// 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;
}
}
}
+288
View File
@@ -0,0 +1,288 @@
/// <reference path="angular-mocks.d.ts" />
///////////////////////////////////////
// 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' });
@@ -0,0 +1 @@
""
+125 -57
View File
@@ -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 <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
@@ -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;
}
}
}
}
+1
View File
@@ -0,0 +1 @@
""
+82
View File
@@ -0,0 +1,82 @@
// Type definitions for Angular JS 1.0 (ngResource module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// 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;
}
}
+5 -5
View File
@@ -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 <http://github.com/diegovilar>
// 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
+14
View File
@@ -0,0 +1,14 @@
/// <reference path="angular-route.d.ts" />
/**
* @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: '/'});
+64
View File
@@ -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
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// 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;
}
}
+22
View File
@@ -0,0 +1,22 @@
// Type definitions for Angular JS 1.0 (ngSanitize module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// ngSanitize module (angular-sanitize.js)
///////////////////////////////////////////////////////////////////////////////
declare module ng.sanitize {
///////////////////////////////////////////////////////////////////////////
// SanitizeService
// see http://docs.angularjs.org/api/ngSanitize.$sanitize
///////////////////////////////////////////////////////////////////////////
interface ISanitizeService {
(html: string): string;
}
}
+1 -1
View File
@@ -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 <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+155
View File
@@ -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;
@@ -0,0 +1 @@
""
+15
View File
@@ -182,6 +182,7 @@ mod.value('name', 23);
mod.value('name', "23");
mod.value(My.Namespace);
// Promise signature tests
var foo: ng.IPromise<number>;
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: {}
});
+109 -54
View File
@@ -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<any>): boolean;
}
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see http://docs.angularjs.org/api/ng.$interval
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
(func: Function, delay: number, count?: number, invokeApply?: boolean): IPromise<any>;
cancel(promise: IPromise<any>): 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;
}
///////////////////////////////////////////////////////////////////////////
+10 -11
View File
@@ -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);
}
+8 -2
View File
@@ -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 <https://github.com/borisyankov/>
// 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;
}
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;
}
+14 -14
View File
@@ -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 {
+187 -167
View File
@@ -5,39 +5,50 @@
/// <reference path="../phantomjs/phantomjs.d.ts" />
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<T>(array: T[], fn: (self: Casper, item: T, index: number) => void): Casper;
echo(message: string, style?: string): Casper;
evaluate<T>(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;
}
+6
View File
@@ -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 = {};
+3
View File
@@ -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;
}
+79 -43
View File
@@ -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;
}
+585 -644
View File
File diff suppressed because it is too large Load Diff
+6 -6
View File
@@ -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;
+49
View File
@@ -0,0 +1,49 @@
/// <reference path="flight.d.ts" />
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();
+238
View File
@@ -0,0 +1,238 @@
/// <reference path="../jquery/jquery.d.ts" />
// Type definitions for Flight 1.1.1
// Project: http://flightjs.github.com/flight/
// Definitions by: Jonathan Hedrén <https://github.com/jonathanhedren/>
// 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;
+1 -1
View File
@@ -72,7 +72,7 @@ declare module jquery.flot {
}
interface seriesOptions {
color?: number;
color?: any; // color or number
label?: string;
lines?: linesOptions;
bars?: barsOptions;
+6 -2
View File
@@ -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");
+8 -6
View File
@@ -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;
@@ -0,0 +1,41 @@
/// <reference path="google.visualization.d.ts" />
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]);
}
+369
View File
@@ -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
}
}
+220
View File
@@ -0,0 +1,220 @@
/// <reference path="greasemonkey.d.ts" />
////////////////
// 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;
+235
View File
@@ -0,0 +1,235 @@
// Type definitions for Greasemonkey
// Project: http://www.greasespot.net/
// Definitions by: Kota Saito <https://github.com/kotas>
// 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;
+13 -1
View File
@@ -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);
});
};
+1281 -199
View File
File diff suppressed because it is too large Load Diff
+116
View File
@@ -0,0 +1,116 @@
///<reference path="ix.d.ts"/>
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<string>();
Ix.Enumerable.catchException<string>();
Ix.Enumerable.onErrorResumeNext(ax, ax, ax);
Ix.Enumerable.onErrorResumeNext<string>();
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<string>;
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();
+112
View File
@@ -0,0 +1,112 @@
// Type definitions for IxJS 1.0.6 / ix.js
// Project: https://github.com/Reactive-Extensions/IxJS
// Definitions by: Igor Oleinikov <https://github.com/Igorbek>
///<reference path="l2o.d.ts"/>
declare module Ix {
export interface Observer<T> {
onNext? (value: T): void;
onError? (error: Error): void;
onCompleted? (): void;
}
export interface Enumerable<T> {
isEmpty(): boolean;
minBy<TKey>(keySelector: (item: T) => TKey, comparer: Comparer<TKey, TKey>): Enumerable<T>;
minBy(keySelector: (item: T) => number): Enumerable<T>;
maxBy<TKey>(keySelector: (item: T) => TKey, comparer: Comparer<TKey, TKey>): Enumerable<T>;
maxBy(keySelector: (item: T) => number): Enumerable<T>;
share<TResult>(selector: (source: Enumerable<T>) => Enumerable<TResult>): Enumerable<TResult>;
share(): Enumerable<T>;
publish<TResult>(selector: (source: Enumerable<T>) => Enumerable<TResult>): Enumerable<TResult>;
publish(): Enumerable<T>;
memoize(): Enumerable<T>;
do(onNext: (value: T) => void, onError?: (error: Error) => void, onCompleted?: () => void): Enumerable<T>;
doAction(onNext: (value: T) => void, onError?: (error: Error) => void, onCompleted?: () => void): Enumerable<T>;
do(onbserver: Observer<T>): Enumerable<T>;
doAction(onbserver: Observer<T>): Enumerable<T>;
bufferWithCount(count: number, skip?: number): Enumerable<T>;
ignoreElements(): Enumerable<T>;
distinctBy<TKey>(keySelector: (item: T) => TKey, comparer?: EqualityComparer<TKey, TKey>): Enumerable<T>;
distinctUntilChanged<TKey>(keySelector: (item: T) => TKey, comparer?: EqualityComparer<TKey, TKey>): Enumerable<T>;
distinctUntilChanged(): Enumerable<T>;
// if need to set comparer without keySelector
distinctUntilChanged(_: boolean, comparer: EqualityComparer<T, T>): Enumerable<T>;
expand(selector: (item: T) => Enumerable<T>): Enumerable<T>;
startWith(...values: T[]): Enumerable<T>;
scan<TSeed, TAccumulator>(seed: TSeed, accumulate: (acc: TAccumulator, item: T) => TAccumulator): Enumerable<TAccumulator>;
scan(accumulate: (acc: T, item: T) => T): Enumerable<T>;
takeLast(count: number): Enumerable<T>;
skipLast(count: number): Enumerable<T>;
repeat(count?: number): Enumerable<T>;
catch(handler: (error: Error) => Enumerable<T>): Enumerable<T>;
catchException(handler: (error: Error) => Enumerable<T>): Enumerable<T>;
catch(second: Enumerable<T>, ...other: Enumerable<T>[]): Enumerable<T>;
catchException(second: Enumerable<T>, ...other: Enumerable<T>[]): Enumerable<T>;
// todo: Enumerable<Enumerable<T>>.catch(): Enumerable<T>
//catch<TInner, T extends Enumerable<TInner>>(): Enumerable<TInner>;
finally(finallyAction: () => void): Enumerable<T>;
finallyDo(finallyAction: () => void): Enumerable<T>;
onErrorResumeNext(second: Enumerable<T>): Enumerable<T>;
retry(retryCount?: number): Enumerable<T>;
}
export interface EnumerableStatic {
throw<T>(error: Error): Enumerable<T>;
throwException<T>(error: Error): Enumerable<T>;
defer<T>(enumerableFactory: () => Enumerable<T>): Enumerable<T>;
generate<TState, TResult>(
initialState: TState,
condition: Predicate<TState>,
iterate: (state: TState) => TState,
resultSelector: (state: TState) => TResult): Enumerable<TResult>;
using<TResource extends Disposable, T>(
resourceFactory: () => TResource,
enumerableFactory: (resource: TResource) => Enumerable<T>): Enumerable<T>;
catch<T>(...sources: Enumerable<T>[]): Enumerable<T>;
catchException<T>(...sources: Enumerable<T>[]): Enumerable<T>;
onErrorResumeNext<T>(...sources: Enumerable<T>[]): Enumerable<T>;
while<T>(condition: EnumerablePredicate<Enumerable<T>>, source: Enumerable<T>): Enumerable<T>;
whileDo<T>(condition: EnumerablePredicate<Enumerable<T>>, source: Enumerable<T>): Enumerable<T>;
if<T>(condition: () => boolean, thenSource: Enumerable<T>, elseSource?: Enumerable<T>): Enumerable<T>;
ifThen<T>(condition: () => boolean, thenSource: Enumerable<T>, elseSource?: Enumerable<T>): Enumerable<T>;
doWhile<T>(source: Enumerable<T>, condition: EnumerablePredicate<Enumerable<T>>): Enumerable<T>;
case<T>(selector: () => number, sources: { [key: number]: Enumerable<T>; }, defaultSource?: Enumerable<T>): Enumerable<T>;
case<T>(selector: () => string, sources: { [key: string]: Enumerable<T>; }, defaultSource?: Enumerable<T>): Enumerable<T>;
switchCase<T>(selector: () => number, sources: { [key: number]: Enumerable<T>; }, defaultSource?: Enumerable<T>): Enumerable<T>;
switchCase<T>(selector: () => string, sources: { [key: string]: Enumerable<T>; }, defaultSource?: Enumerable<T>): Enumerable<T>;
for<T, TResult>(source: Enumerable<T>, resultSelector: EnumerableFunc<T, TResult>): Enumerable<TResult>;
forIn<T, TResult>(source: Enumerable<T>, resultSelector: EnumerableFunc<T, TResult>): Enumerable<TResult>;
}
}
+221
View File
@@ -0,0 +1,221 @@
///<reference path="l2o.d.ts"/>
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<number>();
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<number>;
try {
while (e.moveNext()) { var c = e.getCurrent(); }
}
finally {
e.dispose();
}
}
// Dictionary
{
var dic = new Ix.Dictionary<number, string>(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<number, string>;
var key = kv.key;
var value = kv.value;
}
// Lookup
{
var lookup: Ix.Lookup<number, string>;
var key = lookup.toEnumerable().first().key;
lookup.toEnumerable().first().first();
lookup.has(1);
lookup.length();
lookup.get(1).first();
}
+256
View File
@@ -0,0 +1,256 @@
// Type definitions for IxJS 1.0.6 / l2o.js
// Project: https://github.com/Reactive-Extensions/IxJS
// Definitions by: Igor Oleinikov <https://github.com/Igorbek>
declare module Ix {
export interface Disposable {
dispose(): void;
}
export interface Enumerator<T> extends Disposable {
moveNext(): boolean;
getCurrent(): T;
}
export interface EnumeratorStatic {
new <T>(moveNext: () => boolean, getCurrent: () => T, dispose: () => void): Enumerator<T>;
create<T>(moveNext: () => boolean, getCurrent: () => T, dispose?: () => void): Enumerator<T>;
}
var Enumerator: EnumeratorStatic;
export interface EnumerableFunc<T, TResult> {
(item: T, index: number, self: Enumerable<T>): TResult;
}
export interface EnumerablePredicate<T> extends EnumerableFunc<T, boolean> { }
export interface Predicate<T> {
(item: T): boolean;
}
export interface EqualityComparer<TFirst, TSecond> {
(item1: TFirst, item2: TSecond): boolean;
}
export interface Comparer<TFirst, TSecond> {
(item1: TFirst, item2: TSecond): number;
}
export interface Enumerable<T> {
// base functions
getEnumerator(): Enumerator<T>;
// "extension" functions
aggregate<TAccumulate, TResult>(seed: TAccumulate, func: (accumulate: TAccumulate, current: T, index: number, self: Enumerable<T>) => TAccumulate, resultSelector: (accumulate: TAccumulate) => TResult): TResult;
aggregate<TAccumulate>(seed: TAccumulate, func: (accumulate: TAccumulate, current: T, index: number, self: Enumerable<T>) => TAccumulate): TAccumulate;
aggregate(func: (accumulate: T, current: T, index: number, self: Enumerable<T>) => T): T;
reduce(func: (accumulate: T, current: T, index: number, self: Enumerable<T>) => T): T;
reduce<TAccumulate>(func: (accumulate: TAccumulate, current: T, index: number, self: Enumerable<T>) => TAccumulate, seed: TAccumulate): TAccumulate;
all(predicate: EnumerablePredicate<T>, thisArg?: any): boolean;
every(predicate: EnumerablePredicate<T>, thisArg?: any): boolean; // alias
any(predicate?: EnumerablePredicate<T>, thisArg?: any): boolean;
some(predicate?: EnumerablePredicate<T>, thisArg?: any): boolean; // alias
average(selector?: EnumerableFunc<T, number>): number;
max(selector?: EnumerableFunc<T, number>): number;
min(selector?: EnumerableFunc<T, number>): number;
sum(selector?: EnumerableFunc<T, number>): number;
concat<T>(...sources: Enumerable<T>[]): Enumerable<T>;
contains<TValue>(value: TValue, comparer: EqualityComparer<T, TValue>): boolean;
contains(value: T): boolean;
count(predicate?: EnumerablePredicate<T>, thisArg?: any): number;
defaultIfEmpty(defaultValue?: T): Enumerable<T>;
distinct(comparer?: EqualityComparer<T, T>): Enumerable<T>;
elementAt(index: number): T;
elementAtOrDefault(index: number): T;
except<TOther>(second: Enumerable<TOther>, comparer: EqualityComparer<T, TOther>): Enumerable<T>;
except(second: Enumerable<T>): Enumerable<T>;
first(predicate?: Predicate<T>): T;
firstOrDefault(predicate?: Predicate<T>): T;
last(predicate?: Predicate<T>): T;
lastOrDefault(predicate?: Predicate<T>): T;
single(predicate?: Predicate<T>): T;
singleOrDefault(predicate?: Predicate<T>): T;
forEach(action: EnumerableFunc<T, void>, thisArg?: any): void;
groupBy<TKey, TElement, TResult>(
keySelector: (item: T) => TKey,
elementSelector: (item: T) => TElement,
resultSelector: (key: TKey, values: Enumerable<TElement>) => TResult,
comparer?: EqualityComparer<TKey, TKey>): Enumerable<TResult>;
groupBy<TKey, TElement>(
keySelector: (item: T) => TKey,
elementSelector: (item: T) => TElement): Grouping<TKey, TElement>;
// spec 3.5.2, waiting for restriction on generative recursion removal
/*groupBy<TKey>(
keySelector: (item: T) => TKey): Grouping<TKey, T>;*/
// if need to set comparer without resultSelector
groupBy<TKey, TElement>(
keySelector: (item: T) => TKey,
elementSelector: (item: T) => TElement,
_: boolean,
comparer: EqualityComparer<TKey, TKey>): Grouping<TKey, TElement>;
// if need to set resultSelector without elementSelector
groupBy<TKey, TResult>(
keySelector: (item: T) => TKey,
_: boolean,
resultSelector: (key: TKey, values: Enumerable<T>) => TResult,
comparer?: EqualityComparer<TKey, TKey>): Enumerable<TResult>;
// if need to set comparer without elementSelector and resultSelector
// spec 3.5.2, waiting for restriction on generative recursion removal
/*groupBy<TKey>(
keySelector: (item: T) => TKey,
_: boolean,
__: boolean,
comparer: EqualityComparer<TKey, TKey>): Grouping<TKey, T>;*/
groupJoin<TInner, TOuterKey, TInnerKey, TResult>(
inner: Enumerable<TInner>,
outerKeySelector: (item: T) => TOuterKey,
innerKeySelector: (item: TInner) => TInnerKey,
resultSelector: (outer: T, innerSequence: Enumerable<TInner>) => TResult,
comparer: EqualityComparer<TOuterKey, TInnerKey>): Enumerable<TResult>;
groupJoin<TInner, TKey, TResult>(
inner: Enumerable<TInner>,
outerKeySelector: (item: T) => TKey,
innerKeySelector: (item: TInner) => TKey,
resultSelector: (outer: T, innerSequence: Enumerable<TInner>) => TResult): Enumerable<TResult>;
join<TInner, TOuterKey, TInnerKey, TResult>(
inner: Enumerable<TInner>,
outerKeySelector: (item: T) => TOuterKey,
innerKeySelector: (item: TInner) => TInnerKey,
resultSelector: (outer: T, inner: TInner) => TResult,
comparer: EqualityComparer<TOuterKey, TInnerKey>): Enumerable<TResult>;
join<TInner, TKey, TResult>(
inner: Enumerable<TInner>,
outerKeySelector: (item: T) => TKey,
innerKeySelector: (item: TInner) => TKey,
resultSelector: (outer: T, inner: TInner) => TResult): Enumerable<TResult>;
intersect<TSecond>(second: Enumerable<TSecond>, comparer: EqualityComparer<T, TSecond>): Enumerable<T>;
intersect(second: Enumerable<T>): Enumerable<T>;
union(second: Enumerable<T>, comparer?: EqualityComparer<T, T>): Enumerable<T>;
orderBy<TKey>(keySelector: (item: T) => TKey, comparer?: Comparer<TKey, TKey>): OrderedEnumerable<T>;
orderByDescending<TKey>(keySelector: (item: T) => TKey, comparer?: Comparer<TKey, TKey>): OrderedEnumerable<T>;
reverse(): Enumerable<T>;
select<TResult>(selector: EnumerableFunc<T, TResult>, thisArg?: any): Enumerable<TResult>;
map<TResult>(selector: EnumerableFunc<T, TResult>, thisArg?: any): Enumerable<TResult>;
selectMany<TCollection, TResult>(collectionSelector: (item: T, index: number) => Enumerable<TCollection>,
resultSelector: (outer: T, inner: TCollection) => TResult): Enumerable<TResult>;
selectMany<TCollection>(collectionSelector: (item: T, index: number) => Enumerable<TCollection>): Enumerable<TCollection>;
sequenceEqual<TSecond>(second: Enumerable<TSecond>, comparer: EqualityComparer<T, TSecond>): boolean;
sequenceEqual(second: Enumerable<T>): boolean;
skip(count: number): Enumerable<T>;
skipWhile(selector: EnumerablePredicate<T>, thisArg?: any): Enumerable<T>;
take(count: number): Enumerable<T>;
takeWhile(selector: EnumerablePredicate<T>, thisArg?: any): Enumerable<T>;
toArray(): T[];
toDictionary<TKey, TValue>(
keySelector: (item: T) => TKey,
elementSelector: (item: T) => TValue,
comparer?: EqualityComparer<TKey, TKey>): Dictionary<TKey, TValue>;
// spec 3.5.2, waiting for restriction on generative recursion removal
/*toDictionary<TKey>(
keySelector: (item: T) => TKey): Dictionary<TKey, T>;*/
// if need to set comparer without elementSelector
// spec 3.5.2, waiting for restriction on generative recursion removal
/*toDictionary<TKey>(
keySelector: (item: T) => TKey,
_: boolean,
comparer: EqualityComparer<TKey, TKey>): Dictionary<TKey, T>;*/
toLookup<TKey, TValue>(
keySelector: (item: T) => TKey,
elementSelector: (item: T) => TValue,
comparer?: EqualityComparer<TKey, TKey>): Lookup<TKey, TValue>;
// spec 3.5.2, waiting for restriction on generative recursion removal
/*toLookup<TKey>(
keySelector: (item: T) => TKey): Lookup<TKey, T>;*/
// if need to set comparer without elementSelector
// spec 3.5.2, waiting for restriction on generative recursion removal
/*toLookup<TKey>(
keySelector: (item: T) => TKey,
_: boolean,
comparer: EqualityComparer<TKey, TKey>): Lookup<TKey, T>;*/
where(selector: EnumerablePredicate<T>, thisArg?: any): Enumerable<T>;
filter(selector: EnumerablePredicate<T>, thisArg?: any): Enumerable<T>;
zip<TRight, TResult>(right: Enumerable<TRight>, selector: (left: T, right: TRight) => TResult): Enumerable<TResult>;
}
export interface Grouping<TKey, T> extends Enumerable<T> {
key: TKey;
}
export interface OrderedEnumerable<T> extends Enumerable<T> {
thenBy<TKey>(keySelector: (item: T) => TKey, comparer?: Comparer<TKey, TKey>): OrderedEnumerable<T>;
thenByDescending<TKey>(keySelector: (item: T) => TKey, comparer?: Comparer<TKey, TKey>): OrderedEnumerable<T>;
}
class Dictionary<TKey, TValue> {
constructor(capacity?: number, comparer?: EqualityComparer<TKey, TKey>);
toEnumerable(): Enumerable<KeyValuePair<TKey, TValue>>;
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<TKey, TValue> {
key: TKey;
value: TValue;
}
export interface Lookup<TKey, TValue> {
toEnumerable(): Enumerable<Grouping<TKey, TValue>>;
has(key: TKey): boolean;
length(): number;
get(key: TKey): Enumerable<TValue>;
}
export interface EnumerableStatic {
new <T>(getEnumerator: () => Enumerator<T>): Enumerable<T>;
create<T>(getEnumerator: () => Enumerator<T>): Enumerable<T>;
concat<T>(...sources: Enumerable<T>[]): Enumerable<T>;
empty<T>(): Enumerable<T>;
fromArray<T>(array: T[]): Enumerable<T>;
return<T>(value: T): Enumerable<T>;
returnValue<T>(value: T): Enumerable<T>; // alias for <IE9
range(start: number, count: number): Enumerable<number>;
repeat<T>(value: T, repeatCount?: number): Enumerable<T>;
sequenceEqual<TFirst, TSecond>(first: Enumerable<TFirst>, second: Enumerable<TSecond>, comparer: EqualityComparer<TFirst, TSecond>): boolean;
sequenceEqual<T>(first: Enumerable<T>, second: Enumerable<T>): boolean;
}
var Enumerable: EnumerableStatic;
}
+8 -8
View File
@@ -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;
}
+1
View File
@@ -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<T>(baseName: string, methodNames: any[]): T;
function pp(value: any): string;
function getEnv(): Env;
+8
View File
@@ -0,0 +1,8 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="jquery.base64.d.ts" />
var encoded = $.base64.encode("");
$.base64.decode(encoded);
var encodedUTF8 = $.base64.encode("", true);
$.base64.decode(encodedUTF8, true);
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for jQuery Plugin - base64 codec
// Project: https://github.com/yatt/jquery.base64/
// Definitions by: Shinya Mochizuki <https://github.com/enrapt-mochizuki/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface JQueryBase64Static {
encode(data: string, isUTF8?: boolean): string;
decode(data: string, isUTF8?: boolean): string;
}
interface JQueryStatic {
base64: JQueryBase64Static;
}
+42
View File
@@ -0,0 +1,42 @@
///<reference path="../jquery/jquery.d.ts" />
///<reference path="jquery.cleditor.d.ts" />
// 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", "<p>"], ["Header 1", "<h1>"], ["Header 2", "<h2>"],
["Header 3", "<h3>"], ["Header 4","<h4>"], ["Header 5","<h5>"],
["Header 6","<h6>"]],
useCSS: false, // use CSS to style HTML when possible (not supported in ie)
docType: // Document type contained within the editor
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
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"
});
});
+98
View File
@@ -0,0 +1,98 @@
// Type definitions for jQuery CLEditor Plugin 1.4.3
// Project: http://premiumsoftware.net/CLEditor
// Definitions by: Jeffery Grajkowski <https://github.com/pushplay/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../jquery/jquery.d.ts" />
/**
* 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;
}
+2 -2
View File
@@ -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: François Guillot <http://fguillot.developpez.com/>
// Definitions by: François Guillot <http://fguillot.developpez.com/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+1
View File
@@ -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;
+2 -2
View File
@@ -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;
+1 -1
View File
@@ -30,7 +30,7 @@ interface KnockoutComputedStatic {
deferUpdates: boolean;
}
interface KnockoutComputedFunctions {
interface KnockoutSubscription {
deferUpdates: boolean;
}
+10 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="knockout.es5.d.ts" />
/// <reference path="knockout.es5.d.ts" />
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();
+16 -1
View File
@@ -8,7 +8,22 @@
interface KnockoutStatic {
track(obj: any, propertyNames?: Array<string>): 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<any>;
valueHasMutated(obj: any, propertyName: string): void;
}
interface KnockoutDefinePropertyOptions {
get(): any;
set?(value: any): void;
}
interface Array<T> {
remove(item): T[];
removeAll(items: T[]): T[];
removeAll(): T[];
destroy(item: T): void;
destroyAll(items: T[]): void;
destroyAll(): void;
}
+8
View File
@@ -19,6 +19,14 @@ interface KnockoutObservable<T> {
syncWith(topic: string, initializeWithLatestValue?: boolean, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservable<T>;
}
interface KnockoutObservableArray<T> {
subscribeTo(topic: string, useLastPublishedValueToInitialize?: boolean, transform?: (val: any) => T): KnockoutObservableArray<T>;
unsubscribeFrom(topic: string): KnockoutObservableArray<T>;
publishOn(topic: string, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservableArray<T>;
stopPublishingOn(topic: string): KnockoutObservableArray<T>;
syncWith(topic: string, initializeWithLatestValue?: boolean, skipInitialPublish?: boolean, equalityComparer?: (newValue: T, oldValue: T) => boolean): KnockoutObservableArray<T>;
}
interface KnockoutStatic {
postbox: KnockoutPostBox;
}
+12
View File
@@ -0,0 +1,12 @@
/// <reference path="knockout.rx.d.ts"/>
var ax: Rx.IObservable<number>;
var ao = ax.toKoObservable();
ao(100);
ao.getSubscriptionsCount();
ao.toObservable();
ao.toObservable("change");
ao.toObservable<Error>("error");
@@ -0,0 +1 @@
""
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for knockout.rx 0.1
// Project: https://github.com/Igorbek/knockout.rx
// Definitions by: Igor Oleinikov <https://github.com/Igorbek>
/// <reference path="../knockout/knockout.d.ts"/>
/// <reference path="../rx.js/rx.js.d.ts"/>
interface KnockoutSubscribableFunctions<T> {
toObservable(event?: string): Rx.IObservable<T>;
toObservable<TEvent>(event: string): Rx.IObservable<TEvent>;
}
interface KnockoutObservableFunctions<T> {
toObservableWithReplyLatest(): Rx.IObservable<T>;
}
interface KnockoutComputedFunctions<T> {
toObservableWithReplyLatest(): Rx.IObservable<T>;
}
declare module Rx {
interface IObservable<T> {
toKoSubscribable(): KnockoutSubscribable<T>;
toKoObservable(initialValue?: T): KnockoutObservable<T>;
}
}
+1
View File
@@ -0,0 +1 @@
""
+4 -4
View File
@@ -117,10 +117,10 @@ interface KnockoutValidationStatic {
addRule<T>(observable: KnockoutObservable<T>, rule: KnockoutValidationRule): KnockoutObservable<T>;
addAnonymousRule(observable: KnockoutObservableBase, ruleObj: KnockoutValidationAnonymousRuleDefinition): void;
addAnonymousRule(observable: KnockoutObservable<any>, ruleObj: KnockoutValidationAnonymousRuleDefinition): void;
insertValidationMessage(element: Element): Element;
parseInputValidationAttributes(element: Element, valueAccessor: () => KnockoutObservableBase): void;
parseInputValidationAttributes(element: Element, valueAccessor: () => KnockoutObservable<any>): void;
rules: KnockoutValidationRuleDefinitions;
@@ -129,12 +129,12 @@ interface KnockoutValidationStatic {
utils: KnockoutValidationUtils;
localize(msgTranslations: any): void;
validateObservable(observable: KnockoutObservableBase): boolean;
validateObservable(observable: KnockoutObservable<any>): boolean;
}
interface KnockoutStatic {
validation: KnockoutValidationStatic;
validatedObservable(initialValue: any): KnockoutObservableBase;
validatedObservable(initialValue: any): KnockoutObservable<any>;
applyBindingsWithValidation(viewModel: any, rootNode?: any, options?: KnockoutValidationConfiguration): void;
}
+22 -12
View File
@@ -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<Array>, 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;
};
+113 -109
View File
@@ -4,25 +4,18 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface KnockoutSubscribableFunctions {
extend(source);
dispose(): void;
peek(): any;
valueHasMutated(): void;
valueWillMutate(): void;
interface KnockoutSubscribableFunctions<T> {
notifySubscribers(valueToWrite: T, event?: string): void;
}
interface KnockoutComputedFunctions extends KnockoutSubscribableFunctions {
getDependenciesCount(): number;
getSubscriptionsCount(): number;
hasWriteFunction(): boolean;
interface KnockoutComputedFunctions<T> {
}
interface KnockoutObservableFunctions extends KnockoutSubscribableFunctions {
interface KnockoutObservableFunctions<T> {
equalityComparer(a: any, b: any): boolean;
}
interface KnockoutObservableArrayFunctions<T> extends KnockoutObservableFunctions {
interface KnockoutObservableArrayFunctions<T> {
// General Array functions
indexOf(searchElement: T, fromIndex?: number): number;
slice(start: number, end?: number): T[];
@@ -34,12 +27,13 @@ interface KnockoutObservableArrayFunctions<T> 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<T> extends KnockoutObservableFunction
}
interface KnockoutSubscribableStatic {
fn: KnockoutSubscribableFunctions;
fn: KnockoutSubscribableFunctions<any>;
new (): KnockoutSubscription;
new <T>(): KnockoutSubscribable<T>;
}
interface KnockoutSubscription extends KnockoutSubscribableFunctions {
subscribe(callback: (newValue: any) => void, target?:any, topic?: string): KnockoutSubscription;
notifySubscribers(valueToWrite, topic?: string);
interface KnockoutSubscription {
dispose(): void;
}
interface KnockoutSubscribable<T> extends KnockoutSubscribableFunctions<T> {
subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription;
subscribe<TEvent>(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription;
extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable<T>;
getSubscriptionsCount(): number;
}
interface KnockoutComputedStatic {
fn: KnockoutComputedFunctions;
fn: KnockoutComputedFunctions<any>;
<T>(): KnockoutComputed<T>;
<T>(func: () => T, context?: any, options?: any): KnockoutComputed<T>;
@@ -68,51 +68,50 @@ interface KnockoutComputedStatic {
(options?: any): KnockoutComputed<any>;
}
interface KnockoutComputed<T> extends KnockoutComputedFunctions {
(): T;
(value: T): void;
interface KnockoutComputed<T> extends KnockoutSubscribable<T>, KnockoutComputedFunctions<T> {
(): 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<T>;
}
interface KnockoutObservableArrayStatic {
fn: KnockoutObservableArrayFunctions<any>;
<T>(value?: T[]): KnockoutObservableArray<T>;
}
interface KnockoutObservableArray<T> extends KnockoutObservableArrayFunctions<T> {
(): T[];
(value: T[]): void;
subscribe(callback: (newValue: T[]) => void, target?:any, topic?: string): KnockoutSubscription;
notifySubscribers(valueToWrite: T[], topic?: string);
interface KnockoutObservableArray<T> extends KnockoutObservable<T[]>, KnockoutObservableArrayFunctions<T> {
extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray<T>;
}
interface KnockoutObservableStatic {
fn: KnockoutObservableFunctions;
fn: KnockoutObservableFunctions<any>;
<T>(value?: T): KnockoutObservable<T>;
}
/** use as method to get/set the value */
interface KnockoutObservableBase extends KnockoutObservableFunctions {
getSubscriptionsCount(): number;
}
interface KnockoutObservable<T> extends KnockoutSubscribable<T>, KnockoutObservableFunctions<T> {
(): T;
(value: T): void;
interface KnockoutObservable<T> 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<T>;
}
interface KnockoutComputedDefine<T> {
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<T>(a: T[], b: T[]): Array<KnockoutArrayChange<T>>;
arrayForEach<T>(array: T[], action: (item: T) => void): void;
arrayForEach(array: any[], action: (any) => void ): void;
arrayIndexOf(array: any[], item: any): number;
arrayIndexOf<T>(array: T[], item: T): number;
arrayFirst<T>(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<T>(array: T[]): T[];
arrayGetDistinctValues(array: any[]): any[];
arrayMap<T, U>(array: T[], mapping: (item: T) => U): U[];
arrayMap(array: any[], mapping: (item) => any): any[];
arrayFilter<T>(array: T[], predicate: (item: T) => boolean): T[];
arrayFilter(array: any[], predicate: (item) => boolean): any[];
arrayPushAll<T>(array: T[], valuesToPush: T[]): T[];
arrayPushAll(array: any[], valuesToPush: any[]): any[];
arrayPushAll<T>(array: KnockoutObservableArray<T>, valuesToPush: T[]): T[];
arrayPushAll(array: KnockoutObservableArray<any>, 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<T> {
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<Array>, options: Object, targetNode: Node, parentBindingContext: KnockoutBindingContext): any;
renderTemplateForEach(template: any, arrayOrObservableArray: KnockoutObservable<Array>, 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;
};
}
+3510 -2455
View File
File diff suppressed because it is too large Load Diff
+929
View File
@@ -0,0 +1,929 @@
/// <reference path="lodash.d.ts" />
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<string>>_('test');
result = <_.LoDashWrapper<number>>_(1);
result = <_.LoDashWrapper<boolean>>_(true);
result = <_.LoDashArrayWrapper<string>>_(['test1', 'test2']);
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_({'key1': 'test1', 'key2': 'test2'});
result = <_.LoDashWrapper<string>>_.chain('test');
result = <_.LoDashWrapper<string>>_('test').chain();
result = <_.LoDashWrapper<number>>_.chain(1);
result = <_.LoDashWrapper<number>>_(1).chain();
result = <_.LoDashWrapper<boolean>>_.chain(true);
result = <_.LoDashWrapper<boolean>>_(true).chain();
result = <_.LoDashArrayWrapper<string>>_.chain(['test1', 'test2']);
result = <_.LoDashArrayWrapper<string>>_(['test1', 'test2']).chain();
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_.chain({'key1': 'test1', 'key2': 'test2'});
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_({'key1': 'test1', 'key2': 'test2'}).chain();
//Wrapped array shortcut methods
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).concat(5, 6);
result = <_.LoDashWrapper<string>>_([1, 2, 3, 4]).join(',');
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).pop();
_([1, 2, 3, 4]).push(5, 6, 7);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).reverse();
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).shift();
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).slice(1, 2);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).slice(2);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).sort((a, b) => 1);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).splice(1);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).splice(1, 2, 5, 6);
result = <_.LoDashWrapper<number>>_([1, 2, 3, 4]).unshift(5, 6);
result = <number[]>_.tap([1, 2, 3, 4], function(array) { console.log(array); });
result = <_.LoDashWrapper<string>>_('test').tap(function(value) { console.log(value); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).tap(function(array) { console.log(array); });
result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_({'key1': 'test1', 'key2': 'test2'}).tap(function(array) { console.log(array); });
result = <string>_('test').toString();
result = <string>_([1, 2, 3]).toString();
result = <string>_({'key1': 'test1', 'key2': 'test2'}).toString();
result = <string>_('test').valueOf();
result = <number[]>_([1, 2, 3]).valueOf();
result = <_.Dictionary<string>>_({'key1': 'test1', 'key2': 'test2'}).valueOf();
result = <string>_('test').value();
result = <number[]>_([1, 2, 3]).value();
result = <_.Dictionary<string>>_({'key1': 'test1', 'key2': 'test2'}).value();
// /*************
// * Arrays *
// *************/
result = <any[]>_.compact([0, 1, false, 2, '', 3]);
result = <_.LoDashArrayWrapper<any>>_([0, 1, false, 2, '', 3]).compact();
result = <number[]>_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4, 5]).difference([5, 2, 10]);
result = <number[]>_.rest([1, 2, 3]);
result = <number[]>_.rest([1, 2, 3], 2);
result = <number[]>_.rest([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.rest(foodsOrganic, 'test');
result = <IFoodType[]>_.rest(foodsType, { 'type': 'value' });
result = <number[]>_.drop([1, 2, 3]);
result = <number[]>_.drop([1, 2, 3], 2);
result = <number[]>_.drop([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.drop(foodsOrganic, 'test');
result = <IFoodType[]>_.drop(foodsType, { 'type': 'value' });
result = <number[]>_.tail([1, 2, 3])
result = <number[]>_.tail([1, 2, 3], 2)
result = <number[]>_.tail([1, 2, 3], (num) => num < 3)
result = <IFoodOrganic[]>_.tail(foodsOrganic, 'test')
result = <IFoodType[]> _.tail(foodsType, { 'type': 'value' })
result = <number>_.findIndex(['apple', 'banana', 'beet'], function(f) {
return /^b/.test(f);
});
result = <number>_.findIndex(['apple', 'banana', 'beet'], 'apple');
result = <number>_.findIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple'});
result = <number>_.findLastIndex(['apple', 'banana', 'beet'], function(f: string) {
return /^b/.test(f);
});
result = <number>_.findLastIndex(['apple', 'banana', 'beet'], 'apple');
result = <number>_.findLastIndex([{ food: 'apple' }, { food: 'banana' }, { food: 'beet' }], { food: 'apple'});
result = <number>_.first([1, 2, 3]);
result = <number[]>_.first([1, 2, 3], 2);
result = <number[]>_.first([1, 2, 3], function(num) {
return num < 3;
});
result = <IFoodOrganic[]>_.first(foodsOrganic, 'organic');
result = <IFoodType[]>_.first(foodsType, { 'type': 'fruit' });
result = <number>_.head([1, 2, 3]);
result = <number[]>_.head([1, 2, 3], 2);
result = <number[]>_.head([1, 2, 3], function(num) {
return num < 3;
});
result = <IFoodOrganic[]>_.head(foodsOrganic, 'organic');
result = <IFoodType[]>_.head(foodsType, { 'type': 'fruit' });
result = <number>_.take([1, 2, 3]);
result = <number[]>_.take([1, 2, 3], 2);
result = <number[]>_.take([1, 2, 3], (num) => num < 3);
result = <IFoodOrganic[]>_.take(foodsOrganic, 'organic');
result = <IFoodType[]>_.take(foodsType, { 'type': 'fruit' });
result = <number[]>_.flatten([1, [2], [3, [[4]]]]);
result = <any[]>_.flatten([1, [2], [3, [[4]]]], true);
var result: any
result = <string[]>_.flatten(stoogesQuotes, 'quotes');
result = <_.LoDashArrayWrapper<number>>_([1, [2], [3, [[4]]]]).flatten();
result = <_.LoDashArrayWrapper<number>>_([1, [2], [3, [[4]]]]).flatten(true);
result = <_.LoDashArrayWrapper<string>>_(stoogesQuotes).flatten('quotes');
result = <number>_.indexOf([1, 2, 3, 1, 2, 3], 2);
result = <number>_.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
result = <number>_.indexOf([1, 1, 2, 2, 3, 3], 2, true);
result = <number[]>_.initial([1, 2, 3]);
result = <number[]>_.initial([1, 2, 3], 2);
result = <number[]>_.initial([1, 2, 3], function(num) {
return num > 1;
});
result = <IFoodOrganic[]>_.initial(foodsOrganic, 'organic');
result = <IFoodType[]>_.initial(foodsType, { 'type': 'vegetable' });
result = <number[]>_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
result = <number>_.last([1, 2, 3]);
result = <number[]>_.last([1, 2, 3], 2);
result = <number[]>_.last([1, 2, 3], function(num) {
return num > 1;
});
result = <IFoodOrganic[]>_.last(foodsOrganic, 'organic');
result = <IFoodType[]>_.last(foodsType, { 'type': 'vegetable' });
result = <number>_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
result = <number>_.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 = <any[]>_.pull([1, 2, 3, 1, 2, 3], 2, 3);
result = <number[]>_.range(10);
result = <number[]>_.range(1, 11);
result = <number[]>_.range(0, 30, 5);
result = <number[]>_.range(0, -10, -1);
result = <number[]>_.range(1, 4, 0);
result = <number[]>_.range(0);
result = <number[]>_.remove([1, 2, 3, 4, 5, 6], function(num: number) { return num % 2 == 0; });
result = <IFoodOrganic[]>_.remove(foodsOrganic, 'organic');
result = <IFoodType[]>_.remove(foodsType, { 'type': 'vegetable'});
result = <number>_.sortedIndex([20, 30, 50], 40);
result = <number>_.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
var sortedIndexDict = {
'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
};
result = <number>_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return sortedIndexDict.wordToNumber[word];
});
result = <number>_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
return this.wordToNumber[word];
}, sortedIndexDict);
result = <number[]>_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
result = <number[]>_.uniq([1, 2, 1, 3, 1]);
result = <number[]>_.uniq([1, 1, 2, 2, 3], true);
result = <string[]>_.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) {
return letter.toLowerCase();
});
result = <number[]>_.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 = <number[]>_.unique([1, 2, 1, 3, 1]);
result = <number[]>_.unique([1, 1, 2, 2, 3], true);
result = <string[]>_.unique(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) {
return letter.toLowerCase();
});
result = <number[]>_.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 = <number[]>_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
result = <any[][]>_.zip(['moe', 'larry'], [30, 40], [true, false]);
result = <any[][]>_.unzip(['moe', 'larry'], [30, 40], [true, false]);
// /* *************
// * Collections *
// ************* */
result = <string[]>_.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
result = <string[]>_.at(['moe', 'larry', 'curly'], 0, 2);
result = <boolean>_.contains([1, 2, 3], 1);
result = <boolean>_.contains([1, 2, 3], 1, 2);
result = <boolean>_.contains({ 'name': 'moe', 'age': 40 }, 'moe');
result = <boolean>_.contains('curly', 'ur');
result = <boolean>_.include([1, 2, 3], 1);
result = <boolean>_.include([1, 2, 3], 1, 2);
result = <boolean>_.include({ 'name': 'moe', 'age': 40 }, 'moe');
result = <boolean>_.include('curly', 'ur');
result = <_.Dictionary<number>>_.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
result = <_.Dictionary<number>>_.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
result = <_.Dictionary<number>>_.countBy(['one', 'two', 'three'], 'length');
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_([4.3, 6.1, 6.4]).countBy(function(num) { return Math.floor(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_([4.3, 6.1, 6.4]).countBy(function(num) { return this.floor(num); }, Math);
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_(['one', 'two', 'three']).countBy('length');
result = <boolean>_.every([true, 1, null, 'yes'], Boolean);
result = <boolean>_.every(stoogesAges, 'age');
result = <boolean>_.every(stoogesAges, { 'age': 50 });
result = <boolean>_.all([true, 1, null, 'yes'], Boolean);
result = <boolean>_.all(stoogesAges, 'age');
result = <boolean>_.all(stoogesAges, { 'age': 50 });
result = <number[]>_.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.filter(foodsCombined, 'organic');
result = <IFoodCombined[]>_.filter(foodsCombined, { 'type': 'fruit' });
result = <number[]>_([1, 2, 3, 4, 5, 6]).filter(function(num) { return num % 2 == 0; });
result = <IFoodCombined[]>_(foodsCombined).filter('organic');
result = <IFoodCombined[]>_(foodsCombined).filter({ 'type': 'fruit' });
result = <number[]>_.select([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.select(foodsCombined, 'organic');
result = <IFoodCombined[]>_.select(foodsCombined, { 'type': 'fruit' });
result = <number[]>_([1, 2, 3, 4, 5, 6]).select(function(num) { return num % 2 == 0; });
result = <IFoodCombined[]>_(foodsCombined).select('organic');
result = <IFoodCombined[]>_(foodsCombined).select({ 'type': 'fruit' });
result = <number>_.find([1, 2, 3, 4], function(num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.find(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.find(foodsCombined, 'organic');
result = <number>_.detect([1, 2, 3, 4], function(num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.detect(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.detect(foodsCombined, 'organic');
result = <number>_.findWhere([1, 2, 3, 4], function(num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.findWhere(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.findWhere(foodsCombined, 'organic');
result = <number>_.findLast([1, 2, 3, 4], function(num) {
return num % 2 == 0;
});
result = <IFoodCombined>_.findLast(foodsCombined, { 'type': 'vegetable' });
result = <IFoodCombined>_.findLast(foodsCombined, 'organic');
result = <number[]>_.forEach([1, 2, 3], function(num) { console.log(num); });
result = <_.Dictionary<number>>_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
result = <number[]>_.each([1, 2, 3], function(num) { console.log(num); });
result = <_.Dictionary<number>>_.each({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).forEach(function(num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_({ 'one': 1, 'two': 2, 'three': 3 }).forEach(function(num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).each(function(num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_({ 'one': 1, 'two': 2, 'three': 3 }).each(function(num) { console.log(num); });
result = <number[]>_.forEachRight([1, 2, 3], function(num) { console.log(num); });
result = <_.Dictionary<number>>_.forEachRight({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
result = <number[]>_.eachRight([1, 2, 3], function(num) { console.log(num); });
result = <_.Dictionary<number>>_.eachRight({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).forEachRight(function(num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_({ 'one': 1, 'two': 2, 'three': 3 }).forEachRight(function(num) { console.log(num); });
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3]).eachRight(function(num) { console.log(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number>>>_({ 'one': 1, 'two': 2, 'three': 3 }).eachRight(function(num) { console.log(num); });
result = <_.Dictionary<number[]>>_.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
result = <_.Dictionary<number[]>>_.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
result = <_.Dictionary<string[]>>_.groupBy(['one', 'two', 'three'], 'length');
result = <_.LoDashObjectWrapper<_.Dictionary<number[]>>>_([4.2, 6.1, 6.4]).groupBy(function(num) { return Math.floor(num); });
result = <_.LoDashObjectWrapper<_.Dictionary<number[]>>>_([4.2, 6.1, 6.4]).groupBy(function(num) { return this.floor(num); }, Math);
result = <_.LoDashObjectWrapper<_.Dictionary<string[]>>>_(['one', 'two', 'three']).groupBy('length');
result = <_.Dictionary<IKey>>_.indexBy(keys, 'dir');
result = <_.Dictionary<IKey>>_.indexBy(keys, function(key) { return String.fromCharCode(key.code); });
result = <_.Dictionary<IKey>>_.indexBy(keys, function(key) { this.fromCharCode(key.code); }, String);
result = <any[]>_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
result = <any[]>_.invoke([123, 456], String.prototype.split, '');
result = <any[]>_.map([1, 2, 3], function(num) { return num * 3; });
result = <any[]>_.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
result = <any[]>_.map(stoogesAges, 'name');
result = <any[]>_.collect([1, 2, 3], function(num) { return num * 3; });
result = <any[]>_.collect({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
result = <any[]>_.collect(stoogesAges, 'name');
result = <number>_.max([4, 2, 8, 6]);
result = <IStoogesAge>_.max(stoogesAges, function(stooge) { return stooge.age; });
result = <IStoogesAge>_.max(stoogesAges, 'age');
result = <number>_.min([4, 2, 8, 6]);
result = <IStoogesAge>_.min(stoogesAges, function(stooge) { return stooge.age; });
result = <IStoogesAge>_.min(stoogesAges, 'age');
result = <string[]>_.pluck(stoogesAges, 'name');
result = <number>_.reduce<number, number>([1, 2, 3], function(sum: number, num: number) {
return sum + num;
});
result = <any>_.reduce<number, any>({ 'a': 1, 'b': 2, 'c': 3 }, function(r: any, num: number, key: string) {
r[key] = num * 3;
return r;
}, {});
result = <any>_.foldl([1, 2, 3], function(sum: number, num: number) {
return sum + num;
});
result = <any>_.foldl({ 'a': 1, 'b': 2, 'c': 3 }, function(r: any, num: number, key: string) {
r[key] = num * 3;
return r;
}, {});
result = <any>_.inject([1, 2, 3], function(sum: number, num: number) {
return sum + num;
});
result = <any>_.inject({ 'a': 1, 'b': 2, 'c': 3 }, function(r: any, num: number, key: string) {
r[key] = num * 3;
return r;
}, {});
result = <any>_.reduceRight([[0, 1], [2, 3], [4, 5]], function(a: number[], b: number[]) { return a.concat(b); }, []);
result = <any>_.foldr([[0, 1], [2, 3], [4, 5]], function(a: number[], b: number[]) { return a.concat(b); }, []);
result = <number[]>_.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
result = <IFoodCombined[]>_.reject(foodsCombined, 'organic');
result = <IFoodCombined[]>_.reject(foodsCombined, { 'type': 'fruit' });
result = <number>_.sample([1, 2, 3, 4]);
result = <number[]>_.sample([1, 2, 3, 4], 2);
result = <number[]>_.shuffle([1, 2, 3, 4, 5, 6]);
result = <number>_.size([1, 2]);
result = <number>_.size({ 'one': 1, 'two': 2, 'three': 3 });
result = <number>_.size('curly');
result = <boolean>_.some([null, 0, 'yes', false], Boolean);
result = <boolean>_.some(foodsCombined, 'organic');
result = <boolean>_.some(foodsCombined, { 'type': 'meat' });
result = <boolean>_.any([null, 0, 'yes', false], Boolean);
result = <boolean>_.any(foodsCombined, 'organic');
result = <boolean>_.any(foodsCombined, { 'type': 'meat' });
result = <number[]>_.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
result = <number[]>_.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
result = <string[]>_.sortBy(['banana', 'strawberry', 'apple'], 'length');
(function(a: any, b: any, c: any, d: any){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
result = <IStoogesCombined[]>_.where(stoogesCombined, { 'age': 40 });
result = <IStoogesCombined[]>_.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 = <Function>_.compose(greet, format);
result = <_.LoDashObjectWrapper<Function>>_(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 = <Function>_.curry(function(a, b, c) {
console.log(a + b + c);
});
result = <_.LoDashObjectWrapper<Function>>_(function(a, b, c) {
console.log(a + b + c);
}).curry();
declare var source: any;
result = <Function>_.debounce(function() {}, 150);
jQuery('#postbox').on('click', <Function>_.debounce(function() {}, 300, {
'leading': true,
'trailing': false
}));
source.addEventListener('message', <Function>_.debounce(function() {}, 250, {
'maxWait': 1000
}), false);
result = <_.LoDashObjectWrapper<Function>>_(function() {}).debounce(150);
jQuery('#postbox').on('click', <_.LoDashObjectWrapper<Function>>_(function() {}).debounce(300, {
'leading': true,
'trailing': false
}));
source.addEventListener('message', <_.LoDashObjectWrapper<Function>>_(function() {}).debounce(250, {
'maxWait': 1000
}), false);
result = <number>_.defer(function() { console.log('deferred'); });
result = <_.LoDashWrapper<number>>_(function() { console.log('deferred'); }).defer();
var log = _.bind(console.log, console);
result = <number>_.delay(log, 1000, 'logged later');
result = <_.LoDashWrapper<number>>_(log).delay(1000, 'logged later');
var fibonacci = <Function>_.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 = <Function>_.memoize(function(name: string) { return data[name]; }, _.identity);
stooge('curly');
stooge['cache']['curly'].name = 'jerome';
stooge('curly');
var initialize = <Function>_.once(function(){ });
initialize();
initialize();
var greetPartial = function(greeting: string, name: string) { return greeting + ' ' + name; };
var hi = <Function>_.partial(greetPartial, 'hi');
hi('moe');
var defaultsDeep = <Function>_.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 = <any>_.assign({ 'name': 'moe' }, { 'age': 40 });
result = <any>_.assign({ 'name': 'moe' }, { 'age': 40 }, function(a: any, b: any) {
return typeof a == 'undefined' ? b : a;
});
result = <_.LoDashObjectWrapper<any>>_({ 'name': 'moe' }).assign({ 'age': 40 });
result = <_.LoDashObjectWrapper<any>>_({ 'name': 'moe' }).assign({ 'age': 40 }, function(a: any, b: any) {
return typeof a == 'undefined' ? b : a;
});
result = <any>_.extend({ 'name': 'moe' }, { 'age': 40 });
result = <any>_.extend({ 'name': 'moe' }, { 'age': 40 }, function(a: any, b: any) {
return typeof a == 'undefined' ? b : a;
});
result = <_.LoDashObjectWrapper<any>>_({ 'name': 'moe' }).extend({ 'age': 40 });
result = <_.LoDashObjectWrapper<any>>_({ 'name': 'moe' }).extend({ 'age': 40 }, function(a: any, b: any) {
return typeof a == 'undefined' ? b : a;
});
var result = <any>_.clone(stoogesAges);
var result = <any>_.clone(stoogesAges, true);
var result = <any>_.clone(stoogesAges, true, function(value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
});
var result = <any>_.cloneDeep(stoogesAges);
var result = <any>_.cloneDeep(stoogesAges, function(value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
});
var foodDefaults = { 'name': 'apple' };
result = <any>_.defaults(foodDefaults, { 'name': 'banana', 'type': 'fruit' });
result = <any>_(foodDefaults).defaults({ 'name': 'banana', 'type': 'fruit' });
result = <string>_.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
return num % 2 == 0;
});
result = <string>_.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
return num % 2 == 1;
});
result = <any>_.forIn(new Dog('Dagny'), function(value, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<any>>_(new Dog('Dagny')).forIn(function(value, key) {
console.log(key);
});
result = <any>_.forInRight(new Dog('Dagny'), function(value, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<any>>_(new Dog('Dagny')).forInRight(function(value, key) {
console.log(key);
});
result = <any>_.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<any>>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwn(function(num, key) {
console.log(key);
});
result = <any>_.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
console.log(key);
});
result = <_.LoDashObjectWrapper<any>>_({ '0': 'zero', '1': 'one', 'length': 2 }).forOwnRight(function(num, key) {
console.log(key);
});
result = <string[]>_.functions(_);
result = <string[]>_.methods(_);
result = <_.LoDashArrayWrapper<string>>_(_).functions();
result = <_.LoDashArrayWrapper<string>>_(_).methods();
result = <boolean>_.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
result = <any>_.invert({ 'first': 'moe', 'second': 'larry' });
(function(...args: any[]) { return <boolean>_.isArguments(arguments); })(1, 2, 3);
(function () { return <boolean>_.isArray(arguments); })();
result = <boolean>_.isArray([1, 2, 3]);
result = <boolean>_.isBoolean(null);
result = <boolean>_.isDate(new Date());
result = <boolean>_.isElement(document.body);
result = <boolean>_.isEmpty([1, 2, 3]);
result = <boolean>_.isEmpty({});
result = <boolean>_.isEmpty('');
var moe = { 'name': 'moe', 'age': 40 };
var copy = { 'name': 'moe', 'age': 40 };
result = <boolean>_.isEqual(moe, copy);
var words = ['hello', 'goodbye'];
var otherWords = ['hi', 'goodbye'];
result = <boolean>_.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 = <boolean>_.isFinite(-101);
result = <boolean>_.isFinite('10');
result = <boolean>_.isFinite(true);
result = <boolean>_.isFinite('');
result = <boolean>_.isFinite(Infinity);
result = <boolean>_.isFunction(_);
result = <boolean>_.isNaN(NaN);
result = <boolean>_.isNaN(new Number(NaN));
result = <boolean>_.isNaN(undefined);
result = <boolean>_.isNull(null);
result = <boolean>_.isNull(undefined);
result = <boolean>_.isNumber(8.4 * 5);
result = <boolean>_.isObject({});
result = <boolean>_.isObject([1, 2, 3]);
result = <boolean>_.isObject(1);
class Stooge {
constructor(
public name: string,
public age: number
) {}
}
result = <boolean>_.isPlainObject(new Stooge('moe', 40));
result = <boolean>_.isPlainObject([1, 2, 3]);
result = <boolean>_.isPlainObject({ 'name': 'moe', 'age': 40 });
result = <boolean>_.isRegExp(/moe/);
result = <boolean>_.isString('moe');
result = <boolean>_.isUndefined(void 0);
result = <string[]>_.keys({ 'one': 1, 'two': 2, 'three': 3 });
var mergeNames = {
'stooges': [
{ 'name': 'moe' },
{ 'name': 'larry' }
]
};
var mergeAges = {
'stooges': [
{ 'age': 40 },
{ 'age': 50 }
]
};
result = <any>_.merge(mergeNames, mergeAges);
var mergeFood = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var mergeOtherFood = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
result = <any>_.merge(mergeFood, mergeOtherFood, function(a: any, b: any) {
return _.isArray(a) ? a.concat(b) : undefined;
});
result = <any>_.omit({ 'name': 'moe', 'age': 40 }, 'age');
result = <any>_.omit({ 'name': 'moe', 'age': 40 }, ['age']);
result = <any>_.omit({ 'name': 'moe', 'age': 40 }, function(value) {
return typeof value == 'number';
});
result = <any[][]>_.pairs({ 'moe': 30, 'larry': 40 });
result = <any>_.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
result = <any>_.pick({ 'name': 'moe', '_userid': 'moe1' }, ['name']);
result = <any>_.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) {
return key.charAt(0) != '_';
});
result = <any>_.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 = <any>_.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(r: any, num: number, key: string) {
r[key] = num * 3;
});
result = <any[]>_.values({ 'one': 1, 'two': 2, 'three': 3 });
/**********
* Utilities *
***********/
result = <string>_.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 = <typeof _>_.noConflict();
result = <number>_.parseInt('08');
result = <number>_.random(0, 5);
result = <number>_.random(5);
result = <number>_.random(5, true);
result = <number>_.random(1.2, 5.2);
result = <number>_.random(0, 5, true);
var object = {
'cheese': 'crumpets',
'stuff': function() {
return 'nonsense';
}
};
result = <any>_.result(object, 'cheese');
result = <any>_.result(object, 'stuff');
var tempObject = {};
result = <typeof _>_.runInContext(tempObject);
result = <_.TemplateExecutor>_.template('hello <%= name %>');
result = <string>_.template('<b><%- value %></b>', { 'value': '<script>' });
var listTemplate = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>';
result = <string>_.template(listTemplate, { 'people': ['moe', 'larry'] });
result = <string>_.template('hello ${ name }', { 'name': 'curly' });
result = <string>_.template('<% print("hello " + name); %>!', { 'name': 'larry' });
var listTemplate = '<% $.each(people, function(name) { %><li><%- name %></li><% }); %>';
result = <string>_.template(listTemplate, { 'people': ['moe', 'larry'] }, { 'imports': { '$': jQuery } });
result = <_.TemplateExecutor>_.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
result = <_.TemplateExecutor>_.template('hi <%= data.name %>!', null, { 'variable': 'data' });
result = <string>(<_.TemplateExecutor>result).source;
class Mage {
public castSpell(n: number) {
return n;
}
public cast(n: number) {
return n;
}
}
var mage = new Mage();
result = <any[]>_.times(3, _.partial(_.random, 1, 6));
result = <any[]>_.times(3, function(n: number) { mage.castSpell(n); });
result = <any[]>_.times(3, function(n: number) { this.cast(n); }, mage);
result = <string>_.unescape('Moe, Larry &amp; Curly');
result = <string>_.uniqueId('contact_');
result = <string>_.uniqueId();
/**********
* Utilities *
***********/
result = <string>_.VERSION;
result = <_.Support>_.support;
result = <_.TemplateSettings>_.templateSettings;
+4045
View File
File diff suppressed because it is too large Load Diff
+2639
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
""
+84 -1
View File
@@ -1,5 +1,7 @@
/// <reference path="mocha.d.ts" />
var mocha: Mocha;
function test_describe() {
describe('something', () => { });
@@ -49,4 +51,85 @@ function test_afterEach() {
afterEach(() => { });
afterEach((done) => { done(); });
}
}
function test_reporter_string(){
mocha.reporter('html');
}
function test_reporter_function(){
mocha.reporter(function(){});
}
function test_setup_slow_option(){
mocha.setup({slow: 25});
}
function test_setup_timeout_option(){
mocha.setup({timeout: 25});
}
function test_setup_globals_option(){
mocha.setup({globals: ['mocha']});
}
function test_setup_ui_option(){
mocha.setup({ui: 'bdd'});
}
function test_setup_reporter_string_option(){
mocha.setup({reporter: 'html'});
}
function test_setup_reporter_function_option(){
mocha.setup({reporter: function(){}});
}
function test_setup_bail_option(){
mocha.setup({bail: false});
}
function test_setup_ignore_leaks_option(){
mocha.setup({ignoreLeaks: false});
}
function test_setup_grep_string_option(){
mocha.setup({grep: "describe"});
}
function test_setup_grep_regex_option(){
mocha.setup({grep: new RegExp('describe')});
}
function test_setup_grep_regex_literal_option(){
mocha.setup({grep: /(expect|should)/i });
}
function test_setup_all_options(){
mocha.setup({
slow: 25,
timeout: 25,
ui: 'bdd',
globals: ['mocha'],
reporter: 'html',
bail: true,
ignoreLeaks: true,
grep: 'test'
});
}
function test_run(){
mocha.run(function(){})
}
function test_growl(){
mocha.growl();
}
function test_chaining(){
mocha
.setup({slow:25})
.growl()
.reporter('html')
.reporter(function(){});
}
+50 -12
View File
@@ -4,14 +4,52 @@
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
interface Mocha {
setup(options: MochaSetupOptions): void;
run(callback: () => void): void;
// Setup mocha with the given setting options.
setup(options: MochaSetupOptions): Mocha;
//Run tests and invoke `fn()` when complete.
run(callback?: () => void): void;
// Set reporter as function
reporter(reporter: () => void): Mocha;
// Set reporter, defaults to "dot"
reporter(reporter: string): Mocha;
// Enable growl support.
growl(): Mocha
}
interface MochaSetupOptions {
slow: number;
timeout: number;
ui: string;
//milliseconds to wait before considering a test slow
slow?: number;
// timeout in milliseconds
timeout?: number;
// ui name "bdd", "tdd", "exports" etc
ui?: string;
//array of accepted globals
globals?: Array;
// reporter instance (function or string), defaults to `mocha.reporters.Dot`
reporter?: any;
// bail on the first test failure
bail?: Boolean;
// ignore global leaks
ignoreLeaks?: Boolean;
// grep string or regexp to filter tests with
grep?: any;
}
declare module mocha {
interface Done {
(error?: Error): void;
}
}
declare var describe : {
@@ -23,27 +61,27 @@ declare var describe : {
declare var it: {
(expectation: string, assertion?: () => void): void;
(expectation: string, assertion?: (done: (error?: Error) => void) => void): void;
(expectation: string, assertion?: (done: mocha.Done) => void): void;
only(expectation: string, assertion?: () => void): void;
only(expectation: string, assertion?: (done: (error?: Error) => void) => void): void;
only(expectation: string, assertion?: (done: mocha.Done) => void): void;
skip(expectation: string, assertion?: () => void): void;
skip(expectation: string, assertion?: (done: (error?: Error) => void) => void): void;
skip(expectation: string, assertion?: (done: mocha.Done) => void): void;
timeout(ms: number): void;
};
declare function before(action: () => void): void;
declare function before(action: (done: (error?: Error) => void) => void): void;
declare function before(action: (done: mocha.Done) => void): void;
declare function after(action: () => void): void;
declare function after(action: (done: (error?: Error) => void) => void): void;
declare function after(action: (done: mocha.Done) => void): void;
declare function beforeEach(action: () => void): void;
declare function beforeEach(action: (done: (error?: Error) => void) => void): void;
declare function beforeEach(action: (done: mocha.Done) => void): void;
declare function afterEach(action: () => void): void;
declare function afterEach(action: (done: (error?: Error) => void) => void): void;
declare function afterEach(action: (done: mocha.Done) => void): void;
+4
View File
@@ -47,4 +47,8 @@ $(function () {
var elem;
Modernizr.hasEvent('gesturestart', elem);
if (!Modernizr.autofocus) {
$("[autofocus]").focus();
}
});
+8 -7
View File
@@ -47,6 +47,7 @@ interface InputTypesboolean {
}
interface ModernizrStatic {
autofocus: boolean;
fontface: boolean;
backgroundsize: boolean;
borderimage: boolean;
@@ -91,9 +92,9 @@ interface ModernizrStatic {
touch: boolean;
webgl: boolean;
load(resources: Array);
load(resourceObject: any);
load(resourceString: string);
load(resources: Array): void;
load(resourceObject: any): void;
load(resourceString: string): void;
prefixed(): boolean;
prefixed(property: string): boolean;
@@ -101,11 +102,11 @@ interface ModernizrStatic {
mq(mediaQuery: string): boolean;
addTest(feature: string, test: () => any);
addTest(feature: string, test: boolean);
addTest(feature: any);
addTest(feature: string, test: () => any): void;
addTest(feature: string, test: boolean): void;
addTest(feature: any): void;
testStyles(rule: string, callback: (element, rule) => void, nodes?: number, testnames?: string[]): boolean;
testStyles(rule: string, callback: (element: HTMLDivElement, rule: string) => void, nodes?: number, testnames?: string[]): boolean;
testProp(property: string): boolean;
testAllProps(property: string, prefix?: string): boolean;
testAllProps(property: string, obj: any, element: any): boolean;
+1 -1
View File
@@ -156,7 +156,7 @@ interface NodeBuffer {
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
length: number;
copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): void;
copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
slice(start?: number, end?: number): NodeBuffer;
readUInt8(offset: number, noAsset?: boolean): number;
readUInt16LE(offset: number, noAssert?: boolean): number;
+19 -19
View File
@@ -68,14 +68,14 @@ declare var Buffer: {
************************************************/
interface EventEmitter {
addListener(event: string, listener: Function): void;
on(event: string, listener: Function): void;
once(event: string, listener: Function): void;
removeListener(event: string, listener: Function): void;
removeAllListeners(event?: string): 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): void;
emit(event: string, arg1?: any, arg2?: any): boolean;
}
interface WritableStream extends EventEmitter {
@@ -161,7 +161,7 @@ interface NodeBuffer {
write(string: string, offset?: number, length?: number, encoding?: string): number;
toString(encoding?: string, start?: number, end?: number): string;
length: number;
copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): void;
copy(targetBuffer: NodeBuffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
slice(start?: number, end?: number): NodeBuffer;
readUInt8(offset: number, noAsset?: boolean): number;
readUInt16LE(offset: number, noAssert?: boolean): number;
@@ -209,25 +209,25 @@ declare module "querystring" {
declare module "events" {
export interface NodeEventEmitter {
addListener(event: string, listener: Function): void;
on(event: string, listener: Function): any;
once(event: string, listener: Function): void;
removeListener(event: string, listener: Function): void;
removeAllListeners(event?: string): void;
addListener(event: string, listener: Function): NodeEventEmitter;
on(event: string, listener: Function): NodeEventEmitter;
once(event: string, listener: Function): NodeEventEmitter;
removeListener(event: string, listener: Function): NodeEventEmitter;
removeAllListeners(event?: string): NodeEventEmitter;
setMaxListeners(n: number): void;
listeners(event: string): Function[];
emit(event: string, arg1?: any, arg2?: any): void;
emit(event: string, arg1?: any, arg2?: any): boolean;
}
export class EventEmitter implements NodeEventEmitter {
addListener(event: string, listener: Function): void;
on(event: string, listener: Function): any;
once(event: string, listener: Function): void;
removeListener(event: string, listener: Function): void;
removeAllListeners(event?: string): 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): void;
emit(event: string, arg1?: any, arg2?: any): boolean;
}
}
+32
View File
@@ -0,0 +1,32 @@
///<reference path="./NProgress.d.ts"/>
function test_basics() {
NProgress.start();
NProgress.inc();
NProgress.done();
NProgress.set(0.5);
var status = NProgress.status;
var version = NProgress.version;
}
function test_configuration() {
NProgress.configure({
speed: 0.3
});
NProgress.configure({
trickle: false
});
NProgress.configure({
ease: 'ease',
minimum: 0.09,
showSpinner: false,
speed: 420,
template: "<div>blah</div>",
trickle: false,
trickleRate: 0.42,
trickleSpeed: 42
});
}
+105
View File
@@ -0,0 +1,105 @@
// Type definitions for NProgress
// Project: https://github.com/rstacruz/nprogress
// Definitions by: Judah Gabriel Himango <http://debuggerdotbreak.wordpress.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface NProgressStatic {
/**
* Shows the progress bar and begins trickling progress.
* @returns {NProgressConfigureOptions} The current NProgress object, useful for chaining.
*/
start(): NProgressStatic;
/**
* Finishes loading by transitioning it to 100%, then fading out.
* @param {boolean} forceShow Forces the progress bar to show, even if it's not being shown. (The default behavior is that .done() will not do anything if .start() isn't called.)
* @returns {NProgressConfigureOptions} The current NProgress object, useful for chaining.
*/
done(forceShow?: boolean): NProgressStatic;
/**
* Increments the progress bar with a random amount. This will never get to 100%: use it for every image load (or similar).
* @returns {NProgressConfigureOptions} The current NProgress object, useful for chaining.
*/
inc(): NProgressStatic;
/**
* Removes the progress indicator.
*/
remove(): void;
/**
* Sets the progress percentage.
* @param {number} progressPercent A number between 0.0 and 1.0 that represents the progress percentage.
* @returns {NProgressConfigureOptions} The current NProgress object, useful for chaining.
*/
set(progressPercent: number): NProgressStatic;
/**
* Configures the progress indicator.
* @param {NProgressConfigureOptions} options An object containing the configuration options.
* @returns {NProgressConfigureOptions} The current NProgress object, useful for chaining.
*/
configure(options: NProgressConfigureOptions): NProgressStatic;
/**
* Gets the NProgress version.
*/
version: string;
/**
* Gets the status. If started, it will be the last progress number set.
*/
status: any;
/**
* Gets whether progress has been started.
* @returns {boolean} Whether the progress has started.
*/
isStarted(): boolean;
}
interface NProgressConfigureOptions {
/**
* The minimum progress percentage. Default is 0.08.
*/
minimum?: number;
/**
* How much to increase per trickle. Example: .02. Default is true.
*/
trickleRate?: number;
/**
* How often to trickle, in milliseconds. Default is 800.
*/
trickleSpeed?: number;
/**
* Whether to show the spinner. Defaults to true. Default is true.
*/
showSpinner?: boolean;
/**
* Whether to enable trickling the progress. Default is true.
*/
trickle?: boolean;
/**
* The CSS easing animation to use. Default is 'ease'.
*/
ease?: string;
/**
* The animation speed in milliseconds. Default is 200.
*/
speed?: number;
/**
* The HTML markup inserted for the progress indicator. To keep the progress bar working, keep an element with role='bar' in there.
*/
template?: string;
}
declare var NProgress: NProgressStatic;
+4856
View File
File diff suppressed because it is too large Load Diff
Vendored
+36 -36
View File
@@ -8,10 +8,10 @@ declare function Q<T>(promise: Q.IPromise<T>): Q.Promise<T>;
declare module Q {
interface IPromise<T> {
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason) => IPromise<U>): IPromise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason) => U): IPromise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason) => IPromise<U>): IPromise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason) => U): IPromise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason: any) => U): IPromise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => U): IPromise<U>;
}
interface Deferred<T> {
@@ -19,28 +19,28 @@ declare module Q {
resolve(value: T): void;
reject(reason: any): void;
notify(value: any): void;
makeNodeResolver(): (reason, value: T) => void;
makeNodeResolver(): (reason: any, value: T) => void;
}
interface Promise<T> {
fin(finallyCallback: () => any): Promise<T>;
finally(finallyCallback: () => any): Promise<T>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason) => IPromise<U>, onProgress?: Function): Promise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason) => U, onProgress?: Function): Promise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason) => IPromise<U>, onProgress?: Function): Promise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason) => U, onProgress?: Function): Promise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason: any) => IPromise<U>, onProgress?: Function): Promise<U>;
then<U>(onFulfill: (value: T) => IPromise<U>, onReject?: (reason: any) => U, onProgress?: Function): Promise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => IPromise<U>, onProgress?: Function): Promise<U>;
then<U>(onFulfill: (value: T) => U, onReject?: (reason: any) => U, onProgress?: Function): Promise<U>;
spread<U>(onFulfilled: Function, onRejected?: Function): Promise<U>;
fail<U>(onRejected: (reason) => U): Promise<U>;
fail<U>(onRejected: (reason) => IPromise<U>): Promise<U>;
catch<U>(onRejected: (reason) => U): Promise<U>;
catch<U>(onRejected: (reason) => IPromise<U>): Promise<U>;
fail<U>(onRejected: (reason: any) => U): Promise<U>;
fail<U>(onRejected: (reason: any) => IPromise<U>): Promise<U>;
catch<U>(onRejected: (reason: any) => U): Promise<U>;
catch<U>(onRejected: (reason: any) => IPromise<U>): Promise<U>;
progress(onProgress: (progress) => any): Promise<T>;
progress(onProgress: (progress: any) => any): Promise<T>;
done(onFulfilled?: (value: T) => any, onRejected?: (reason) => any, onProgress?: (progress) => any): void;
done(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any, onProgress?: (progress: any) => any): void;
get<U>(propertyName: String): Promise<U>;
set<U>(propertyName: String, value: any): Promise<U>;
@@ -78,17 +78,17 @@ declare module Q {
export function when<T, U>(value: T, onFulfilled: (val: T) => IPromise<U>): Promise<U>;
export function when<T, U>(value: T, onFulfilled: (val: T) => U): Promise<U>;
export function when<T, U>(value: IPromise<T>, onFulfilled: (val: T) => IPromise<U>, onRejected?: (reason) => IPromise<U>, onProgress?: (progress) => any): Promise<U>;
export function when<T, U>(value: IPromise<T>, onFulfilled: (val: T) => IPromise<U>, onRejected?: (reason) => U, onProgress?: (progress) => any): Promise<U>;
export function when<T, U>(value: IPromise<T>, onFulfilled: (val: T) => U, onRejected?: (reason) => IPromise<U>, onProgress?: (progress) => any): Promise<U>;
export function when<T, U>(value: IPromise<T>, onFulfilled: (val: T) => U, onRejected?: (reason) => U, onProgress?: (progress) => any): Promise<U>;
export function when<T, U>(value: IPromise<T>, onFulfilled: (val: T) => IPromise<U>, onRejected?: (reason: any) => IPromise<U>, onProgress?: (progress: any) => any): Promise<U>;
export function when<T, U>(value: IPromise<T>, onFulfilled: (val: T) => IPromise<U>, onRejected?: (reason: any) => U, onProgress?: (progress: any) => any): Promise<U>;
export function when<T, U>(value: IPromise<T>, onFulfilled: (val: T) => U, onRejected?: (reason: any) => IPromise<U>, onProgress?: (progress: any) => any): Promise<U>;
export function when<T, U>(value: IPromise<T>, onFulfilled: (val: T) => U, onRejected?: (reason: any) => U, onProgress?: (progress: any) => any): Promise<U>;
//export function try(method: Function, ...args: any[]): Promise<any>; // <- This is broken currently - not sure how to fix.
export function fbind<T>(method: (...args: any[]) => IPromise<T>, ...args: any[]): (...args: any[]) => Promise<T>;
export function fbind<T>(method: (...args: any[]) => T, ...args: any[]): (...args: any[]) => Promise<T>;
export function fcall<T>(method: (...args) => T, ...args: any[]): Promise<T>;
export function fcall<T>(method: (...args: any[]) => T, ...args: any[]): Promise<T>;
export function send<T>(obj: any, functionName: string, ...args: any[]): Promise<T>;
export function invoke<T>(obj: any, functionName: string, ...args: any[]): Promise<T>;
@@ -110,15 +110,15 @@ declare module Q {
export function allResolved<T>(promises: any[]): Promise<Promise<T>[]>;
export function allResolved<T>(promises: IPromise<T>[]): Promise<Promise<T>[]>;
export function spread<U>(promises: any[], onFulfilled: (...args: any[]) => IPromise<U>, onRejected: (reason) => IPromise<U>): Promise<U>;
export function spread<U>(promises: any[], onFulfilled: (...args: any[]) => IPromise<U>, onRejected: (reason) => U): Promise<U>;
export function spread<U>(promises: any[], onFulfilled: (...args: any[]) => U, onRejected: (reason) => IPromise<U>): Promise<U>;
export function spread<U>(promises: any[], onFulfilled: (...args: any[]) => U, onRejected: (reason) => U): Promise<U>;
export function spread<U>(promises: any[], onFulfilled: (...args: any[]) => IPromise<U>, onRejected: (reason: any) => IPromise<U>): Promise<U>;
export function spread<U>(promises: any[], onFulfilled: (...args: any[]) => IPromise<U>, onRejected: (reason: any) => U): Promise<U>;
export function spread<U>(promises: any[], onFulfilled: (...args: any[]) => U, onRejected: (reason: any) => IPromise<U>): Promise<U>;
export function spread<U>(promises: any[], onFulfilled: (...args: any[]) => U, onRejected: (reason: any) => U): Promise<U>;
export function spread<T, U>(promises: IPromise<T>[], onFulfilled: (...args: T[]) => IPromise<U>, onRejected: (reason) => IPromise<U>): Promise<U>;
export function spread<T, U>(promises: IPromise<T>[], onFulfilled: (...args: T[]) => IPromise<U>, onRejected: (reason) => U): Promise<U>;
export function spread<T, U>(promises: IPromise<T>[], onFulfilled: (...args: T[]) => U, onRejected: (reason) => IPromise<U>): Promise<U>;
export function spread<T, U>(promises: IPromise<T>[], onFulfilled: (...args: T[]) => U, onRejected: (reason) => U): Promise<U>;
export function spread<T, U>(promises: IPromise<T>[], onFulfilled: (...args: T[]) => IPromise<U>, onRejected: (reason: any) => IPromise<U>): Promise<U>;
export function spread<T, U>(promises: IPromise<T>[], onFulfilled: (...args: T[]) => IPromise<U>, onRejected: (reason: any) => U): Promise<U>;
export function spread<T, U>(promises: IPromise<T>[], onFulfilled: (...args: T[]) => U, onRejected: (reason: any) => IPromise<U>): Promise<U>;
export function spread<T, U>(promises: IPromise<T>[], onFulfilled: (...args: T[]) => U, onRejected: (reason: any) => U): Promise<U>;
export function timeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>;
@@ -131,18 +131,18 @@ declare module Q {
export function defer<T>(): Deferred<T>;
export function reject(reason?): Promise<any>;
export function reject(reason?: any): Promise<any>;
export function promise<T>(resolver: (resolve: (val: IPromise<T>) => void , reject: (reason) => void , notify: (progress) => void ) => void ): Promise<T>;
export function promise<T>(resolver: (resolve: (val: T) => void , reject: (reason) => void , notify: (progress) => void ) => void ): Promise<T>;
export function promise<T>(resolver: (resolve: (val: IPromise<T>) => void , reject: (reason: any) => void , notify: (progress: any) => void ) => void ): Promise<T>;
export function promise<T>(resolver: (resolve: (val: T) => void , reject: (reason: any) => void , notify: (progress: any) => void ) => void ): Promise<T>;
export function promised<T>(callback: (...any) => T): (...any) => Promise<T>;
export function promised<T>(callback: (...args: any[]) => T): (...args: any[]) => Promise<T>;
export function isPromise(object): boolean;
export function isPromiseAlike(object): boolean;
export function isPending(object): boolean;
export function isPromise(object: any): boolean;
export function isPromiseAlike(object: any): boolean;
export function isPending(object: any): boolean;
export function async<T>(generatorFunction: any): (...args) => Promise<T>;
export function async<T>(generatorFunction: any): (...args: any[]) => Promise<T>;
export function nextTick(callback: Function): void;
export var oneerror: () => void;
+8 -2
View File
@@ -134,11 +134,17 @@ interface Config {
current: Object;
reorder: boolean;
requireExpects: boolean;
testTimeout: number;
urlConfig: Array;
testTimeout: number;
urlConfig: Array<URLConfigItem>;
done: any;
}
interface URLConfigItem {
id: string;
label: string;
tooltip: string;
}
interface LifecycleObject {
/**
* Runs before each test
+17 -17
View File
@@ -1,26 +1,26 @@
/*
/*
require-2.1.8.d.ts may be freely distributed under the MIT license.
Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/require.d.ts
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
@@ -70,7 +70,7 @@ interface RequireConfig {
// The root path to use for all module lookups.
baseUrl?: string;
// Path mappings for module names not found directly under
// Path mappings for module names not found directly under
// baseUrl.
paths?: { [key: string]: any; };
@@ -222,7 +222,7 @@ interface Require {
* Configure require.js
**/
config(config: RequireConfig): Require;
/**
* CommonJS require call
* @param module Module to load
@@ -242,7 +242,7 @@ interface Require {
* @see Require()
* @param ready Called when required modules are ready.
**/
(modules: string[], ready: (...modules: any[]) => void ): void;
(modules: string[], ready: Function): void;
/**
* Generate URLs from require module
+13 -1
View File
@@ -47,7 +47,7 @@ interface Select2Options {
closeOnSelect?: boolean;
openOnEnter?: boolean;
id?: (object: any) => string;
matcher?: (term: string, text: string, option: JQuery) => boolean;
matcher?: (term: string, text: string, option: any) => boolean;
formatSelection?: (object: any, container: JQuery) => string;
formatResult?: (object: any, container: JQuery, query: any) => string;
formatResultCssClass?: (object: any) => string;
@@ -71,7 +71,19 @@ interface Select2Options {
escapeMarkup?: (markup: string) => string;
}
interface Select2JQueryEventObject extends JQueryEventObject {
val: any;
added: any;
removed: any;
}
interface JQuery {
off(events?: "change", selector?: any, handler?: (eventObject: Select2JQueryEventObject) => any): JQuery;
on(events: "change", selector?: string, data?: any, handler?: (eventObject: Select2JQueryEventObject) => any): JQuery;
on(events: "change", selector?: string, handler?: (eventObject: Select2JQueryEventObject) => any): JQuery;
on(events: "change", handler?: (eventObject: Select2JQueryEventObject) => any): JQuery;
select2(): JQuery;
select2(it: IdTextPair): JQuery;
select2(options: Select2Options): JQuery;
+310 -32
View File
@@ -3,6 +3,8 @@
// Definitions by: Stanislav Vyshchepan <http://gandjustas.blogspot.ru> and Andrey Markeev <http://markeev.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Sys {
export class EventArgs {
static Empty: Sys.EventArgs;
@@ -25,12 +27,40 @@ declare module Sys {
initialize(): void;
updated(): void;
}
export interface IContainer {
addComponent(component: Component): void;
findComponent(id: string): Component;
getComponents(): Component[];
removeComponent(component: Component);
}
export class Application extends Component implements IContainer {
addComponent(component: Component): void;
findComponent(id: string): Component;
getComponents(): Component[];
removeComponent(component: Component);
static add_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void);
static remove_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void);
}
export class ApplicationLoadEventArgs {
constructor(components: Component[], isPartialLoad: boolean);
public components: Component[];
public isPartialLoad: boolean;
}
module UI {
export class Control { }
export class Control extends Component { }
export class DomEvent {
static addHandler(element: HTMLElement, eventName: string, handler: (e: Event) => void);
static removeHandler(element: HTMLElement, eventName: string, handler: (e: Event) => void);
}
export class DomElement {
static getBounds(element: HTMLElement): { x: number; y: number; width: number; height: number; };
}
}
module Net {
export class WebRequest {
@@ -1210,7 +1240,7 @@ declare module SPClientTemplates {
export interface TemplateOverrides {
View?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template
Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template
Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template
/** Defines templates for rendering groups (aggregations). */
Group?: GroupCallback;
/** Defines templates for list items rendering. */
@@ -1234,10 +1264,10 @@ declare module SPClientTemplates {
/** allbacks called after rendered html inserted into DOM. Can be function (ctx: RenderContext) => void or array of functions.*/
OnPostRender?: any;
/** View style (SPView.StyleID) for which the templates should be applied.
/** View style (SPView.StyleID) for which the templates should be applied.
If not defined, the templates will be applied only to default view style. */
ViewStyle?: number;
/** List template type (SPList.BaseTemplate) for which the template should be applied.
/** List template type (SPList.BaseTemplate) for which the template should be applied.
If not defined, the templates will be applied to all lists. */
ListTemplateType?: number;
/** Base view ID (SPView.BaseViewID) for which the template should be applied.
@@ -2400,12 +2430,12 @@ declare module SP {
/** Specifies a Collaborative Application Markup Language (CAML) query on a list. */
export class CamlQuery extends SP.ClientValueObject {
constructor();
/** This method creates a Collaborative Application Markup Language (CAML) string
that can be used to recursively get all of the items in a list, including
/** This method creates a Collaborative Application Markup Language (CAML) string
that can be used to recursively get all of the items in a list, including
the items in the subfolders. */
static createAllItemsQuery(): SP.CamlQuery;
/** This method creates a Collaborative Application Markup Language (CAML) string
that can be used to recursively get all of the folders in a list, including
/** This method creates a Collaborative Application Markup Language (CAML) string
that can be used to recursively get all of the folders in a list, including
the subfolders. */
static createAllFoldersQuery(): SP.CamlQuery;
/** Returns true if the query returns dates in Coordinated Universal Time (UTC) format. */
@@ -5817,7 +5847,7 @@ declare module SP {
/** Contains information about an actor retrieved from server. An actor is a user, document, site, or tag. */
export class SocialActor extends SP.ClientValueObject {
/** The AccountName property returns the user account name.
/** The AccountName property returns the user account name.
This property is only available for social actors of type "user". */
get_accountName(): string;
/** Identifies whether the actor is a user, document, site, or tag. */
@@ -5848,7 +5878,7 @@ declare module SP {
get_personalSiteUri(): string;
/** Represents the status of retrieving the actor */
get_status(): SocialStatusCode;
/** The StatusText property returns the most recent post of the user.
/** The StatusText property returns the most recent post of the user.
This property is only available for social actors of type "user". */
get_statusText(): string;
/** Returns the GUID of the tag.
@@ -5863,10 +5893,10 @@ declare module SP {
/** Identifies an actor to the server. An actor can be a user, document, site, or tag. */
export class SocialActorInfo extends SP.ClientValueObject {
/** User account name.
/** User account name.
This property is only available for social actors of type "user". */
get_accountName(): string;
/** User account name.
/** User account name.
This property is only available for social actors of type "user". */
set_accountName(value: string): string;
/** Identifies whether the actor is a user, document, site, or tag. */
@@ -5977,7 +6007,7 @@ declare module SP {
}
/** Provides information about an overlay.
An overlay is a substring in a post that represents a user, document, site, tag, or link.
An overlay is a substring in a post that represents a user, document, site, tag, or link.
The SocialPost class contains an array of SocialDataOverlay objects.
Each of the SocialDataOverlay objects specifies a link or one or more actors. */
export class SocialDataOverlay extends SP.ClientValueObject {
@@ -6014,8 +6044,8 @@ declare module SP {
The most recent post that was requested can be removed from the feed if the current user does not have access to it.
Consequently, the feed does not always contain the post with the date specified in this property. */
get_newestProcessed(): string;
/** The OldestProcessed property returns the date-time of the oldest post that was requested.
The oldest post that was requested can be removed from the feed if the current user does not have access to it.
/** The OldestProcessed property returns the date-time of the oldest post that was requested.
The oldest post that was requested can be removed from the feed if the current user does not have access to it.
Consequently, the feed does not always contain the post with the date specified in this property */
get_oldestProcessed(): string;
/** Contains the social threads in the feed. */
@@ -6032,7 +6062,7 @@ declare module SP {
get_owner(): SocialActor;
/** Specifies the URI of the personal site portal. */
get_personalSitePortalUri(): string;
/** Creates a post in the current user's newsfeed, in the specified user's feed, or in the specified thread.
/** Creates a post in the current user's newsfeed, in the specified user's feed, or in the specified thread.
This method returns a new or a modified thread.
@param targetId Optional, specifies the target of the post.
If this parameter is null, the post is created as a root post in the current user's feed.
@@ -6065,19 +6095,19 @@ declare module SP {
getFullThread(threadId: string): SocialThread;
/** Returns a feed containing mention reference threads from the current user's personal feed. */
getMentions(clearUnreadMentions: boolean, options: SocialFeedOptions): SocialFeed;
/** Returns the server's count of unread mentions of the current user.
The server maintains a count of unread mentions in posts, but does not track which mentions have been read.
When a new mention is stored on the server, it increments the unread mention for the user specified by the mention.
/** Returns the server's count of unread mentions of the current user.
The server maintains a count of unread mentions in posts, but does not track which mentions have been read.
When a new mention is stored on the server, it increments the unread mention for the user specified by the mention.
The unread mention count is cleared by the GetMentions method. */
getUnreadMentionCount(): SP.IntResult;
/** Specifies that the current user likes the specified post.
Returns a digest thread containing the specified post.
/** Specifies that the current user likes the specified post.
Returns a digest thread containing the specified post.
A digest thread contains the root post and a selection of reply posts */
likePost(postId: string): SocialThread;
/** Specifies that the current user does not like the specified post.
/** Specifies that the current user does not like the specified post.
Returns a digest thread containing the specified post. */
unlikePost(postId: string): SocialThread;
/** Prevents any user from adding a new reply post to the specified thread.
/** Prevents any user from adding a new reply post to the specified thread.
Once a thread is locked, no new reply posts can be added until after the thread has been unlocked with the unlockThread method.
This method returns a digest of the locked thread */
lockThread(threadId: string): SocialThread;
@@ -6117,9 +6147,9 @@ declare module SP {
get_followedSitesUri(): string;
/** Adds the specified actor to the current user's list of followed items.
Returns one of the following values, wrapped into the SP.IntResult object:
0 = ok,
1 = alreadyFollowing,
2 = limitReached,
0 = ok,
1 = alreadyFollowing,
2 = limitReached,
3 = internalError */
follow(actor: SocialActorInfo): SP.IntResult;
stopFollowing(actor: SocialActorInfo): SP.BooleanResult;
@@ -6252,10 +6282,10 @@ declare module SP {
get_text(): string;
/** Specifies the text that is substituted for the placeholder */
set_text(value: string): string;
/** Specifies the URI of the document, site, or link.
/** Specifies the URI of the document, site, or link.
This property is only available if the ItemType property specifies that the item is a Document, Link, or Site. */
get_uri(): string;
/** Specifies the URI of the document, site, or link.
/** Specifies the URI of the document, site, or link.
This property is only available if the ItemType property specifies that the item is a Document, Link, or Site. */
set_uri(value: string): string;
}
@@ -7060,6 +7090,93 @@ declare module SP {
}
}
declare module SP {
export module UI {
export module Controls {
export interface INavigationOptions {
assetId?: string;
siteTitle?: string;
siteUrl?: string;
appTitle?: string;
appTitleIconUrl?: string;
rightToLeft?: boolean;
appStartPage?: string;
appIconUrl?: string;
appHelpPageUrl?: string;
appHelpPageOnClick?: string;
settingsLinks?: ISettingsLink[];
language?: string;
clientTag?: string;
appWebUrl?: string;
onCssLoaded?: string;
bottomHeaderVisible?: boolean;
topHeaderVisible?: boolean;
}
export class NavigationOptions implements INavigationOptions { }
export interface ISettingsLink {
linkUrl: string;
displayName: string;
}
export class SettingsLink implements ISettingsLink {
linkUrl: string;
displayName: string;
}
export class Navigation {
constructor(placeholderDOMElementId: string, options: INavigationOptions);
public get_assetId(): string;
public get_siteTitle(): string;
public get_siteUrl(): string;
public get_appTitle(): string;
public set_appTitle(value: string): string;
public get_appTitleIconUrl(): string;
public set_appTitleIconUrl(value: string): string;
public get_rightToLeft(): boolean;
public set_rightToLeft(value: boolean): boolean;
public get_appStartPage(): string;
public set_appStartPage(value: string): string;
public get_appIconUrl(): string;
public set_appIconUrl(value: string): string;
public get_appHelpPageUrl(): string;
public set_appHelpPageUrl(value: string): string;
public get_appHelpPageOnClick(): string;
public set_appHelpPageOnClick(value: string): string;
public get_settingsLinks(): ISettingsLink[];
public set_settingsLinks(value: ISettingsLink[]): ISettingsLink[];
public setVisible(value: boolean): void;
public setTopHeaderVisible(value: boolean): void;
public setBottomHeaderVisible(value: boolean): void;
public remove(): void;
static getVersionedLayoutsUrl(pageName: string): string;
}
export class ControlManager {
static getControl(placeHolderId: string): any;
}
}
}
}
declare module SP {
export module UserProfiles {
@@ -7223,7 +7340,7 @@ declare module SP {
/** Specifies the person's title. */
get_title(): string;
/** Represents all user profile properties including custom.
The privacy settings affect which properties can be retrieved.
The privacy settings affect which properties can be retrieved.
Multiple values are delimited by the vertical bar "|".
Null values are specified as empty strings. */
get_userProfileProperties(): { [name: string]: string; };
@@ -7312,7 +7429,7 @@ declare module SP {
/** Updates the properties for followed item with specified URL.
@param url URL that identifies the followed item.
The url parameter can identify an existing document or site using the url property of the original item.
The url parameter can also identify a document with the following format: http://host/site?listId=<listGuid>&itemId=<itemId>
The url parameter can also identify a document with the following format: http://host/site?listId=<listGuid>&itemId=<itemId>
@param data Application-defined data stored with the followed item. */
updateData(url: string, data: FollowedItemData): void;
/** Returns the refreshed item that is being pointed to in the Social list.
@@ -7382,11 +7499,11 @@ declare module SP {
/** Specifies the site identification (GUID) in the Content database for this item if this item is a site, or for its parent site if this item is not a site. */
set_siteId(value: string): string;
/** Specifies the subtype of this item.
If the ItemType is Site, the Subtype specifies the web template identification.
If the ItemType is Site, the Subtype specifies the web template identification.
If the ItemType is Document, the Subtype has a value of 1. */
get_subtype(): number;
/** Specifies the subtype of this item.
If the ItemType is Site, the Subtype specifies the web template identification.
If the ItemType is Site, the Subtype specifies the web template identification.
If the ItemType is Document, the Subtype has a value of 1. */
set_subtype(value: number): number;
/** Specifies the item of this item */
@@ -8164,3 +8281,164 @@ interface ISPClientAutoFillData {
AutoFillMenuOptionType?: number;
}
declare class SPClientPeoplePicker {
static ValueName: string; // = 'Key';
static DisplayTextName: string; // = 'DisplayText';
static SubDisplayTextName: string; // = 'Title';
static DescriptionName: string; // = 'Description';
static SIPAddressName: string; // = 'SIPAddress';
static SuggestionsName: string; // = 'MultipleMatches';
static UnvalidatedEmailAddressKey: string; // = "UNVALIDATED_EMAIL_ADDRESS";
static KeyProperty: string; // = 'AutoFillKey';
static DisplayTextProperty: string; // = 'AutoFillDisplayText';
static SubDisplayTextProperty: string; // = 'AutoFillSubDisplayText';
static TitleTextProperty: string; // = 'AutoFillTitleText';
static DomainProperty: string; // = 'DomainText';
static SPClientPeoplePickerDict: {
[pickerIelementId: string]: SPClientPeoplePicker;
};
static InitializeStandalonePeoplePicker(clientId: string, value: ISPClientPeoplePickerEntity[], schema: ISPClientPeoplePickerSchema): void;
public TopLevelElementId: string;// '',
public EditorElementId: string;//'',
public AutoFillElementId: string;//'',
public ResolvedListElementId: string;//'',
public InitialHelpTextElementId: string;//'',
public WaitImageId: string;//'',
public HiddenInputId: string;//'',
public AllowEmpty: boolean;//true,
public ForceClaims: boolean;//false,
public AutoFillEnabled: boolean;//true,
public AllowMultipleUsers: boolean;//false,
public OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void;
public OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void;
public OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void;
public UrlZone: string;//null,
public AllUrlZones: boolean;//false,
public SharePointGroupID: number;//0,
public AllowEmailAddresses: boolean;//false,
public PPMRU: SPClientPeoplePickerMRU;
public UseLocalSuggestionCache: boolean;//true,
public CurrentQueryStr: string;//'',
public LatestSearchQueryStr: string;// '',
public InitialSuggestions: ISPClientPeoplePickerEntity[];
public CurrentLocalSuggestions: ISPClientPeoplePickerEntity[];
public CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity;
public VisibleSuggestions: number;//5,
public PrincipalAccountType: string;//'',
public PrincipalAccountTypeEnum: SP.Utilities.PrincipalType;
public EnabledClaimProviders: string;//'',
public SearchPrincipalSource: SP.Utilities.PrincipalSource;//null,
public ResolvePrincipalSource: SP.Utilities.PrincipalSource;//null,
public MaximumEntitySuggestions: number;//30,
public EditorWidthSet: boolean;//false,
public QueryScriptInit: boolean;//false,
public AutoFillControl: string;//null,
public TotalUserCount: number;//0,
public UnresolvedUserCount: number;//0,
public UserQueryDict: ISPClientPeoplePickerEntity;
public ProcessedUserList: ISPClientPeoplePickerEntity;
public HasInputError: boolean;//false,
public HasServerError: boolean;//false,
public ShowUserPresence: boolean;//true,
public TerminatingCharacter: string;//';',
public UnresolvedUserElmIdToReplace: string;//'',
public WebApplicationID: SP.Guid;//'{00000000-0000-0000-0000-000000000000}',
public GetAllUserInfo(): ISPClientPeoplePickerEntity[];
}
interface ISPClientPeoplePickerSchema {
TopLevelElementId?: string;
EditorElementId?: string;
AutoFillElementId?: string;
ResolvedListElementId?: string;
InitialHelpTextElementId?: string;
WaitImageId?: string;
HiddenInputId?: string;
AllowMultipleValues?: boolean;
Required?: boolean;
AutoFillEnabled?: boolean;
ForceClaims?: boolean;
AllowEmailAddresses?: boolean;
AllUrlZones?: boolean;
UseLocalSuggestionCache?: boolean;
UserNoQueryPermission?: boolean;
VisibleSuggestions?: number;
MaximumEntitySuggestions?: number;
ErrorMessage?: string;
InitialHelpText?: string;
InitialSuggestions?: ISPClientPeoplePickerEntity[];
UrlZone?: SP.UrlZone;
WebApplicationID?: SP.Guid;
SharePointGroupID?: number;
/** Specify User, DL, SecGroup or SPGroup*/
PrincipalAccountType?: string;
EnabledClaimProvider?: string;
ResolvePrincipalSource?: SP.Utilities.PrincipalSource;
SearchPrincipalSource?: SP.Utilities.PrincipalSource;
OnUserResolvedClientScript?: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void;
OnValueChangedClientScript?: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void;
/** Number or '100%'*/
Width?: any;
Rows?: number;
}
declare class SPClientPeoplePickerMRU {
static PPMRUVersion: number;// = 1;
static MaxPPMRUItems: number;// = 200;
static PPMRUDomLocalStoreKey: string;// = "ClientPeoplePickerMRU";
static GetSPClientPeoplePickerMRU(): SPClientPeoplePickerMRU;
GetItems(strKey: string): Object[];
SetItem(strSearchTerm: string, objEntity: Object): void;
ResetCache(): void;
}
interface ISPClientPeoplePickerEntity {
Key?: string;
Description?: string;
DisplayText?: string;
EntityType?: string;
ProviderDisplayName?: string;
ProviderName?: string;
IsResolved?: boolean;
EntityData?: {
Title: string;
MobilePhone: string;
Department: string;
Email: string;
};
MultipleMatches: Object[];
DomainText?: string;
[key: string]: any;
}
declare module Microsoft {
export module Office {
export module Server {
export module ReputationModel {
export class Reputation {
constructor();
static setLike(context: SP.ClientContext, listId: string, itemId: number, like: boolean);
static setRating(context: SP.ClientContext, listId: string, itemId: number, rating: number);
}
}
}
}
}
+2 -2
View File
@@ -87,7 +87,7 @@ declare module Slick {
* @method subscribe
* @param fn {Function} Event handler.
*/
public subscribe<T>(fn: (eventData: EventData, data: T) => any ): void;
public subscribe(fn: (eventData: EventData, data: T) => any ): void;
/***
* Removes an event handler added with <code>subscribe(fn)</code>.
@@ -1529,7 +1529,7 @@ declare module Slick {
public getGroups(): Group<T, any>[];
public getIdxById(): string;
public getRowById(): T;
public getItemById(): T;
public getItemById(id: any): T;
public getItemByIdx(): T;
public mapRowsToIds(rowArray: T[]): string[];
public setRefreshHints(hints: RefreshHints): void;
+9 -4
View File
@@ -2813,7 +2813,12 @@ interface Array<T> {
* ['a','b'].subtract('b','c') -> ['a']
**/
subtract(...args: T[]): T[];
/**
* @see subtract
**/
subtract(args: T[]): T[];
/**
* Sums all values in the array.
* @param map Property on each element in the array or callback function to sum up the elements.
@@ -4392,9 +4397,9 @@ interface Date {
* }); -> ex. 1 day ago
**/
format(format: string, locale?: string): string;
short(): string;
long(): string;
full(): string;
short(locale?: string): string;
long(locale?: string): string;
full(locale?: string): string;
/**
* Returns a string representation of the offset from UTC time. If [iso]
+1
View File
@@ -0,0 +1 @@
""