diff --git a/.gitignore b/.gitignore index 4f0152028d..d943bb9299 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,4 @@ node_modules .settings/launch.json .vscode +yarn.lock diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 44f0d8e9a0..1036be548d 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped) +* [:link:](ejson/ejson.d.ts) [ejson](https://www.npmjs.com/package/ejson) by [Shantanu Bhadoria](https://github.com/shantanubhadoria) * [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak) @@ -1189,7 +1190,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ng-stomp/ng-stomp.d.ts) [ngStomp](https://github.com/beevelop/ng-stomp) by [Lukasz Potapczuk](https://github.com/lpotapczuk) * [:link:](ngstorage/ngstorage.d.ts) [ngstorage](https://github.com/gsklee/ngStorage) by [Jakub Pistek](https://github.com/kubiq) * [:link:](nightmare/nightmare.d.ts) [Nightmare](https://github.com/segmentio/nightmare) by [horiuchi](https://github.com/horiuchi) -* [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook), [Hans Bakker](https://github.com/wind-rider) +* [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook), [Hans Bakker](https://github.com/wind-rider), [Shantanu Bhadoria](https://github.com/shantanubhadoria) * [:link:](nock/nock.d.ts) [nock](https://github.com/pgte/nock) by [bonnici](https://github.com/bonnici) * [:link:](node-imap/imap.d.ts) [node imap](https://github.com/mscdex/node-imap) by [Steve Fenton](https://github.com/Steve-Fenton) * [:link:](oauth2-server/oauth2-server.d.ts) [Node OAuth2 Server](https://github.com/thomseddon/node-oauth2-server) by [Robbie Van Gorkom](https://github.com/vangorra) @@ -1664,7 +1665,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](supertest/supertest.d.ts) [SuperTest](https://github.com/visionmedia/supertest) by [Alex Varju](https://github.com/varju) * [:link:](supertest-as-promised/supertest-as-promised.d.ts) [SuperTest as Promised](https://github.com/WhoopInc/supertest-as-promised) by [Tanguy Krotoff](https://github.com/tkrotoff) * [:link:](svg-injector/svg-injector.d.ts) [SVG Injector](https://github.com/iconic/SVGInjector) by [Patrick Westerhoff](https://github.com/poke) -* [:link:](svg-pan-zoom/svg-pan-zoom.d.ts) [svg-pan-zoom](https://github.com/ariutta/svg-pan-zoom) by [Chintan Shah](https://github.com/Promact) +* [:link:](svg-pan-zoom/svg-pan-zoom-2.3.9.d.ts) [svg-pan-zoom](https://github.com/ariutta/svg-pan-zoom) by [Chintan Shah](https://github.com/Promact) +* [:link:](svg-pan-zoom/svg-pan-zoom.d.ts) [svg-pan-zoom](https://github.com/ariutta/svg-pan-zoom) by [César Vidril](https://github.com/Yimiprod) * [:link:](svg-sprite/svg-sprite.d.ts) [svg-sprite](https://github.com/jkphl/svg-sprite) by [Qubo](https://github.com/tkqubo) * [:link:](svgjs/svgjs.d.ts) [svg.js](http://www.svgjs.com) by [Sean Hess](https://seanhess.github.io) * [:link:](svg2png/svg2png.d.ts) [svg2png node package](https://github.com/domenic/svg2png) by [hans windhoff](https://github.com/hansrwindhoff) diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 730bd78af2..a864dbcb13 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,8 +1,17 @@ -case 1. Add a new type definition. -- [ ] checked compilation succeeds with `--target es6` and `--noImplicitAny` options. -- [ ] has correct [naming convention](http://definitelytyped.org/guides/contributing.html#naming-the-file) -- [ ] has a [test file](http://definitelytyped.org/guides/contributing.html#tests) with the suffix of `-tests.ts` or `-tests.tsx`. +Please fill in this template. -case 2. Improvement to existing type definition. -- documentation or source code reference which provides context for the suggested changes. url http://api.jquery.com/html . - - it has been reviewed by a DefinitelyTyped member. +- [ ] Prefer to make your PR against the `types-2.0` branch. +- [ ] Test the change in your own code. +- [ ] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped#make-a-pull-request). +- [ ] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes). +- [ ] Run `npm run lint -- package-name` if a `tslint.json` is present. + +If adding a new definition: +- [ ] The package does not provide its own types, and you can not add them. +- [ ] If this is for an NPM package, match the name. If not, do not conflict with the name of an NPM package. +- [ ] Run `tsc` without errors. +- [ ] Include the required [files](https://github.com/DefinitelyTyped/DefinitelyTyped#create-a-new-package) and header. Base these on the README, *not* on an existing project. + +If changing an existing definition: +- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <> +- [ ] Increase the version number in the header if appropriate. diff --git a/README.md b/README.md index b188982fbf..ab2080714b 100644 --- a/README.md +++ b/README.md @@ -4,36 +4,222 @@ > The repository for *high quality* TypeScript type definitions. -For more information see the [definitelytyped.org](http://definitelytyped.org) website. +Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date. -## Usage -Include a line like this: +## What are declaration files? -```typescript -/// +See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). + + +## How do I get them? + +### npm + +This is the preferred method. This is only available for TypeScript 2.0+ users. For example: + +```sh +npm install --save-dev @types/node ``` -## Contributions +The types should then be automatically included by the compiler. +See more in the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html). + +For an NPM package "foo", typings for it will be at "@types/foo". +If you can't find your package, look for it on [TypeSearch](https://microsoft.github.io/TypeSearch/). + +If you still can't find it, check if it [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own typings. +This is usually provided in a `"types"` or `"typings"` field in the `package.json`, +or just look for any ".d.ts" files in the package and manually include them with a `/// `. + + +### Other methods + +These can be used by TypeScript 1.0. + +* [Typings](https://github.com/typings/typings) +* [NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped) +* Manually download from the `master` branch of this repository + +You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). + + +## How can I contribute? DefinitelyTyped only works because of contributions by users like you! -Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) on how to contribute to DefinitelyTyped. +### Test -## How to get the definitions +Before you share your improvement with the world, use it yourself. -* Directly from the GitHub repos -* [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped) -* [Typings - TypeScript Definition Manager](https://github.com/typings/typings) +#### Test editing an exiting package -## List of definitions +To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html). +You can also directly edit the types in `node_modules/@types/foo/index.d.ts`, or copy them from there and follow the steps below. -* See [CONTRIBUTORS.md](CONTRIBUTORS.md) -## Requested definitions +#### Test a new package + +Add to your `tsconfig.json`: + +```json +"baseUrl": "types", +"typeRoots": ["types"], +``` + +(You can also use `src/types`.) +Create `types/foo/index.d.ts` containing declarations for the module "foo". +You should now be able import from `"foo"` in your code and it will route to the new type definition. +Then build *and* run the code to make sure your type definition actually corresponds to what happens at runtime. +Once you've tested your definitions with real code, make a PR contributing the definition by copying `types/foo` to `DefinitelyTyped/foo` and adding a `tsconfig.json` and `foo-tests.ts`. + + +### Make a pull request + +Once you've tested your package, you can share it on DefinitelyTyped. + +First, [fork](https://guides.github.com/activities/forking/) this repository. +Then inside your repository: + +* `git checkout types-2.0` + +New work should generally be done on the `types-2.0` branch. +If you want your changes to be available to `typings` users, then you may edit `master` instead. + + +#### Edit an existing package + +* `cd my-package-to-edit` +* Make changes. Remember to edit tests. +* You may also want to add yourself to "Definitions by" section of the package header. +* `npm install -g typescript@2.0` and run `tsc`. + +When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors. +If it doesn't, you can do so yourself in the comment associated with the PR. + + +#### Create a new package + +If you are the library author, or can make a pull request to the library, [bundle](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) types instead of publishing to DefinitelyTyped. + +If you are adding typings for an NPM package, create a directory with the same name. +If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM. +(You can use `npm info foo` to check for the existence of the `foo` package.) + +Your package should have this structure: + +| File | Purpose | +| --- | --- | +| index.d.ts | This contains the typings for the package. | +| foo-tests.ts | This contains sample code which tests the typings. This code does *not* run, but it is type-checked. | +| tsconfig.json | This allows you to run `tsc` within the package. | + +Generate these by running `npm run new-package -- new-package-name`. + +You may edit the `tsconfig.json` to add new files or to add the `"jsx"` compiler option. + +DefinitelyTyped members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down. + +For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/types-2.0/base64-js). + + +#### Common mistakes + +* First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html). +* Formatting: Either use all tabs, or always use 4 spaces. Also, always use semicolons, and use egyptian braces. +* `interface X {}`: An empty interface is essentially the `{}` type: it places no constraints on an object. +* `interface IFoo {}`: Don't add `I` to the front of an interface name. +* `interface Foo { new(): Foo; }`: + This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); } +* `const Class: { new(): IClass; }`: + Prefer to use a class declaration `class Class { constructor(); }` instead of a new-able constant. +* `namespace foo {}`: + Do not add a namespace just so that the `import * as foo` syntax will work. + If it is commonJs module with a single export, you should use the `import foo = require("foo")` syntax. + See more explanation [here](https://stackoverflow.com/questions/39415661/why-cant-i-import-a-class-or-function-with-import-as-x-from-y). +* `getMeAT(): T`: + If a type parameter does not appear in the types of any parameters, you don't really have a generic function, you just have a disguised type assertion. + Prefer to use a real type assertion, e.g. `getMeAT() as number`. + Example where a type parameter is acceptable: `function id(value: T): T;`. + Example where it is not acceptable: `function parseJson(json: string): T;`. + Exception: `new Map()` is OK. + + +#### Removing a package + +When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own types, types should be removed from DefinitelyTyped to avoid confusion. +Make a PR doing the following: +* Delete the directory. +* Add a new entry to `notNeededPackages.json`. + - `libraryName`: Descriptive name of the library, e.g. "Angular 2" instead of "angular2". (May be identical to "typingsPackageName".) + - `typingsPackageName`: This is the name of the directory you just deleted. + - `sourceRepoURL`: This should point to the repository that contains the typings. + - `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version. +* Any other packages in DefinitelyTyped that referenced the deleted package should be updated to reference the bundled types. + To do this, add a `package.json` with `"dependencies": { "foo": "x.y.z" }`. + + +#### Lint + +To lint a package, just add a `tslint.json` to that package containing `{ "extends": "../tslint.json" }`. All new packages must be linted. +If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example: + +```json +{ + "extends": "../tslint.json", + "rules": { + // This package uses the Function type, and it will take effort to fix. + "forbidden-types": false + } +} +``` + +(To indicate that a lint rule truly does not apply, use `// tslint:disable:rule-name` or better, `//tslint:disable-next-line:rule-name`.) + +Only `.d.ts` files are linted. +Test the linter by running `npm run lint -- package-name`. Do not use a globally installed tslint. + + +## FAQ + +#### What exactly is the relationship between this repository and the `@types` packages on NPM? + +The `types-2.0` branch is automatically published to the `@types` scope on NPM thanks to [types-publisher](https://github.com/Microsoft/types-publisher). +This usually happens within an hour of changes being merged. + +Changes to the `master` branch are also manually merged into the `types-2.0` branch, but this takes longer. + +#### I'm writing a definition that depends on another definition. Should I use `` or an import? + +If the module you're referencing is an external module (uses `export`), use an import. +If the module you're referenceing is an ambient module (uses `declare module`, or just declares globals), use ``. + +#### What do I do about older versions of typings? + +Currently we don't support this, though it is [planned](https://github.com/Microsoft/types-publisher/issues/3). +If you're adding a new major version of a library, you can copy `index.d.ts` to `foo-v2.3.d.ts` and edit `index.d.ts` to be the new version. + +#### I notice some packages having a `package.json` here. + +Usually you won't need this. When publishing a package we will normally automatically create a `package.json` for it. +A `package.json` may be included for the sake of specifying dependencies. Here's an [example](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/types-2.0/pikaday/package.json). +We do not allow other fields, such as `"description"`, to be defined manually. +Also, if you need to reference an older version of typings, you must do that by adding `"dependencies": { "@types/foo": "x.y.z" }` to the package.json. + +#### I notice some `tsconfig.json` are missing `"noImplicitAny": true` or `"strictNullChecks": true`. + +Then they are wrong. You can help by submitting a pull request to fix them. + +#### Definitions in types-2.0 seem written differently than in master. + +If you're targeting types-2.0, write it like the types-2.0 definitions. +If you're targeting master, we may change it to the new style when merging from master to types-2.0. + +#### Can I request a definition? Here are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). + ## License This project is licensed under the MIT license. diff --git a/acl/index.d.ts b/acl/index.d.ts index 6939c9ce9f..140a5050c3 100644 --- a/acl/index.d.ts +++ b/acl/index.d.ts @@ -16,7 +16,7 @@ type Action = () => any; type Callback = (err: Error) => any; type AnyCallback = (err: Error, obj: any) => any; type AllowedCallback = (err: Error, allowed: boolean) => any; -type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; +type GetUserId = (req: http.IncomingMessage, res: http.ServerResponse) => Value; interface AclStatic { new (backend: Backend, logger: Logger, options: Option): Acl; diff --git a/ajv/index.d.ts b/ajv/index.d.ts index 691b6b6ad0..bf487fd341 100644 --- a/ajv/index.d.ts +++ b/ajv/index.d.ts @@ -81,7 +81,7 @@ declare namespace Ajv { passContext?: boolean; loopRequired?: number; ownProperties?: boolean; - multipleOfPrecision?: boolean; + multipleOfPrecision?: boolean | number; errorDataPath?: string, messages?: boolean; beautify?: boolean; diff --git a/amcharts/index.d.ts b/amcharts/index.d.ts index fbc2ee4ac9..45c848e5af 100644 --- a/amcharts/index.d.ts +++ b/amcharts/index.d.ts @@ -24,6 +24,9 @@ declare namespace AmCharts { /** Set it to true if you want UTC time to be used instead of local time. */ var useUTC: boolean; + /** Object with themes */ + var themes: any; + /** Clears all the charts on page, removes listeners and intervals. */ function clear(): void; diff --git a/angular-dynamic-locale/index.d.ts b/angular-dynamic-locale/index.d.ts index 12de09a10b..dc3e1ababf 100644 --- a/angular-dynamic-locale/index.d.ts +++ b/angular-dynamic-locale/index.d.ts @@ -18,6 +18,7 @@ declare module 'angular' { interface tmhDynamicLocaleProvider extends angular.IServiceProvider { localeLocationPattern(location: string): tmhDynamicLocaleProvider; localeLocationPattern(): string; + storageKey(storageKey: string): void; useStorage(storageName: string): void; useCookieStorage(): void; } diff --git a/angular-material/index.d.ts b/angular-material/index.d.ts index c7279513d0..26568f2631 100644 --- a/angular-material/index.d.ts +++ b/angular-material/index.d.ts @@ -158,6 +158,7 @@ declare module 'angular' { hideDelay(delay: number): T; position(position: string): T; parent(parent?: string | Element | JQuery): T; // default: root node + toastClass(toastClass: string): T; } interface ISimpleToastPreset extends IToastPreset { @@ -337,6 +338,7 @@ declare module 'angular' { onRemoving?: Function; onDomRemoved?: Function; origin?: string | JQuery | Element; + onCloseSuccess?: ((panel: IPanelRef, closeReason: string) => any); } interface IPanelRef { @@ -409,6 +411,16 @@ declare module 'angular' { interceptorTypes: { CLOSE: string, }; + closeReasons: { + CLICK_OUTSIDE: string, + ESCAPE: string, + }; + absPosition: { + TOP: string, + RIGHT: string, + BOTTOM: string, + LEFT: string, + }; } } } diff --git a/angular-sanitize/index.d.ts b/angular-sanitize/index.d.ts index 4dc09ead11..3aedca87cc 100644 --- a/angular-sanitize/index.d.ts +++ b/angular-sanitize/index.d.ts @@ -31,8 +31,6 @@ declare module 'angular' { // Supports http/https/ftp/mailto and plain email address links. // see http://code.angularjs.org/1.2.0/docs/api/ngSanitize.filter:linky interface ILinky { - (text: string, target?: string): string; - } + (text: string, target: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; } - } -} +} \ No newline at end of file diff --git a/angular-signalr-hub/index.d.ts b/angular-signalr-hub/index.d.ts index 80927788ec..02238f5244 100644 --- a/angular-signalr-hub/index.d.ts +++ b/angular-signalr-hub/index.d.ts @@ -6,6 +6,11 @@ /// /// +declare module "angular-signalr-hub" { + let _: string; + export = _; +} + declare namespace ngSignalr { interface HubFactory { /** diff --git a/angular-ui-router-default/angular-ui-router-default-tests.ts b/angular-ui-router-default/angular-ui-router-default-tests.ts new file mode 100644 index 0000000000..2b6bfbe61e --- /dev/null +++ b/angular-ui-router-default/angular-ui-router-default-tests.ts @@ -0,0 +1,39 @@ +/// + +angular.module("test", [ + "ui.router", + "ui.router.default" +]) + .config(function($stateProvider: angular.ui.IStateProvider) { + $stateProvider + .state('concrete', { + // no abstract or default + }) + .state('string', { + abstract: true, + default: 'concrete' + }) + .state('func_str', { + abstract: true, + default: function($rootScope): string { return $rootScope.test; } + }) + .state('func_promise', { + abstract: true, + default: function($q: ng.IQService): ng.IPromise { + return $q.when("concrete"); + } + }) + .state('injection_str', { + abstract: true, + default: ["$rootScope", function($rootScope) { + return $rootScope.test; + }] + }) + .state('injection_promise', { + abstract: true, + default: ["$q", function($q: ng.IQService) { + return $q.when("concrete"); + }] + }) + ; + }); diff --git a/angular-ui-router-default/angular-ui-router-default.d.ts b/angular-ui-router-default/angular-ui-router-default.d.ts new file mode 100644 index 0000000000..9d102681cf --- /dev/null +++ b/angular-ui-router-default/angular-ui-router-default.d.ts @@ -0,0 +1,17 @@ +// Type definitions for angular-ui-router-default 0.5+ +// Project: https://github.com/nonplus/angular-ui-router-default +// Definitions by: Stepan Riha +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.ui { + export type StateDefaultSpecifier = string + | ((...args: any[]) => string) + | ((...args: any[]) => ng.IPromise) + | (string | ((...args: any[]) => string))[] + | (string | ((...args: any[]) => ng.IPromise))[]; + interface IState { + default?: StateDefaultSpecifier + } +} diff --git a/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts b/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts new file mode 100644 index 0000000000..3f14b2a40f --- /dev/null +++ b/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts @@ -0,0 +1,30 @@ +/// + +angular.module("test", [ + "ui.bootstrap", + "ui.router", + "ui.router.default" +]) + .config(function($stateProvider: angular.ui.IStateProvider) { + $stateProvider + .state('contacts', { + // no modal + resolve: { + a: function() { + return "a"; + }, + b: function() { + return ["a", "b"]; + } + } + }) + .state('contacts.contact', { + // boolean modal + modal: true + }) + .state('contacts.contact.edit', { + // string[] modal + modal: ["a", "b"] + }) + ; + }); diff --git a/angular-ui-router-uib-modal/angular-ui-router-uib-modal.d.ts b/angular-ui-router-uib-modal/angular-ui-router-uib-modal.d.ts new file mode 100644 index 0000000000..598fe964fe --- /dev/null +++ b/angular-ui-router-uib-modal/angular-ui-router-uib-modal.d.ts @@ -0,0 +1,12 @@ +// Type definitions for angular-ui-uib-modal 0.11+ (ui.router module) +// Project: https://github.com/nonplus/angular-ui-router-uib-modal +// Definitions by: Stepan Riha +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.ui { + interface IState { + modal?: boolean | string[]; + } +} diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts index 639534e8be..29a344426f 100644 --- a/angular/angular-tests.ts +++ b/angular/angular-tests.ts @@ -191,8 +191,25 @@ mod.controller({ MyCtrl2: function() {}, MyCtrl3: ['$fooService', function($fooService: any) { }] }); -mod.directive('name', function ($scope: ng.IScope) { }) -mod.directive('name', ['$scope', function ($scope: ng.IScope) { }]) +mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => { + return (scope, el, attrs) => { + let foo = 'none'; + el.click(e => { + foo = e.type; + $rootScope.$apply(); + }); + scope.$watch(() => foo, () => el.text(foo)); + }; +}); +mod.directive('myDirectiveB', ['$rootScope', function ($rootScope: ng.IRootScopeService) { + return { + link(scope, el, attrs) { + el.click(e => { + el.hide(); + }); + } + }; +}]); mod.directive({ myFooDir: () => ({ template: 'my-foo-dir.tpl.html' @@ -278,8 +295,14 @@ namespace TestQ { b: string; c: boolean; } + interface TValue { + e: number; + f: boolean; + } var tResult: TResult; var promiseTResult: angular.IPromise; + var tValue: TValue; + var promiseTValue: angular.IPromise; var $q: angular.IQService; var promiseAny: angular.IPromise; @@ -348,6 +371,22 @@ namespace TestQ { let result: angular.IPromise; result = $q.when(tResult); result = $q.when(promiseTResult); + + result = $q.when(tValue, (result: TValue) => tResult); + result = $q.when(tValue, (result: TValue) => tResult, (any) => any); + result = $q.when(tValue, (result: TValue) => tResult, (any) => any, (any) => any); + + result = $q.when(promiseTValue, (result: TValue) => tResult); + result = $q.when(promiseTValue, (result: TValue) => tResult, (any) => any); + result = $q.when(promiseTValue, (result: TValue) => tResult, (any) => any, (any) => any); + + result = $q.when(tValue, (result: TValue) => promiseTResult); + result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any); + result = $q.when(tValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); + + result = $q.when(promiseTValue, (result: TValue) => promiseTResult); + result = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => any); + result = $q.when(promiseTValue, (result: TValue) => promiseTResult, (any) => any, (any) => any); } } diff --git a/angular/index.d.ts b/angular/index.d.ts index e7e1ccce71..324a0bd64b 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -1043,6 +1043,7 @@ declare namespace angular { * @param value Value or a promise */ when(value: IPromise|T): IPromise; + when(value: IPromise|T, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; /** * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. */ @@ -1779,7 +1780,7 @@ declare namespace angular { /////////////////////////////////////////////////////////////////////////// interface IDirectiveFactory { - (...args: any[]): IDirective; + (...args: any[]): IDirective | IDirectiveLinkFn; } interface IDirectiveLinkFn { @@ -1787,8 +1788,8 @@ declare namespace angular { scope: IScope, instanceElement: JQuery, instanceAttributes: IAttributes, - controller: {}, - transclude: ITranscludeFunction + controller?: IController | IController[] | {[key: string]: IController}, + transclude?: ITranscludeFunction ): void; } @@ -1816,7 +1817,6 @@ declare namespace angular { controller?: string | Injectable; controllerAs?: string; /** - * @deprecated * Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before * the controller constructor is called, this use is now deprecated. Please place initialization code that * relies upon bindings inside a $onInit method on the controller, instead. diff --git a/angular/legacy/angular-sanitize-1.2-tests.ts b/angular/legacy/angular-sanitize-1.2-tests.ts index 94bb6615ec..644d40b364 100644 --- a/angular/legacy/angular-sanitize-1.2-tests.ts +++ b/angular/legacy/angular-sanitize-1.2-tests.ts @@ -1,10 +1,32 @@ -var shouldBeString: string; +/////////////////////////////////////////////////////////////////////////////// +// Variables +/////////////////////////////////////////////////////////////////////////////// +let shouldBeString: string; +let testInputText: string = 'TEST'; -declare var $sanitizeService: ng.sanitize.ISanitizeService; -shouldBeString = $sanitizeService(shouldBeString); +/////////////////////////////////////////////////////////////////////////////// +// Test sanitize service +/////////////////////////////////////////////////////////////////////////////// +declare let $sanitizeService: ng.sanitize.ISanitizeService; +shouldBeString = $sanitizeService(testInputText); -declare var $linky: ng.sanitize.filter.ILinky; -shouldBeString = $linky(shouldBeString); -shouldBeString = $linky(shouldBeString, shouldBeString); +/////////////////////////////////////////////////////////////////////////////// +// Test `linky` filter +/////////////////////////////////////////////////////////////////////////////// +declare let $linky: ng.sanitize.filter.ILinky; + +// Should be string for simple text and target parameters +shouldBeString = $linky(testInputText, testInputText); + +// Should be string for simple text, target and attributes parameters +let attributesAsFunction = () => { +}; +shouldBeString = $linky(shouldBeString, testInputText, { + "attributeKey1": "attributeValue1", + "attributeKey2": "attributeValue2" +}); +shouldBeString = $linky(shouldBeString, testInputText, (url: string) => { + return {"attributeKey1": "attributeValue1"} +}); \ No newline at end of file diff --git a/apn/index.d.ts b/apn/index.d.ts index 7a36c396b4..83d7d98ccd 100644 --- a/apn/index.d.ts +++ b/apn/index.d.ts @@ -137,6 +137,7 @@ export declare class Connection extends events.EventEmitter { } export interface NotificationAlertOptions { title?: string; + subtitle?: string; body: string; "title-loc-key"?: string; "title-loc-args"?: string[]; diff --git a/applicationinsights/index.d.ts b/applicationinsights/index.d.ts index 96d5773fa5..45c89556a6 100644 --- a/applicationinsights/index.d.ts +++ b/applicationinsights/index.d.ts @@ -346,24 +346,24 @@ interface Client { * Log an incoming http request to your server. The request data will be tracked during the response "finish" event if it is successful or the request "error" * event if it fails. The request duration is automatically calculated as the timespan between when the trackRequest method was called, and when the response "finish" * or request "error" events were fired. - * @param request The http.ServerRequest object to track + * @param request The http.IncomingMessage object to track * @param response The http.ServerResponse object for this request * @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty. */ - trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: { + trackRequest(request: any /* http.IncomingMessage */, response: any /* http.ServerResponse */, properties?: { [key: string]: string; }): void; /** * Log an incoming http request to your server. The request data is tracked synchronously rather than waiting for the response "finish"" or request "error"" events. * Use this if you need your request telemetry to respect custom app insights operation and user context (for example if you set any appInsights.client.context.tags). - * @param request The http.ServerRequest object to track + * @param request The http.IncomingMessage object to track * @param response The http.ServerResponse object for this request * @param ellapsedMilliseconds The duration for this request. Defaults to 0. * @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty. * @param error An error that was returned for this request if it was unsuccessful. Defaults to null. */ - trackRequestSync(request: any /*http.ServerRequest */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: { + trackRequestSync(request: any /*http.IncomingMessage */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: { [key: string]: string;}, error?: any) : void; /** diff --git a/archiver/archiver-tests.ts b/archiver/archiver-tests.ts index 3bef66a44c..d79b29f079 100644 --- a/archiver/archiver-tests.ts +++ b/archiver/archiver-tests.ts @@ -11,4 +11,12 @@ var readStream = FS.createReadStream('./archiver.d.ts'); archiver.pipe(writeStream); archiver.append(readStream, {name: 'archiver.d.ts'}); -archiver.finalize(); \ No newline at end of file +archiver.finalize(); + +archiver.directory('./path', './someOtherPath'); +archiver.directory('./path', { name: "testName"} ); + +archiver.directory('./', "", {}); +archiver.directory('./', {name: 'test'}, {}); + +archiver.bulk({ mappaing: {} }); \ No newline at end of file diff --git a/archiver/index.d.ts b/archiver/index.d.ts index df824c3915..d67705e2ea 100644 --- a/archiver/index.d.ts +++ b/archiver/index.d.ts @@ -25,6 +25,11 @@ interface nameInterface { interface Archiver extends STREAM.Transform { pipe(writeStream: FS.WriteStream): void; append(source: FS.ReadStream | Buffer | string, name: nameInterface): void; + + directory(dirpath: string, destpath: nameInterface | string): void; + directory(dirpath: string, destpath: nameInterface | string, data: any | Function): void; + + bulk(mappings: any): void; finalize(): void; } diff --git a/assert/index.d.ts b/assert/index.d.ts index abd31688f1..35220dbb87 100644 --- a/assert/index.d.ts +++ b/assert/index.d.ts @@ -1,10 +1,15 @@ -// Type definitions for assert and power-assert -// Project: https://github.com/Jxck/assert -// Project: https://github.com/twada/power-assert +// Type definitions for assert +// Project: https://github.com/defunctzombie/commonjs-assert // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// copy from assert external module in node.d.ts +// Definitions for commonjs-assert match that of node.js' assert module, +// but commonjs-assert is intended to be used as an independent module, +// for instance when making a stand-alone site or app that doesn't have +// access to node modules. For that reason, these definitions define a +// "assert" module. This will conflict with node.d.ts and other assert +// modules such as "power-assert", but a project should realistically +// only be using one of these at a time. declare function assert(value:any, message?:string):void; declare namespace assert { @@ -51,3 +56,7 @@ declare namespace assert { export function ifError(value:any):void; } + +declare module "assert" { + export = assert; +} diff --git a/async-polling/async-polling-tests.ts b/async-polling/async-polling-tests.ts new file mode 100644 index 0000000000..ec9e5200f2 --- /dev/null +++ b/async-polling/async-polling-tests.ts @@ -0,0 +1,64 @@ +/// + +import * as AsyncPolling from "async-polling"; + +// Tests based on examples in https://github.com/cGuille/async-polling#readme + +AsyncPolling(end => { + end(); +}, 3000).run(); + +function someAsynchroneProcess(callback: (error?: Error, response?: any) => any): any { + callback(); +} + +let polling = AsyncPolling(end => { + someAsynchroneProcess(function (error, response) { + if (error) { + end(error); + return; + } + + end(null, response); + }); +}, 3000); +polling.on("error", (error: Error) => {}); +polling.on("result", (result: any) => {}); +polling.run(); +polling.stop(); + +AsyncPolling(function(end) { + this.stop(); + end(); +}, 3000).run(); + +let i = 0; + +polling = AsyncPolling(function(end) { + ++i; + if (i === 3) { + return end(new Error("i is " + i)); + } + if (i >= 5) { + this.stop(); + return end(null, `#${i} stop`); + } + end(null, `#${i} wait a second...`); +}, 1000); + +const eventNames: AsyncPolling.EventName[] = ["run", "start", "end", "schedule", "stop"]; +eventNames.forEach(eventName => { + polling.on(eventName, () => { + console.log("lifecycle:", eventName); + }); +}); + +polling.on("result", (result: any) => { + console.log("result:", result); +}); + +polling.on("error", (error: Error) => { + console.error("error:", error); +}); + +polling.run(); \ No newline at end of file diff --git a/async-polling/async-polling.d.ts b/async-polling/async-polling.d.ts new file mode 100644 index 0000000000..579d041e37 --- /dev/null +++ b/async-polling/async-polling.d.ts @@ -0,0 +1,18 @@ +// Type definitions for AsyncPolling +// Project: https://github.com/cGuille/async-polling +// Definitions by: Zlatko Andonovski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "async-polling" { + module AsyncPolling { + export type EventName = "run"|"start"|"error"|"result"|"end"|"schedule"|"stop"; + } + + function AsyncPolling(pollingFunc: (end: (err?: Error, result?: Result) => any) => any, delay: number): { + run: () => any; + stop: () => any; + on: (eventName: AsyncPolling.EventName, listener: Function) => any; + } + + export = AsyncPolling; +} \ No newline at end of file diff --git a/async/async-tests.ts b/async/async-tests.ts index de5fbb387f..5bd138fb06 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -1,23 +1,24 @@ - - -var fs, path; +/// +/// +import * as fs from "fs"; function callback() {} +function funcStringCbErrBoolean(v:string, cb:(err:Error,res:boolean) => void) {} -async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); -async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); -async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { }); +async.map(['file1', 'file2', 'file3'], fs.stat, function (err:Error, results:Array) { }); +async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err:Error, results:Array) { }); +async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err:Error, results:Array) { }); -async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); -async.select(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); +async.filter(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.filterSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.filterLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.select(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.selectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.selectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); -async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); -async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); +async.reject(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.rejectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,results:Array) { }); +async.rejectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,results:Array) { }); async.parallel([ function () { }, @@ -41,9 +42,9 @@ var openFilesObj = { file2: "fileTwo" } -var saveFile = function () { } -async.each(openFiles, saveFile, function (err) { }); -async.eachSeries(openFiles, saveFile, function (err) { }); +var saveFile = function (file:string,cb:(err:Error)=>void) { } +async.each(openFiles, saveFile, function (err:Error) { }); +async.eachSeries(openFiles, saveFile, function (err:Error) { }); var documents, requestApi; async.eachLimit(documents, 20, requestApi, function (err) { }); @@ -73,9 +74,9 @@ async.foldl(numArray, 0, reducer, function (err, result) { }); async.reduceRight(numArray, 0, reducer, function (err, result) { }); async.foldr(numArray, 0, reducer, function (err, result) { }); -async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); +async.detect(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err,result:string) { }); +async.detectSeries(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err,result) { }); +async.detectLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err,result) { }); async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { fs.stat(file, function (err, stats) { @@ -83,13 +84,13 @@ async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { }); }, function (err, results) { }); -async.some(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); -async.any(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.some(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.someLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.any(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); -async.every(['file1', 'file2', 'file3'], path.exists, function (result) { }); -async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); -async.all(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.every(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.everyLimit(['file1', 'file2', 'file3'], 2, funcStringCbErrBoolean, function (err:Error,result:boolean) { }); +async.all(['file1', 'file2', 'file3'], funcStringCbErrBoolean, function (err:Error,result:boolean) { }); async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); @@ -107,7 +108,7 @@ async.series([ ], function (err, results) { }); -async.series([ +async.series([ function (callback) { callback(null, 'one'); }, @@ -131,7 +132,7 @@ async.series({ }, function (err, results) { }); -async.series({ +async.series({ one: function (callback) { setTimeout(function () { callback(null, 1); @@ -171,7 +172,7 @@ async.parallel([ ], function (err, results) { }); -async.parallel([ +async.parallel([ function (callback) { setTimeout(function () { callback(null, 'one'); @@ -200,7 +201,7 @@ async.parallel({ }, function (err, results) { }); -async.parallel({ +async.parallel({ one: function (callback) { setTimeout(function () { callback(null, 1); @@ -266,7 +267,7 @@ async.waterfall([ ], function (err, result) { }); -var q = async.queue(function (task: any, callback) { +var q = async.queue(function (task: any, callback) { console.log('hello ' + task.name); callback(); }, 2); @@ -319,7 +320,7 @@ q.resume(); q.kill(); // tests for strongly typed tasks -var q2 = async.queue(function (task: string, callback) { +var q2 = async.queue(function (task: string, callback) { console.log('Task: ' + task); callback(); }, 1); @@ -382,10 +383,10 @@ async.retry({ times: 3, interval: (retryCount) => { return 200 * retryCount; } } async.parallel([ - function (callback) { }, + function (callback: ( err:Error, val:string ) => void ) { }, function (callback) { } ], -function (results) { +function (err:Error,results:Array) { async.series([ function (callback) { }, function email_link(callback) { } @@ -435,3 +436,357 @@ async.dir(function (name, callback) { callback(null, { hello: name }); }, 1000); }, "world"); + +// each + +async.each({ + "a": 1, + "b": 2 +}, function(val: number, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.each: ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.each: done."); + +}); + +async.eachSeries({ + "a": 1, + "b": 2 +}, function(val: number, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.eachSeries: ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.eachSeries: done."); + +}); + +async.eachLimit({ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + "f": 6 +}, 2, function(val: number, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.eachLimit: ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.eachLimit: done."); + +}); + +// forEachOf/eachOf + +async.eachOf({ + "a": 1, + "b": 2 +}, function(val: number, key: string, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.forEachOf/eachOf: ${key} = ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.forEachOf/eachOf: done."); + +}); + +async.forEachOfSeries({ + "a": 1, + "b": 2 +}, function(val: number, key: string, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.forEachOfSeries: ${key} = ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.forEachOfSeries: done."); + +}); + +async.forEachOfLimit({ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + "f": 6 +}, 2, function(val: number, key: string, next: ErrorCallback): void { + + setTimeout(function(): void { + + console.log(`async.forEachOfLimit: ${key} = ${val}`); + + next(); + + }, 500); + +}, function(err?: Error): void { + + console.log("async.forEachOfLimit: done."); + +}); + +// map + +async.map({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.map: ${val}`); + + next(null, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.map: done with results", results); + +}); + +async.mapSeries({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.mapSeries: ${val}`); + + next(null, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.mapSeries: done with results", results); + +}); + +async.mapLimit({ + "a": 1, + "b": 2, + "c": 3, + "d": 4, + "e": 5, + "f": 6 +}, 2, function(val: number, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.mapLimit: ${val}`); + + next(null, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.mapLimit: done with results", results); + +}); + +// mapValues + +async.mapValues({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, key: string, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.mapValues: ${key} = ${val}`); + + next(null, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.mapValues: done with results", results); + +}); + +async.mapValuesSeries({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, key: string, next: AsyncResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.mapValuesSeries: ${key} = ${val}`); + + next(null, val.toString()); + + }, 500); + +}, function(err: Error, results: string[]): void { + + console.log("async.mapValuesSeries: done with results", results); + +}); + +// filter/select/reject + +async.filter({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, next: AsyncBooleanResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.filter/select: ${val}`); + + next(null, val % 2 === 0); + + }, 500); + +}, function(err: Error, results: number[]): void { + + console.log("async.filter/select: done with results", results); + +}); + +async.reject({ + "a": 1, + "b": 2, + "c": 3 +}, function(val: number, next: AsyncBooleanResultCallback): void { + + setTimeout(function(): void { + + console.log(`async.reject: ${val}`); + + next(null, val % 2 === 0); + + }, 500); + +}, function(err: Error, results: number[]): void { + + console.log("async.reject: done with results", results); + +}); + +// concat + +async.concat({ + "a": "1", + "b": "2", + "c": "3" +}, function(item: string, next: AsyncResultCallback): void { + + console.log(`async.concat: ${item}`); + + next(null, [item, item, item]); + +}, function(err: Error, results: string[]) { + + console.log("async.concat: done with results", results); + +}); + +// detect/find + +async.detect({ + "a": 1, + "b": 2, + "c": 3 +}, function(item: number, next: AsyncBooleanResultCallback): void { + + console.log(`async.detect/find: ${item}`); + + next(null, item > 1); + +}, function(err: Error, result: number) { + + if (err) { + + console.log(err); + + } else { + + console.log("async.detect/find: done with result", result); + } + +}); + +// every/all + +async.every({ + "a": 1, + "b": 2, + "c": 3 +}, function(item: number, next: AsyncBooleanResultCallback): void { + + console.log(`async.every/all: ${item}`); + + next(null, item > 0); + +}, function(err: Error, result: boolean) { + + console.log("async.every/all: done with result", result); + +}); + +// some/any + +async.some({ + "a": 1, + "b": 2, + "c": 3 +}, function(item: number, next: AsyncBooleanResultCallback): void { + + console.log(`async.some/any: ${item}`); + + next(null, item > 2); + +}, function(err: Error, result: boolean) { + + console.log("async.some/any: done with result", result); + +}); diff --git a/async/index.d.ts b/async/index.d.ts index 96da35c1ea..45d39ea955 100644 --- a/async/index.d.ts +++ b/async/index.d.ts @@ -1,24 +1,26 @@ // Type definitions for Async 2.0.1 // Project: https://github.com/caolan/async -// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman +// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman , Angus Fenying // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Dictionary { [key: string]: T; } -interface ErrorCallback { (err?: Error): void; } -interface AsyncResultCallback { (err: Error, result: T): void; } -interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } -interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } +interface ErrorCallback { (err?: T): void; } +interface AsyncWaterfallCallback { (err: E, ...args: any[]): void; } +interface AsyncBooleanResultCallback { (err: E, truthValue: boolean): void; } +interface AsyncResultCallback { (err: E, result: T): void; } +interface AsyncResultArrayCallback { (err: E, results: T[]): void; } +interface AsyncResultObjectCallback { (err: E, results: Dictionary): void; } -interface AsyncFunction { (callback: (err?: Error, result?: T) => void): void; } -interface AsyncIterator { (item: T, callback: ErrorCallback): void; } -interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } -interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } -interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } -interface AsyncBooleanIterator { (item: T, callback: (err: string, truthValue: boolean) => void): void; } +interface AsyncFunction { (callback: (err?: E, result?: T) => void): void; } +interface AsyncIterator { (item: T, callback: ErrorCallback): void; } +interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } +interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } +interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } +interface AsyncBooleanIterator { (item: T, callback: AsyncBooleanResultCallback): void; } -interface AsyncWorker { (task: T, callback: ErrorCallback): void; } -interface AsyncVoidFunction { (callback: ErrorCallback): void; } +interface AsyncWorker { (task: T, callback: ErrorCallback): void; } +interface AsyncVoidFunction { (callback: ErrorCallback): void; } interface AsyncQueue { length(): number; @@ -26,10 +28,10 @@ interface AsyncQueue { running(): number; idle(): boolean; concurrency: number; - push(task: T, callback?: ErrorCallback): void; - push(task: T[], callback?: ErrorCallback): void; - unshift(task: T, callback?: ErrorCallback): void; - unshift(task: T[], callback?: ErrorCallback): void; + push(task: T, callback?: ErrorCallback): void; + push(task: T[], callback?: ErrorCallback): void; + unshift(task: T, callback?: ErrorCallback): void; + unshift(task: T[], callback?: ErrorCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -51,8 +53,8 @@ interface AsyncPriorityQueue { concurrency: number; started: boolean; paused: boolean; - push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; - push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -88,104 +90,122 @@ interface AsyncCargo { interface Async { // Collections - each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; - eachSeries(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; - eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; - forEachOf(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; - forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - forEachOfSeries(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; - forEachOfSeries(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void; - forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; - map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - mapValuesLimit(obj: {[name: string]: T}, limit: number, iteratee: (value: string, key: T, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; - mapValues(obj: {[name: string]: T}, iteratee: (value: string, key: T, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + each(arr: Dictionary, iterator: AsyncIterator, callback?: ErrorCallback): void; + eachSeries: typeof async.each; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; + eachLimit(arr: Dictionary, limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; + forEach: typeof async.each; + forEachSeries: typeof async.each; + forEachLimit: typeof async.eachLimit; + forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOf(obj: Dictionary, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfSeries: typeof async.forEachOf; + forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfLimit(obj: Dictionary, limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + eachOf: typeof async.forEachOf; + eachOfSeries: typeof async.forEachOf; + eachOfLimit: typeof async.forEachOfLimit; + map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + map(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + mapSeries: typeof async.map; + mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + mapLimit(arr: Dictionary, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; + mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultCallback): void; mapValuesSeries: typeof async.mapValues; - filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - select(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - filterSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - selectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - selectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - reject(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - rejectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - rejectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): any; - reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; - reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + filter(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filter(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filterSeries: typeof async.filter; + filterLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + filterLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; + select: typeof async.filter; + selectSeries: typeof async.filter; + selectLimit: typeof async.filterLimit; + reject: typeof async.filter; + rejectSeries: typeof async.filter; + rejectLimit: typeof async.filterLimit; + reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): void; + inject: typeof async.reduce; + foldl: typeof async.reduce; + reduceRight: typeof async.reduce; + foldr: typeof async.reduce; + detect(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detect(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detectSeries: typeof async.detect; + detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; + detectLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; find: typeof async.detect; - detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; - findSeries: typeof async.detectSeries; - detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): any; + findSeries: typeof async.detect; findLimit: typeof async.detectLimit; - sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - anyLimit: typeof async.someLimit; - someSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + some(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + some(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + someSeries: typeof async.some; + someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + someLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + any: typeof async.some; anySeries: typeof async.someSeries; - any(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; - every(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - all(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; - concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; - concatSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + anyLimit: typeof async.someLimit; + every(arr: T[], iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + every(arr: Dictionary, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + everySeries: typeof async.every; + everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + everyLimit(arr: Dictionary, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; + all: typeof async.every; + allSeries: typeof async.every; + allLimit: typeof async.everyLimit; + + concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + concat(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; + concatSeries: typeof async.concat; // Control Flow - series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; - series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; - parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; - parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; - whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void; - forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void; - waterfall(tasks: Function[], callback?: (err: Error, results?: any) => void): void; + series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; + series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; + parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; + parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; + whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; + until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: ErrorCallback): void; + during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; + doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; + forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; + waterfall(tasks: Function[], callback?: AsyncResultCallback): void; compose(...fns: Function[]): Function; seq(...fns: Function[]): Function; applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. - queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; - priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; - cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; - auto(tasks: any, concurrency?: number, callback?: (error: Error, results: any) => void): void; - autoInject(tasks: any, callback?: (error: Error, results: any) => void): void; - retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; - retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; - retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; - apply(fn: Function, ...arguments: any[]): AsyncFunction; + queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; + priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; + cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; + auto(tasks: any, concurrency?: number, callback?: AsyncResultCallback): void; + autoInject(tasks: any, callback?: AsyncResultCallback): void; + retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: AsyncResultCallback): void; + retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: AsyncResultCallback): void; + retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; + apply(fn: Function, ...arguments: any[]): AsyncFunction; nextTick(callback: Function, ...args: any[]): void; setImmediate: typeof async.nextTick; - allLimit(arr: T[], limit: number, iteratee: AsyncBooleanIterator, cb?: (result: boolean) => any) : any; - everySeries(arr: T[], iteratee: AsyncBooleanIterator, cb?: (result: boolean) => any) : any - allSeries: typeof async.everySeries; + reflect(fn: AsyncFunction) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void; + reflectAll(tasks: AsyncFunction[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[]; - reflect(fn: AsyncFunction) : (callback: (err: void, result: {error?: Error, value?: T}) => void) => void; - reflectAll(tasks: AsyncFunction[]): ((callback: (err: void, result: {error?: Error, value?: T}) => void) => void)[]; + timeout(fn: AsyncFunction, milliseconds: number, info: any): AsyncFunction; - timeout(fn: AsyncFunction, milliseconds: number, info: any): AsyncFunction; + times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + transform(arr: T[], iteratee: (acc: R[], item: T, key: string, callback: (error?: E) => void) => void): void; + transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: string, callback: (error?: E) => void) => void): void; + transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void): void; + transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void): void; - transform(arr: T[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void; - transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: string, callback: (error?: Error) => void) => void): void; - transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void; - transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: Error) => void) => void): void; - - race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; + race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; // Utils memoize(fn: Function, hasher?: Function): Function; diff --git a/autobahn/index.d.ts b/autobahn/index.d.ts index 0d3f8a068e..e93d3c065f 100644 --- a/autobahn/index.d.ts +++ b/autobahn/index.d.ts @@ -213,7 +213,7 @@ declare namespace autobahn { retry_delay_jitter?: number; url?: string; protocols?: string[]; - onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler; + onchallenge?: OnChallengeHandler; realm?: string; authmethods?: string[]; authid?: string; diff --git a/automapper-ts/automapper-ts-tests.ts b/automapper-ts/automapper-ts-tests.ts new file mode 100644 index 0000000000..5e18f75789 --- /dev/null +++ b/automapper-ts/automapper-ts-tests.ts @@ -0,0 +1,1990 @@ +/// +/// + +var globalScope = this; + +declare module jasmine { + interface Matchers { + toEqualData(data: any): boolean; + fail(message: string): boolean; + } +} + +declare function expect(): jasmine.Matchers; + +module AutoMapperJs { + describe('AutoMapper', () => { + beforeEach(() => { + jasmine.addMatchers(ExtendJasmine.addCustomMatchers()); + + // clear mappings (please, don't try this at home!) + for (var key in (automapper)._mappings) { + if (!(automapper)._mappings.hasOwnProperty(key)) { + continue; + } + delete (automapper)._mappings[key]; + } + }); + + it('should validate mapping using strictMode set to \'true\' (with valid mappings)', () => { + // arrange + automapper.createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp); + + // act and assert + automapper.assertConfigurationIsValid(true); + }); + + it('should set strictMode to \'true\' when no value is provided and validate (with valid mappings)', () => { + // arrange + automapper.createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp); + + // act and assert + automapper.assertConfigurationIsValid(); + }); + + it('should validate mapping using strictMode set to \'false\'', () => { + // arrange + automapper.createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp); + automapper.createMap('AssertMappingConfigUntestableA', 'AssertMappingConfigUntestableB'); + + // act and assert + automapper.assertConfigurationIsValid(false); + }); + + it('should fail when validating mappings using strictMode set to \'true\' (with unvalidatable mappings)', () => { + // arrange + automapper.createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp); + automapper.createMap('AssertMappingConfigUntestableA', 'AssertMappingConfigUntestableB'); + + // act + try { + automapper.assertConfigurationIsValid(true); + } catch (e) { + // assert + var errorMessage: string = e.message; + var dekeyedErrorMessage = + errorMessage.substr(0, errorMessage.indexOf('\'') + 1) + + errorMessage.substr(errorMessage.lastIndexOf('\'')); + + expect(dekeyedErrorMessage).toEqual(`Mapping '' cannot be validated, since mapping.sourceType or mapping.destinationType are unspecified.`); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + + it('should fail when auto mapping a property which does not exist on destination', () => { + // arrange + var srcType = AssertConfigPropertiesProp; + var dstType = AssertConfigPropertiesProp2; + + var srcName = AutoMapperHelper.getClassName(srcType); + var dstName = AutoMapperHelper.getClassName(dstType); + + automapper.createMap(srcType, dstType); + + try { + // act + automapper.assertConfigurationIsValid(true); + } catch (e) { + // assert + expect(e.message).toEqual(`Mapping '${srcName}=>${dstName}' is invalid: Source member 'prop' is configured to be mapped, ` + + `but does not exist on destination type (source: '${srcName}', destination: '${dstName}').`); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + + it('should succeed when mapping objects with ignored properties not existing on the other side', () => { + // arrange + var srcType = AssertConfigPropertiesProp; + var dstType = AssertConfigPropertiesProp2; + + var srcName = AutoMapperHelper.getClassName(srcType); + var dstName = AutoMapperHelper.getClassName(dstType); + + automapper + .createMap(srcType, dstType) + .forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }) + .forMember('prop2', (opts: IMemberConfigurationOptions) => { opts.ignore(); }); + + // act and assert + automapper.assertConfigurationIsValid(true); + }); + + it('should fail when auto mapping a property which does not exist on source', () => { + // arrange + var srcType = AssertConfigPropertiesProp; + var dstType = AssertConfigPropertiesPropProp2; + + var srcName = AutoMapperHelper.getClassName(srcType); + var dstName = AutoMapperHelper.getClassName(dstType); + + automapper.createMap(srcType, dstType); + + try { + // act + automapper.assertConfigurationIsValid(true); + } catch (e) { + // assert + expect(e.message).toEqual(`Mapping '${srcName}=>${dstName}' is invalid: Destination member 'prop2' does not exist on source type (source: '${srcName}', destination: '${dstName}').`); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + + it('should fail when providing configuration for a property which does not exist on destination', () => { + // arrange + var srcType = AssertConfigPropertiesProp; + var dstType = AssertConfigPropertiesPropProp2; + + var srcName = AutoMapperHelper.getClassName(srcType); + var dstName = AutoMapperHelper.getClassName(dstType); + + automapper + .createMap(srcType, dstType) + .forMember('prop3', (opts: IMemberConfigurationOptions) => { opts.ignore(); }); + + try { + // act + automapper.assertConfigurationIsValid(true); + } catch (e) { + // assert + expect(e.message).toEqual(`Mapping '${srcName}=>${dstName}' is invalid: Destination member 'prop3' is configured, but does not exist on destination type (source: '${srcName}', destination: '${dstName}').`); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + + it('should fail when providing configuration for a property which does not exist on source', () => { + // arrange + var srcType = AssertConfigPropertiesProp; + var dstType = AssertConfigPropertiesPropProp2; + + var srcName = AutoMapperHelper.getClassName(srcType); + var dstName = AutoMapperHelper.getClassName(dstType); + + automapper + .createMap(srcType, dstType) + .forSourceMember('prop2', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }); + + try { + // act + automapper.assertConfigurationIsValid(true); + } catch (e) { + // assert + expect(e.message).toEqual(`Mapping '${srcName}=>${dstName}' is invalid: Source member 'prop2' is configured, but does not exist on source type (source: '${srcName}', destination: '${dstName}').`); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + }); + + describe('AutoMapper (asynchronous mapping)', () => { + beforeEach(() => { + jasmine.addMatchers(ExtendJasmine.addCustomMatchers()); + }); + + it('should be able to map asynchronous using forMember', (done) => { + // arrange + var objFrom = { prop: 'prop' }; + + var fromKey = 'async-forMember-'; + var toKey = 'valid-1'; + + // act + automapper + .createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { + var func = (o: IMemberConfigurationOptions, c: IMemberCallback) => { + c(o.intermediatePropertyValue + ' (async)'); + }; + + // do something asynchronous + setTimeout((): void => { + func(opts, cb); + }, 10); + }) + .forMember('prop', (opts: IMemberConfigurationOptions) => { + return opts.intermediatePropertyValue + ' (sync)'; + }); + + automapper.mapAsync(fromKey, toKey, objFrom, (result: any) => { + // assert + expect(result.prop).toEqual(objFrom.prop + ' (async)' + ' (sync)'); + done(); + }); + }); + + it('should be able to map asynchronous using forMember in combination with a constant value', (done: () => void) => { + // arrange + var objFrom = { prop: 'prop' }; + + var fromKey = 'async-forMember-'; + var toKey = 'valid-2'; + + // act + automapper + .createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { + var func = (o: IMemberConfigurationOptions, c: IMemberCallback) => { + c(o.intermediatePropertyValue + ' (async)'); + }; + + // do something asynchronous + setTimeout((): void => { + func(opts, cb); + }, 10); + }) + .forMember('prop', 'Async With Constant Value'); + + automapper.mapAsync(fromKey, toKey, objFrom, (result: any) => { + // assert + expect(result.prop).toEqual('Async With Constant Value'); + done(); + }); + }); + + it('should be able to map asynchronous using an asynchronous forMember in combination with a synchronous forMember mapping', (done: () => void) => { + // arrange + var objFrom = { prop1: 'prop1', prop2: 'prop2' }; + + var fromKey = 'async-forMember-'; + var toKey = 'valid-3'; + + // act + automapper + .createMap(fromKey, toKey) + .forMember('prop1', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { + var func = (o: IMemberConfigurationOptions, c: IMemberCallback) => { + c(o.intermediatePropertyValue + ' (async)'); + }; + + // do something asynchronous + setTimeout((): void => { + func(opts, cb); + }, 10); + }) + .forMember('prop2', (opts: IMemberConfigurationOptions): any => opts.intermediatePropertyValue); + + automapper.mapAsync(fromKey, toKey, objFrom, (result: any) => { + // assert + expect(result.prop1).toEqual(objFrom.prop1 + ' (async)'); + expect(result.prop2).toEqual(objFrom.prop2); + done(); + }); + }); + + it('should fail when mapping an asynchronous mapping using synchronous map function', () => { + // arrange + var objFrom = { prop: 'prop' }; + + var fromKey = 'async-forMember-'; + var toKey = 'invalid-1'; + + automapper + .createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { + var func = (o: IMemberConfigurationOptions, c: IMemberCallback) => { + c(o.intermediatePropertyValue + ' (async)'); + } + + // do something asynchronous + setTimeout((): void => { + func(opts, cb); + }, 10); + }) + .forMember('prop', (opts: IMemberConfigurationOptions) => { + return opts.intermediatePropertyValue + ' (sync)'; + }); + + // act + try { + var objB = automapper.map(fromKey, toKey, objFrom); + } catch (e) { + // assert + expect(e.message).toEqual('Impossible to use asynchronous mapping using automapper.map(); use automapper.mapAsync() instead.'); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + + it('should be able to map asynchronous using forSourceMember', (done: () => void) => { + // arrange + var objFrom = { prop: 'prop' }; + + var fromKey = 'async-forSourceMember-'; + var toKey = 'valid-1'; + + automapper + .createMap(fromKey, toKey) + .forSourceMember('prop', (opts: ISourceMemberConfigurationOptions, cb: IMemberCallback) => { + var func = (o: ISourceMemberConfigurationOptions, c: IMemberCallback) => { + c('AsyncValue'); + }; + + // do something asynchronous + setTimeout((): void => { + func(opts, cb); + }, 10); + }); + + // act + automapper.mapAsync(fromKey, toKey, objFrom, (result: any) => { + // assert + expect(result.prop).toEqual('AsyncValue'); + done(); + }); + }); + + it('should be able to use convertUsing to map an object with a custom asynchronous type resolver function', (done: () => void) => { + var objA = { propA: 'propA' }; + + var fromKey = '{D1534A0F-6120-475E-B7E2-BF2489C58571}'; + var toKey = '{1896FF99-1A28-4FE6-800B-072D5616B02D}'; + + automapper + .createMap(fromKey, toKey) + .convertUsing((opts: IResolutionContext, cb: IMapCallback): void => { + var func = (o: IResolutionContext, c: IMapCallback) => { + var res = { propA: o.sourceValue.propA + ' (custom async mapped with resolution context)' }; + c(res); + }; + + // do something asynchronous + setTimeout((): void => { + func(opts, cb); + }, 10); + }); + + // act + automapper.mapAsync(fromKey, toKey, objA, (result: any) => { + // assert + expect(result.propA).toEqual(objA.propA + ' (custom async mapped with resolution context)'); + done(); + }); + }); + + it('should asynchronously map an array', (done: () => void) => { + // arrange + var arrA = [{ prop1: 'From A', prop2: 'From A too' }]; + + var fromKey = '{60D9DGH6-DSEC-48GF-9BAC-0805FCAF91B7}'; + var toKey = '{AC6D5B97-9AE3-BERT-ZB60-AZFEDZXE541A}'; + + automapper.createMap(fromKey, toKey) + .forMember('prop1', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { + var func = (o: IMemberConfigurationOptions, c: IMemberCallback) => { + c(o.intermediatePropertyValue); + }; + + // do something asynchronous + setTimeout((): void => { + func(opts, cb); + }, 10); + }); + // act + var arrB = automapper.mapAsync(fromKey, toKey, arrA, (result: any) => { + // assert + expect(result).toEqualData(arrA); + done(); + }); + }); + }); + + describe('AutoMapper', () => { + beforeEach(() => { + jasmine.addMatchers(ExtendJasmine.addCustomMatchers()); + }); + + it('should have a global automapper object', () => { + expect(automapper).not.toBeUndefined(); + expect(automapper).not.toBeNull(); + + expect(automapper.createMap).not.toBeUndefined(); + expect(automapper.createMap).not.toBeNull(); + expect(typeof automapper.createMap === 'function').toBeTruthy(); + + expect(automapper.map).not.toBeUndefined(); + expect(automapper.map).not.toBeNull(); + expect(typeof automapper.map === 'function').toBeTruthy(); + }); + + it('should return the Singleton instance when instantiating the Singleton directly', () => { + // arrange + var caught = false; + + // act + var mapper = new AutoMapper(); + expect(automapper).toBe(mapper); + }); + + it('should use created mapping profile', () => { + // arrange + var fromKey = '{5700E351-8D88-4327-A216-3CC94A308EDF}'; + var toKey = '{BB33A261-3CA9-48FC-85E6-2C269F73728D}'; + + automapper.createMap(fromKey, toKey); + + // act + automapper.map(fromKey, toKey, {}); + + // assert + }); + + it('should fail when using a non-existing mapping profile', () => { + // arrange + var caught = false; + + var fromKey = '{5AEFD48C-4472-41E7-BA7E-0977A864E116}'; + var toKey = '{568DCA5E-477E-4739-86B2-38BB237B8EF8}'; + + // act + try { + automapper.map(fromKey, toKey, {}); + } catch (e) { + caught = true; + + // assert + expect(e.message).toEqual('Could not find map object with a source of ' + fromKey + ' and a destination of ' + toKey); + } + + if (!caught) { + // assert + expect().fail('Using a non-existing mapping profile should result in an error.'); + } + }); + + it('should be able to use forAllMemberMappings', () => { + // arrange + var fromKey = '{5700E351-8D88-4327-A216-3CCBHJ808EDF}'; + var toKey = '{BB33A261-3CA9-48FC-85E6-2C269FDFT28D}'; + + var source = { prop1: 'prop1', prop2: 'prop2' }; + var suffix = ' [forAllMembers]'; + + automapper.createMap(fromKey, toKey) + .forMember('prop1', (opts: IMemberConfigurationOptions): any => opts.intermediatePropertyValue) + .forMember('prop2', (opts: IMemberConfigurationOptions): any => opts.intermediatePropertyValue) + .forAllMembers((destinationObject: any, + destinationPropertyName: string, + value: any): void => { + destinationObject[destinationPropertyName] = value + suffix; + }); + + // act + var destination = automapper.map(fromKey, toKey, source); + + // assert + expect(destination.prop1).toEqual(source.prop1 + suffix); + expect(destination.prop2).toEqual(source.prop2 + suffix); + }); + + it('should be able to use forAllMemberMappings when automapping', () => { + // arrange + var fromKey = '{5700E351-8D88-4327-A216-3CCBHJ808EDF}'; + var toKey = '{BB33A261-3CA9-48FC-85E6-2C269FDFT28D}'; + + var source = { prop1: 'prop1', prop2: 'prop2' }; + var suffix = ' [forAllMembers]'; + + automapper.createMap(fromKey, toKey) + .forAllMembers((destinationObject: any, + destinationPropertyName: string, + value: any): void => { + destinationObject[destinationPropertyName] = value + suffix; + }); + + // act + var destination = automapper.map(fromKey, toKey, source); + + // assert + expect(destination.prop1).toEqual(source.prop1 + suffix); + expect(destination.prop2).toEqual(source.prop2 + suffix); + }); + + it('should accept multiple forMember calls for the same destination property and overwrite with the last one specified', () => { + //arrange + var objA = { prop1: 'From A', prop2: 'From A too' }; + + var fromKey = '{7AC4134B-ECC1-464B-B144-5B9D8F5B568E}'; + var toKey = '{2BDE907C-1CE6-4CC5-A601-9A94CC665837}'; + + automapper + .createMap(fromKey, toKey) + .forMember('prop1', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop2'); }) + .forMember('prop1', (opts: IMemberConfigurationOptions) => { opts.ignore(); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop2: objA.prop2 }); + }); + + it('should be able to ignore a source property using the forSourceMember function', () => { + // arrange + var objA = { prop1: 'From A', prop2: 'From A too' }; + + var fromKey = '{AD88481E-597B-4C1B-967B-3D700B8BAB0F}'; + var toKey = '{2A6714C4-784E-47D3-BBF4-6205834EC8D5}'; + + automapper + .createMap(fromKey, toKey) + .forSourceMember('prop1', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop2: 'From A too' }); + }); + + it('should be able to custom map a source property using the forSourceMember function', () => { + // arrange + var objA = { prop1: 'From A', prop2: 'From A too' }; + + var fromKey = '{AD88481E-597B-4C1B-967B-3D700B8BAB0F}'; + var toKey = '{2A6714C4-784E-47D3-BBF4-6205834EC8D5}'; + + automapper + .createMap(fromKey, toKey) + .forSourceMember('prop1', (opts: ISourceMemberConfigurationOptions) => { return 'Yeah!'; }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop1: 'Yeah!', prop2: 'From A too' }); + }); + + it('should be able to ignore a source property already specified (by forMember) using the forSourceMember function', () => { + // arrange + var objA = { prop1: 'From A', prop2: 'From A too' }; + + var fromKey = '{AD88481E-597B-4C1B-967B-3D701B8CAB0A}'; + var toKey = '{2A6714C4-784E-47D3-BBF4-620583DEC86A}'; + + automapper + .createMap(fromKey, toKey) + .forMember('prop1', 12) + .forSourceMember('prop1', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop2: 'From A too' }); + }); + + it('should fail when forSourceMember is used with anything else than a function', () => { + // arrange + var caught = false; + + var fromKey = '{5EE20DF9-84B3-4A6A-8C5D-37AEDC44BE87}'; + var toKey = '{986C959D-2E2E-41FA-9857-8EF519467AEB}'; + + try { + // act + automapper + .createMap(fromKey, toKey) + .forSourceMember('prop1', 12); + } catch (e) { + // assert + caught = true; + expect(e.message).toEqual('Configuration of forSourceMember has to be a function with one (sync) or two (async) options parameters.'); + } + + if (!caught) { + // assert + expect().fail('Using anything else than a function with forSourceMember should result in an error.'); + } + }); + + it('should be able to use forMember to map a source property to a destination property with a different name', () => { + //arrange + var objA = { prop1: 'From A', prop2: 'From A too' }; + + var fromKey = '{7AC4134B-ECC1-464B-B144-5B9D8F5B568E}'; + var toKey = '{2BDE907C-1CE6-4CC5-A601-9A94CC665837}'; + + automapper + .createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop2'); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop1: objA.prop1, prop: objA.prop2 }); + }); + + it('should use forAllMembers function for each mapped destination property when specified', () => { + // arrange + var objA = { prop1: 'From A', prop2: 'From A too' }; + + var fromKey = '{C4056539-FA86-4398-A10B-C41D3A791F26}'; + var toKey = '{01C64E8D-CDB5-4307-9011-0C7F1E70D115}'; + + var forAllMembersSpy = jasmine.createSpy('forAllMembersSpy').and.callFake((destinationObject: any, destinationProperty: string, value: any) => { + destinationObject[destinationProperty] = value; + }); + + automapper + .createMap(fromKey, toKey) + .forAllMembers(forAllMembersSpy); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(forAllMembersSpy).toHaveBeenCalled(); + expect(forAllMembersSpy.calls.count()).toBe(Object.keys(objB).length); + }); + + it('should be able to use forMember with a constant value', () => { + // arrange + var objA = { prop: 1 }; + + var fromKey = '{54E67626-B877-4824-82E6-01E9F411B78F}'; + var toKey = '{2D7FDB88-97E9-45EF-A111-C9CC9C188227}'; + + var constantResult = 2; + + automapper + .createMap(fromKey, toKey) + .forMember('prop', constantResult); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.prop).toBe(constantResult); + }); + + it('should be able to use forMember with a function returning a constant value', () => { + // arrange + var objA = { prop: 1 }; + + var fromKey = '{74C12B56-1DD1-4EA0-A640-D1F814971124}'; + var toKey = '{BBC617B8-26C8-42A0-A204-45CC77073355}'; + + var constantResult = 3; + + automapper + .createMap(fromKey, toKey) + .forMember('prop', () => { return constantResult; }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.prop).toBe(constantResult); + }); + + it('should be able to use forMember with a function using the source object', () => { + // arrange + var objA = { prop: { subProp: { value: 1 } } }; + + var fromKey = '{54E67626-B877-4824-82E6-01E9F411B78F}'; + var toKey = '{2D7FDB88-97E9-45EF-A111-C9CC9C188227}'; + + automapper + .createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions) => { return opts.sourceObject[opts.sourcePropertyName].subProp.value * 2; }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.prop).toBe(objA.prop.subProp.value * 2); + }); + + it('should be able to use forMember to ignore a property', () => { + // arrange + var objA = { prop: 1 }; + + var fromKey = '{76D26B33-888A-4DF7-ABDA-E5B99E944272}'; + var toKey = '{18192391-85FF-4729-9A08-5954FCFE3954}'; + + automapper + .createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions) => { opts.ignore(); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.hasOwnProperty('prop')).not.toBeTruthy(); + }); + + it('should be able to use forMember to map a source property to a destination property with a different name', () => { + // arrange + var objA = { propDiff: 1 }; + + var fromKey = '{A317A36A-AD92-4346-A015-AE06FC862DB4}'; + var toKey = '{03B05E43-3028-44FD-909F-652E2DA5E607}'; + + automapper + .createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions) => { opts.mapFrom('propDiff'); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.prop).toEqual(objA.propDiff); + }); + + it('should be able to use stack forMember calls to map a source property to a destination property using multiple mapping steps', () => { + // arrange + var birthdayString = '2000-01-01T00:00:00.000Z'; + var objA = { birthdayString: birthdayString }; + + var fromKey = '{564F1F57-FD4F-413C-A9D3-4B1C1333A20B}'; + var toKey = '{F9F45923-2D13-4EF1-9685-4883AD1D2F98}'; + + automapper + .createMap(fromKey, toKey) + .forMember('birthday', (opts: IMemberConfigurationOptions) => { opts.mapFrom('birthdayString'); }) + .forMember('birthday', (opts: IMemberConfigurationOptions) => { return new Date(opts.intermediatePropertyValue); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.birthday instanceof Date).toBeTruthy(); + expect(objB.birthday.toISOString()).toEqual('2000-01-01T00:00:00.000Z'); + }); + + it('should be able to use stack forMember calls to map a source property to a destination property using multiple mapping steps in any order', () => { + // arrange + var birthdayString = '2000-01-01T00:00:00.000Z'; + var objA = { birthdayString: birthdayString }; + + var fromKey = '{1609A9B5-6083-448B-8FD6-51DAD106B63D}'; + var toKey = '{47AF7D2D-A848-4C5B-904F-39402E2DCDD5}'; + + automapper + .createMap(fromKey, toKey) + .forMember('birthday', (opts: IMemberConfigurationOptions) => { return new Date(opts.intermediatePropertyValue); }) + .forMember('birthday', (opts: IMemberConfigurationOptions) => { opts.mapFrom('birthdayString'); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.birthday instanceof Date).toBeTruthy(); + expect(objB.birthday.toISOString()).toEqual('2000-01-01T00:00:00.000Z'); + }); + + it('should not map properties that are not an object\'s own properties', () => { + var objA = new ClassA(); + objA.propA = 'propA'; + + var fromKey = '{A317A36A-AD92-4346-A015-AE06FC862DB4}'; + var toKey = '{03B05E43-3028-44FD-909F-652E2DA5E607}'; + + automapper + .createMap(fromKey, toKey); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.propA).toEqual(objA.propA); + }); + + it('should be able to use convertUsing to map an object with a custom type resolver function', () => { + var objA = { propA: 'propA' }; + + var fromKey = '{D1534A0F-6120-475E-B7E2-BF2489C58571}'; + var toKey = '{1896FF99-1A28-4FE6-800B-072D5616B02D}'; + + automapper + .createMap(fromKey, toKey) + .convertUsing(function(resolutionContext: IResolutionContext): any { + return { propA: resolutionContext.sourceValue.propA + ' (custom mapped with resolution context)' }; + }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.propA).toEqual(objA.propA + ' (custom mapped with resolution context)'); + }); + + it('should be able to use convertUsing to map an object with a custom type resolver class', () => { + // arrange + var objA = { propA: 'propA' }; + + var fromKey = '{6E7F5757-1E55-4B55-BB86-44FF5B33DE2F}'; + var toKey = '{8521AE41-C3AF-4FCD-B7C7-A915C037D69E}'; + + automapper + .createMap(fromKey, toKey) + .convertUsing(CustomTypeConverterDefinition); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.propA).toEqual(objA.propA + ' (convertUsing with a class definition)'); + }); + + it('should be able to use convertUsing to map an object with a custom type resolver instance', () => { + // arrange + // NOTE BL The CustomTypeConverter class definition is defined at the bottom, since TypeScript + // does not allow classes to be defined inline. + + var objA = { propA: 'propA' }; + + var fromKey = '{BDF3758C-B38E-4343-95B6-AE0F80C8B9C4}'; + var toKey = '{13DD7AE1-4177-4A80-933B-B60A55859E50}'; + + automapper + .createMap(fromKey, toKey) + .convertUsing(new CustomTypeConverterInstance()); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.propA).toEqual(objA.propA + ' (convertUsing with a class instance)'); + }); + + it('should fail when directly using the type converter base class', () => { + // arrange + var caught = false; + var objA = { propA: 'propA' }; + + var fromKey = 'should fail when directly using '; + var toKey = 'the type converter base class'; + + automapper + .createMap(fromKey, toKey) + .convertUsing(TypeConverter); + + try { + // act + var objB = automapper.map(fromKey, toKey, objA); + } catch (e) { + // assert + caught = true; + expect(e.message).toEqual('The TypeConverter.convert method is abstract. Use a TypeConverter extension class instead.'); + } + + if (!caught) { + // assert + expect().fail('Using the type converter base class directly should fail.'); + } + }); + + it('should fail when convertUsing is used with a function not having exactly one (resolutionContext) parameter.', () => { + // arrange + var caught = false; + + var fromKey = '{1EF9AC11-BAA1-48DB-9C96-9DFC40E33BCA}'; + var toKey = '{C4DA81D3-9072-4140-BFA7-431C35C01F54}'; + + try { + // act + automapper + .createMap(fromKey, toKey) + .convertUsing(() => { + return {}; + }); + + //var objB = automapper.map(fromKey, toKey, objA); + } catch (e) { + // assert + caught = true; + expect(e.message).toEqual('The value provided for typeConverterClassOrFunction is invalid. ' + + 'Error: The function provided does not provide exactly one (resolutionContext) parameter.'); + } + + if (!caught) { + // assert + expect().fail('Using anything else than a function with forSourceMember should result in an error.'); + } + }); + + it('should be able to use convertToType to map a source object to a destination object which is an instance of a given class', () => { + //arrange + var objA = { ApiProperty: 'From A' }; + + + var fromKey = '{7AC4134B-ECC1-464B-B144-5C9D8F5B5A7E}'; + var toKey = '{2BDE907C-1CE6-4CC5-A601-9A94CA6C4737}'; + + automapper + .createMap(fromKey, toKey) + .forMember('property', (opts: IMemberConfigurationOptions) => { opts.mapFrom('ApiProperty'); }) + .convertToType(DemoToBusinessType); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB instanceof DemoToBusinessType).toBeTruthy(); + expect(objB.property).toEqual(objA.ApiProperty); + }); + + it('should be able to use a condition to map or ignore a property', () => { + // arrange + var objA = { prop: 1, prop2: 2 }; + + var fromKey = '{76D23B33-888A-4DF7-BEBE-E5B99E944272}'; + var toKey = '{18192191-85FE-4729-A980-5954FCFE3954}'; + + automapper + .createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions) => { opts.condition((sourceObject: any) => sourceObject.prop === 0); }) + .forMember('prop2', (opts: IMemberConfigurationOptions) => { opts.condition((sourceObject: any) => sourceObject.prop2 === 2); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB.hasOwnProperty('prop')).not.toBeTruthy(); + expect(objB.hasOwnProperty('prop2')).toBeTruthy(); + }); + + it('should be able to ignore all unmapped members using the ignoreAllNonExisting function', () => { + // arrange + var objA = { + propA: 'Prop A', + propB: 'Prop B', + propC: 'Prop C', + propD: 'Prop D' + }; + + var fromKey = '{AD88481E-597B-4C1C-9A7B-3D70DB8BCB0F}'; + var toKey = '{2A6614C4-784E-47D3-BBF4-6205834EA8D1}'; + + automapper + .createMap(fromKey, toKey) + .forMember('propA', (opts: IMemberConfigurationOptions) => opts.mapFrom('propA')) + .ignoreAllNonExisting(); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ propA: 'Prop A' }); + }); + + it('should be able to create a map and use it using class types', () => { + // arrange + var objA = new ClassA(); + objA.propA = 'Value'; + + // act + automapper.createMap(ClassA, ClassB); + var objB = automapper.map(ClassA, ClassB, objA); + + // assert + expect(objB instanceof ClassB).toBeTruthy(); + expect(objB).toEqualData({ propA: 'Value' }); + }); + + it('should throw an error when creating a map using class types and specifying a conflicting destination type', () => { + // arrange + var caught = false; + + // act + try { + automapper + .createMap(ClassA, ClassB) + .convertToType(ClassC); + } catch (e) { + caught = true; + // assert + expect(e.message).toEqual('Destination type class can only be set once.'); + } + + if (!caught) { + // assert + expect(null).fail('AutoMapper should throw an error when creating a map using class types and specifying a conflicting destination type.'); + } + }); + + it('should be able to use forMember to map a nested source property to a destination property', () => { + //arrange + var objA = { prop1: { propProp1: 'From A' }, prop2: 'From A too' }; + + var fromKey = '{7AC4134B-ECC1-464B-B144-5B9D8F5B568E}'; + var toKey = '{2BDE907C-1CE6-4CC5-A601-9A94CC665837}'; + + automapper + .createMap(fromKey, toKey) + .forMember('propFromNestedSource', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop1.propProp1'); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop2: objA.prop2, propFromNestedSource: objA.prop1.propProp1 }); + }); + + it('should be able to stack forMember calls when mapping a nested source property to a destination property', () => { + //arrange + var objA = { prop1: { propProp1: 'From A' }, prop2: 'From A too' }; + var addition = ' - sure works!'; + + var fromKey = '{7AC4134B-ECC1-464B-B144-5B99CF5B558E}'; + var toKey = '{2BDE907C-1CE6-4CC5-56A1-9A94CC6658C7}'; + + automapper + .createMap(fromKey, toKey) + .forMember('propFromNestedSource', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop1.propProp1'); }) + .forMember('propFromNestedSource', (opts: IMemberConfigurationOptions) => { return opts.intermediatePropertyValue + addition; }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop2: objA.prop2, propFromNestedSource: objA.prop1.propProp1 + addition }); + }); + + it('should be able to stack forMember calls when mapping a nested source property to a destination property in any order', () => { + //arrange + var objA = { prop1: { propProp1: 'From A' }, prop2: 'From A too' }; + var addition = ' - sure works!'; + + var fromKey = '{7AC4134B-ECD1-46EB-B14A-5B9D8F5B5F8E}'; + var toKey = '{BBD6907C-ACE6-4FC8-A60D-1A943C66D83F}'; + + automapper + .createMap(fromKey, toKey) + .forMember('propFromNestedSource', (opts: IMemberConfigurationOptions) => { return opts.intermediatePropertyValue + addition; }) + .forMember('propFromNestedSource', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop1.propProp1'); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop2: objA.prop2, propFromNestedSource: objA.prop1.propProp1 + addition }); + }); + + it('should be able to stack forMember mapFrom calls when mapping a nested source property to a destination property', () => { + //arrange + var objA = { prop1: { propProp1: 'From A', propProp2: { propProp2Prop: 'From A' } }, prop2: 'From A too' }; + var addition = ' - sure works!'; + + var fromKey = '{7AC4134B-ECD1-46EB-B14A-5B9D8F5B5F8E}'; + var toKey = '{BBD6907C-ACE6-4FC8-A60D-1A943C66D83F}'; + + automapper + .createMap(fromKey, toKey) + .forMember('propFromNestedSource', (opts: IMemberConfigurationOptions) => { return opts.intermediatePropertyValue + addition; }) + .forMember('propFromNestedSource', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop1.propProp2.propProp2Prop'); }) + .forMember('propFromNestedSource', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop1.propProp1'); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop2: objA.prop2, propFromNestedSource: objA.prop1.propProp1 + addition }); + }); + + it('should be able to use forMember to map to a nested destination', () => { + //arrange + var objA = { prop1: { propProp1: 'From A', propProp2: { propProp2Prop: 'From A' } }, prop2: 'From A too' }; + var addition = ' - sure works!'; + + var fromKey = '{7AC4134B-ECD1-46EB-B14A-5B9D8F5B5F8E}'; + var toKey = '{BBD6907C-ACE6-4FC8-A60D-1A943C66D83F}'; + + automapper + .createMap(fromKey, toKey) + .forMember('nested.property', (opts: IMemberConfigurationOptions) => { return opts.intermediatePropertyValue + addition; }) + .forMember('nested.property', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop1.propProp2.propProp2Prop'); }) + .forMember('nested.property', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop1.propProp1'); }); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop2: objA.prop2, nested: { property: objA.prop1.propProp1 + addition }}); + }); + + it('should be able to use mapFrom to switch properties and ignore a property as well', () => { + // arrange + var objA = { prop1: 'From A', prop2: 'From A too', prop3: 'Also from A (really)' }; + + var fromKey = 'should be able to use mapFrom to switch '; + var toKey = 'properties and ignore a property as well'; + + // act + automapper + .createMap(fromKey, toKey) + .forMember('prop1', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop2'); }) + .forMember('prop2', (opts: IMemberConfigurationOptions) => { opts.mapFrom('prop1'); }) + .forSourceMember('prop3', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }); + + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop1: objA.prop2, prop2: objA.prop1 }); + }); + + it('should be able to create a new property using a constant value', () => { + // arrange + var objA = { }; + + var fromKey = 'should be able to create a new property '; + var toKey = 'using a constant value'; + + // act + automapper + .createMap(fromKey, toKey) + .forMember('prop4', (opts: IMemberConfigurationOptions) => { return 12; }); + + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop4: 12 }); + }); + + it('should just return source object when no properties are created using null source object', () => { + // arrange + var objA: any = null; + + var fromKey = 'should just return source object when no '; + var toKey = 'properties created using null source object'; + + // act + automapper + .createMap(fromKey, toKey); + + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toBeNull(); + }); + + it('should be able to create a new property using a constant value (null source object)', () => { + // arrange + var objA: any = null; + + var fromKey = 'should be able to create a new property '; + var toKey = 'using a constant value (null source object)'; + + // act + automapper + .createMap(fromKey, toKey) + .forMember('prop4', (opts: IMemberConfigurationOptions) => { return 12; }); + + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData({ prop4: 12 }); + }); + }); + + it('should map a source object with empty nested objects', () => { + // arrange + var src: any = { + homeAddress: null /*{ + address1: '200 Main St', + address2: '200 Main St', + city: 'Los Angeles', + state: 'CA', + zip: '90000' + }*/, + businessAddress: { + address1: '200 Main St', + // address2: '200 Main St', + city: 'Los Angeles', + state: 'CA', + zip: '90000' + } + }; + + var fromKey = '{60E9DC56-D6E1-48FF-9BAC-0805FCAF91B7}'; + var toKey = '{AC6D5A97-9AEF-42C7-BD60-A5F3D17E541A}'; + + automapper + .createMap(fromKey, toKey) + // .forMember('homeAddress.address1', (opts: IMemberConfigurationOptions) => { opts.mapFrom('homeAddress.address1'); }) + .forMember('homeAddress.address2', (opts: IMemberConfigurationOptions) => { opts.mapFrom('homeAddress.address2'); }) + // .forMember('homeAddress.city', (opts: IMemberConfigurationOptions) => { opts.mapFrom('homeAddress.city'); }) + // .forMember('homeAddress.state', (opts: IMemberConfigurationOptions) => { opts.mapFrom('homeAddress.state'); }) + // .forMember('homeAddress.zip', (opts: IMemberConfigurationOptions) => { opts.mapFrom('homeAddress.zip'); }) + + .forMember('businessAddress.address1', (opts: IMemberConfigurationOptions) => { opts.mapFrom('businessAddress.address1'); }) + .forMember('businessAddress.address2', (opts: IMemberConfigurationOptions) => null) + .forMember('businessAddress.city', (opts: IMemberConfigurationOptions) => { opts.mapFrom('businessAddress.city'); }) + .forMember('businessAddress.state', (opts: IMemberConfigurationOptions) => { opts.mapFrom('businessAddress.state'); }) + .forMember('businessAddress.zip', (opts: IMemberConfigurationOptions) => { opts.mapFrom('businessAddress.zip'); }) + ; + + // act + var dst = automapper.map(fromKey, toKey, src); + + // assert + expect(dst).not.toBeNull(); + + expect(dst.homeAddress).toBeNull(); + + expect(dst.businessAddress.address1).toBe(src.businessAddress.address1); + expect(dst.businessAddress.address2).toBeUndefined(); + expect(dst.businessAddress.city).toBe(src.businessAddress.city); + expect(dst.businessAddress.state).toBe(src.businessAddress.state); + expect(dst.businessAddress.zip).toBe(src.businessAddress.zip); + }); + + describe('AutoMapper - Currying support', () => { + beforeEach(() => { + jasmine.addMatchers(ExtendJasmine.addCustomMatchers()); + }); + + it('should be able to use currying when calling createMap', () => { + // arrange + var fromKey = '{808D9D7F-AA89-4D07-917E-A528F055EE64}'; + var toKey1 = '{B364C0A0-9E24-4424-A569-A4C14101947C}'; + var toKey2 = '{1055CA5A-4FC4-44CB-B4D8-B004F43D8840}'; + + var source = { prop: 'Value' }; + + // act + var mapFromKeyCurry = automapper.createMap(fromKey); + + mapFromKeyCurry(toKey1) + .forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }); + + mapFromKeyCurry(toKey2); + + var result1 = automapper.map(fromKey, toKey1, source); + var result2 = automapper.map(fromKey, toKey2, source); + + // assert + expect(typeof mapFromKeyCurry === 'function').toBeTruthy(); + expect(result1.prop).toBeUndefined(); + expect(result2.prop).toEqual(source.prop); + }); + + it('should be able to use currying (one parameter) when calling map', () => { + // arrange + var fromKey = 'should be able to use currying (one parameter)'; + var toKey1 = 'when calling map (1)'; + var toKey2 = 'when calling map (2)'; + + var source = { prop: 'Value' }; + + // act + var createMapFromKeyCurry = automapper.createMap(fromKey); + + createMapFromKeyCurry(toKey1) + .forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }); + + createMapFromKeyCurry(toKey2); + + var result1MapCurry = automapper.map(fromKey); + var result2MapCurry = automapper.map(fromKey); + + var result1 = result1MapCurry(toKey1, source); + var result2 = result2MapCurry(toKey2, source); + + // assert + expect(typeof createMapFromKeyCurry === 'function').toBeTruthy(); + expect(typeof result1MapCurry === 'function').toBeTruthy(); + expect(typeof result2MapCurry === 'function').toBeTruthy(); + + expect(result1.prop).toBeUndefined(); + expect(result2.prop).toEqual(source.prop); + }); + + it('should be able to use currying when calling map', () => { + // arrange + var fromKey = '{FC18523B-5A7C-4193-B938-B6AA2EABB37A}'; + var toKey1 = '{609202F4-15F7-4512-9178-CFAF073800E1}'; + var toKey2 = '{85096AE2-92FB-43D7-8FC3-EC14DDC1DFDD}'; + + var source = { prop: 'Value' }; + + // act + var createMapFromKeyCurry = automapper.createMap(fromKey); + + createMapFromKeyCurry(toKey1) + .forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }); + + createMapFromKeyCurry(toKey2); + + var result1MapCurry = automapper.map(fromKey, toKey1); + var result2MapCurry = automapper.map(fromKey, toKey2); + + var result1 = result1MapCurry(source); + var result2 = result2MapCurry(source); + + // assert + expect(typeof createMapFromKeyCurry === 'function').toBeTruthy(); + expect(typeof result1MapCurry === 'function').toBeTruthy(); + expect(typeof result2MapCurry === 'function').toBeTruthy(); + + expect(result1.prop).toBeUndefined(); + expect(result2.prop).toEqual(source.prop); + }); + + it('should be able to use currying when calling mapAsync', (done: () => void) => { + // arrange + var fromKey = '{1CA8523C-5A7C-4193-B938-B6AA2EABB37A}'; + var toKey1 = '{409212FD-15E7-4512-9178-CFAF073800EG}'; + var toKey2 = '{85096AE2-92FA-43N7-8FA3-EC14DDC1DFDE}'; + + var source = { prop: 'Value' }; + + // act + var createMapFromKeyCurry = automapper.createMap(fromKey); + + createMapFromKeyCurry(toKey1) + .forSourceMember('prop', (opts: ISourceMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value 1'); }); + + createMapFromKeyCurry(toKey2) + .forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value 2'); }); + + var result1MapCurry = automapper.mapAsync(fromKey, toKey1); + var result2MapCurry = automapper.mapAsync(fromKey, toKey2); + + // assert + expect(typeof createMapFromKeyCurry === 'function').toBeTruthy(); + expect(typeof result1MapCurry === 'function').toBeTruthy(); + expect(typeof result2MapCurry === 'function').toBeTruthy(); + + var resCount = 0; + var result1 = result1MapCurry(source, (result: any) => { + // assert + expect(result.prop).toEqual('Constant Value 1'); + if (++resCount === 2) { + done(); + } + }); + + var result2 = result2MapCurry(source, (result: any) => { + // assert + expect(result.prop).toEqual('Constant Value 2'); + if (++resCount === 2) { + done(); + } + }); + }); + + it('should be able to use currying when calling mapAsync with one parameter', (done: () => void) => { + // arrange + var fromKey = '{1CA8523C-5AVC-4193-BS38-B6AA2EABB37A}'; + var toKey = '{409212FD-1527-4512-9178-CFAG073800EG}'; + + var source = { prop: 'Value' }; + + // act + automapper.createMap(fromKey, toKey) + .forSourceMember('prop', (opts: ISourceMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value'); }); + + var mapAsyncCurry = automapper.mapAsync(fromKey); + + // assert + expect(typeof mapAsyncCurry === 'function').toBeTruthy(); + + var result = mapAsyncCurry(toKey, source, (result: any) => { + // assert + expect(result.prop).toEqual('Constant Value'); + done(); + }); + }); + + it('should be able to use currying when calling mapAsync with two parameters', (done: () => void) => { + // arrange + var fromKey = '{1CA852SC-5AVC-4193-BS38-B6AA2KABB3LA}'; + var toKey = '{409212FD-1Q27-45G2-9178-CFAG073800EG}'; + + var source = { prop: 'Value' }; + + // act + automapper.createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value'); }); + + var mapAsyncCurry = automapper.mapAsync(fromKey, toKey); + + // assert + expect(typeof mapAsyncCurry === 'function').toBeTruthy(); + + var result = mapAsyncCurry(source, (result: any) => { + // assert + expect(result.prop).toEqual('Constant Value'); + done(); + }); + }); + + it('should be able to use currying when calling mapAsync with three parameters', (done: () => void) => { + // NOTE BL 20151214 I wonder why anyone would like calling this one? Maybe this one will be removed in + // the future. Please get in touch if you need this one to stay in place... + + // arrange + var fromKey = '{1CA852SC-5AVC-ZZ93-BS38-B6AA2KABB3LA}'; + var toKey = '{409212FD-1Q27-45G2-91BB-CFAG0738WCEG}'; + + var source = { prop: 'Value' }; + + // act + automapper.createMap(fromKey, toKey) + .forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value'); }); + + var mapAsyncCurry = automapper.mapAsync(fromKey, toKey, source); + + // assert + expect(typeof mapAsyncCurry === 'function').toBeTruthy(); + + var result = mapAsyncCurry((result: any) => { + // assert + expect(result.prop).toEqual('Constant Value'); + done(); + }); + }); + + it('should fail when calling mapAsync without parameters', () => { + // arrange + + // act + try { + var mapAsyncCurry = (automapper).mapAsync(); + } catch (e) { + // assert + expect(e.message).toEqual('The mapAsync function expects between 1 and 4 parameters, you provided 0.'); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + + it('should fail when calling mapAsync with > 4 parameters', () => { + // arrange + + // act + try { + var mapAsyncCurry = (automapper).mapAsync(undefined, undefined, undefined, undefined, undefined); + } catch (e) { + // assert + expect(e.message).toEqual('The mapAsync function expects between 1 and 4 parameters, you provided 5.'); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + + + it('should fail when specifying < 2 parameters to the asynchronous map function', () => { + // arrange + + // act + try { + (new AsyncAutoMapper()).map(undefined); + } catch (e) { + // assert + expect(e.message).toEqual('The AsyncAutoMapper.map function expects between 2 and 5 parameters, you provided 1.'); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + + it('should fail when specifying > 5 parameters to the asynchronous map function', () => { + // arrange + + // act + try { + (new AsyncAutoMapper()).map(undefined, undefined, undefined, undefined, undefined, undefined); + } catch (e) { + // assert + expect(e.message).toEqual('The AsyncAutoMapper.map function expects between 2 and 5 parameters, you provided 6.'); + return; + } + + // assert + expect(null).fail('Expected error was not raised.'); + }); + }); + + describe('AutoMapper.initialize', () => { + beforeEach(() => { + jasmine.addMatchers(ExtendJasmine.addCustomMatchers()); + }); + + it('should use created mapping profile', () => { + // arrange + var fromKey = '{5700E351-8D88-A327-A216-3CC94A308EDE}'; + var toKey = '{BB33A261-3CA9-A8FC-85E6-2C269F73728C}'; + + automapper.initialize((config: IConfiguration) => { + config.createMap(fromKey, toKey); + }); + + // act + automapper.map(fromKey, toKey, {}); + + // assert + }); + + it('should be able to use a naming convention to convert Pascal case to camel case', () => { + automapper.initialize((config: IConfiguration) => { + config.addProfile(new PascalCaseToCamelCaseMappingProfile()); + }); + + const sourceKey = 'PascalCase'; + const destinationKey = 'CamelCase'; + + const sourceObject = { FullName: 'John Doe' }; + + automapper + .createMap(sourceKey, destinationKey) + .withProfile('PascalCaseToCamelCase'); + + var result = automapper.map(sourceKey, destinationKey, sourceObject); + + expect(result).toEqualData({ fullName: 'John Doe' }); + }); + + it('should be able to use a naming convention to convert camelCase to PascalCase', () => { + automapper.initialize((config: IConfiguration) => { + config.addProfile(new CamelCaseToPascalCaseMappingProfile()); + }); + + const sourceKey = 'CamelCase2'; + const destinationKey = 'PascalCase2'; + + const sourceObject = { fullName: 'John Doe' }; + + automapper + .createMap(sourceKey, destinationKey) + .withProfile('CamelCaseToPascalCase'); + + var result = automapper.map(sourceKey, destinationKey, sourceObject); + + expect(result).toEqualData({ FullName: 'John Doe' }); + }); + + it('should be able to use forMember besides using a profile', () => { + automapper.initialize((config: IConfiguration) => { + config.addProfile(new CamelCaseToPascalCaseMappingProfile()); + }); + + const sourceKey = 'CamelCase'; + const destinationKey = 'PascalCase'; + + const sourceObject = { fullName: 'John Doe', age: 20 }; + + automapper + .createMap(sourceKey, destinationKey) + .forMember('theAge', (opts: IMemberConfigurationOptions) => opts.mapFrom('age')) + .withProfile('CamelCaseToPascalCase'); + + var result = automapper.map(sourceKey, destinationKey, sourceObject); + + expect(result).toEqualData({ FullName: 'John Doe', theAge: sourceObject.age }); + }); + + it('should use profile when only profile properties are specified', () => { + automapper.initialize((config: IConfiguration) => { + config.addProfile(new ValidatedAgeMappingProfile2()); + }); + + const sourceKey = '{918D9D7F-AA89-4D07-917E-A528F07EEF42}'; + const destinationKey = '{908D9D6F-BA89-4D17-915E-A528E988EE64}'; + + const sourceObject = { fullName: 'John Doe', proclaimedAge: 21, ageOnId: 15 }; + + automapper + .createMap(sourceKey, destinationKey) + .withProfile('ValidatedAgeMappingProfile2'); + + var result = automapper.map(sourceKey, destinationKey, sourceObject); + + expect(result).toEqualData({ fullName: 'John Doe', age: sourceObject.ageOnId }); + expect(result instanceof Person).toBeTruthy(); + expect(result instanceof BeerBuyingYoungster).not.toBeTruthy(); + }); + + it('should fail when using a non-existimg profile', () => { + // arrange + var caught = false; + var profileName = 'Non-existing profile'; + const sourceKey = 'should fail when using '; + const destinationKey = 'a non-existimg profile'; + const sourceObject = { }; + + // act + try { + automapper + .createMap(sourceKey, destinationKey) + .withProfile(profileName); + var result = automapper.map(sourceKey, destinationKey, sourceObject); + } catch (e) { + caught = true; + + // assert + expect(e.message).toEqual('Could not find profile with profile name \'' + profileName + '\'.'); + } + + if (!caught) { + // assert + expect().fail('Using a non-existing mapping profile should result in an error.'); + } + }); + + it('should merge forMember calls when specifying the same destination property normally and using profile', () => { + automapper.initialize((config: IConfiguration) => { + config.addProfile(new ValidatedAgeMappingProfile()); + }); + + const sourceKey = '{808D9D7F-AA89-4D07-917E-A528F078E642}'; + const destinationKey = '{808D9D6F-BA89-4D17-915E-A528E178EE64}'; + + const sourceObject = { fullName: 'John Doe', proclaimedAge: 21, ageOnId: 15 }; + + automapper + .createMap(sourceKey, destinationKey) + .forMember('ageOnId', (opts: IMemberConfigurationOptions) => opts.ignore()) + .forMember('age', (opts: IMemberConfigurationOptions) => opts.mapFrom('proclaimedAge')) + .convertToType(BeerBuyingYoungster) + .withProfile('ValidatedAgeMappingProfile'); + + var result = automapper.map(sourceKey, destinationKey, sourceObject); + + expect(result).toEqualData({ fullName: 'John Doe', age: sourceObject.ageOnId }); + expect(result instanceof Person).toBeTruthy(); + expect(result instanceof BeerBuyingYoungster).not.toBeTruthy(); + }); + + it('should be able to use currying when calling initialize(cfg => cfg.createMap)', () => { + // arrange + var fromKey = '{808D9D7F-AA89-4D07-917E-A528F078EE64}'; + var toKey1 = '{B364C0A0-9E24-4424-A569-A4C14102147C}'; + var toKey2 = '{1055CA5A-4FC4-44CA-B4D8-B004F43D4440}'; + + var source = { prop: 'Value' }; + + // act + var mapFromKeyCurry: (destinationKey: string) => ICreateMapFluentFunctions; + + automapper.initialize((config: IConfiguration) => { + mapFromKeyCurry = config.createMap(fromKey); + + mapFromKeyCurry(toKey1) + .forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); }); + + mapFromKeyCurry(toKey2); + }); + + var result1 = automapper.map(fromKey, toKey1, source); + var result2 = automapper.map(fromKey, toKey2, source); + + // assert + expect(typeof mapFromKeyCurry === 'function').toBeTruthy(); + expect(result1.prop).toBeUndefined(); + expect(result2.prop).toEqual(source.prop); + }); + + }); + + describe('AutoMapper', () => { + beforeEach(() => { + jasmine.addMatchers(ExtendJasmine.addCustomMatchers()); + }); + + it('should auto map matching properties', () => { + // arrange + var objA = { prop1: 'From A', prop2: 'From A too' }; + + var fromKey = '{7F5AF9AC-2E9E-4676-8BE1-3E72866B11E8}'; + var toKey = '{8089EBDC-3BBB-4988-95F2-683CC1AD23A3}'; + + automapper.createMap(fromKey, toKey); + + // act + var objB = automapper.map(fromKey, toKey, objA); + + // assert + expect(objB).toEqualData(objA); + }); + + it('should map an array', () => { + // arrange + var arrA = [{ prop1: 'From A', prop2: 'From A too' }]; + + var fromKey = '{60D9DB56-D6E1-48FF-9BAC-0805FCAF91B7}'; + var toKey = '{AC6D5B97-9AE3-4267-BD60-A5FED17E541A}'; + + automapper.createMap(fromKey, toKey); + + // act + var arrB = automapper.map(fromKey, toKey, arrA); + + // assert + expect(arrB).toEqualData(arrA); + }); + + it('should map an array and handle empty items', () => { + // arrange + var arrA = [{ prop1: 'From A', prop2: 'From A too' }, undefined]; + + var fromKey = '{60D9DB56-D6E1-48FF-9BAC-0805FCAF91B7}'; + var toKey = '{AC6D5B97-9AE3-4267-BD60-A5FED17E541A}'; + + automapper.createMap(fromKey, toKey); + + // act + var arrB = automapper.map(fromKey, toKey, arrA); + + // assert + expect(arrB).toEqualData(arrA); + }); + }); + + /** AutoMapper helper functions */ + class AutoMapperHelper { + public static getClassName(classType: new() => any): string { + if (classType && (classType).name) { + return (classType).name; + } + // source: http://stackoverflow.com/a/13914278/702357 + if (classType && classType.constructor) { + let className = classType.toString(); + if (className) { + // classType.toString() is "function classType (...) { ... }" + let matchParts = className.match(/function\s*(\w+)/); + if (matchParts && matchParts.length === 2) { + return matchParts[1]; + } + } + + // for browsers which have name property in the constructor + // of the object, such as chrome + if ((classType.constructor).name) { + return (classType.constructor).name; + } + + if (classType.constructor.toString()) { + var str = classType.constructor.toString(); + + if (str.charAt(0) === '[') { + // executed if the return of object.constructor.toString() is "[object objectClass]" + var arr = str.match(/\[\w+\s*(\w+)\]/); + } else { + // executed if the return of object.constructor.toString() is "function objectClass () {}" + // (IE and Firefox) + var arr = str.match(/function\s*(\w+)/); + } + + if (arr && arr.length === 2) { + return arr[1]; + } + } + } + + throw new Error(`Unable to extract class name from type '${classType}'`); + } + } + + class AssertConfigPropertiesProp { + prop: string = undefined; // TODO Wiki: properties are only available when initialized: http://stackoverflow.com/a/20534039/702357 + } + + class AssertConfigPropertiesProp2 { + prop2: string = undefined; + } + + class AssertConfigPropertiesPropProp2 { + prop: string = undefined; + prop2: string = undefined; + } + + class ClassA { + public propA: string; + } + + class ClassB { + public propA: string; + } + + class ClassC { + public propA: string; + } + + class DemoToBusinessType { + } + + class CustomTypeConverterInstance extends TypeConverter { + public convert(resolutionContext: IResolutionContext): any { + return { propA: resolutionContext.sourceValue.propA + ' (convertUsing with a class instance)' }; + } + } + + class CustomTypeConverterDefinition extends TypeConverter { + public convert(resolutionContext: IResolutionContext): any { + return { propA: resolutionContext.sourceValue.propA + ' (convertUsing with a class definition)' }; + } + } + + class PascalCaseToCamelCaseMappingProfile extends Profile { + public sourceMemberNamingConvention: INamingConvention; + public destinationMemberNamingConvention: INamingConvention; + + public profileName = 'PascalCaseToCamelCase'; + + public configure() { + this.sourceMemberNamingConvention = new PascalCaseNamingConvention(); + this.destinationMemberNamingConvention = new CamelCaseNamingConvention(); + + super.createMap('a', 'b'); + } + } + + class CamelCaseToPascalCaseMappingProfile extends Profile { + public sourceMemberNamingConvention: INamingConvention; + public destinationMemberNamingConvention: INamingConvention; + + public profileName = 'CamelCaseToPascalCase'; + + public configure() { + this.sourceMemberNamingConvention = new CamelCaseNamingConvention(); + this.destinationMemberNamingConvention = new PascalCaseNamingConvention(); + } + } + + class ValidatedAgeMappingProfile extends Profile { + public profileName = 'ValidatedAgeMappingProfile'; + + public configure() { + const sourceKey = '{808D9D7F-AA89-4D07-917E-A528F078E642}'; + const destinationKey = '{808D9D6F-BA89-4D17-915E-A528E178EE64}'; + + this.createMap(sourceKey, destinationKey) + .forMember('proclaimedAge', (opts: IMemberConfigurationOptions) => opts.ignore()) + .forMember('age', (opts: IMemberConfigurationOptions) => opts.mapFrom('ageOnId')) + .convertToType(Person); + } + } + + class ValidatedAgeMappingProfile2 extends Profile { + public profileName = 'ValidatedAgeMappingProfile2'; + + public configure() { + const sourceKey = '{918D9D7F-AA89-4D07-917E-A528F07EEF42}'; + const destinationKey = '{908D9D6F-BA89-4D17-915E-A528E988EE64}'; + + this.createMap(sourceKey, destinationKey) + .forMember('proclaimedAge', (opts: IMemberConfigurationOptions) => opts.ignore()) + .forMember('age', (opts: IMemberConfigurationOptions) => opts.mapFrom('ageOnId')) + .convertToType(Person); + } + } + + class Person { + fullName: string; + age: number; + } + + class BeerBuyingYoungster extends Person { + } + class ExtendJasmine { + public static addCustomMatchers(): jasmine.CustomMatcherFactories { + var customMatchers: jasmine.CustomMatcherFactories = { + /** toEqualData compares to data objects using property matching */ + toEqualData: (util: jasmine.MatchersUtil, customEqualityTesters: Array): any => { + return { + compare: function (actual: any, expected: any): jasmine.CustomMatcherResult { + var pass = ExtendJasmine.equalsData(actual, expected); + return { + pass: pass, + message: pass + ? 'Data sets do equal. Congratulations ;) !' + : 'Data sets do not equal: expected "' + JSON.stringify(expected) + '", actual "' + JSON.stringify(actual) + '".' + }; + } + }; + }, + "fail": (util: jasmine.MatchersUtil, customEqualityTesters: Array): any => { + return { + compare: function (actual: any, message: string): jasmine.CustomMatcherResult { + return { + pass: false, + message: message || 'Jasmine test failed. Please provide a fix.' + }; + } + } + } + }; + return customMatchers; + } + + public static equalsData(actual: any, expected: any): boolean { + var toClass = {}.toString; + + // check array. + var actualType = toClass.call(actual); + var expectedType = toClass.call(expected); + + if (actualType === '[object Array]') { + // check both are arrays + if (expectedType !== '[object Array]') { + return false; + } + + // check both have same length + if (expected.length !== actual.length) { + return false; + } + + for (var i = 0; i < actual.length; i++) { + // check each item in the array + if (!ExtendJasmine.equalsData(actual[i], expected[i])) + return false; + } + } + else if (actualType === '[object Object]') { + // check both are objects + if (expectedType !== '[object Object]') { + return false; + } + + // check each property in the object + for (var propertyName in expected) { + if (!expected.hasOwnProperty(propertyName)) { + continue; + } + + if (!actual.hasOwnProperty(propertyName)) { + return false; + } + + if (!ExtendJasmine.equalsData(actual[propertyName], expected[propertyName])) + return false; + } + } else { + var actualIsUndefined = typeof actual === 'undefined'; + var expectedIsUndefined = typeof expected === 'undefined'; + if (actualIsUndefined !== expectedIsUndefined) { + return false; + } + + return actual === expected; + } + + return true; + } + } +} \ No newline at end of file diff --git a/automapper-ts/automapper-ts.d.ts b/automapper-ts/automapper-ts.d.ts new file mode 100644 index 0000000000..b2bf17a966 --- /dev/null +++ b/automapper-ts/automapper-ts.d.ts @@ -0,0 +1,559 @@ +// Type definitions for automapper-ts +// Project: https://github.com/loedeman/AutoMapper +// Definitions by: Bert Loedeman +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module AutoMapperJs { + /** + * AutoMapper implementation, for both creating maps and performing maps. Comparable usage and functionality to the original + * .NET AutoMapper library is the pursuit of this implementation. + */ + class AutoMapper { + /** + * Initializes the mapper with the supplied configuration. + * @param {(config: IConfiguration) => void} Configuration function to call. + */ + initialize(configFunction: (config: IConfiguration) => void): void; + + /** + * Create a createMap curry function which expects only a destination key. + * @param {string} sourceKey The map source key. + * @returns {(destinationKey: string) => ICreateMapFluentFunctions} + */ + createMap(sourceKey: string | (new() => any)): (destinationKey: string | (new() => any)) => ICreateMapFluentFunctions; + + /** + * Create a mapping profile. + * @param {string} sourceKey The map source key. + * @param {string} destinationKey The map destination key. + * @returns {Core.ICreateMapFluentFunctions} + */ + createMap(sourceKey: string | (new() => any), destinationKey: string | (new() => any)): ICreateMapFluentFunctions; + + /** + * Create a map curry function which expects a destination key and a source object. + * @param sourceKey Source key, for instance the source type name. + * @returns {(destinationKey: string, sourceObject: any) => any} + */ + map(sourceKey: string | (new() => any)): (destinationKey: string | (new() => any), sourceObject: any) => any; + + /** + * Create a map curry function which expects only a source object. + * @param sourceKey Source key, for instance the source type name. + * @param destinationKey Destination key, for instance the destination type name. + * @returns {(sourceObject: any) => any} + */ + map(sourceKey: string | (new() => any), destinationKey: string | (new() => any)): (sourceObject: any) => any; + + /** + * Execute a mapping from the source object to a new destination object with explicit mapping configuration and supplied mapping options (using createMap). + * @param sourceKey Source key, for instance the source type name. + * @param destinationKey Destination key, for instance the destination type name. + * @param sourceObject The source object to map. + * @returns {any} Destination object. + */ + map(sourceKey: string | (new() => any), destinationKey: string | (new() => any), sourceObject: any): any; + + /** + * Create a mapAsync curry function which expects a destination key, a source object and a callback function. + * @param sourceKey Source key, for instance the source type name. + * @returns {(destinationKey: string, sourceObject: any, callback: IMapCallback) => void} + */ + mapAsync(sourceKey: string | (new() => any)): (destinationKey: string | (new() => any), sourceObject: any, callback: IMapCallback) => void; + + /** + * Create a map curry function which expects only a source object and a callback function. + * @param sourceKey Source key, for instance the source type name. + * @param destinationKey Destination key, for instance the destination type name. + * @param sourceObject The source object to map. + * @returns {(callback: IMapCallback) => void} + */ + mapAsync(sourceKey: string | (new() => any), destinationKey: string | (new() => any), sourceObject: any): (callback: IMapCallback) => void; + + /** + * Create a map curry function which expects only a source object and a callback function. + * @param sourceKey Source key, for instance the source type name. + * @param destinationKey Destination key, for instance the destination type name. + * @returns {(sourceObject: any, callback: IMapCallback) => void} + */ + mapAsync(sourceKey: string | (new() => any), destinationKey: string | (new() => any)): (sourceObject: any, callback: IMapCallback) => void; + + /** + * Execute an asynchronous mapping from the source object to a new destination object with explicit mapping configuration and supplied mapping options (using createMap). + * @param sourceKey Source key, for instance the source type name. + * @param destinationKey Destination key, for instance the destination type name. + * @param sourceObject The source object to map. + * @param {IMapCallback} callback The callback to call when asynchronous mapping is complete. + */ + mapAsync(sourceKey: string | (new() => any), destinationKey: string | (new() => any), sourceObject: any, callback: IMapCallback): void; + + /** + * Validates mapping configuration by dry-running. Since JS does not + * fully support typing, it only checks if properties match on both + * sides. The function needs IMapping.sourceTypeClass and + * IMapping.destinationTypeClass to function. + * @param {boolean} strictMode Whether or not to fail when properties + * sourceTypeClass or destinationTypeClass + * are unavailable. + */ + assertConfigurationIsValid(strictMode?: boolean): void; + } + + class AsyncAutoMapper { + /* For Test Purposes Only */ + } + + /** + * Converts source type to destination type instead of normal member mapping + */ + class TypeConverter implements ITypeConverter { + /** + * Performs conversion from source to destination type. + * @param {IResolutionContext} resolutionContext Resolution context. + * @returns {any} Destination object. + */ + convert(resolutionContext: IResolutionContext): any; + } + + export class Profile implements IProfile { + /** Profile name */ + public profileName: string; + + /** Naming convention for source members */ + public sourceMemberNamingConvention: INamingConvention; + + /** Naming convention for destination members */ + public destinationMemberNamingConvention: INamingConvention; + + /** + * Create a createMap curry function which expects only a destination key. + * @param {string} sourceKey The map source key. + * @returns {(destinationKey: string) => ICreateMapFluentFunctions} + */ + protected createMap(sourceKey: string): (destinationKey: string) => ICreateMapFluentFunctions; + + /** + * Create a mapping profile. + * @param {string} sourceKey The map source key. + * @param {string} destinationKey The map destination key. + * @returns {Core.ICreateMapFluentFunctions} + */ + protected createMap(sourceKey: string, destinationKey: string): ICreateMapFluentFunctions; + + /** + * Implement this method in a derived class and call the CreateMap method to associate that map with this profile. + * Avoid calling the AutoMapper class / automapper instance from this method. + */ + public configure(): void; + } + + /** + * Defines the PascalCase naming convention strategy. + */ + class PascalCaseNamingConvention implements INamingConvention { + /** Regular expression on how to tokenize a member. */ + splittingExpression: RegExp; + + /** Character to separate on. */ + separatorCharacter: string; + + /** + * Transformation function called when this convention is the destination naming convention. + * @param {string[]} sourcePropertyNameParts Array containing tokenized source property name parts. + * @returns {string} Destination property name + */ + transformPropertyName(sourcePropertyNameParts: string[]): string; + } + + /** + * Defines the camelCase naming convention strategy. + */ + class CamelCaseNamingConvention implements INamingConvention { + /** Regular expression on how to tokenize a member. */ + splittingExpression: RegExp; + + /** Character to separate on. */ + separatorCharacter: string; + + /** + * Transformation function called when this convention is the destination naming convention. + * @param {string[]} sourcePropertyNameParts Array containing tokenized source property name parts. + * @returns {string} Destination property name + */ + transformPropertyName(sourcePropertyNameParts: string[]): string; + } + + + + interface IProperty { + name: string; + metadata: IPropertyMetadata; + level: number; + sourceMapping: boolean; + ignore: boolean; + async: boolean; + children?: IProperty[]; + destinations?: IProperty[]; + conversionValuesAndFunctions: any[]; + conditionFunction?: (sourceObject: any) => boolean; + } + + interface IPropertyMetadata { + mapping: IMapping; + root: IProperty; + parent: IProperty; + destinations: {[name: string]: IPropertyDestinationMetadata}; + destinationCount: number; + } + + interface IPropertyDestinationMetadata { + source: IProperty; + destination: IProperty; + } + + interface IMemberMappingMetaData { + destination: string; + source: string; + sourceMapping: boolean; + ignore: boolean; + async: boolean; + condition: (sourceObject: any) => boolean; + } + + /** + * Member mapping properties. + */ + interface IForMemberMapping { + /** The source member property name. */ + sourceProperty: string; + /** The destination member property name parts for nested property support (e.g. 'type.name'). */ + destinationProperty: string; + /** Source or destination mapping. */ + sourceMapping: boolean; + /** All mapping values and/or functions resulting from stacked for(Source)Member calls. */ + mappingValuesAndFunctions: Array; + /** Whether or not this destination property must be ignored. */ + ignore: boolean; + /** Whether or not this member mapping has an asynchronous mapping function. */ + async: boolean; + /** + * The object will only be mapped when the condition is met. + * @param {any} sourceObject The source object to check. + * @returns {boolean} + */ + conditionFunction: (sourceObject: any) => boolean; + } + + /** + * Interface for returning an object with available 'sub' functions to enable method chaining (e.g. automapper.createMap().forMember().forMember() ...) + */ + interface ICreateMapFluentFunctions { + /** + * Customize configuration for an individual destination member. + * @param sourceProperty The destination member property name. + * @param valueOrFunction The value or function to use for this individual member. + * @returns {IAutoMapperCreateMapChainingFunctions} + */ + forMember: (sourceProperty: string, valueOrFunction: any | + ((opts: IMemberConfigurationOptions) => any) | + ((opts: IMemberConfigurationOptions, cb: IMemberCallback) => void)) => ICreateMapFluentFunctions; + + /** + * Customize configuration for an individual source member. + * @param sourceProperty The source member property name. + * @param sourceMemberConfigFunction The function to use for this individual member. + * @returns {IAutoMapperCreateMapChainingFunctions} + */ + forSourceMember: (sourceProperty: string, + sourceMemberConfigFunction: ((opts: ISourceMemberConfigurationOptions) => any) | + ((opts: ISourceMemberConfigurationOptions, cb: IMemberCallback) => void) + ) => ICreateMapFluentFunctions; + + /** + * Customize configuration for all destination members. + * @param func The function to use for this individual member. + * @returns {IAutoMapperCreateMapChainingFunctions} + */ + forAllMembers: (func: (destinationObject: any, destinationPropertyName: string, value: any) => void) => ICreateMapFluentFunctions; + + /** + * Ignore all members not specified explicitly. + */ + ignoreAllNonExisting: () => ICreateMapFluentFunctions; + + /** + * Skip normal member mapping and convert using a custom type converter (instantiated during mapping). + * @param typeConverterClassOrFunction The converter class or function to use when converting. + */ + convertUsing: (typeConverterClassOrFunction: ((resolutionContext: IResolutionContext) => any) | + ((resolutionContext: IResolutionContext, callback: IMapCallback) => void) | + ITypeConverter | + (new() => ITypeConverter) + ) => void; + + /** + * Specify to which class type AutoMapper should convert. When specified, AutoMapper will create an instance of the given type, instead of returning a new object literal. + * @param typeClass The destination type class. + * @returns {IAutoMapperCreateMapChainingFunctions} + */ + convertToType: (typeClass: new () => any) => ICreateMapFluentFunctions; + + /** + * Specify which profile should be used when mapping. + * @param {string} profileName The profile name. + * @returns {IAutoMapperCreateMapChainingFunctions} + */ + withProfile: (profileName: string) => void; + } + + /** + * The mapping configuration for the current mapping keys/types. + */ + interface IMapping { + /** The mapping source key. */ + sourceKey: string; + + /** The mapping destination key. */ + destinationKey: string; + + /** The mappings for forAllMembers functions. */ + forAllMemberMappings: Array<(destinationObject: any, destinationPropertyName: string, value: any) => void>; + + properties: IProperty[]; + + /** + * Skip normal member mapping and convert using a type converter. + * @param resolutionContext Context information regarding resolution of a destination value + * @returns {any} Destination object. + */ + typeConverterFunction: ((resolutionContext: IResolutionContext) => any) | + ((resolutionContext: IResolutionContext, callback: IMapCallback) => void); + + /** The source type class to convert from. */ + sourceTypeClass: any; + + /** The destination type class to convert to. */ + destinationTypeClass: any; + + /** The profile used when mapping. */ + profile?: IProfile; + + /** Whether or not to ignore all properties not specified using createMap. */ + ignoreAllNonExisting?: boolean; + + /** Whether or not an mapping has to be asynchronous. */ + async: boolean; + + /* + * PERFORMANCE ENHANCEMENTS + */ + + /** + * Item mapping function to use. + */ + mapItemFunction: IMapItemFunction | IAsyncMapItemFunction; + } + + // export interface IMappingMapOptimized extends IMapping { + // final: boolean; + // forMemberMappingsArray: Array; + // } + + /** + * Context information regarding resolution of a destination value + */ + export interface IResolutionContext { + /** Source value */ + sourceValue: any; + + /** Destination value */ + destinationValue: any; + + /** Source property name */ + sourcePropertyName?: string; + + /** Destination property name */ + destinationPropertyName?: string; + + /** Index of current collection mapping */ + arrayIndex?: number; + } + + /** + * Configuration options for forMember mapping function. + */ + interface IMemberConfigurationOptions { + /** + * Map from a custom source property name. + * @param sourcePropertyName The source property to map. + */ + mapFrom: (sourcePropertyName: string) => void; + + /** + * When this configuration function is used, the (destination) property is ignored + * when mapping. + */ + ignore?: () => void; + + /** + * If specified, the property will only be mapped when the condition is fulfilled. + */ + condition: (predicate: ((sourceObject: any) => boolean)) => void; + + /** The source object to map. */ + sourceObject: any; + + /** The source property to map. */ + sourcePropertyName: string; + + /** + * The intermediate destination property value, used for stacking multiple for(Source)Member calls + * while elaborating the intermediate result. + */ + intermediatePropertyValue: any; + } + + /** + * Configuration options for forSourceMember mapping function. + */ + interface ISourceMemberConfigurationOptions { + /** + * When this configuration function is used, the source property is ignored + * when mapping. + */ + ignore: () => void; + } + + /** + * Member callback interface + */ + interface IMemberCallback { + /** + * Callback function to call when the async operation is executed. + * @param {any} callbackValue Callback value to be used as output for the for(Source)Member call. + */ + (callbackValue: any): void; + } + + /** + * Member callback interface + */ + interface IMapCallback { + /** + * Callback function to call when the async operation is executed. + * @param {any} result Callback value to be used as output for the mapAsync call. + */ + (result: any): void; + } + + /** + * Converts source type to destination type instead of normal member mapping + */ + export interface ITypeConverter { + /** + * Performs conversion from source to destination type. + * @param {IResolutionContext} resolutionContext Resolution context. + * @returns {any} Destination object. + */ + convert: (resolutionContext: IResolutionContext) => any; + } + + /** + * Defines a naming convention strategy. + */ + export interface INamingConvention { + /** Regular expression on how to tokenize a member. */ + splittingExpression: RegExp; + + /** Character to separate on. */ + separatorCharacter: string; + + /** + * Transformation function called when this convention is the destination naming convention. + * @param {string[]} sourcePropertyNameParts Array containing tokenized source property name parts. + * @returns {string} Destination property name + */ + transformPropertyName: (sourcePropertyNameParts: string[]) => string; + } + + /** + * Configuration for profile-specific maps. + */ + export interface IConfiguration { + /** + * Add an existing profile + * @param profile {IProfile} Profile to add. + */ + addProfile(profile: IProfile): void; + + /** + * Create a createMap curry function which expects only a destination key. + * @param {string} sourceKey The map source key. + * @returns {(destinationKey: string) => IAutoMapperCreateMapChainingFunctions} + */ + createMap?(sourceKey: string): (destinationKey: string) => ICreateMapFluentFunctions; + + /** + * Create a mapping profile. + * @param {string} sourceKey The map source key. + * @param {string} destinationKey The map destination key. + * @returns {Core.IAutoMapperCreateMapChainingFunctions} + */ + createMap?(sourceKey: string, destinationKey: string): ICreateMapFluentFunctions; + } + + /** + * Provides a named configuration for maps. Naming conventions become scoped per profile. + */ + export interface IProfile { + /** Profile name */ + profileName: string; + + /** Naming convention for source members */ + sourceMemberNamingConvention: INamingConvention; + + /** Naming convention for destination members */ + destinationMemberNamingConvention: INamingConvention; + + /** + * Implement this method in a derived class and call the CreateMap method to associate that map with this profile. + * Avoid calling the AutoMapper class / automapper instance from this method. + */ + configure: () => void; + } + + export interface IMapItemFunction { + (mapping: IMapping, sourceObject: any, destinationObject: any): any; + } + + export interface IAsyncMapItemFunction { + (mapping: IMapping, sourceObject: any, destinationObject: any, callback: IMapCallback): void; + } + + interface ICreateMapParameters { + mapping: IMapping; + destinationProperty: string; + conversionValueOrFunction: any; + sourceMapping: boolean; + fluentFunctions: ICreateMapFluentFunctions; + } + + interface IGetOrCreatePropertyParameters { + propertyNameParts: string[]; + mapping: IMapping; + parent?: IProperty; + propertyArray: IProperty[]; + destination?: string; + sourceMapping: boolean; + } + + interface ICreatePropertyParameters { + name: string; + mapping: IMapping; + parent: IProperty; + propertyArray: IProperty[]; + sourceMapping: boolean; + } +} + +declare var automapper: AutoMapperJs.AutoMapper; \ No newline at end of file diff --git a/awesomplete/awesomplete-tests.ts b/awesomplete/awesomplete-tests.ts new file mode 100644 index 0000000000..8132ad4555 --- /dev/null +++ b/awesomplete/awesomplete-tests.ts @@ -0,0 +1,57 @@ +/// + +var input = document.getElementById("myinput"); +new Awesomplete(input, {list: "#mylist"}); + +new Awesomplete(input, {list: document.querySelector("#mylist")}); + +new Awesomplete(input, { + list: ["Ada", "Java", "JavaScript", "LOLCODE", "Node.js", "Ruby on Rails"] +}); + +var awesomplete = new Awesomplete(input); +awesomplete.list = ["Ada", "Java", "JavaScript", "LOLCODE", "Node.js", "Ruby on Rails"]; + +new Awesomplete(input, { + list: [ + { label: "Belarus", value: "BY" }, + { label: "China", value: "CN" }, + { label: "United States", value: "US" } + ] +}); + +// Same with arrays: +new Awesomplete(input, { + list: [ + [ "Belarus", "BY" ], + [ "China", "CN" ], + [ "United States", "US" ] + ] +}); + +new Awesomplete('input[type="email"]', { + list: ["aol.com", "att.net", "comcast.net", "facebook.com", "gmail.com", "gmx.com", "googlemail.com", "google.com", "hotmail.com", "hotmail.co.uk", "mac.com", "me.com", "mail.com", "msn.com", "live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk"], + data: function (text: string, input: any) { + return input.slice(0, input.indexOf("@")) + "@" + text; + }, + filter: Awesomplete.FILTER_STARTSWITH +}); + +new Awesomplete('input[data-multiple]', { + filter: function(text: string, input: any) { + return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]); + }, + + replace: function(text: string) { + var before = this.input.value.match(/^.+,\s*|/)[0]; + this.input.value = before + text + ", "; + } +}); + +var ajax = new XMLHttpRequest(); +ajax.open("GET", "https://restcountries.eu/rest/v1/lang/fr", true); +ajax.onload = function() { + var list = JSON.parse(ajax.responseText).map(function(i: any) { return i.name; }); + new Awesomplete(document.querySelector("#ajax-example input"),{ list: list }); +}; +ajax.send(); \ No newline at end of file diff --git a/awesomplete/awesomplete.d.ts b/awesomplete/awesomplete.d.ts new file mode 100644 index 0000000000..d39389f008 --- /dev/null +++ b/awesomplete/awesomplete.d.ts @@ -0,0 +1,49 @@ +// Type definitions for Awesomplete v1.1.0 +// Project: https://leaverou.github.io/awesomplete/ +// Definitions by: webbiesdk , Ben Dixon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Awesomplete { + constructor(input: Element | HTMLElement | string, o?: AwesompleteOptions); + static all: Array; + static $$: (expr: string | NodeSelector, con?: any) => NodeList; + static ITEM: (text: string, input: string) => HTMLElement; + static $: { + (expr: string|Element, con?: NodeSelector): string | Element; + regExpEscape: (s: { replace: (arg0: RegExp, arg1: string) => void }) => any; + create: (tag: string, o: any) => HTMLElement; + fire: (target: EventTarget, type: string, properties: any) => any; + siblingIndex: (el: Element) => number; + }; + static FILTER_STARTSWITH: (text: string, input: string) => boolean; + static FILTER_CONTAINS: (text: string, input: string) => boolean; + static SORT_BYLENGTH: (a: number | any[], b: number | any[]) => number; + static REPLACE: (text: any) => void; + next: () => void; + container: HTMLElement; + select: (selected?: HTMLElement, originalTarget?: HTMLElement) => void; + previous: () => void; + index: number; + opened: number; + list: string | string[] | Element | { label: string, value: any }[] | [string, string][]; + input: HTMLElement | string; + goto: (i: number) => void; + ul: HTMLElement; + close: () => void; + evaluate: () => void; + selected: boolean; + open: () => void; + status: HTMLElement; +} + +interface AwesompleteOptions { + list?: string | string[] | Element | { label: string, value: any }[] | [string, string][]; + minChars?: Number; + maxItems?: Number; + autoFirst?: boolean; + data?: Function; + filter?: Function; + sort?: Function; + item?: Function; + replace?: Function; +} diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index 72c443fab1..cad44082ab 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -1,12 +1,12 @@ import lambda = require('aws-lambda'); -var str: string; -var date: Date; -var anyObj: any; -var num: number; +var str: string = "any string"; +var date: Date = new Date(); +var anyObj: any = { abc: 123 }; +var num: number = 5; var identity: lambda.CognitoIdentity; -var error: Error; -var b: boolean; +var error: Error = new Error(); +var b: boolean = true; var clientCtx: lambda.ClientContext; /* Context */ @@ -35,4 +35,13 @@ function callback(cb: lambda.Callback) { cb(null); cb(error); cb(null, anyObj); -} \ No newline at end of file +} +/* Compatibility functions */ +context.done(); +context.done(error); +context.done(error, anyObj); +context.succeed(str); +context.succeed(anyObj); +context.succeed(str, anyObj); +context.fail(error); +context.fail(str); \ No newline at end of file diff --git a/aws-lambda/index.d.ts b/aws-lambda/index.d.ts index 95bc73466d..065fc7b754 100644 --- a/aws-lambda/index.d.ts +++ b/aws-lambda/index.d.ts @@ -23,7 +23,9 @@ interface Context { getRemainingTimeInMillis(): number; // Functions for compatibility with earlier Node.js Runtime v0.10.42 - log(message: string, object: any): void; + // For more details see http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-using-old-runtime.html#nodejs-prog-model-oldruntime-context-methods + done(error?: Error, result?: any): void; + fail(error: Error): void; fail(message: string): void; succeed(message: string): void; succeed(object: any): void; diff --git a/aws-sdk/index.d.ts b/aws-sdk/index.d.ts index db587e19e2..1f7d807d22 100644 --- a/aws-sdk/index.d.ts +++ b/aws-sdk/index.d.ts @@ -20,7 +20,28 @@ export class EnvironmentCredentials extends Credentials { constructor(profile: string); } -export interface Logger { + export module CognitoIdentity { + export interface CognitoIdentityCredentialsParams { + IdentityPoolId?: string; + AccountId?: string; + Logins?: {[k: string]: any}; + + RoleArn?: string; + RoleSessionName?: string; + WebIdentityToken?: string; + ProviderId?: string; + Policy?: string; + DurationSeconds?: number; + + IdentityId?: string; + } + } + + export class CognitoIdentityCredentials extends Credentials { + constructor(params: CognitoIdentity.CognitoIdentityCredentialsParams); + } + + export interface Logger { write?: (chunk: any, encoding?: string, callback?: () => void) => void; log?: (...messages: any[]) => void; } @@ -357,7 +378,8 @@ export declare class S3 { endpoint: Endpoint; getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any; - putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void; + putObject(params: s3.PutObjectRequest, callback?: (err: Error, data: any) => void): any; + copyObject(params: s3.CopyObjectRequest, callback?: (err: Error, data: any) => void): any; deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void; headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; getSignedUrl(operation: string, params: any): string; @@ -501,7 +523,8 @@ export declare module DynamoDB { interface UpdateParam extends _DDBDC_Writer { Key: _DDBDC_Keys; - AttributeUpdates: { + UpdateExpression?: string; + AttributeUpdates?: { [someKey: string]: { Action: "PUT" | "ADD" | "DELETE"; Value: any @@ -2232,6 +2255,40 @@ export declare module s3 { WebsiteRedirectLocation?: string; } + export interface CopyObjectRequest { + Bucket: string; + CopySource: string; + Key: string; + ACL?: string; + CacheControl?: string; + ContentDisposition?: string; + ContentEncoding?: string; + ContentLanguage?: string; + ContentType?: string; + CopySourceIfMatch?: string; + CopySourceIfModifiedSince?: any; + CopySourceIfNoneMatch?: string; + CopySourceIfUnmodifiedSince?: any; + CopySourceSSECustomerAlgorithm?: string; + CopySourceSSECustomerKey?: any; + CopySourceSSECustomerKeyMD5?: string; + Expires?: any; + GrantFullControl?: string; + GrantRead?: string; + GrantReadACP?: string; + GrantWriteACP?: string; + Metadata?: { [key: string]: string; }; + MetadataDirective?: string; + RequestPayer?: string; + SSECustomerAlgorithm?: string; + SSECustomerKey?: any; + SSECustomerKeyMD5?: string; + SSEKMSKeyId?: string; + ServerSideEncryption?: string; + StorageClass?: string; + WebsiteRedirectLocation?: string; + } + export interface GetObjectRequest { Bucket: string; IfMatch?: string; diff --git a/aws-serverless-express/aws-serverless-express-tests.ts b/aws-serverless-express/aws-serverless-express-tests.ts new file mode 100644 index 0000000000..6a0d7694d9 --- /dev/null +++ b/aws-serverless-express/aws-serverless-express-tests.ts @@ -0,0 +1,29 @@ +/// +/// + +import * as awsServerlessExpress from 'aws-serverless-express'; +import * as express from 'express'; + +const app = express(); +const server = awsServerlessExpress.createServer(app, () => {}); + +const mockEvent = { + key: 'value' +}; + +const mockContext = { + callbackWaitsForEmptyEventLoop: true, + functionName: 'testFunction', + functionVersion: '1', + invokedFunctionArn: 'arn', + memoryLimitInMB: 128, + awsRequestId: 'id', + logGroupName: 'group', + logStreamName: 'stream', + getRemainingTimeInMillis: () => 2000, + done: () => false, + fail: (error: any) => false, + succeed: (message: string) => false +}; + +awsServerlessExpress.proxy(server, mockEvent, mockContext); diff --git a/aws-serverless-express/aws-serverless-express.d.ts b/aws-serverless-express/aws-serverless-express.d.ts new file mode 100644 index 0000000000..50aa0e1a0b --- /dev/null +++ b/aws-serverless-express/aws-serverless-express.d.ts @@ -0,0 +1,24 @@ +// Type definitions for aws-serverless-express +// Project: https://github.com/awslabs/aws-serverless-express +// Definitions by: Ben Speakman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module 'aws-serverless-express' { + + import * as http from 'http'; + import * as lambda from 'aws-lambda'; + + export function createServer( + requestListener: (request: http.IncomingMessage, response: http.ServerResponse) => http.Server, + serverListenCallback?: () => any + ): http.Server; + + export function proxy( + server: http.Server, + event: any, + context: lambda.Context + ): void; +} diff --git a/axios/axios-tests.ts b/axios/axios-tests.ts index 1f05653229..a321e97f19 100644 --- a/axios/axios-tests.ts +++ b/axios/axios-tests.ts @@ -69,6 +69,10 @@ axios.post("http://example.com/", { ] }); +var config: Axios.AxiosXHRConfigBase = {headers: {}}; +config.headers['X-Custom-Header'] = 'baz'; +axios.post("http://example.com/", config); + var getRepoIssue = axios.get("https://api.github.com/repos/mzabriskie/axios/issues/1"); var axiosInstance = axios.create({ diff --git a/axios/index.d.ts b/axios/index.d.ts index 9c4705d093..a2c5bfbd45 100644 --- a/axios/index.d.ts +++ b/axios/index.d.ts @@ -39,7 +39,7 @@ declare namespace Axios { /** * custom headers to be sent */ - headers?: Object; + headers?: {[key: string]: any}; /** * URL parameters to be sent with the request diff --git a/babel-traverse/index.d.ts b/babel-traverse/index.d.ts index 11d51dc2cb..987bf71954 100644 --- a/babel-traverse/index.d.ts +++ b/babel-traverse/index.d.ts @@ -346,7 +346,7 @@ export class NodePath { getData(key: string, def?: any): any; - buildCodeFrameError(msg: string, Error: Error): Error; + buildCodeFrameError(msg: string, Error?: new (msg: string) => TError): TError; traverse(visitor: Visitor, state?: any): void; diff --git a/bases/bases-tests.ts b/bases/bases-tests.ts new file mode 100644 index 0000000000..5414b18764 --- /dev/null +++ b/bases/bases-tests.ts @@ -0,0 +1,10 @@ +/// +import * as bases from 'bases'; + +let bs16String: string = bases.toBase(200, 16); // => 'c8' +let bs62String: string = bases.toBase(99999, 62); // => 'q0T' +let customBaseString: string = bases.toAlphabet(300, 'aAbBcC'); // => 'Abba' + +let frombs16Int: number = bases.fromBase('c8', 16); // => 200 +let frombs62Int: number = bases.fromBase('q0T', 62); // => 99999 +let customBaseInt: number = bases.fromAlphabet('Abba', 'aAbBcC'); // => 300 diff --git a/bases/bases.d.ts b/bases/bases.d.ts new file mode 100644 index 0000000000..2e62cf685a --- /dev/null +++ b/bases/bases.d.ts @@ -0,0 +1,22 @@ +// Type definitions for bases 0.2.1 +// Project: https://github.com/aseemk/bases.js +// Definitions by: Hari Krishna +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "bases" { + export function toAlphabet(num: number, alphabet: string): string; + + export function fromAlphabet(str: string, alphabet: string): number; + + export function toBase(num: number, base: number): string; + + export function fromBase(str: string, base:number): number; + + export let KNOWN_ALPHABETS: any; + + export let NUMERALS: string; + + export let LETTERS_LOWERCASE: string; + + export let LETTERS_UPPERCASE: string; +} diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index 1591d1c3a5..ea1ea69882 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -336,6 +336,29 @@ fooOrBarProm = fooProm.caught(Promise.CancellationError, (reason: any) => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +{ + class CustomError extends Error { + public customField: number; + } + fooProm = fooProm.catch(CustomError, reason => { + let a: number = reason.customField + }) +} + +{ + class CustomErrorWithConstructor extends Error { + constructor(public arg1: boolean, public arg2: number) { + super(); + }; + } + fooProm = fooProm.catch(CustomErrorWithConstructor, reason => { + let a: boolean = reason.arg1; + let b: number = reason.arg2; + }) +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + barProm = fooProm.error((reason: any) => { return bar; }); diff --git a/bluebird/index.d.ts b/bluebird/index.d.ts index 35b506542a..ca8acb2446 100644 --- a/bluebird/index.d.ts +++ b/bluebird/index.d.ts @@ -71,14 +71,19 @@ class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { */ catch(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; caught(predicate: (error: any) => boolean, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; caught(predicate: (error: any) => boolean, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; - catch(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - caught(ErrorClass: Function, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; - catch(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; - caught(ErrorClass: Function, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + + catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + caught(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + + catch(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable): Bluebird; + caught(ErrorClass: new (...args: any[]) => E, onReject: (error: E) => U | Bluebird.Thenable): Bluebird; + catch(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; caught(predicate: Object, onReject: (error: any) => R | Bluebird.Thenable | void | Bluebird.Thenable): Bluebird; + catch(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; caught(predicate: Object, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; @@ -317,6 +322,13 @@ class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { */ cancel(): void; + /** + * Basically sugar for doing: somePromise.catch(function(){}); + * + * Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting. + */ + suppressUnhandledRejections(): void; + /** * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. * diff --git a/bonjour/bonjour-tests.ts b/bonjour/bonjour-tests.ts new file mode 100644 index 0000000000..b97794b071 --- /dev/null +++ b/bonjour/bonjour-tests.ts @@ -0,0 +1,21 @@ +/// +import * as bonjour from 'bonjour'; + +var bonjourOptions: bonjour.BonjourOptions; +var bonjourInstance: bonjour.Bonjour; + +var serviceOptions: bonjour.ServiceOptions; +var service: bonjour.Service; + +var browserOptions: bonjour.BrowserOptions; +var browser: bonjour.Browser; + +bonjourOptions = { interface: '192.168.1.1', port: 5353 }; +bonjourInstance = new bonjour.Bonjour(bonjourOptions); + +serviceOptions = { name: 'My Web Server', type: 'http', port: 3000 }; +service = bonjourInstance.publish(serviceOptions); + +browserOptions = { protocol: 'tcp', type: 'http' }; +browser = bonjour.find(browserOptions); + diff --git a/bonjour/bonjour.d.ts b/bonjour/bonjour.d.ts new file mode 100644 index 0000000000..0ffd9f1171 --- /dev/null +++ b/bonjour/bonjour.d.ts @@ -0,0 +1,71 @@ +// Type definitions for bonjour v3.5.0 +// Project: https://github.com/watson/bonjour +// Definitions by: Quentin Lampin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "bonjour" { + export interface BonjourOptions { + multicast?: boolean; + interface?: string; + port?: number; + ip?: string; + ttl?: number; + loopback?: boolean; + reuseAddr?: boolean; + } + + export interface BrowserOptions { + type?: string; + subtypes?: string[]; + protocol?: string; + txt?: Object; + } + + export interface ServiceOptions { + name: string; + host?: string; + port: number; + type: string; + subtypes?: string[]; + protocol?: 'udp'|'tcp'; + txt?: Object; + } + + export interface Service { + name: string; + type: string; + subtypes: string[]; + protocol: string; + host: string; + port: number; + fqdn: string; + rawTxt: Object; + txt: Object; + published: boolean; + + stop: (cb: ()=>any) => void; + start: () => void; + } + + export class Bonjour { + + constructor(opts: BonjourOptions); + publish(options: ServiceOptions):Service; + unpublishAll(cb: ()=>any): void; + find(options:BrowserOptions, onUp: ()=>any): Browser; + findOne(options:any, cb: (service: Service)=>any): Browser; + destroy():void; + } + + export class Browser { + services: Service[]; + + start():void; + update():void; + stop():void; + } + + export function find(options: BrowserOptions, onUp?: ()=>any): Browser; + export function findOne(options: BrowserOptions): Browser; + +} diff --git a/bootbox/index.d.ts b/bootbox/index.d.ts index ea6d4d9664..40494d5ca5 100644 --- a/bootbox/index.d.ts +++ b/bootbox/index.d.ts @@ -40,6 +40,7 @@ interface BootboxConfirmOptions extends BootboxDialogOptions { interface BootboxPromptOptions extends BootboxBaseOptions { title: string; value?: string; + inputType?: string; callback: (result: string) => any; buttons?: BootboxConfirmPromptButtonMap; } diff --git a/bootstrap-datepicker/index.d.ts b/bootstrap-datepicker/index.d.ts index 39b8846cd0..1f9fd065d2 100644 --- a/bootstrap-datepicker/index.d.ts +++ b/bootstrap-datepicker/index.d.ts @@ -36,6 +36,7 @@ interface DatepickerOptions { multidateSeparator?: string; orientation?: string; assumeNearbyYear?: any; + viewMode?: string; } interface DatepickerCustomFormatOptions { diff --git a/bootstrap-notify/index.d.ts b/bootstrap-notify/index.d.ts index afc7913273..c6939a7c2c 100644 --- a/bootstrap-notify/index.d.ts +++ b/bootstrap-notify/index.d.ts @@ -36,7 +36,10 @@ interface NotifySettings { from?: string; align?: string; }; - offset?: number; + offset?: number | { + x?: number; + y?: number; + }; spacing?: number; z_index?: number; delay?: number; diff --git a/bootstrap-select/bootstrap-select-tests.ts b/bootstrap-select/bootstrap-select-tests.ts new file mode 100644 index 0000000000..9758b1c9ed --- /dev/null +++ b/bootstrap-select/bootstrap-select-tests.ts @@ -0,0 +1,43 @@ +// Bootstrap Select Test +// ================================================================================ +/// +/// + +$(".selectpicker").selectpicker({ + actionsBox: true, + container: "body", + countSelectedText: "counts > #", + deselectAllText: "test", + dropdownAlignRight: true, + dropupAuto: true, + header: "test", + hideDisabled: true, + iconBase: "fa", + liveSearch: true, + liveSearchNormalize: true, + liveSearchPlaceholder: "test", + liveSearchStyle: "contains", + maxOptions: 10, + maxOptionsText: "test", + mobile: true, + multipleSeparator: ", ", + noneSelectedText: "test", + selectAllText: "test", + selectedTextFormat: "values", + selectOnTab: true, + showContent: true, + showIcon: true, + showSubtext: true, + showTick: true, + size: "auto", + style: "test", + tickIcon: "test", + title: "test", + width: "auto" +}) + +$(".selectpicker").selectpicker("val", "foo") +$(".selectpicker").selectpicker("val", ["foo", "bar"]) +$(".selectpicker").selectpicker("selectAll") +$(".selectpicker").selectpicker("setStyle", "btn-large", "add") + diff --git a/bootstrap-select/bootstrap-select.d.ts b/bootstrap-select/bootstrap-select.d.ts new file mode 100644 index 0000000000..9f1436a624 --- /dev/null +++ b/bootstrap-select/bootstrap-select.d.ts @@ -0,0 +1,44 @@ +// Type definitions for bootstrap-select v1.11.2 +// Project: https://silviomoreto.github.io/bootstrap-select/ +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface BootstrapSelectOptions { + actionsBox?: boolean + container?: string | boolean + countSelectedText?: string | Function + deselectAllText?: string + dropdownAlignRight?: string | boolean + dropupAuto?: boolean + header?: string + hideDisabled?: boolean + iconBase?: string + liveSearch?: boolean + liveSearchNormalize?: boolean + liveSearchPlaceholder?: string + liveSearchStyle?: string + maxOptions?: number | boolean + maxOptionsText?: string | Array | Function + mobile?: boolean + multipleSeparator?: string + noneSelectedText?: string + selectAllText?: string + selectedTextFormat?: string + selectOnTab?: boolean + showContent?: boolean + showIcon?: boolean + showSubtext?: boolean + showTick?: boolean + size?: string | number | boolean + style?: string + tickIcon?: string + title?: string + width?: string | boolean +} + +interface JQuery { + selectpicker(opts?: BootstrapSelectOptions): void + selectpicker(method: string, ...args: Array>): void +} diff --git a/bootstrap-table/bootstrap-table.d.ts b/bootstrap-table/bootstrap-table.d.ts new file mode 100644 index 0000000000..d0356dff84 --- /dev/null +++ b/bootstrap-table/bootstrap-table.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Bootstrap Table v1.11.0 +// Project: http://bootstrap-table.wenzhixin.net.cn/ +// Definitions by: Talat Baig +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + bootstrapTable(options?: any): JQuery; +} + +declare var bootstrapTable: JQueryStatic; diff --git a/braintree-web/braintree-web-tests.ts b/braintree-web/braintree-web-tests.ts index 40b34df418..20fd0219f1 100644 --- a/braintree-web/braintree-web-tests.ts +++ b/braintree-web/braintree-web-tests.ts @@ -50,10 +50,18 @@ braintree.client.create({ selector: '#card-number' }, cvv: { - selector: '#cvv' + selector: '#cvv', + type: 'password' }, - expirationDate: { - selector: '#expiration-date' + expirationMonth: { + selector: '#expiration-month', + select: { + options: ["01 - Jan", "02 - Feb", "03 - Mar", "04 - Apr", "05 - May", "06 - Jun", "07 - Jul", "08 - Aug", "09 - Sep", "10 - Oct", "11 - Nov", "12 - Dec"] + } + }, + expirationYear: { + selector: '#expiration-year', + select: true } } }, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) { diff --git a/braintree-web/braintree-web.d.ts b/braintree-web/braintree-web.d.ts index 2cf2d89467..e58cf7455b 100644 --- a/braintree-web/braintree-web.d.ts +++ b/braintree-web/braintree-web.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Braintree-web v3.0.2 +// Type definitions for Braintree-web v3.5.0 // Project: https://github.com/braintree/braintree-web // Definitions by: Guy Shahine // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -540,12 +540,17 @@ declare namespace BraintreeWeb { * @typedef {object} field * @property {string} selector A CSS selector to find the container where the hosted field will be inserted. * @property {string} [placeholder] Will be used as the `placeholder` attribute of the input. If `placeholder` is not natively supported by the browser, it will be polyfilled. - * @property {boolean} [formatInput=true] - Enable or disable automatic formatting on this field. Note: Input formatting does not work properly on Android and iOS, so input formatting is automatically disabled on those browsers. + * @property {string} [type] Will be used as the `type` attribute of the input. To mask `cvv` input, for instance, `type: "password"` can be used. + * @property {boolean} [formatInput=true] - Enable or disable automatic formatting on this field. + * @property {object|boolean} [select] If truthy, this field becomes a `', + modal: `
+
+
+
+
`, + hide: () => $(this.modal).add(this.overlay).fadeOut(100), + show: () => $(this.modal).add(this.overlay).fadeIn(100) + }); + + $.alertable.confirm('You sure?', { + container: 'body' + }); + + $.alertable.prompt('How many?', { + container: 'body' + }); + + $.alertable.defaults.container = 'body'; +} diff --git a/jquery-alertable/jquery-alertable.d.ts b/jquery-alertable/jquery-alertable.d.ts new file mode 100644 index 0000000000..93e219ef18 --- /dev/null +++ b/jquery-alertable/jquery-alertable.d.ts @@ -0,0 +1,29 @@ +// Type definitions for jquery-alertable 1.0.2 +// Project: https://github.com/claviska/jquery-alertable +// Definitions by: Steven Robertson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQueryStatic { + alertable: Alertable; +} + +interface Alertable { + alert(message: string, options?: AlertableOptions): JQueryPromise; + confirm(message: string, options?: AlertableOptions): JQueryPromise; + prompt(message: string, options?: AlertableOptions): JQueryPromise; + defaults: AlertableOptions; +} + +interface AlertableOptions { + container?: string; + html?: boolean; + cancelButton?: string; + okButton?: string; + overlay?: string; + prompt?: string; + modal?: string; + hide?: Function; + show?: Function; +} diff --git a/jquery-handsontable/index.d.ts b/jquery-handsontable/index.d.ts index 7b4deaabdf..bdbd5b713a 100644 --- a/jquery-handsontable/index.d.ts +++ b/jquery-handsontable/index.d.ts @@ -292,6 +292,11 @@ declare namespace Handsontable { */ manualRowResize?: boolean; + /** + * Turns on Manual row move, if set to a boolean or define initial row order, if set to an array of row indexes. + */ + manualRowMove?: boolean; + /** * Setting to true enables the copyPaste plugin, which enables the copying and pasting to the clipboard. */ diff --git a/jquery-mockjax/jquery-mockjax-tests.ts b/jquery-mockjax/jquery-mockjax-tests.ts index 7688645f8e..2a7b7f5ee7 100644 --- a/jquery-mockjax/jquery-mockjax-tests.ts +++ b/jquery-mockjax/jquery-mockjax-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// class Tests { private _noErrorCallbackExpected: (jqXHR: JQueryXHR, textStatus: string, errorThrown: string) => any; diff --git a/jquery.bbq/jquery.bbq-tests.ts b/jquery.bbq/jquery.bbq-tests.ts index fd49051ed3..ef5d81545e 100644 --- a/jquery.bbq/jquery.bbq-tests.ts +++ b/jquery.bbq/jquery.bbq-tests.ts @@ -1,5 +1,4 @@ -/// - +/// // ************** Tests to jquery JQueryParam interface diff --git a/jquery.colorbox/index.d.ts b/jquery.colorbox/index.d.ts index 2ec737fd44..3e9b0ea161 100644 --- a/jquery.colorbox/index.d.ts +++ b/jquery.colorbox/index.d.ts @@ -6,10 +6,10 @@ /// interface ColorboxResizeSettings { - height?: number; - innerHeight?: number; - width?: number; - innerWidth?: number; + height?: number | string; + innerHeight?: number | string; + width?: number | string; + innerWidth?: number | string; } interface ColorboxSettings { @@ -140,35 +140,35 @@ interface ColorboxSettings { /** * Set a fixed total width. This includes borders and buttons. Example: "100%", "500px", or 500 */ - width?: any; + width?: number | string; /** * Set a fixed total height. This includes borders and buttons. Example: "100%", "500px", or 500 */ - height?: any; + height?: number | string; /** * This is an alternative to 'width' used to set a fixed inner width. This excludes borders and buttons. Example: "50%", "500px", or 500 */ - innerWidth?: any; + innerWidth?: number | string; /** * This is an alternative to 'height' used to set a fixed inner height. This excludes borders and buttons. Example: "50%", "500px", or 500 */ - innerHeight?: any; + innerHeight?: number | string; /** * Set the initial width, prior to any content being loaded. */ - initialWidth?: number; + initialWidth?: number | string; /** * Set the initial height, prior to any content being loaded. */ - initialHeight?: number; + initialHeight?: number | string; /** * Set a maximum width for loaded content. Example: "100%", 500, "500px" */ - maxWidth?: any; + maxWidth?: number | string; /** * Set a maximum height for loaded content. Example: "100%", 500, "500px" */ - maxHeight?: any; + maxHeight?: number | string; /** * If true, adds an automatic slideshow to a content group / gallery. */ diff --git a/jquery.colorpicker/index.d.ts b/jquery.colorpicker/index.d.ts index 04508b14f1..566b7d4103 100644 --- a/jquery.colorpicker/index.d.ts +++ b/jquery.colorpicker/index.d.ts @@ -8,12 +8,12 @@ interface JQueryColorpickerOptions { // Events // TODO: Figure out actual types. - cancel: Function, - close: Function, - init: Function, - select: Function, - ok: Function, - open: Function, + cancel?: Function, + close?: Function, + init?: Function, + select?: Function, + ok?: Function, + open?: Function, alpha?: boolean; altAlpha?: boolean; @@ -32,6 +32,8 @@ interface JQueryColorpickerOptions { colorFormat?: string; draggable?: boolean; duration?: string; + format?: string; + horizontal?: boolean; hsv?: boolean; inline?: boolean; inlineFrame?: boolean; diff --git a/jquery.datatables/index.d.ts b/jquery.datatables/index.d.ts index a2fffa4c75..81c5027619 100644 --- a/jquery.datatables/index.d.ts +++ b/jquery.datatables/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for JQuery DataTables 1.10.6 +// Type definitions for JQuery DataTables 1.10.8 // Project: http://www.datatables.net // Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -182,11 +182,22 @@ declare namespace DataTables { destroy(remove?: boolean): DataTable; /** - * Redraw the table. + * Redraw the DataTables in the current context, optionally updating ordering, searching and paging as required. * - * @param reset Reset (default) or hold the current paging position. A full re-sort and re-filter is performed when this method is called, which is why the pagination reset is the default action. + * @param paging This parameter is used to determine what kind of draw DataTables will perform. */ - draw(reset?: boolean): DataTable; + draw(paging?: boolean | string): DataTable; + + /* + * Look up a language token that was defined in the DataTables' language initialisation object. + * + * @param token The language token to lookup from the language object. + * @param def The default value to use if the DataTables initialisation has not specified a value. + * @param numeric If handling numeric output, the number to be presented should be given in this parameter. If not numeric operator is required (for example button label text) this parameter is not required. + * + * @returns Resulting internationalised string. + */ + i18n(token: string, def: any | string, numeric?: number): string; /* * Get the initialisation options used for the table. Since: DataTables 1.10.6 @@ -363,6 +374,7 @@ declare namespace DataTables { length: number; recordsTotal: number; recordsDisplay: number; + serverSide: boolean } //#endregion "page-methods" @@ -412,6 +424,11 @@ declare namespace DataTables { //#region "util-methods" interface UtilityMethods { + /* + * Get a boolean value to indicate if there are any entries in the API instance's result set (i.e. any data, selected rows, etc). + */ + any(): boolean; + /** * Concatenate two or more API instances together * @@ -420,6 +437,11 @@ declare namespace DataTables { */ concat(a: Object, ...b: Object[]): DataTable; + /** + * Get the number of entries in an API instance's result set, regardless of multi-table grouping (e.g. any data, selected rows, etc). Since: 1.10.8 + */ + count(): number; + /** * Iterate over the contents of the API result set. * @@ -887,6 +909,22 @@ declare namespace DataTables { */ data(d: any[] | Object): DataTable; + /** + * Get the id of the selected row. + * + * @param hash Set to true to append a hash (#) to the start of the row id. + */ + id(hash?: boolean): string; + + /** + * Get the id of the selected row. Since: 1.10.8 + * + * @param hash true - Append a hash (#) to the start of the row id. This can be useful for then using the id as a selector + * false - Do not modify the id value. + * @returns Row id. If the row does not have an id available 'undefined' will be returned. + */ + id(hash?: boolean): string; + /** * Get the row index of the row column. */ @@ -947,6 +985,15 @@ declare namespace DataTables { */ every(fn: (rowIdx: number, tableLoop: number, rowLoop: number) => void): DataTable; + /** + * Get the ids of the selected rows. Since: 1.10.8 + * + * @param hash true - Append a hash (#) to the start of each row id. This can be useful for then using the ids as selectors + * false - Do not modify the id value. + * @returns Api instance with the selected rows in its result set. If a row does not have an id available 'undefined' will be returned as the value. + */ + ids(hash?: boolean): DataTable; + /** * Get the row indexes of the selected rows. */ @@ -1034,11 +1081,12 @@ declare namespace DataTables { isDataTable(table: string): boolean; /** - * Get all DataTables on the page + * Get all DataTable tables that have been initialised - optionally you can select to get only currently visible tables and / or retrieve the tables as API instances. * - * @param visible Get only visible tables + * @param visible As a boolean value this options is used to indicate if you want all tables on the page should be returned (false), or visible tables only (true). + * Since 1.10.8 this option can also be given as an object. */ - tables(visible?: boolean): DataTables.DataTable[]; + tables(visible?: boolean | ObjectTablesStatic): DataTables.DataTable[] | DataTables.DataTable; /** * Version number compatibility check function @@ -1077,6 +1125,18 @@ declare namespace DataTables { throttle(fn: Function, period?: number): Function; } + interface ObjectTablesStatic { + /** + * Get only visible tables (true) or all tables regardless of visibility (false). + */ + visible: boolean + + /** + * Return a DataTables API instance for the selected tables (true) or an array (false). + */ + api: boolean + } + //#endregion "Static-Methods" //#region "Settings" @@ -1234,7 +1294,7 @@ declare namespace DataTables { pageLength?: number; /** - * Pagination button display options. Basic Types: simple, simple_numbers, full, full_numbers + * Pagination button display options. Basic Types: numbers (1.10.8) simple, simple_numbers, full, full_numbers */ pagingType?: string; @@ -1248,6 +1308,11 @@ declare namespace DataTables { */ renderer?: string | RendererSettings; + /** + * Data property name that DataTables will use to set element DOM IDs. Since: 1.10.8 + */ + rowId?: string; + /** * Allow the table to reduce in height when a limited number of rows are shown. Since: 1.10 */ @@ -1620,7 +1685,7 @@ declare namespace DataTables { } interface FunctionRowCallback { - (row: Node, data: any[] | Object): void; + (row: Node, data: any[] | Object, index: number): void; } interface FunctionStateLoadCallback { @@ -1662,6 +1727,7 @@ declare namespace DataTables { zeroRecords?: string; paginate?: LanguagePaginateSettings; aria?: LanguageAriaSettings; + url?: string; } interface LanguagePaginateSettings { diff --git a/jquery.datatables/jquery.dataTables-tests.ts b/jquery.datatables/jquery.dataTables-tests.ts index 124630599d..fae4892c55 100644 --- a/jquery.datatables/jquery.dataTables-tests.ts +++ b/jquery.datatables/jquery.dataTables-tests.ts @@ -147,7 +147,7 @@ $(document).ready(function () { var infoCallbackFunc: DataTables.FunctionInfoCallback = function (settings, start, end, total, pre) { }; var initCallbackFunc: DataTables.FunctionInitComplete = function (settings, json) { }; var preDrawFunc: DataTables.FunctionPreDrawCallback = function (settings) { }; - var rowCallbackFunc: DataTables.FunctionRowCallback = function (row, data) { }; + var rowCallbackFunc: DataTables.FunctionRowCallback = function (row, data, index) { }; var stateLoadCallbackFunc: DataTables.FunctionStateLoadCallback = function (settings) { }; var stateLoadedCallbackFunc: DataTables.FunctionStateLoaded = function (settings, data) { }; var stateSaveCallbackFunc: DataTables.FunctionStateSaveCallback = function (settings, data) { }; @@ -219,6 +219,7 @@ $(document).ready(function () { pagingType: "simple", retrieve: true, renderer: "bootstrap", + rowId: "custId", scrollCollapse: true, search: true, searchCols: [{ "search": "", "smart": true, "regex": false, "caseInsensitive": true }], @@ -261,7 +262,7 @@ $(document).ready(function () { { ajax: { data: ajaxDataFunc, - dataSrc: function (data) { }, + dataSrc: function (data: any) { }, }, }; @@ -305,12 +306,16 @@ $(document).ready(function () { destroy = dt.destroy(true); destroy.$(""); - var draw = dt.draw(); + var draw: DataTables.DataTable = dt.draw(); draw = dt.draw(true); + draw = dt.draw("page"); draw.$(""); var initSettings = dt.init(); + var i18n: string = dt.i18n('buttons.copy', 'Copy to clipboard'); + i18n = dt.i18n('select.rows', { _: '%d rows selected', 1: '1 row selected' }, 0); + var off = dt.off("event"); off = dt.off("event", function () { }); off.$(""); @@ -340,7 +345,8 @@ $(document).ready(function () { "end": 20, "length": 10, "recordsTotal": 57, - "recordsDisplay": 57 + "recordsDisplay": 57, + "serverSide": false }; var page_len_get = dt.page.len(); @@ -398,7 +404,7 @@ $(document).ready(function () { .cache('search') .sort() .unique() - .each(function (d) { + .each(function (d: any) { select.append($('')); }); @@ -517,7 +523,7 @@ $(document).ready(function () { columns = dt.columns("selector", modifier); var columns_cache = columns.cache("order"); - dt.columns('.select-filter').eq(0).each(function (colIdx) { + dt.columns('.select-filter').eq(0).each(function (colIdx: any) { // Create the select list and search operation var select = $('') .appendTo( @@ -704,7 +710,7 @@ $(document).ready(function () { .cache('search') .sort() .unique() - .each(function (d) { + .each(function (d: any) { select.append($('')); }); }); @@ -748,6 +754,8 @@ $(document).ready(function () { var row_19 = dt.row("selector").index(); var row_20 = dt.row("selector").node(); var row_21 = dt.row("selector").remove(); + var row_22: string = dt.row("selector").id(); + var row_23: string = dt.row("selector").id(false); var rows_1 = dt.rows(); var rows_2 = dt.rows().remove(); @@ -764,6 +772,8 @@ $(document).ready(function () { var rows_13 = dt.rows.add([{}, {}]); dt.rows().every(function () { }); dt.rows().every(function (rowIdx, tableLoop, rowLoop) { }); + var rows_14: DataTables.DataTable = dt.rows("selector").ids(); + var rows_15: DataTables.DataTable = dt.rows("selector").ids(false); var table3 = $('#example').DataTable(); table3.row.add({ @@ -828,7 +838,7 @@ $(document).ready(function () { ]) .show(); - dt.rows().eq(0).each(function (rowIdx) { + dt.rows().eq(0).each(function (rowIdx: any) { dt .row(rowIdx) .child( @@ -878,6 +888,20 @@ $(document).ready(function () { //#endregion "Methods-Row" + //#region "Methods-Static" + + // Variable is a stand-in for $.fn.dataTable. See extension of JQueryStatic at the top of jquery.dataTables.d.ts. + var staticFn: DataTables.StaticFunctions; + + // With boolean parameter type, always returns DataTables.DataTable[]. + var static_1: DataTables.DataTable[] = staticFn.tables(true); + // With object parameter type, returns DataTables.DataTable[] when "api" property is false. + static_1 = staticFn.tables({ "visible": true, "api": false }); + // With object parameter type, returns DataTables.DataTable when "api" property is true. + var static_2: DataTables.DataTable = staticFn.tables({ "visible": true, "api": true }); + + //#endregion "Methods-Static" + //#region "Methods-Table" var tables = dt.tables(); @@ -901,5 +925,8 @@ $(document).ready(function () { //#region "Methods-Util" + var util_1: boolean = dt.any(); + var util_2: number = dt.count(); + //#endregion "Methods-Util" }); diff --git a/jquery.fileupload/index.d.ts b/jquery.fileupload/index.d.ts index db5f8e27e2..f34325ad8b 100644 --- a/jquery.fileupload/index.d.ts +++ b/jquery.fileupload/index.d.ts @@ -105,6 +105,9 @@ interface JQueryFileInputOptions { */ redirectParamName?: string; + // The HTTP request method must be "POST" or "PUT" + type?: string, + /** * Set the following option to the location of a postMessage window, * to enable postMessage transport uploads: diff --git a/jquery.flagstrap/jquery.flagstrap-tests.ts b/jquery.flagstrap/jquery.flagstrap-tests.ts new file mode 100644 index 0000000000..d274b3b61d --- /dev/null +++ b/jquery.flagstrap/jquery.flagstrap-tests.ts @@ -0,0 +1,77 @@ +/// +/// + +class TestObject { + +} + +$(function () { + // basic test + // written in according to basic example from documentation + var htmlSelect = '
' + + '
' + + '
' + + '
' + + '
' + + '
'; + $('body').html(htmlSelect); + $('#flagstrap').flagStrap(); + + // for this test we expect more than 30 thousands of characters + console.log('characters count: ' + $('#flagstrap').html().length + '\n' + $('#flagstrap').html()); + + // options test + // options -> data attributes + // written in according to options -> data attributes example from documentation + htmlSelect = '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
'; + $('body').html(htmlSelect); + $('#flagstrap2').flagStrap(); + + console.log('\n\ncharacters count: ' + $('#flagstrap2').html().length + '\n' + $('#flagstrap2').html()); + + // options test + // options -> instance options + // written in according to options -> instance options example from documentation + htmlSelect = '
' + + '
' + + '
' + + '
' + + '
' + + '
'; + $('body').html(htmlSelect); + $('#flagstrap3').flagStrap({ + countries: { + "AU": "Australia", + "GB": "United Kingdom", + "US": "United States" + }, + inputName: 'country', + buttonSize: "btn-lg", + buttonType: "btn-primary", + labelMargin: "20px", + scrollable: false, + scrollableHeight: "350px", + onSelect: function(value: any, element: any) { + // + }, + placeholder: { + value: "", + text: "Please select a country" + } + }); + + console.log('\n\ncharacters count: ' + $('#flagstrap3').html().length + '\n' + $('#flagstrap3').html()); +}) + diff --git a/jquery.flagstrap/jquery.flagstrap.d.ts b/jquery.flagstrap/jquery.flagstrap.d.ts new file mode 100644 index 0000000000..a61db5c48d --- /dev/null +++ b/jquery.flagstrap/jquery.flagstrap.d.ts @@ -0,0 +1,84 @@ +// Type definitions for jQuery Flagstrap Plugin v1.0 +// Project: https://github.com/blazeworx/flagstrap +// Definitions by: Felipe de Sena Garcia +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module jQueryFlagStrap { + interface FlagStrapOptions { + /** + * Default: uniquely generated + * the `name` attribute for the actual `select` input + */ + inputName: string; + /** + * Default: uniquely generated + * the `id` attribute for the actual `select` input + */ + inputId?: string; + /** + * Default: "btn-md" + * The bootstrap button size `class` for this drop down + */ + buttonSize: string; + /** + * Default: "btn-default" + * The bootstrap button type `class` for this drop down + */ + buttonType: string; + /** + * Default: "20px" + * The `margin` between `flag` and `text label` + */ + labelMargin: string; + /** + * Default: false + * Scrollable or full height drop down + */ + scrollable: boolean; + /** + * Default: "250px" + * `max-height` for the scrollable drop down + */ + scrollableHeight?: string; + /** + * Default: (all) + * Only show specific countries + * Example: + * + * {"GB": "United Kingdom", "US": "United States"} + * + * will only show the USA and UK. + */ + countries?: Object; + /** + * Default: {value: "", text: "Please select a country"} + * Set the placeholder value and text. To disable the placeholder define as (boolean) false. + */ + placeholder: boolean | FlagStrapPlaceholderOptions; + /** + * Default: null + * This callback gets called each time the select is changed. It receives two parameters, the new value, and the select element. + */ + onSelect?(value: any, element: any): void; + } + + interface FlagStrapStatic { + flagStrap?: void; + } + + interface FlagStrapPlaceholderOptions { + value: string; + text: string; + } +} + +interface JQuery { + /** + * A lightwieght jQuery plugin for creating Bootstrap 3 compatible country select boxes with flags. + */ + + flagStrap(): void; + flagStrap(options: jQueryFlagStrap.FlagStrapOptions): void; +} \ No newline at end of file diff --git a/jquery.pnotify/index.d.ts b/jquery.pnotify/index.d.ts index e4ffbbe9fb..c0d20e3dae 100644 --- a/jquery.pnotify/index.d.ts +++ b/jquery.pnotify/index.d.ts @@ -5,10 +5,9 @@ /// -// could not pass the Travis Test if enabled -//type NoticeTypeOptions = "notice" | "info" | "success" | "error"; -//type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; -//type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; +type NoticeTypeOptions = "notice" | "info" | "success" | "error"; +type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; +type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; interface PNotifyStack { dir1?: string; @@ -137,7 +136,7 @@ interface PNotifyOptions { /** * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".) */ - styling?: string; + styling?: StylingOptions; /** * Additional classes to be added to the notice. (For custom styling.) */ @@ -182,7 +181,7 @@ interface PNotifyOptions { /** * Type of the notice. "notice", "info", "success", or "error". */ - type?: string; + type?: NoticeTypeOptions; /** * Set icon to true to use the default icon for the selected style/type, false for no icon, or a string for your own icon class. */ @@ -263,7 +262,7 @@ interface PNotify { /** * The state can be "initializing", "opening", "open", "closing", and "closed" */ - state?: string; + state?: StateOptions; /** * This function is for updating the notice. diff --git a/jquery.pnotify/jquery.pnotify-tests.ts b/jquery.pnotify/jquery.pnotify-tests.ts index f14a490668..c9465e0444 100644 --- a/jquery.pnotify/jquery.pnotify-tests.ts +++ b/jquery.pnotify/jquery.pnotify-tests.ts @@ -223,7 +223,7 @@ function test_pnotify() { }); var type = "error"; - var stack_bottomright = {"dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25}; + var stack_bottomright = { "dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25 }; var opts = { title: "Over Here", @@ -233,8 +233,8 @@ function test_pnotify() { width: "100%", stack: stack_bottomright, type: "error" + } as PNotifyOptions; - }; new PNotify(opts); new PNotify({ diff --git a/jquery.rateit/jquery.rateit-tests.ts b/jquery.rateit/jquery.rateit-tests.ts new file mode 100644 index 0000000000..989d5c5565 --- /dev/null +++ b/jquery.rateit/jquery.rateit-tests.ts @@ -0,0 +1,48 @@ +/// + +var rateit_simple = $('.rateit').rateit(); + +var rateit_properties_font = $('.rateit').rateit({ + backingfld: '#backingfield', + icon: '@', + mode: 'font', + ispreset: false, + max: 5, + min: 0, + readonly: false, + resetable: false, + step: 0.5, + value: 2 +}); + +var rateit_properties_bg = $('.rateit').rateit({ + backingfld: '#backingfield', + mode: 'bg', + ispreset: false, + max: 5, + min: 0, + readonly: false, + resetable: false, + step: 0.5, + value: 2, + starheight: 16, + starwidth: 16 +}); + +//getters +var val : number = rateit_properties_bg.rateit('value'); +var min : number = rateit_properties_bg.rateit('min'); +var max : number = rateit_properties_bg.rateit('max'); +var readonly :boolean = rateit_properties_bg.rateit('readonly'); +var ispreset :boolean = rateit_properties_bg.rateit('ispreset'); + + +//setters +rateit_properties_bg.rateit('value',4); +rateit_properties_bg.rateit('min',0); +rateit_properties_bg.rateit('max',6); +rateit_properties_bg.rateit('readonly',true); +rateit_properties_bg.rateit('ispreset',false); + +//reset it +rateit_properties_bg.rateit('reset'); \ No newline at end of file diff --git a/jquery.rateit/jquery.rateit.d.ts b/jquery.rateit/jquery.rateit.d.ts new file mode 100644 index 0000000000..d5540792b5 --- /dev/null +++ b/jquery.rateit/jquery.rateit.d.ts @@ -0,0 +1,45 @@ +// Type definitions for jquery.rateit.js 1.1.1 +// Project: https://github.com/gjunge/rateit.js +// Definitions by: Gidon Junge +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +type RateItMode = "bg" | "font"; +interface RateItOptions { + value? : number; + min?: number; + max?: number; + step?:number; + backingfld?:string; + readonly?:boolean; + ispreset? : boolean; + resetable? : boolean; + starwidth?: number; + starheight?: number; + mode?: RateItMode; + icon?: string; +} + +interface JQuery { + rateit() : JQuery; + rateit(options: RateItOptions) : JQuery; + + rateit(method: 'value') : number; + rateit(method: 'value', param: number) : JQuery; + + rateit(method: 'max') : number; + rateit(method: 'max', param: number) : JQuery; + + rateit(method: 'min') : number; + rateit(method: 'min', param: number) : JQuery; + + rateit(method: 'readonly') : boolean; + rateit(method: 'readonly', param: boolean) : JQuery; + + rateit(method: 'ispreset') : boolean; + rateit(method: 'ispreset', param: boolean) : JQuery; + + rateit(method: 'reset') : JQuery; + + rateit(method: string, param: any) : any; +} diff --git a/jquery/index.d.ts b/jquery/index.d.ts index 0a748d5269..f8af62caba 100644 --- a/jquery/index.d.ts +++ b/jquery/index.d.ts @@ -74,7 +74,7 @@ interface JQueryAjaxSettings { */ dataFilter? (data: any, ty: any): any; /** - * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). + * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). */ dataType?: string; /** @@ -168,11 +168,11 @@ interface JQueryAjaxSettings { */ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { /** - * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). + * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). */ overrideMimeType(mimeType: string): any; /** - * Cancel the request. + * Cancel the request. * * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" */ @@ -197,13 +197,13 @@ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { interface JQueryCallback { /** * Add a callback or a collection of callbacks to a callback list. - * + * * @param callbacks A function, or array of functions, that are to be added to the callback list. */ add(callbacks: Function): JQueryCallback; /** * Add a callback or a collection of callbacks to a callback list. - * + * * @param callbacks A function, or array of functions, that are to be added to the callback list. */ add(callbacks: Function[]): JQueryCallback; @@ -225,7 +225,7 @@ interface JQueryCallback { /** * Call all of the callbacks with the given arguments - * + * * @param arguments The argument or list of arguments to pass back to the callback list. */ fire(...arguments: any[]): JQueryCallback; @@ -237,7 +237,7 @@ interface JQueryCallback { /** * Call all callbacks in a list with the given context and arguments. - * + * * @param context A reference to the context in which the callbacks in the list should be fired. * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. */ @@ -245,7 +245,7 @@ interface JQueryCallback { /** * Determine whether a supplied callback is in a list - * + * * @param callback The callback to search for. */ has(callback: Function): boolean; @@ -262,13 +262,13 @@ interface JQueryCallback { /** * Remove a callback or a collection of callbacks from a callback list. - * + * * @param callbacks A function, or array of functions, that are to be removed from the callback list. */ remove(callbacks: Function): JQueryCallback; /** * Remove a callback or a collection of callbacks from a callback list. - * + * * @param callbacks A function, or array of functions, that are to be removed from the callback list. */ remove(callbacks: Function[]): JQueryCallback; @@ -280,7 +280,7 @@ interface JQueryCallback { interface JQueryGenericPromise { /** * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * + * * @param doneFilter A function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. */ @@ -288,7 +288,7 @@ interface JQueryGenericPromise { /** * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * + * * @param doneFilter A function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. */ @@ -316,34 +316,41 @@ interface JQueryPromise extends JQueryGenericPromise { state(): string; /** * Add handlers to be called when the Deferred object is either resolved or rejected. - * + * * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. */ always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; /** * Add handlers to be called when the Deferred object is resolved. - * + * * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. */ done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; /** * Add handlers to be called when the Deferred object is rejected. - * + * * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. */ fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; /** * Add handlers to be called when the Deferred object generates progress notifications. - * + * * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. */ progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; // Deprecated - given no typings pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; + + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + */ + promise(target?: any): JQueryPromise; } /** @@ -356,42 +363,42 @@ interface JQueryDeferred extends JQueryGenericPromise { state(): string; /** * Add handlers to be called when the Deferred object is either resolved or rejected. - * + * * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. */ always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; /** * Add handlers to be called when the Deferred object is resolved. - * + * * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. */ done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; /** * Add handlers to be called when the Deferred object is rejected. - * + * * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. */ fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; /** * Add handlers to be called when the Deferred object generates progress notifications. - * + * * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. */ progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; /** * Call the progressCallbacks on a Deferred object with the given args. - * + * * @param args Optional arguments that are passed to the progressCallbacks. */ notify(value?: any, ...args: any[]): JQueryDeferred; /** * Call the progressCallbacks on a Deferred object with the given context and args. - * + * * @param context Context passed to the progressCallbacks as the this object. * @param args Optional arguments that are passed to the progressCallbacks. */ @@ -399,13 +406,13 @@ interface JQueryDeferred extends JQueryGenericPromise { /** * Reject a Deferred object and call any failCallbacks with the given args. - * + * * @param args Optional arguments that are passed to the failCallbacks. */ reject(value?: any, ...args: any[]): JQueryDeferred; /** * Reject a Deferred object and call any failCallbacks with the given context and args. - * + * * @param context Context passed to the failCallbacks as the this object. * @param args An optional array of arguments that are passed to the failCallbacks. */ @@ -413,7 +420,7 @@ interface JQueryDeferred extends JQueryGenericPromise { /** * Resolve a Deferred object and call any doneCallbacks with the given args. - * + * * @param value First argument passed to doneCallbacks. * @param args Optional subsequent arguments that are passed to the doneCallbacks. */ @@ -421,7 +428,7 @@ interface JQueryDeferred extends JQueryGenericPromise { /** * Resolve a Deferred object and call any doneCallbacks with the given context and args. - * + * * @param context Context passed to the doneCallbacks as the this object. * @param args An optional array of arguments that are passed to the doneCallbacks. */ @@ -429,7 +436,7 @@ interface JQueryDeferred extends JQueryGenericPromise { /** * Return a Deferred's Promise object. - * + * * @param target Object onto which the promise methods have to be attached */ promise(target?: any): JQueryPromise; @@ -520,14 +527,14 @@ interface JQuerySupport { interface JQueryParam { /** * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * + * * @param obj An array or object to serialize. */ (obj: any): string; /** * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * + * * @param obj An array or object to serialize. * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. */ @@ -561,47 +568,47 @@ interface JQuerySerializeArrayElement { value: string; } -interface JQueryAnimationOptions { +interface JQueryAnimationOptions { /** * A string or number determining how long the animation will run. */ - duration?: any; + duration?: any; /** * A string indicating which easing function to use for the transition. */ - easing?: string; + easing?: string; /** * A function to call once the animation is complete. */ - complete?: Function; + complete?: Function; /** * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. */ - step?: (now: number, tween: any) => any; + step?: (now: number, tween: any) => any; /** * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) */ - progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; + progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; /** * A function to call when the animation begins. (version added: 1.8) */ - start?: (animation: JQueryPromise) => any; + start?: (animation: JQueryPromise) => any; /** * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) */ - done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; /** * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) */ - fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; /** * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) */ - always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; /** * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. */ - queue?: any; + queue?: any; /** * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) */ @@ -965,7 +972,7 @@ interface JQueryStatic { /** * Check to see if a DOM element is a descendant of another DOM element. - * + * * @param container The DOM element that may contain the other element. * @param contained The DOM element that may be contained by (a descendant of) the other element. */ @@ -973,7 +980,7 @@ interface JQueryStatic { /** * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * + * * @param collection The object or array to iterate over. * @param callback The function that will be executed on every object. */ @@ -984,7 +991,7 @@ interface JQueryStatic { /** * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * + * * @param collection The object or array to iterate over. * @param callback The function that will be executed on every object. */ @@ -1081,21 +1088,21 @@ interface JQueryStatic { /** * Convert an array-like object into a true JavaScript array. - * + * * @param obj Any object to turn into a native Array. */ makeArray(obj: any): any[]; /** * Translate all items in an array or object to new array of items. - * + * * @param array The Array to translate. * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. */ map(array: T[], callback: (elementOfArray?: T, indexInArray?: number) => U): U[]; /** * Translate all items in an array or object to new array of items. - * + * * @param arrayOrObject The Array or Object to translate. * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. */ @@ -1103,7 +1110,7 @@ interface JQueryStatic { /** * Merge the contents of two arrays together into the first array. - * + * * @param first The first array to merge, the elements of second added. * @param second The second array to merge into the first, unaltered. */ @@ -1121,7 +1128,7 @@ interface JQueryStatic { /** * Takes a well-formed JSON string and returns the resulting JavaScript object. - * + * * @param json The JSON string to parse. */ parseJSON(json: string): any; @@ -1135,21 +1142,21 @@ interface JQueryStatic { /** * Remove the whitespace from the beginning and end of a string. - * + * * @param str Remove the whitespace from the beginning and end of a string. */ trim(str: string): string; /** * Determine the internal JavaScript [[Class]] of an object. - * + * * @param obj Object to get the internal JavaScript [[Class]] of. */ type(obj: any): string; /** * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. - * + * * @param array The Array of DOM elements. */ unique(array: Element[]): Element[]; @@ -1276,7 +1283,7 @@ interface JQuery { * @param attributes An object of attribute-value pairs to set. */ attr(attributes: Object): JQuery; - + /** * Determine whether any of the matched elements are assigned the given class. * @@ -1454,7 +1461,7 @@ interface JQuery { * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). */ innerHeight(height: number|string): JQuery; - + /** * Get the current computed width for the first element in the set of matched elements, including padding but not border. */ @@ -1466,7 +1473,7 @@ interface JQuery { * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). */ innerWidth(width: number|string): JQuery; - + /** * Get the current coordinates of the first element in the set of matched elements, relative to the document. */ @@ -1899,7 +1906,7 @@ interface JQuery { /** * Attach a handler to an event for the elements. - * + * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. @@ -1907,14 +1914,14 @@ interface JQuery { bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. - * + * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. */ bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. - * + * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param eventData An object containing data that will be passed to the event handler. * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. @@ -1922,14 +1929,14 @@ interface JQuery { bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; /** * Attach a handler to an event for the elements. - * + * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. */ bind(eventType: string, preventBubble: boolean): JQuery; /** * Attach a handler to an event for the elements. - * + * * @param events An object containing one or more DOM event types and functions to execute for them. */ bind(events: any): JQuery; @@ -2504,14 +2511,14 @@ interface JQuery { /** * Execute all handlers and behaviors attached to the matched elements for the given event type. - * + * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param extraParameters Additional parameters to pass along to the event handler. */ trigger(eventType: string, extraParameters?: any[]|Object): JQuery; /** * Execute all handlers and behaviors attached to the matched elements for the given event type. - * + * * @param event A jQuery.Event object. * @param extraParameters Additional parameters to pass along to the event handler. */ @@ -2519,7 +2526,7 @@ interface JQuery { /** * Execute all handlers attached to an element for an event. - * + * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param extraParameters An array of additional parameters to pass along to the event handler. */ @@ -2527,7 +2534,7 @@ interface JQuery { /** * Execute all handlers attached to an element for an event. - * + * * @param event A jQuery.Event object. * @param extraParameters An array of additional parameters to pass along to the event handler. */ @@ -2535,21 +2542,21 @@ interface JQuery { /** * Remove a previously-attached event handler from the elements. - * + * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param handler The function that is to be no longer executed. */ unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove a previously-attached event handler from the elements. - * + * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). */ unbind(eventType: string, fls: boolean): JQuery; /** * Remove a previously-attached event handler from the elements. - * + * * @param evt A JavaScript event object as passed to an event handler. */ unbind(evt: any): JQuery; @@ -2560,7 +2567,7 @@ interface JQuery { undelegate(): JQuery; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * + * * @param selector A selector which will be used to filter the event results. * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" * @param handler A function to execute at the time the event is triggered. @@ -2568,27 +2575,27 @@ interface JQuery { undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * + * * @param selector A selector which will be used to filter the event results. * @param events An object of one or more event types and previously bound functions to unbind from them. */ undelegate(selector: string, events: Object): JQuery; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * + * * @param namespace A string containing a namespace to unbind all events from. */ undelegate(namespace: string): JQuery; /** * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * + * * @param handler A function to execute when the event is triggered. */ unload(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * + * * @param eventData A plain object of data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ @@ -2603,13 +2610,13 @@ interface JQuery { /** * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * + * * @param handler A function to execute when the event is triggered. */ error(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * + * * @param eventData A plain object of data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ @@ -2617,13 +2624,13 @@ interface JQuery { /** * Add a collection of DOM elements onto the jQuery stack. - * + * * @param elements An array of elements to push onto the stack and make into a new jQuery object. */ pushStack(elements: any[]): JQuery; /** * Add a collection of DOM elements onto the jQuery stack. - * + * * @param elements An array of elements to push onto the stack and make into a new jQuery object. * @param name The name of a jQuery method that generated the array of elements. * @param arguments The arguments that were passed in to the jQuery method (for serialization). @@ -2632,56 +2639,56 @@ interface JQuery { /** * Insert content, specified by the parameter, after each element in the set of matched elements. - * + * * param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert after each element in the set of matched elements. * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. */ after(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; /** * Insert content, specified by the parameter, after each element in the set of matched elements. - * + * * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. */ after(func: (index: number, html: string) => string|Element|JQuery): JQuery; /** * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * + * * param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. */ append(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; /** * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * + * * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. */ append(func: (index: number, html: string) => string|Element|JQuery): JQuery; /** * Insert every element in the set of matched elements to the end of the target. - * + * * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. */ appendTo(target: JQuery|any[]|Element|string): JQuery; /** * Insert content, specified by the parameter, before each element in the set of matched elements. - * + * * param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert before each element in the set of matched elements. * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. */ before(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; /** * Insert content, specified by the parameter, before each element in the set of matched elements. - * + * * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. */ before(func: (index: number, html: string) => string|Element|JQuery): JQuery; /** * Create a deep copy of the set of matched elements. - * + * * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). */ @@ -2689,7 +2696,7 @@ interface JQuery { /** * Remove the set of matched elements from the DOM. - * + * * param selector A selector expression that filters the set of matched elements to be removed. */ detach(selector?: string): JQuery; @@ -2701,62 +2708,62 @@ interface JQuery { /** * Insert every element in the set of matched elements after the target. - * + * * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. */ insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; /** * Insert every element in the set of matched elements before the target. - * + * * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. */ insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; /** * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * + * * param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. */ prepend(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; /** * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * + * * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. */ prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; /** * Insert every element in the set of matched elements to the beginning of the target. - * + * * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. */ prependTo(target: JQuery|any[]|Element|string): JQuery; /** * Remove the set of matched elements from the DOM. - * + * * @param selector A selector expression that filters the set of matched elements to be removed. */ remove(selector?: string): JQuery; /** * Replace each target element with the set of matched elements. - * + * * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. */ replaceAll(target: JQuery|any[]|Element|string): JQuery; /** * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * + * * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. */ replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; /** * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * + * * param func A function that returns content with which to replace the set of matched elements. */ replaceWith(func: () => Element|JQuery): JQuery; @@ -2767,13 +2774,13 @@ interface JQuery { text(): string; /** * Set the content of each element in the set of matched elements to the specified text. - * + * * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. */ text(text: string|number|boolean): JQuery; /** * Set the content of each element in the set of matched elements to the specified text. - * + * * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. */ text(func: (index: number, text: string) => string): JQuery; @@ -2791,20 +2798,20 @@ interface JQuery { /** * Wrap an HTML structure around each element in the set of matched elements. - * + * * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. */ wrap(wrappingElement: JQuery|Element|string): JQuery; /** * Wrap an HTML structure around each element in the set of matched elements. - * + * * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. */ wrap(func: (index: number) => string|JQuery): JQuery; /** * Wrap an HTML structure around all elements in the set of matched elements. - * + * * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. */ wrapAll(wrappingElement: JQuery|Element|string): JQuery; @@ -2812,27 +2819,27 @@ interface JQuery { /** * Wrap an HTML structure around the content of each element in the set of matched elements. - * + * * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. */ wrapInner(wrappingElement: JQuery|Element|string): JQuery; /** * Wrap an HTML structure around the content of each element in the set of matched elements. - * + * * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. */ wrapInner(func: (index: number) => string): JQuery; /** * Iterate over a jQuery object, executing a function for each matched element. - * + * * @param func A function to execute for each matched element. */ each(func: (index: number, elem: Element) => any): JQuery; /** * Retrieve one of the elements matched by the jQuery object. - * + * * @param index A zero-based integer indicating which element to retrieve. */ get(index: number): HTMLElement; @@ -2848,7 +2855,7 @@ interface JQuery { index(): number; /** * Search for a given element from among the matched elements. - * + * * @param selector A selector representing a jQuery collection in which to look for an element. */ index(selector: string|JQuery|Element): number; @@ -2867,66 +2874,66 @@ interface JQuery { /** * Add elements to the set of matched elements. - * + * * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. */ add(selector: string, context?: Element): JQuery; /** * Add elements to the set of matched elements. - * + * * @param elements One or more elements to add to the set of matched elements. */ add(...elements: Element[]): JQuery; /** * Add elements to the set of matched elements. - * + * * @param html An HTML fragment to add to the set of matched elements. */ add(html: string): JQuery; /** * Add elements to the set of matched elements. - * + * * @param obj An existing jQuery object to add to the set of matched elements. */ add(obj: JQuery): JQuery; /** * Get the children of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ children(selector?: string): JQuery; /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * + * * @param selector A string containing a selector expression to match elements against. */ closest(selector: string): JQuery; /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * + * * @param selector A string containing a selector expression to match elements against. * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. */ closest(selector: string, context?: Element): JQuery; /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * + * * @param obj A jQuery object to match elements against. */ closest(obj: JQuery): JQuery; /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * + * * @param element An element to match elements against. */ closest(element: Element): JQuery; /** * Get an array of all the elements and selectors matched against the current element up through the DOM tree. - * + * * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. */ @@ -2944,52 +2951,52 @@ interface JQuery { /** * Reduce the set of matched elements to the one at the specified index. - * + * * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. - * + * */ eq(index: number): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. - * + * * @param selector A string containing a selector expression to match the current set of elements against. */ filter(selector: string): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. - * + * * @param func A function used as a test for each element in the set. this is the current DOM element. */ filter(func: (index: number, element: Element) => any): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. - * + * * @param element An element to match the current set of elements against. */ filter(element: Element): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. - * + * * @param obj An existing jQuery object to match the current set of elements against. */ filter(obj: JQuery): JQuery; /** * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * + * * @param selector A string containing a selector expression to match elements against. */ find(selector: string): JQuery; /** * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * + * * @param element An element to match elements against. */ find(element: Element): JQuery; /** * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * + * * @param obj A jQuery object to match elements against. */ find(obj: JQuery): JQuery; @@ -3001,38 +3008,38 @@ interface JQuery { /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * + * * @param selector A string containing a selector expression to match elements against. */ has(selector: string): JQuery; /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * + * * @param contained A DOM element to match elements against. */ has(contained: Element): JQuery; /** * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * + * * @param selector A string containing a selector expression to match elements against. */ is(selector: string): boolean; /** * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * + * * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. */ is(func: (index: number, element: Element) => boolean): boolean; /** * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * + * * @param obj An existing jQuery object to match the current set of elements against. */ is(obj: JQuery): boolean; /** * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * + * * @param elements One or more elements to match the current set of elements against. */ is(elements: any): boolean; @@ -3044,42 +3051,42 @@ interface JQuery { /** * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. - * + * * @param callback A function object that will be invoked for each element in the current set. */ map(callback: (index: number, domElement: Element) => any): JQuery; /** * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. - * + * * @param selector A string containing a selector expression to match elements against. */ next(selector?: string): JQuery; /** * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ nextAll(selector?: string): JQuery; /** * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * + * * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. * @param filter A string containing a selector expression to match elements against. */ nextUntil(selector?: string, filter?: string): JQuery; /** * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * + * * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. * @param filter A string containing a selector expression to match elements against. */ nextUntil(element?: Element, filter?: string): JQuery; /** * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * + * * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. * @param filter A string containing a selector expression to match elements against. */ @@ -3087,25 +3094,25 @@ interface JQuery { /** * Remove elements from the set of matched elements. - * + * * @param selector A string containing a selector expression to match elements against. */ not(selector: string): JQuery; /** * Remove elements from the set of matched elements. - * + * * @param func A function used as a test for each element in the set. this is the current DOM element. */ not(func: (index: number, element: Element) => boolean): JQuery; /** * Remove elements from the set of matched elements. - * + * * @param elements One or more DOM elements to remove from the matched set. */ not(elements: Element|Element[]): JQuery; /** * Remove elements from the set of matched elements. - * + * * @param obj An existing jQuery object to match the current set of elements against. */ not(obj: JQuery): JQuery; @@ -3117,35 +3124,35 @@ interface JQuery { /** * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ parent(selector?: string): JQuery; /** * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ parents(selector?: string): JQuery; /** * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. * @param filter A string containing a selector expression to match elements against. */ parentsUntil(selector?: string, filter?: string): JQuery; /** * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. * @param filter A string containing a selector expression to match elements against. */ parentsUntil(element?: Element, filter?: string): JQuery; /** * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. * @param filter A string containing a selector expression to match elements against. */ @@ -3153,35 +3160,35 @@ interface JQuery { /** * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ prev(selector?: string): JQuery; /** * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ prevAll(selector?: string): JQuery; /** * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. * @param filter A string containing a selector expression to match elements against. */ prevUntil(selector?: string, filter?: string): JQuery; /** * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. * @param filter A string containing a selector expression to match elements against. */ prevUntil(element?: Element, filter?: string): JQuery; /** * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. * @param filter A string containing a selector expression to match elements against. */ @@ -3189,14 +3196,14 @@ interface JQuery { /** * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ siblings(selector?: string): JQuery; /** * Reduce the set of matched elements to a subset specified by a range of indices. - * + * * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. */ @@ -3204,32 +3211,32 @@ interface JQuery { /** * Show the queue of functions to be executed on the matched elements. - * + * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. */ queue(queueName?: string): any[]; /** * Manipulate the queue of functions to be executed, once for each matched element. - * + * * @param newQueue An array of functions to replace the current queue contents. */ queue(newQueue: Function[]): JQuery; /** * Manipulate the queue of functions to be executed, once for each matched element. - * + * * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. */ queue(callback: Function): JQuery; /** * Manipulate the queue of functions to be executed, once for each matched element. - * + * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. * @param newQueue An array of functions to replace the current queue contents. */ queue(queueName: string, newQueue: Function[]): JQuery; /** * Manipulate the queue of functions to be executed, once for each matched element. - * + * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. */ diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 638002eace..479081c477 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -209,6 +209,50 @@ function test_ajax() { url: "test.js" }); jqXHR.abort('aborting because I can'); + + //Test the promise exposed by the jqXHR object + + // done method + $.ajax({ + url: "test.js" + }).promise().done((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }); + + // fail method + $.ajax({ + url: "test.js" + }).promise().fail((jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // always method with successful request + $.ajax({ + url: "test.js" + }).promise().always((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }); + + // always method with failed request + $.ajax({ + url: "test.js" + }).promise().always((jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // then method (as of 1.8) + $.ajax({ + url: "test.js" + }).promise().then((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }, (jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // generic then method + var p: JQueryPromise = $.ajax({ url: "test.js" }).promise() + .then(() => "Hello") + .then((x) => x.length); } function test_ajaxComplete() { diff --git a/js-base64/js-base64.d.ts b/js-base64/js-base64.d.ts index 30fd18620d..bd195e3885 100644 --- a/js-base64/js-base64.d.ts +++ b/js-base64/js-base64.d.ts @@ -19,34 +19,36 @@ add methods: - [ ] noConflict */ -interface Base64 { - /** - * .encode - * @param {String} string - * @return {String} - */ - encode(base64: string): string; - - /** - * .encodeURI - * @param {String} string - * @return {String} - */ - encodeURI(base64: string): string - - /** - * .decode - * @param {String} string - * @return {String} - */ - decode(base64: string): string - - /** - * Library version - */ - VERSION:string -} - declare module 'js-base64' { - const Base64: Base64 -} \ No newline at end of file + namespace JSBase64 { + const Base64: Base64Static + interface Base64Static { + /** + * .encode + * @param {String} string + * @return {String} + */ + encode(base64: string): string; + + /** + * .encodeURI + * @param {String} string + * @return {String} + */ + encodeURI(base64: string): string + + /** + * .decode + * @param {String} string + * @return {String} + */ + decode(base64: string): string + + /** + * Library version + */ + VERSION:string + } + } + export = JSBase64 +} diff --git a/jstimezonedetect/jstimezonedetect-tests.ts b/jstimezonedetect/jstimezonedetect-tests.ts new file mode 100644 index 0000000000..c4907aa6b0 --- /dev/null +++ b/jstimezonedetect/jstimezonedetect-tests.ts @@ -0,0 +1,5 @@ +/// + +import * as jstz from 'jstimezonedetect'; + +jstz.determine().name() === 'America/Montreal'; diff --git a/jstimezonedetect/jstimezonedetect.d.ts b/jstimezonedetect/jstimezonedetect.d.ts new file mode 100644 index 0000000000..9709f52724 --- /dev/null +++ b/jstimezonedetect/jstimezonedetect.d.ts @@ -0,0 +1,16 @@ +// Type definitions for jsTimezoneDetect +// Project: https://bitbucket.org/pellepim/jstimezonedetect +// Definitions by: Olivier Lamothe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface JsTimezoneDetect { + determine: ()=> { + name: ()=> string; + } +} + +declare var jstimezonedetect: JsTimezoneDetect; + +declare module "jstimezonedetect" { + export = jstimezonedetect; +} diff --git a/jstree/jstree-tests.ts b/jstree/jstree-tests.ts index e91b33825d..e82115c645 100644 --- a/jstree/jstree-tests.ts +++ b/jstree/jstree-tests.ts @@ -99,7 +99,7 @@ var treeWithNewCoreProperties = $('#treeWithNewCoreProperties').jstree({ // tree with new checkbox properties var treeWithNewCheckboxProperties = $('#treeWithNewCheckboxProperties').jstree({ checkbox: { - cascade: true, + cascade: '', tie_selection: true } }); diff --git a/kafka-node/index.d.ts b/kafka-node/index.d.ts index 89d68de63e..049278ac51 100644 --- a/kafka-node/index.d.ts +++ b/kafka-node/index.d.ts @@ -9,6 +9,7 @@ export declare class Client { constructor(connectionString: string, clientId: string, options?: ZKOptions); close(callback?: Function): void; + topicExists(topics: Array, callback: Function): void; } export declare class Producer { @@ -65,6 +66,8 @@ export declare class Offset { fetch(payloads: Array, cb: (error: any, data: any) => any): void; commit(groupId: string, payloads: Array, cb: (error: any, data: any) => any): void; fetchCommits(groupId: string, payloads: Array, cb: (error: any, data: any) => any): void; + fetchLatestOffsets(topics: Array, cb: (error: any, data: any) => any): void; + on(eventName: string, cb: (error: any) => any): void; } export declare class KeyedMessage { @@ -99,6 +102,8 @@ export interface ConsumerOptions { export interface Topic { topic: string; offset?: number; + encoding?: string; + autoCommit?: boolean; } export interface OffsetRequest { diff --git a/kefir/index.d.ts b/kefir/index.d.ts index 12afaad5e2..94eb4a41c8 100644 --- a/kefir/index.d.ts +++ b/kefir/index.d.ts @@ -7,6 +7,17 @@ +export interface Subscription { + unsubscribe(): void; + closed: boolean; // Actually, `readonly` but it's avaiable in tsc starting with 2.0.0 +} + +export interface Observer { + value?: (value: T) => void; + error?: (error: S) => void; + end?: () => void; +} + export interface Observable { // Subscribe / add side effects onValue(callback: (value: T) => void): void; @@ -22,6 +33,13 @@ export interface Observable { flatten(transformer?: (value: T) => U[]): Stream; toPromise(PromiseConstructor?: any): any; toESObservable(): any; + // This method is designed to replace all other methods for subscribing + observe(params: Observer): Subscription; + observe( + onValue?: (value: T) => void, + onError?: (error: S) => void, + onEnd?: () => void + ): Subscription; } export interface Stream extends Observable { diff --git a/kefir/kefir-tests.ts b/kefir/kefir-tests.ts index 56055d0a22..acd0f5ae16 100644 --- a/kefir/kefir-tests.ts +++ b/kefir/kefir-tests.ts @@ -69,6 +69,19 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke Kefir.sequentially(1000, [1, 2]).log('my stream'); Kefir.sequentially(1000, [1, 2]).offLog('my stream'); Kefir.sequentially(1000, [1, 2]).toPromise().then((x: number) => console.log('fulfilled with:', x)); + Kefir.sequentially(1000, [1, 2]).observe({}); + Kefir.sequentially(1000, [1, 2]).observe({ + value: _ => {}, + error: _ => {}, + end: () => {}, + }); + Kefir.sequentially(1000, [1, 2]).observe(); + const subscription = Kefir.sequentially(1000, [1, 2]).observe( + _ => {}, + _ => {}, + () => {} + ); + if (!subscription.closed) subscription.unsubscribe(); } // Modify an observable diff --git a/kendo-ui/index.d.ts b/kendo-ui/index.d.ts index 6a1c5fbdff..d7ba989b61 100644 --- a/kendo-ui/index.d.ts +++ b/kendo-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kendo UI Professional v2016.3.914 +// Type definitions for Kendo UI Professional v2016.3.1028 // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -1026,6 +1026,8 @@ declare namespace kendo.data { class DataSource extends Observable{ options: DataSourceOptions; + transport: any; + static create(options?: DataSourceOptions): DataSource; constructor(options?: DataSourceOptions); @@ -1112,7 +1114,7 @@ declare namespace kendo.data { } interface DataSourceFilterItem extends DataSourceFilter { - operator?: string; + operator?: string|Function; field?: string; value?: any; } @@ -1245,6 +1247,7 @@ declare namespace kendo.data { type?: string; change? (e: DataSourceChangeEvent): void; error?(e: DataSourceErrorEvent): void; + push?(e: DataSourcePushEvent): void; sync?(e: DataSourceEvent): void; requestStart?(e: DataSourceRequestStartEvent): void; requestEnd?(e: DataSourceRequestEndEvent): void; @@ -1274,6 +1277,12 @@ declare namespace kendo.data { node?: any; } + interface DataSourcePushEvent extends DataSourceEvent { + items?: DataSourceItemOrGroup[]; + type?: string; + + } + interface DataSourceErrorEvent extends DataSourceEvent { xhr: JQueryXHR; status: string; @@ -1480,6 +1489,7 @@ declare namespace kendo.mobile { statusBarStyle?: string; transition?: string; useNativeScrolling?: boolean; + init?(e: ApplicationEvent): void; } interface ApplicationEvent { @@ -1529,7 +1539,16 @@ declare namespace kendo.drawing.pdf { } declare namespace kendo.ui { - class Alert extends kendo.ui.Widget { + class AgendaView implements kendo.ui.SchedulerView { + static fn: AgendaView; + + startDate(): Date; + endDate(): Date; + + static extend(proto: Object): AgendaView; + } + + class Alert extends kendo.ui.Dialog { static fn: Alert; @@ -2034,12 +2053,13 @@ declare namespace kendo.ui { } - class Confirm extends kendo.ui.Widget { + class Confirm extends kendo.ui.Dialog { static fn: Confirm; options: ConfirmOptions; + result: JQueryPromise; element: JQuery; wrapper: JQuery; @@ -2800,66 +2820,95 @@ declare namespace kendo.ui { } interface EditorMessages { - bold?: string; - italic?: string; - underline?: string; - strikethrough?: string; - superscript?: string; - subscript?: string; - justifyCenter?: string; - justifyLeft?: string; - justifyRight?: string; - justifyFull?: string; - insertUnorderedList?: string; - insertOrderedList?: string; - indent?: string; - outdent?: string; - createLink?: string; - unlink?: string; - insertImage?: string; - insertFile?: string; - insertHtml?: string; - viewHtml?: string; - fontName?: string; - fontNameInherit?: string; - fontSize?: string; - fontSizeInherit?: string; - formatBlock?: string; - formatting?: string; - foreColor?: string; - backColor?: string; - style?: string; - emptyFolder?: string; - uploadFile?: string; - editAreaTitle?: string; - orderBy?: string; - orderBySize?: string; - orderByName?: string; - invalidFileType?: string; - deleteFile?: string; - overwriteFile?: string; - directoryNotFound?: string; - imageWebAddress?: string; - imageAltText?: string; - imageWidth?: string; - imageHeight?: string; - fileWebAddress?: string; - fileTitle?: string; - linkWebAddress?: string; - linkText?: string; - linkToolTip?: string; - linkOpenInNewWindow?: string; - dialogUpdate?: string; - dialogInsert?: string; - dialogCancel?: string; - createTable?: string; - createTableHint?: string; + accessibilityTab?: string; addColumnLeft?: string; addColumnRight?: string; addRowAbove?: string; addRowBelow?: string; - deleteRow?: string; + alignCenter?: string; + alignCenterBottom?: string; + alignCenterMiddle?: string; + alignCenterTop?: string; + alignLeft?: string; + alignLeftBottom?: string; + alignLeftMiddle?: string; + alignLeftTop?: string; + alignRemove?: string; + alignRight?: string; + alignRightBottom?: string; + alignRightMiddle?: string; + alignRightTop?: string; + alignment?: string; + associateCellsWithHeaders?: string; + backColor?: string; + background?: string; + bold?: string; + border?: string; + style?: string; + caption?: string; + cellMargin?: string; + cellPadding?: string; + cellSpacing?: string; + cellTab?: string; + cleanFormatting?: string; + collapseBorders?: string; + columns?: string; + createLink?: string; + createTable?: string; + createTableHint?: string; + cssClass?: string; deleteColumn?: string; + deleteRow?: string; + dialogCancel?: string; + dialogInsert?: string; + dialogOk?: string; + dialogUpdate?: string; + editAreaTitle?: string; + fileTitle?: string; + fileWebAddress?: string; + fontName?: string; + fontNameInherit?: string; + fontSize?: string; + fontSizeInherit?: string; + foreColor?: string; + formatBlock?: string; + formatting?: string; + height?: string; + id?: string; + imageAltText?: string; + imageHeight?: string; + imageWebAddress?: string; + imageWidth?: string; + indent?: string; + insertFile?: string; + insertHtml?: string; + insertImage?: string; + insertOrderedList?: string; + insertUnorderedList?: string; + italic?: string; + justifyCenter?: string; + justifyFull?: string; + justifyLeft?: string; + justifyRight?: string; + linkOpenInNewWindow?: string; + linkText?: string; + linkToolTip?: string; + linkWebAddress?: string; + outdent?: string; + print?: string; + rows?: string; + selectAllCells?: string; + strikethrough?: string; + subscript?: string; + summary?: string; + superscript?: string; + tableTab?: string; + tableWizard?: string; + underline?: string; + unlink?: string; + viewHtml?: string; + width?: string; + wrapText?: string; } interface EditorPasteCleanup { @@ -5132,12 +5181,13 @@ declare namespace kendo.ui { } - class Prompt extends kendo.ui.Widget { + class Prompt extends kendo.ui.Dialog { static fn: Prompt; options: PromptOptions; + result: JQueryPromise; element: JQuery; wrapper: JQuery; @@ -5533,6 +5583,7 @@ declare namespace kendo.ui { minorTimeHeaderTemplate?: string|Function; selected?: boolean; selectedDateFormat?: string; + selectedShortDateFormat?: string; showWorkHours?: boolean; slotTemplate?: string|Function; startTime?: Date; @@ -6059,6 +6110,7 @@ declare namespace kendo.ui { comparerType?: string; dataType?: string; from?: string; + showButton?: boolean; to?: string; allowNulls?: boolean; messageTemplate?: string; @@ -6093,6 +6145,7 @@ declare namespace kendo.ui { cells?: SpreadsheetSheetRowCell[]; height?: number; index?: number; + type?: string; } interface SpreadsheetSheetSortColumn { @@ -7282,7 +7335,7 @@ declare namespace kendo.ui { destroy(): void; disable(): void; enable(enable?: boolean): void; - getFiles(): void; + getFiles(): any; removeAllFiles(): void; removeFile(): void; removeFileByUid(): void; @@ -7461,6 +7514,8 @@ declare namespace kendo.ui { content(content?: string): kendo.ui.Window; content(content?: JQuery): kendo.ui.Window; destroy(): void; + isMaximized(): boolean; + isMinimized(): boolean; maximize(): kendo.ui.Window; minimize(): kendo.ui.Window; open(): kendo.ui.Window; @@ -11008,7 +11063,6 @@ declare namespace kendo.dataviz.ui { autoBind?: boolean; axisDefaults?: ChartAxisDefaults; categoryAxis?: ChartCategoryAxisItem[]; - valueAxis?: ChartValueAxisItem[]; chartArea?: ChartChartArea; dataSource?: any|any|kendo.data.DataSource; legend?: ChartLegend; @@ -11024,6 +11078,7 @@ declare namespace kendo.dataviz.ui { title?: ChartTitle; tooltip?: ChartTooltip; transitions?: boolean; + valueAxis?: ChartValueAxisItem[]; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; zoomable?: boolean|ChartZoomable; @@ -16919,7 +16974,7 @@ declare namespace kendo { function bind(element: Element, viewModel: any, namespace?: any): void; function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void; function observableHierarchy(array: any): void; - function confirm(text: string): void; + function confirm(text: string): JQueryPromise; function culture(culture: string): void; function destroy(element: string): void; function destroy(element: JQuery): void; @@ -16930,7 +16985,7 @@ declare namespace kendo { function parseFloat(value: string, culture?: string): number; function parseInt(value: string, culture?: string): number; function parseColor(color: string, noerror: boolean): kendo.Color; - function prompt(text: string, defaultValue: string): void; + function prompt(text: string, defaultValue: string): JQueryPromise; function proxyModelSetters(): void; function proxyModelSetters(data: kendo.data.Model): void; function resize(element: string, force: boolean): void; @@ -16938,7 +16993,7 @@ declare namespace kendo { function resize(element: Element, force: boolean): void; function saveAs(options: any): void; function stringify(value: any): string; - function throttle(fn: Function, timeout: number): void; + function throttle(fn: Function, timeout: number): Function; function touchScroller(element: string): void; function touchScroller(element: JQuery): void; function touchScroller(element: Element): void; @@ -17023,6 +17078,8 @@ declare namespace kendo.spreadsheet { clear(options?: any): void; clearFilter(indices: any): void; clearFilter(indices: number): void; + editor(): string; + editor(value?: string): void; enable(): boolean; enable(value?: boolean): void; fillFrom(srcRange: Range, direction?: number): void; diff --git a/klaw/klaw-tests.ts b/klaw/klaw-tests.ts new file mode 100644 index 0000000000..5e7ecdebf7 --- /dev/null +++ b/klaw/klaw-tests.ts @@ -0,0 +1,46 @@ +/// +/// + +import * as klaw from "klaw"; +const path = require('path'); + +// README.md: Streams 1 (push) example: + +let items: klaw.Item[] = [] // files, directories, symlinks, etc + +klaw('/some/dir') + .on('data', function(item: klaw.Item) { + items.push(item) + }) + .on('end', function() { + console.dir(items) // => [ ... array of files] + }) + +// README.md: Streams 2 & 3 (pull) with error handling + +klaw('/some/dir') + .on('readable', function() { + let item: klaw.Item; + while (item = this.read()) { + items.push(item) + } + }) + .on('error', function(err: Error, item: klaw.Item) { + console.log(err.message) + console.log(item.path) // the file the error occurred on + }) + .on('end', function() { + console.log(items) // => [ ... array of files] + }) + +// README.md: Example (ignore hidden directories): + +var filterFunc = function(item: klaw.Item): boolean { + var basename = path.basename(item.path) + return basename === '.' || basename[0] !== '.' +} + +klaw('/some/dir', { filter: filterFunc }) + .on('data', function(item: klaw.Item) { + // only items of none hidden folders will reach here + }) diff --git a/klaw/klaw.d.ts b/klaw/klaw.d.ts new file mode 100644 index 0000000000..e2b641f546 --- /dev/null +++ b/klaw/klaw.d.ts @@ -0,0 +1,44 @@ +// Type definitions for klaw v1.3.0 +// Project: https://github.com/jprichardson/node-klaw +// Definitions by: Matthew McEachen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "klaw" { + + import * as fs from "fs" + import { Readable, ReadableOptions } from 'stream' + + function K(root: string, options?: K.Options): K.Walker + + namespace K { + interface Item { + path: string + stats: fs.Stats + } + + type QueueMethod = "shift" | "pop" + + interface Options extends ReadableOptions { + queueMethod?: QueueMethod + pathSorter?: (a: Array) => Array + fs?: any // fs or mock-fs + filter?: (a: Item) => boolean + } + + type Event = "close" | "data" | "end" | "readable" | "error" + + interface Walker { + on(event: Event, listener: Function): this + on(event: "close", listener: () => void): this + on(event: "data", listener: (item: Item) => void): this + on(event: "end", listener: () => void): this + on(event: "readable", listener: () => void): this + on(event: "error", listener: (err: Error) => void): this + read(): Item + } + } + + export = K +} diff --git a/knex/index.d.ts b/knex/index.d.ts index 9188816b36..0b69f64109 100644 --- a/knex/index.d.ts +++ b/knex/index.d.ts @@ -380,6 +380,8 @@ declare namespace Knex { foreign(column: string): ForeignConstraintBuilder; foreign(columns: string[]): MultikeyForeignConstraintBuilder; dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; + dropUnique(columnNames: string[], indexName?: string): TableBuilder; + dropPrimary(constraintName?: string): TableBuilder; } interface CreateTableBuilder extends TableBuilder { diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index eaab2ca8bd..353c382973 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -453,6 +453,10 @@ knex.schema.raw("SET sql_mode='TRADITIONAL'") table.dropColumn('name'); table.string('first_name'); table.string('last_name'); + table.dropUnique(["name1", "name2"], "index_name"); + table.dropUnique(["name1", "name2"]); + table.dropPrimary(); + table.dropPrimary("constraint_name"); }); knex('users') diff --git a/knockout/index.d.ts b/knockout/index.d.ts index f0e9fe023f..a7b4cd6411 100644 --- a/knockout/index.d.ts +++ b/knockout/index.d.ts @@ -332,7 +332,7 @@ interface KnockoutUtils { } interface KnockoutArrayChange { - status: "added" | "deleted"; + status: "added" | "deleted" | "retained"; value: T; index: number; moved?: number; diff --git a/koa-bodyparser/index.d.ts b/koa-bodyparser/index.d.ts index dc17939ead..64e745daf2 100644 --- a/koa-bodyparser/index.d.ts +++ b/koa-bodyparser/index.d.ts @@ -16,6 +16,12 @@ import * as Koa from "koa"; +declare module "koa" { + interface Request { + body: any; + } +} + declare function bodyParser(opts?: { /** * requested encoding. Default is utf-8 by co-body diff --git a/koa-passport/koa-passport-tests.ts b/koa-passport/koa-passport-tests.ts new file mode 100644 index 0000000000..cdfe4938f4 --- /dev/null +++ b/koa-passport/koa-passport-tests.ts @@ -0,0 +1,41 @@ +/// +/// + +import * as Koa from 'koa'; +import * as passport from 'koa-passport'; + +const app = new Koa(); +let ctx: Koa.Context; + + +app.use(passport.initialize()); +app.use(passport.session()); + +app.use(async (ctx: Koa.Context): Promise => { + ctx.isAuthenticated(); + ctx.isUnauthenticated(); + ctx.login({}); + ctx.logout(); + ctx.state.user; +}); + + +app.use(async (ctx: Koa.Context, next: () => Promise) => { + return passport.authenticate('local', (user: any, info: any, status: any) => { + if (user === false) { + ctx.status = 401; + ctx.body = { success: false }; + } else { + ctx.body = { success: true }; + return ctx.login(user); + } + })(ctx, next); +}); + +app.use( + passport.authenticate('local', { + successRedirect: '/app', + failureRedirect: '/' + }) +); + diff --git a/koa-passport/koa-passport.d.ts b/koa-passport/koa-passport.d.ts new file mode 100644 index 0000000000..f89d534ee2 --- /dev/null +++ b/koa-passport/koa-passport.d.ts @@ -0,0 +1,68 @@ +// Type definitions for koa-passport 2.x +// Project: https://github.com/rkusa/koa-passport +// Definitions by: horiuchi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* =================== USAGE =================== + + import * as passport from 'koa-passport'; + app.use(passport.initialize()); + app.use(passport.session()); + + =============================================== */ +/// +/// + +declare module "koa-passport" { + + import * as Koa from "koa"; + module "koa" { + interface Request { + authInfo?: any; + user?: any; + + login(user: any): Promise; + login(user: any, options: Object): Promise; + logIn(user: any): Promise; + logIn(user: any, options: Object): Promise; + + logout(): void; + logOut(): void; + + isAuthenticated(): boolean; + isUnauthenticated(): boolean; + } + } + + import * as passport from "passport"; + + interface Middleware { (ctx: Koa.Context, next: () => Promise): any; } + interface KoaPassport { + use(strategy: passport.Strategy): this; + use(name: string, strategy: passport.Strategy): this; + unuse(name: string): this; + framework(fw: passport.Framework): this; + initialize(options?: { userProperty: string; }): Middleware; + session(options?: { pauseStream: boolean; }): Middleware; + + authenticate(strategy: string, callback?: Function): Middleware; + authenticate(strategy: string, options: Object, callback?: Function): Middleware; + authenticate(strategies: string[], callback?: Function): Middleware; + authenticate(strategies: string[], options: Object, callback?: Function): Middleware; + authorize(strategy: string, callback?: Function): Middleware; + authorize(strategy: string, options: Object, callback?: Function): Middleware; + authorize(strategies: string[], callback?: Function): Middleware; + authorize(strategies: string[], options: Object, callback?: Function): Middleware; + serializeUser(fn: (user: any, done: (err: any, id: any) => void) => void): void; + deserializeUser(fn: (id: any, done: (err: any, user: any) => void) => void): void; + transformAuthInfo(fn: (info: any, done: (err: any, info: any) => void) => void): void; + } + const koaPassport: KoaPassport; + + namespace KoaPassport { + interface Profile extends passport.Profile { } + interface Framework extends passport.Framework { } + } + + export = koaPassport; +} diff --git a/koa-send/koa-send-tests.ts b/koa-send/koa-send-tests.ts new file mode 100644 index 0000000000..630bdcbddb --- /dev/null +++ b/koa-send/koa-send-tests.ts @@ -0,0 +1,23 @@ +/// +/// + +import * as Koa from "koa"; +import * as send from "koa-send"; + +const app = new Koa(); + +app.use(async (ctx: Koa.Context) => { + const path: string = await send(ctx, 'stimpy.html'); +}); + +app.use(async (ctx: Koa.Context) => { + await send(ctx, 'stimpy.html', { + root: '../static-files', + index: 'index.html', + maxAge: 10, + hidden: true, + format: true, + gzip: true, + setHeaders: () => {}, + }); +}); diff --git a/koa-send/koa-send.d.ts b/koa-send/koa-send.d.ts new file mode 100644 index 0000000000..9ed8805412 --- /dev/null +++ b/koa-send/koa-send.d.ts @@ -0,0 +1,27 @@ +// Type definitions for koa-send v3.x +// Project: https://github.com/koajs/send +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "koa-send" { + + import * as Koa from "koa"; + + interface ISendOptions { + root?: string; + index?: string; + maxAge?: number; + hidden?: boolean; + format?: boolean; + gzip?: boolean; + setHeaders?: Function; + } + + function send(ctx: Koa.Context, path: string, opts?: ISendOptions): Promise; + + namespace send {} + + export = send; +} diff --git a/koa-session-minimal/koa-session-minimal-tests.ts b/koa-session-minimal/koa-session-minimal-tests.ts new file mode 100644 index 0000000000..7ee723d3aa --- /dev/null +++ b/koa-session-minimal/koa-session-minimal-tests.ts @@ -0,0 +1,31 @@ +/// +/// + +import * as Koa from "koa"; +import * as session from "koa-session-minimal"; + +const app = new Koa(); + +const ONE_DAY = 24 * 3600 * 1000; + +app.use(session({ + key: 'SESSID', + cookie: { + maxAge: ONE_DAY, + httpOnly: false, + } +})); + +app.use((ctx) => { + if (ctx.path === '/favicon.ico') return // ignore favicon + + if (!('count' in ctx.session)) ctx.session.count = 0 // init counter + + ctx.session.count += 1 + ctx.body = ctx.session.count + + ctx.sessionHandler.regenerateId() // change session id +}); + +app.listen(80) + diff --git a/koa-session-minimal/koa-session-minimal.d.ts b/koa-session-minimal/koa-session-minimal.d.ts new file mode 100644 index 0000000000..e0369fcc1b --- /dev/null +++ b/koa-session-minimal/koa-session-minimal.d.ts @@ -0,0 +1,50 @@ +// Type definitions for koa-session-minimal v3.x +// Project: https://github.com/longztian/koa-session-minimal +// Definitions by: Longzhang Tian +// Definitions: https://github.com/hellopao/DefinitelyTyped + +/* =================== USAGE =================== + + import * as Koa from "koa"; + import session = require("koa-session-minimal"); + + const app = new Koa(); + app.use(session()); + + =============================================== */ + +/// +/// + +declare module "koa-session-minimal" { + + import * as Koa from "koa"; + import * as cookies from "cookies"; + + module "koa" { + interface Request { + session: any; + sessionHandler: { regenerateId: () => void }; + } + } + + function session(opts?: { + /** + * session cookie name and store key prefix. Default is 'koa:sess' + */ + key?: string; + + /** + * cookie options + */ + cookie?: cookies.IOptions | { (ctx?: Koa.Context): cookies.IOptions }; + + /** + * session store + */ + store?: any; + }): { (ctx: Koa.Context, next?: () => any): any }; + + namespace session {} + export = session; +} diff --git a/koa/index.d.ts b/koa/index.d.ts index 6cdb0cbcd1..7fa9dd1cc9 100644 --- a/koa/index.d.ts +++ b/koa/index.d.ts @@ -159,6 +159,7 @@ declare class Koa extends EventEmitter { constructor(); // From node.d.ts + listen(): http.Server; listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): http.Server; listen(port: number, hostname?: string, listeningListener?: Function): http.Server; listen(port: number, backlog?: number, listeningListener?: Function): http.Server; diff --git a/koa/koa-tests.ts b/koa/koa-tests.ts index b3bf036df7..1b261fdf44 100644 --- a/koa/koa-tests.ts +++ b/koa/koa-tests.ts @@ -19,3 +19,5 @@ app.use(ctx => { }); app.listen(3000); + +const server = app.listen(); diff --git a/kue/index.d.ts b/kue/index.d.ts index 0c017da93e..a8919048ac 100644 --- a/kue/index.d.ts +++ b/kue/index.d.ts @@ -7,7 +7,7 @@ import events = require('events'); import express = require('express'); -export import redis = require('redis'); +import redisClientFactory = require('redis'); export declare class Queue extends events.EventEmitter { name: string; @@ -15,7 +15,7 @@ export declare class Queue extends events.EventEmitter { promoter: any; workers: Worker[]; shuttingDown: boolean; - client: redis.RedisClient; + client: redisClientFactory.RedisClient; testMode: TestMode; static singleton: Queue; @@ -60,7 +60,7 @@ export declare class Job extends events.EventEmitter { public id: number; public type: string; public data: any; - public client: redis.RedisClient; + public client: redisClientFactory.RedisClient; private _max_attempts; static priorities: Priorities; @@ -106,7 +106,7 @@ export declare class Job extends events.EventEmitter { declare class Worker extends events.EventEmitter { queue: Queue; type: string; - client: redis.RedisClient; + client: redisClientFactory.RedisClient; job: Job; constructor(queue: Queue, type: string); @@ -124,10 +124,10 @@ declare class Worker extends events.EventEmitter { interface Redis { configureFactory(options: Object, queue: Queue): void; - createClient(): redis.RedisClient; - createClientFactory(options: Object): redis.RedisClient; - client(): redis.RedisClient; - pubsubClient(): redis.RedisClient; + createClient(): redisClientFactory.RedisClient; + createClientFactory(options: Object): redisClientFactory.RedisClient; + client(): redisClientFactory.RedisClient; + pubsubClient(): redisClientFactory.RedisClient; reset(): void; } diff --git a/ldclient-js/ldclient-js-tests.ts b/ldclient-js/ldclient-js-tests.ts new file mode 100644 index 0000000000..cf4ec2b2b6 --- /dev/null +++ b/ldclient-js/ldclient-js-tests.ts @@ -0,0 +1,32 @@ +/// + +// Implicitly calls LDClient#identify +const ldClient = LDClient.initialize( + 'ENV KEY', + { + key: 'USER KEY', + name: 'USER NAME', + custom: { + 'CUSTOM ATTRIBUTE': ['CUSTOM VALUE'], + }, + }, + { + hash: 'SECURE USER HASH', + } +); + +ldClient.on('ready', () => { + const defaultValue = false; + ldClient.variation('FLAG-KEY', defaultValue); + console.log('All flag values:', ldClient.allFlags()); +}); + +function changeCallback(changes: LaunchDarkly.LDFlagChangeset) { + console.log('Flags changed:', changes); +} + +ldClient.on('change', changeCallback); + +document.getElementById('disable-change-tracking').addEventListener('click', () => { + ldClient.off('change', changeCallback); +}); diff --git a/ldclient-js/ldclient-js.d.ts b/ldclient-js/ldclient-js.d.ts new file mode 100644 index 0000000000..47792db29a --- /dev/null +++ b/ldclient-js/ldclient-js.d.ts @@ -0,0 +1,238 @@ +// Type definitions for ldclient-js v1.1.2 +// Project: https://github.com/launchdarkly/js-client +// Definitions by: Isaac Sukin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * The LaunchDarkly JavaScript client interfaces. + * + * Documentation: http://docs.launchdarkly.com/docs/js-sdk-reference + */ +declare namespace LaunchDarkly { + /** + * The names of events to which users of the client can subscribe. + */ + export type LDEventName = 'ready' | 'change'; + + /** + * The types of values a feature flag can have. + * + * Flags can have any JSON-serializable value. + */ + export type LDFlagValue = any; + + /** + * A map of feature flags from their keys to their values. + */ + export type LDFlagSet = { + [key: string]: LDFlagValue, + }; + + /** + * A map of feature flag keys to objects holding changes in their values. + */ + export type LDFlagChangeset = { + [key: string]: { + current: LDFlagValue, + previous: LDFlagValue, + }, + }; + + /** + * The parameters required to (un)subscribe to/from LaunchDarkly events. + * + * See LDClient#on and LDClient#off. + */ + type LDEventSignature = ( + key: LDEventName, + callback: (current?: LDFlagValue | LDFlagChangeset, previous?: LDFlagValue) => void, + context?: any + ) => void; + + /** + * LaunchDarkly initialization options. + */ + export interface LDOptions { + /** + * The signed user key for Secure Mode. + * + * @see http://docs.launchdarkly.com/docs/js-sdk-reference#secure-mode + */ + hash: string; + + /** + * The initial set of flags to use until the remote set is retrieved. + * + * If "localStorage" is specified, the flags will be saved locally and + * retrieved from storage. Alternatively an LDFlagSet can be specified + * which will be used as the initial source of flag values. + */ + bootstrap?: 'localStorage' | LDFlagSet; + } + + /** + * A LaunchDarkly user object. + */ + export interface LDUser { + /** + * A unique string identifying a user. + */ + key: string; + + /** + * The user's name. + * + * You can search for users on the User page by name. + */ + name?: string; + + /** + * The user's first name. + */ + firstName?: string; + + /** + * The user's last name. + */ + lastName?: string; + + /** + * The user's email address. + * + * If an `avatar` URL is not provided, LaunchDarkly will use Gravatar + * to try to display an avatar for the user on the Users page. + */ + email?: string; + + /** + * An absolute URL to an avatar image for the user. + */ + avatar?: string; + + /** + * The user's IP address. + * + * If you provide an IP, LaunchDarkly will use a geolocation service to + * automatically infer a `country` for the user, unless you've already + * specified one. + */ + ip?: string; + + /** + * The country associated with the user. + */ + country?: string; + + /** + * Whether to show the user on the Users page in LaunchDarkly. + */ + anonymous?: boolean; + + /** + * Any additional attributes associated with the user. + */ + custom?: { + [key: string]: string | boolean | number | Array, + }; + } + + /** + * The LaunchDarkly client's instance interface. + * + * @see http://docs.launchdarkly.com/docs/js-sdk-reference + */ + export interface LDClient { + /** + * Identifies a user to LaunchDarkly. + * + * This only needs to be called if the user changes identities because + * normally the user's identity is set during client initialization. + * + * @param user + * A map of user options. Must contain at least the `key` property + * which identifies the user. + * @param hash + * The signed user key for Secure Mode; see + * http://docs.launchdarkly.com/docs/js-sdk-reference#secure-mode + * @param onDone + * A callback to invoke after the user is identified. + */ + identify: (user: LDUser, hash?: string, onDone?: () => void) => void; + + /** + * Retrieves a flag's value. + * + * @param key + * The key of the flag for which to retrieve the corresponding value. + * @param defaultValue + * The value to use if the flag is not available (for example, if the + * user is offline or a flag is requested that does not exist). + * + * @returns + * The flag's value. + */ + variation: (key: string, defaultValue?: LDFlagValue) => LDFlagValue; + + /** + * Registers an event listener. + * + * @param key + * The name of the event for which to listen. This can be "ready", + * "change", or "change:FLAG-KEY". + * @param callback + * The function to execute when the event fires. For the "change" + * event, the callback receives one parameter: an LDFlagChangeset + * describing the changes. For "change:FLAG-KEY" events, the callback + * receives two parameters: the current (new) value and the previous + * value of the relevant flag. + * @param context + * The "this" context to use for the callback. + */ + on: LDEventSignature; + + /** + * Deregisters an event listener. + * + * @param key + * The name of the event for which to stop listening. This can be + * "ready", "change", or "change:FLAG-KEY". + * @param callback + * The function to deregister. + * @param context + * The "this" context for the callback. + */ + off: LDEventSignature; + + /** + * Track page events to use in goals or A/B tests. + * + * LaunchDarkly automatically tracks pageviews and clicks that are + * specified in the Goals section of their dashboard. This can be used + * to track custom goals or other events that do not currently have + * goals. + * + * @param key + * The event to record. + * @param data + * Additional information to associate with the event. + */ + track: (key: string, data?: any) => void; + + /** + * Returns a map of all available flags to the current user's values. + */ + allFlags: () => LDFlagSet; + } + +} + +/** + * The LaunchDarkly static global. + */ +declare var LDClient: { + initialize: ( + key: string, + user: LaunchDarkly.LDUser, + options?: LaunchDarkly.LDOptions + ) => LaunchDarkly.LDClient; +}; diff --git a/leaflet/index.d.ts b/leaflet/index.d.ts index e203a066ec..b67134a8b6 100644 --- a/leaflet/index.d.ts +++ b/leaflet/index.d.ts @@ -1,9 +1,47 @@ -// Type definitions for Leaflet.js 1.0.0-rc3 +// Type definitions for Leaflet.js 1.0.0 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +type NativeMouseEvent = MouseEvent; + declare namespace L { + export class Class { + static extend(props:any):any/* how to return constructor of self extended type ? */; + static include(props:any):any /* how to return self extended type ? */; + static mergeOptions(props:any): any /* how to return self extended type ? */; + static addInitHook(initHookFn: ()=> void): any/* how to return self extended type ? */; + } + + export class DomUtil { + static get(id: string): HTMLElement; + static get(id: HTMLElement): HTMLElement; + static getStyle(el: HTMLElement, styleAttrib: string): string; + static create(tagName: String, className?: String, container?: HTMLElement): HTMLElement; + static remove(el: HTMLElement):void; + static empty(el: HTMLElement):void; + static toFront(el: HTMLElement):void; + static toBack(el: HTMLElement):void; + static hasClass(el: HTMLElement, name: String): Boolean; + static addClass(el: HTMLElement, name: String):void; + static removeClass(el: HTMLElement, name: String):void; + static setClass(el: HTMLElement, name: String):void; + static getClass(el: HTMLElement): String; + static setOpacity(el: HTMLElement, opacity: Number):void; + static testProp(props: String[]): String|boolean/*=false*/; + static setTransform(el: HTMLElement, offset: Point, scale?: Number):void; + static setPosition(el: HTMLElement, position: Point):void; + static getPosition(el: HTMLElement): Point + static disableTextSelection(): void + static enableTextSelection(): void + static disableImageDrag(): void + static enableImageDrag(): void + static preventOutline(el: HTMLElement): void + static restoreOutline(): void + } + export interface CRS { latLngToPoint(latlng: LatLng, zoom: number): Point; latLngToPoint(latlng: LatLngLiteral, zoom: number): Point; @@ -209,7 +247,7 @@ declare namespace L { * with an object (e.g. the user clicks on the map, causing the map to fire * 'click' event). */ - export interface Evented { + export interface Evented extends Class { /** * Adds a listener function (fn) to a particular event type of the object. * You can optionally specify the context of the listener (object the this @@ -445,6 +483,7 @@ declare namespace L { zoomReverse?: boolean; detectRetina?: boolean; crossOrigin?: boolean; + [name: string]: any; } export interface TileLayer extends GridLayer { @@ -523,8 +562,7 @@ declare namespace L { noClip?: boolean; } - export interface Polyline extends Path { - toGeoJSON(): Object; // should import GeoJSON typings + interface InternalPolyline extends Path { getLatLngs(): Array; setLatLngs(latlngs: Array): this; setLatLngs(latlngs: Array): this; @@ -540,6 +578,10 @@ declare namespace L { addLatLng(latlng: Array): this; } + export interface Polyline extends InternalPolyline { + toGeoJSON(): GeoJSON.LineString | GeoJSON.MultiLineString; + } + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; @@ -552,8 +594,8 @@ declare namespace L { export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; - export interface Polygon extends Polyline { - toGeoJSON(): Object; // should import GeoJSON typings + export interface Polygon extends InternalPolyline { + toGeoJSON(): GeoJSON.Polygon | GeoJSON.MultiPolygon; } export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; @@ -582,7 +624,7 @@ declare namespace L { } export interface CircleMarker extends Path { - toGeoJSON(): Object; // should import GeoJSON typings + toGeoJSON(): GeoJSON.Point; setLatLng(latLng: LatLng): this; setLatLng(latLng: LatLngLiteral): this; setLatLng(latLng: LatLngTuple): this; @@ -650,7 +692,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the layer group (as a GeoJSON GeometryCollection). */ - toGeoJSON(): Object; // should import GeoJSON typings + toGeoJSON(): GeoJSON.GeometryCollection; /** * Adds the given layer to the group. @@ -747,7 +789,7 @@ declare namespace L { */ export function featureGroup(layers?: Array): FeatureGroup; - type StyleFunction = (feature: any) => PathOptions; + type StyleFunction = (feature: GeoJSON.Feature) => PathOptions; export interface GeoJSONOptions extends LayerOptions { /** @@ -763,7 +805,7 @@ declare namespace L { * } * ``` */ - pointToLayer?: (geoJsonPoint: Object, latlng: LatLng) => Layer; // should import GeoJSON typings + pointToLayer?: (geoJsonPoint: GeoJSON.Point, latlng: LatLng) => Layer; // should import GeoJSON typings /** * A Function defining the Path options for styling GeoJSON lines and polygons, @@ -777,7 +819,7 @@ declare namespace L { * } * ``` */ - style?: (geoJsonFeature: Object) => PathOptions; + style?: StyleFunction; /** * A Function that will be called once for each created Feature, after it @@ -789,7 +831,7 @@ declare namespace L { * function (feature, layer) {} * ``` */ - onEachFeature?: (feature: Object, layer: Layer) => void; + onEachFeature?: (feature: GeoJSON.Feature, layer: Layer) => void; /** * A Function that will be used to decide whether to show a feature or not. @@ -802,7 +844,7 @@ declare namespace L { * } * ``` */ - filter?: (geoJsonFeature: Object) => boolean; + filter?: (geoJsonFeature: GeoJSON.Feature) => boolean; /** * A Function that will be used for converting GeoJSON coordinates to LatLngs. @@ -815,36 +857,36 @@ declare namespace L { * Represents a GeoJSON object or an array of GeoJSON objects. * Allows you to parse GeoJSON data and display it on the map. Extends FeatureGroup. */ - export interface GeoJSON extends FeatureGroup {} - - export namespace GeoJSON { + export interface GeoJSON extends FeatureGroup { /** * Adds a GeoJSON object to the layer. */ - export function addData(data: Object): Layer; + addData(data: GeoJSON.GeoJsonObject): Layer; /** * Resets the given vector layer's style to the original GeoJSON style, * useful for resetting style after hover events. */ - export function resetStyle(layer: Layer): Layer; + resetStyle(layer: Layer): Layer; /** * Changes styles of GeoJSON vector layers with the given style function. */ - export function setStyle(style: PathOptions | StyleFunction): Layer; + setStyle(style: StyleFunction): this; /** * Creates a Layer from a given GeoJSON feature. Can use a custom pointToLayer * and/or coordsToLatLng functions if provided as options. */ - export function geometryToLayer(featureData: Object, options?: GeoJSONOptions): Layer; + geometryToLayer(featureData: GeoJSON.Feature, options?: GeoJSONOptions): Layer; /** * Creates a LatLng object from an array of 2 numbers (longitude, latitude) or * 3 numbers (longitude, latitude, altitude) used in GeoJSON for points. */ - export function coordsToLatLng(coords: [number, number] | [number, number, number]): LatLng; + coordsToLatLng(coords: [number, number]): LatLng; + + coordsToLatLng(coords: [number, number, number]): LatLng; /** * Creates a multidimensional array of LatLngs from a GeoJSON coordinates array. @@ -852,24 +894,26 @@ declare namespace L { * arrays of points, etc., 0 by default). * Can use a custom coordsToLatLng function. */ - export function coordsToLatLngs(coords: Array, levelsDeep?: number, coordsToLatLng?: (coords: [number, number] | [number, number, number]) => LatLng): LatLng[]; // Not entirely sure how to define arbitrarily nested arrays + coordsToLatLngs(coords: Array, levelsDeep?: number, coordsToLatLng?: (coords: [number, number] | [number, number, number]) => LatLng): LatLng[]; // Not entirely sure how to define arbitrarily nested arrays /** * Reverse of coordsToLatLng */ - export function latLngToCoords(latlng: LatLng): [number, number] | [number, number, number]; + latLngToCoords(latlng: LatLng): [number, number] | [number, number, number]; /** * Reverse of coordsToLatLngs closed determines whether the first point should be * appended to the end of the array to close the feature, only used when levelsDeep is 0. * False by default. */ - export function latLngsToCoords(latlngs: Array, levelsDeep?: number, closed?: boolean): [number, number] | [number, number, number]; + latLngsToCoords(latlngs: Array, levelsDeep?: number, closed?: boolean): [number, number] | [number, number, number]; /** * Normalize GeoJSON geometries/features into GeoJSON features. */ - export function asFeature(geojson: Object): Object; + asFeature(geojson: GeoJSON.GeometryObject): GeoJSON.Feature; + + asFeature(geojson: GeoJSON.Feature): GeoJSON.Feature; } /** @@ -879,7 +923,7 @@ declare namespace L { * map (you can alternatively add it later with addData method) and * an options object. */ - export function geoJSON(geojson?: Object, options?: GeoJSONOptions): GeoJSON; + export function geoJSON(geojson?: GeoJSON.GeoJsonObject, options?: GeoJSONOptions): GeoJSON; type Zoom = boolean | 'center'; @@ -1117,7 +1161,7 @@ declare namespace L { latlng: LatLng; layerPoint: Point; containerPoint: Point; - originalEvent: MouseEvent; // how can I reference the global MouseEvent? + originalEvent: NativeMouseEvent; } export interface LocationEvent extends Event { @@ -1177,6 +1221,38 @@ declare namespace L { distance: number; } + export namespace DomEvent { + export function on(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: Object): typeof DomEvent; + + export function on(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: Object): typeof DomEvent; + + export function off(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: Object): typeof DomEvent; + + export function off(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: Object): typeof DomEvent; + + export function stopPropagation(ev: Event): typeof DomEvent; + + export function disableScrollPropagation(el: HTMLElement): typeof DomEvent; + + export function disableClickPropagation(el: HTMLElement): typeof DomEvent; + + export function preventDefault(ev: Event): typeof DomEvent; + + export function stop(ev: Event): typeof DomEvent; + + export function getMousePosition(ev: Event, container?: HTMLElement): Point; + + export function getWheelDelta(ev: Event): number; + + export function addListener(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: Object): typeof DomEvent; + + export function addListener(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: Object): typeof DomEvent; + + export function removeListener(el: HTMLElement, types: string, fn: (ev: Event) => any, context?: Object): typeof DomEvent; + + export function removeListener(el: HTMLElement, eventMap: {[eventName: string]: Function}, context?: Object): typeof DomEvent; + } + interface DefaultMapPanes { mapPane: HTMLElement; tilePane: HTMLElement; @@ -1233,8 +1309,8 @@ declare namespace L { panTo(latlng: LatLngTuple, options?: PanOptions): this; panBy(offset: Point): this; panBy(offset: PointTuple): this; - setMaxBounds(bounds: Bounds): this; // is this really bounds and not lanlngbounds? - setMaxBounds(bounds: BoundsLiteral): this; + setMaxBounds(bounds: LatLngBounds): this; + setMaxBounds(bounds: LatLngBoundsLiteral): this; setMinZoom(zoom: number): this; setMaxZoom(zoom: number): this; panInsideBounds(bounds: LatLngBounds, options?: PanOptions): this; @@ -1337,8 +1413,12 @@ declare namespace L { createShadow(oldIcon?: HTMLElement): HTMLElement; } + export interface IconDefault extends Icon { + imagePath: string; + } + export namespace Icon { - export const Default: Icon; + export const Default: IconDefault; } export function icon(options: IconOptions): Icon; @@ -1395,45 +1475,25 @@ declare namespace L { export const gecko: boolean; export const android: boolean; export const android23: boolean; - export const chrome: boolean; - export const safari: boolean; - export const win: boolean; - export const ie3d: boolean; - export const webkit3d: boolean; - export const gecko3d: boolean; - export const opera12: boolean; - export const any3d: boolean; - export const mobile: boolean; - export const mobileWebkit: boolean; - export const mobiWebkit3d: boolean; - export const mobileOpera: boolean; - export const mobileGecko: boolean; - export const touch: boolean; - export const msPointer: boolean; - export const pointer: boolean; - export const retina: boolean; - export const canvas: boolean; - export const vml: boolean; - export const svg: boolean; } } diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index 155855ed56..34a5fa245f 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -166,11 +166,72 @@ mapPixelBounds = map.getPixelBounds(); mapPixelBounds = map.getPixelWorldBounds(); mapPixelBounds = map.getPixelWorldBounds(12); +let tileLayerOptions: L.TileLayerOptions = {}; +tileLayerOptions = { + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 2, + errorTileUrl: '', + zoomOffset: 0, + tms: true, + zoomReverse: true, + detectRetina: true, + crossOrigin: false, + opacity: 1, + updateWhenIdle: true, + updateWhenZooming: true, + updateInterval: 500, + attribution: '', + zIndex: 1, + noWrap: true, + pane: '', + className: '', + keepBuffer: 1, + foo: 'bar', + bar: () => 'foo', + abc: (data: any) => 'foobar' +}; + +tileLayerOptions.subdomains = 'a'; +tileLayerOptions.subdomains = ['a', 'b']; + +tileLayerOptions.tileSize = 256; +tileLayerOptions.tileSize = point; +//tileLayerOptions.tileSize = pointTuple; investigate if this is valid + +tileLayerOptions.bounds = latLngBounds; +tileLayerOptions.bounds = latLngBoundsLiteral; + +let tileLayer: L.TileLayer; +tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'); +tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayerOptions); +tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}&{bar}&{abc}', {foo: 'bar', bar: (data: any) => 'foo', abc: () => ''}); + +let eventHandler = () => {}; +let domEvent: Event = {} as Event; +L.DomEvent + .on(htmlElement, 'click', eventHandler) + .addListener(htmlElement, 'click', eventHandler) + .off(htmlElement, 'click', eventHandler) + .removeListener(htmlElement, 'click', eventHandler) + .on(htmlElement, {'click': eventHandler}) + .addListener(htmlElement, {'click': eventHandler}) + .off(htmlElement, {'click': eventHandler}, eventHandler) + .removeListener(htmlElement, {'click': eventHandler}, eventHandler) + .stopPropagation(domEvent) + .disableScrollPropagation(htmlElement) + .disableClickPropagation(htmlElement) + .preventDefault(domEvent) + .stop(domEvent); +point = L.DomEvent.getMousePosition(domEvent); +point = L.DomEvent.getMousePosition(domEvent, htmlElement); +const wheelDelta: number = L.DomEvent.getWheelDelta(domEvent); + map = map // addControl // removeControl - .addLayer(L.tileLayer('')) - .removeLayer(L.tileLayer('')) // use a different type of layer + .addLayer(tileLayer) + .removeLayer(tileLayer) // use a different type of layer .eachLayer((currentLayer) => { layer = currentLayer; }) @@ -237,8 +298,8 @@ map = map .panTo(latLngTuple, panOptions) .panBy(point) .panBy(pointTuple) - .setMaxBounds(bounds) // investigate if this really receives Bounds instead of LatLngBounds - .setMaxBounds(boundsLiteral) + .setMaxBounds(latLngBounds) + .setMaxBounds(latLngBoundsLiteral) .setMinZoom(5) .setMaxZoom(10) .panInsideBounds(latLngBounds) diff --git a/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts b/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts new file mode 100644 index 0000000000..d6a9ac4ae2 --- /dev/null +++ b/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver-tests.ts @@ -0,0 +1,56 @@ +/// + +declare var cordovaSQLiteDriver: LocalForageDriver; + +() => { + + var driverName: string = cordovaSQLiteDriver._driver; + + var config = { + driver: driverName, + name: 'localforage' + }; + + cordovaSQLiteDriver._initStorage(config); + + cordovaSQLiteDriver.clear((err: any) => { + var newError: any = err; + }); + + cordovaSQLiteDriver.length((err: any, num: number) => { + var newError: any = err; + var newNumber: number = num; + }); + + cordovaSQLiteDriver.key(0, (err: any, value: string) => { + var newError: any = err; + var newValue: string = value; + }); + + cordovaSQLiteDriver.keys((err: any, keys: Array) => { + var newError: any = err; + var newArray: Array = keys; + }); + + cordovaSQLiteDriver.getItem("key",(err: any, str: string) => { + var newError: any = err; + var newStr: string = str + }); + + cordovaSQLiteDriver.setItem("key", "value", (err: any, str: string) => { + var newError: any = err; + var newStr: string = str + }); + + cordovaSQLiteDriver.setItem("key", "value", (str: string) => { + var newStr: string = str; + }); + + cordovaSQLiteDriver.removeItem("key",(err: any) => { + var newError: any = err; + }); + + cordovaSQLiteDriver.removeItem("key", (err: any) => { + var newError: any = err; + }); +} \ No newline at end of file diff --git a/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver.d.ts b/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver.d.ts new file mode 100644 index 0000000000..22327f12b9 --- /dev/null +++ b/localforage-cordovasqlitedriver/localforage-cordovasqlitedriver.d.ts @@ -0,0 +1,11 @@ +// Type definitions for localforage-cordovasqlitedriver module v1.0+ +// Project: https://github.com/thgreasi/localForage-cordovaSQLiteDriver +// Definitions by: Thodoris Greasidis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "localforage-cordovasqlitedriver" { + var cordovaSQLiteDriver: LocalForageDriver; + export = cordovaSQLiteDriver; +} diff --git a/localforage/index.d.ts b/localforage/index.d.ts index c727d93b3a..e5d42d6d12 100644 --- a/localforage/index.d.ts +++ b/localforage/index.d.ts @@ -12,56 +12,12 @@ interface LocalForageOptions { storeName?: string; - version?: string; + version?: number; description?: string; } -interface LocalForageDriver { - _driver: string; - - _initStorage(options: LocalForageOptions): void; - - _support: boolean | Promise; - - clear(callback: (err: any) => void): void; - - getItem(key: string, callback: (err: any, value: any) => void): void; - - key(keyIndex: number, callback: (err: any, key: string) => void): void; - - keys(callback: (err: any, keys: string[]) => void): void; - - length(callback: (err: any, numberOfKeys: number) => void): void; - - removeItem(key: string, callback: (err: any) => void): void; - - setItem(key: string, value: any, callback: (err: any, value: any) => void): void; -} - -interface LocalForage { - LOCALSTORAGE: string; - WEBSQL: string; - INDEXEDDB: string; - - /** - * Set and persist localForage options. This must be called before any other calls to localForage are made, but can be called after localForage is loaded. - * If you set any config values with this method they will persist after driver changes, so you can call config() then setDriver() - * @param {ILocalForageConfig} options? - */ - config(options: LocalForageOptions): boolean; - createInstance(options: LocalForageOptions): LocalForage; - - driver(): string; - /** - * Force usage of a particular driver or drivers, if available. - * @param {string} driver - */ - setDriver(driver: string | string[]): Promise; - setDriver(driver: string | string[], callback: () => void, errorCallback: (error: any) => void): void; - defineDriver(driver: LocalForageDriver): Promise; - defineDriver(driver: LocalForageDriver, callback: () => void, errorCallback: (error: any) => void): void; - +interface LocalForageDbMethods { getItem(key: string): Promise; getItem(key: string, callback: (err: any, value: T) => void): void; @@ -86,16 +42,71 @@ interface LocalForage { iterate(iteratee: (value: any, key: string, iterationNumber: number) => any): Promise; iterate(iteratee: (value: any, key: string, iterationNumber: number) => any, callback: (err: any, result: any) => void): void; - +} + +interface LocalForageDriverSupportFunc { + (): Promise; +} + +interface LocalForageDriver extends LocalForageDbMethods { + _driver: string; + + _initStorage(options: LocalForageOptions): void; + + _support: boolean | LocalForageDriverSupportFunc; +} + +interface LocalForageSerializer { + serialize(value: T | ArrayBuffer | Blob, callback: (value: string, error: any) => {}): void; + + deserialize(value: string): T | ArrayBuffer | Blob; + + stringToBuffer(serializedString: string): ArrayBuffer; + + bufferToString(buffer: ArrayBuffer): string; +} + +interface LocalForage extends LocalForageDbMethods { + LOCALSTORAGE: string; + WEBSQL: string; + INDEXEDDB: string; + + /** + * Set and persist localForage options. This must be called before any other calls to localForage are made, but can be called after localForage is loaded. + * If you set any config values with this method they will persist after driver changes, so you can call config() then setDriver() + * @param {ILocalForageConfig} options? + */ + config(options: LocalForageOptions): boolean; + /** * Create a new instance of localForage to point to a different store. * All the configuration options used by config are supported. * @param {LocalForageOptions} options */ createInstance(options: LocalForageOptions): LocalForage; + + driver(): string; + /** + * Force usage of a particular driver or drivers, if available. + * @param {string} driver + */ + setDriver(driver: string | string[]): Promise; + setDriver(driver: string | string[], callback: () => void, errorCallback: (error: any) => void): void; + defineDriver(driver: LocalForageDriver): Promise; + defineDriver(driver: LocalForageDriver, callback: () => void, errorCallback: (error: any) => void): void; + /** + * Return a particular driver + * @param {string} driver + */ + getDriver(driver: string): Promise; + + getSerializer(): Promise; + getSerializer(callback: (serializer: LocalForageSerializer) => void): void; + + supports(driverName: string): boolean; } declare module "localforage" { - var localforage: LocalForage; + let localforage: LocalForage; export = localforage; } diff --git a/localforage/localForage-tests.ts b/localforage/localForage-tests.ts index a4abe394b7..721db8ba86 100644 --- a/localforage/localForage-tests.ts +++ b/localforage/localForage-tests.ts @@ -1,65 +1,108 @@  -declare var localForage: LocalForage; +declare let localForage: LocalForage; -() => { +namespace LocalForageTest { localForage.clear((err: any) => { - var newError: any = err; + let newError: any = err; }); localForage.iterate((str: string, key: string, num: number) => { - var newStr: string = str; - var newKey: string = key; - var newNum: number = num; + let newStr: string = str; + let newKey: string = key; + let newNum: number = num; }); localForage.length((err: any, num: number) => { - var newError: any = err; + let newError: any = err; + let newNumber: number = num; + }); + + localForage.length().then((num: number) => { var newNumber: number = num; }); localForage.key(0, (err: any, value: string) => { - var newError: any = err; - var newValue: string = value; + let newError: any = err; + let newValue: string = value; }); localForage.keys((err: any, keys: Array) => { - var newError: any = err; + let newError: any = err; + let newArray: Array = keys; + }); + + localForage.keys().then((keys: Array) => { var newArray: Array = keys; }); localForage.getItem("key",(err: any, str: string) => { - var newError: any = err; - var newStr: string = str + let newError: any = err; + let newStr: string = str }); localForage.getItem("key").then((str: string) => { - var newStr: string = str; + let newStr: string = str; }); localForage.setItem("key", "value",(err: any, str: string) => { - var newError: any = err; - var newStr: string = str + let newError: any = err; + let newStr: string = str }); localForage.setItem("key", "value").then((str: string) => { - var newStr: string = str; + let newStr: string = str; }); localForage.removeItem("key",(err: any) => { - var newError: any = err; + let newError: any = err; }); localForage.removeItem("key").then(() => { }); - var config = localForage.config({ + localForage.getDriver("CustomDriver").then((result: LocalForageDriver) => { + var driver: LocalForageDriver = result; + // we need to use a variable for proper type guards before TS 2.0 + var _support = driver._support; + if (typeof _support === "function") { + // _support = _support.bind(driver); + _support().then((result: boolean) => { + let doesSupport: boolean = result; + }); + } else if (typeof _support === "boolean") { + let doesSupport: boolean = _support; + } + }); + + { + let config: boolean; + + config = localForage.config({ name: "testyo", driver: localForage.LOCALSTORAGE }); + } + + { + let store: LocalForage; - var store = localForage.createInstance({ + store = localForage.createInstance({ name: "da instance", driver: localForage.LOCALSTORAGE }); + } + + { + let testSerializer: LocalForageSerializer; + + localForage.getSerializer() + .then((serializer: LocalForageSerializer) => { + testSerializer = serializer; + }); + + localForage.getSerializer((serializer: LocalForageSerializer) => { + testSerializer = serializer; + }); + } } \ No newline at end of file diff --git a/lodash/index.d.ts b/lodash/index.d.ts index 3bdd09fab4..ebdc7b5d2a 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -355,6 +355,9 @@ declare module _ { */ set(key: string, value: any): _.Dictionary; } + interface MapCacheConstructor { + new (): MapCache; + } interface LoDashWrapperBase { } @@ -384,7 +387,15 @@ declare module _ { unshift(...items: T[]): LoDashImplicitArrayWrapper; } - interface LoDashExplicitArrayWrapper extends LoDashExplicitWrapperBase> { } + interface LoDashExplicitArrayWrapper extends LoDashExplicitWrapperBase> { + pop(): LoDashExplicitObjectWrapper; + push(...items: T[]): LoDashExplicitArrayWrapper; + shift(): LoDashExplicitObjectWrapper; + sort(compareFn?: (a: T, b: T) => number): LoDashExplicitArrayWrapper; + splice(start: number): LoDashExplicitArrayWrapper; + splice(start: number, deleteCount: number, ...items: any[]): LoDashExplicitArrayWrapper; + unshift(...items: T[]): LoDashExplicitArrayWrapper; + } interface LoDashImplicitNumberArrayWrapper extends LoDashImplicitArrayWrapper { } @@ -1579,12 +1590,13 @@ declare module _ { * * @param array The array to search. * @param predicate The function invoked per iteration. - * @param thisArg The this binding of predicate. + * @param fromIndex The index to search from. * @return Returns the index of the found element, else -1. */ findIndex( array: List, - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** @@ -1592,7 +1604,8 @@ declare module _ { */ findIndex( array: List, - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** @@ -1600,7 +1613,8 @@ declare module _ { */ findIndex( array: List, - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1609,21 +1623,24 @@ declare module _ { * @see _.findIndex */ findIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** * @see _.findIndex */ findIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** * @see _.findIndex */ findIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1632,21 +1649,24 @@ declare module _ { * @see _.findIndex */ findIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** * @see _.findIndex */ findIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** * @see _.findIndex */ findIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1655,21 +1675,24 @@ declare module _ { * @see _.findIndex */ findIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findIndex */ findIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findIndex */ findIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): LoDashExplicitWrapper; } @@ -1678,21 +1701,24 @@ declare module _ { * @see _.findIndex */ findIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findIndex */ findIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findIndex */ findIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): LoDashExplicitWrapper; } @@ -1712,12 +1738,13 @@ declare module _ { * * @param array The array to search. * @param predicate The function invoked per iteration. - * @param thisArg The function invoked per iteration. + * @param fromIndex The index to search from. * @return Returns the index of the found element, else -1. */ findLastIndex( array: List, - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** @@ -1725,7 +1752,8 @@ declare module _ { */ findLastIndex( array: List, - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** @@ -1733,7 +1761,8 @@ declare module _ { */ findLastIndex( array: List, - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1742,21 +1771,24 @@ declare module _ { * @see _.findLastIndex */ findLastIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** * @see _.findLastIndex */ findLastIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** * @see _.findLastIndex */ findLastIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1765,21 +1797,24 @@ declare module _ { * @see _.findLastIndex */ findLastIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): number; /** * @see _.findLastIndex */ findLastIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): number; /** * @see _.findLastIndex */ findLastIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): number; } @@ -1788,21 +1823,24 @@ declare module _ { * @see _.findLastIndex */ findLastIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findLastIndex */ findLastIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findLastIndex */ findLastIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): LoDashExplicitWrapper; } @@ -1811,21 +1849,24 @@ declare module _ { * @see _.findLastIndex */ findLastIndex( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findLastIndex */ findLastIndex( - predicate?: string + predicate?: string, + fromIndex?: number ): LoDashExplicitWrapper; /** * @see _.findLastIndex */ findLastIndex( - predicate?: W + predicate?: W, + fromIndex?: number ): LoDashExplicitWrapper; } @@ -6883,26 +6924,32 @@ declare module _ { * right to left. * @param collection Searches for a value in this list. * @param callback The function called per iteration. - * @param thisArg The this binding of callback. + * @param fromIndex The index to search from. * @return The found element, else undefined. **/ findLast( collection: Array, - callback: ListIterator): T; + callback: ListIterator, + fromIndex?: number + ): T; /** * @see _.find **/ findLast( collection: List, - callback: ListIterator): T; + callback: ListIterator, + fromIndex?: number + ): T; /** * @see _.find **/ findLast( collection: Dictionary, - callback: DictionaryIterator): T; + callback: DictionaryIterator, + fromIndex?: number + ): T; /** * @see _.find @@ -6910,7 +6957,9 @@ declare module _ { **/ findLast( collection: Array, - whereValue: W): T; + whereValue: W, + fromIndex?: number + ): T; /** * @see _.find @@ -6918,7 +6967,9 @@ declare module _ { **/ findLast( collection: List, - whereValue: W): T; + whereValue: W, + fromIndex?: number + ): T; /** * @see _.find @@ -6926,7 +6977,9 @@ declare module _ { **/ findLast( collection: Dictionary, - whereValue: W): T; + whereValue: W, + fromIndex?: number + ): T; /** * @see _.find @@ -6934,7 +6987,9 @@ declare module _ { **/ findLast( collection: Array, - pluckValue: string): T; + pluckValue: string, + fromIndex?: number + ): T; /** * @see _.find @@ -6942,7 +6997,9 @@ declare module _ { **/ findLast( collection: List, - pluckValue: string): T; + pluckValue: string, + fromIndex?: number + ): T; /** * @see _.find @@ -6950,7 +7007,9 @@ declare module _ { **/ findLast( collection: Dictionary, - pluckValue: string): T; + pluckValue: string, + fromIndex?: number + ): T; } interface LoDashImplicitArrayWrapper { @@ -6958,20 +7017,26 @@ declare module _ { * @see _.findLast */ findLast( - callback: ListIterator): T; + callback: ListIterator, + fromIndex?: number + ): T; /** * @see _.findLast * @param _.where style callback */ findLast( - whereValue: W): T; + whereValue: W, + fromIndex?: number + ): T; /** * @see _.findLast * @param _.where style callback */ findLast( - pluckValue: string): T; + pluckValue: string, + fromIndex?: number + ): T; } //_.flatMap @@ -10403,7 +10468,7 @@ declare module _ { */ memoize: { (func: T, resolver?: Function): T & MemoizedFunction; - Cache: MapCache; + Cache: MapCacheConstructor; } } @@ -18195,6 +18260,34 @@ declare module _ { constant(): LoDashExplicitObjectWrapper<() => TResult>; } + //_.defaultTo + interface LoDashStatic { + /** + * Checks `value` to determine whether a default value should be returned in + * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, + * or `undefined`. + * + * @param value The value to check. + * @param defaultValue The default value. + * @returns Returns the resolved value. + */ + defaultTo(value: T, defaultValue: T): T; + } + + interface LoDashImplicitWrapperBase { + /** + * @see _.defaultTo + */ + defaultTo(value: TResult): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitWrapperBase { + /** + * @see _.defaultTo + */ + defaultTo(value: TResult): LoDashExplicitObjectWrapper; + } + //_.identity interface LoDashStatic { /** @@ -21020,6 +21113,1835 @@ declare module "lodash" { export = _; } +/************************************************* + * * + * The lodash method _.XXX exported as a module. * + * * + *************************************************/ + + +declare module "lodash.after" { + const after: typeof _.after; + export = after; +} + + +declare module "lodash.ary" { + const ary: typeof _.ary; + export = ary; +} + + +declare module "lodash.assign" { + const assign: typeof _.assign; + export = assign; +} + + +declare module "lodash.assignIn" { + const assignIn: typeof _.assignIn; + export = assignIn; +} + + +declare module "lodash.assignInWith" { + const assignInWith: typeof _.assignInWith; + export = assignInWith; +} + + +declare module "lodash.assignWith" { + const assignWith: typeof _.assignWith; + export = assignWith; +} + + +declare module "lodash.at" { + const at: typeof _.at; + export = at; +} + + +declare module "lodash.before" { + const before: typeof _.before; + export = before; +} + + +declare module "lodash.bind" { + const bind: typeof _.bind; + export = bind; +} + + +declare module "lodash.bindAll" { + const bindAll: typeof _.bindAll; + export = bindAll; +} + + +declare module "lodash.bindKey" { + const bindKey: typeof _.bindKey; + export = bindKey; +} + + +declare module "lodash.castArray" { + const castArray: typeof _.castArray; + export = castArray; +} + + +declare module "lodash.chain" { + const chain: typeof _.chain; + export = chain; +} + + +declare module "lodash.chunk" { + const chunk: typeof _.chunk; + export = chunk; +} + + +declare module "lodash.compact" { + const compact: typeof _.compact; + export = compact; +} + + +declare module "lodash.concat" { + const concat: typeof _.concat; + export = concat; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.cond" { + const cond: typeof _.cond; + export = cond; +} +*/ + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.conforms" { + const conforms: typeof _.conforms; + export = conforms; +} +*/ + +declare module "lodash.constant" { + const constant: typeof _.constant; + export = constant; +} + + +declare module "lodash.countBy" { + const countBy: typeof _.countBy; + export = countBy; +} + + +declare module "lodash.create" { + const create: typeof _.create; + export = create; +} + + +declare module "lodash.curry" { + const curry: typeof _.curry; + export = curry; +} + + +declare module "lodash.curryRight" { + const curryRight: typeof _.curryRight; + export = curryRight; +} + + +declare module "lodash.debounce" { + const debounce: typeof _.debounce; + export = debounce; +} + + +declare module "lodash.defaults" { + const defaults: typeof _.defaults; + export = defaults; +} + + +declare module "lodash.defaultsDeep" { + const defaultsDeep: typeof _.defaultsDeep; + export = defaultsDeep; +} + + +declare module "lodash.defer" { + const defer: typeof _.defer; + export = defer; +} + + +declare module "lodash.delay" { + const delay: typeof _.delay; + export = delay; +} + + +declare module "lodash.difference" { + const difference: typeof _.difference; + export = difference; +} + + +declare module "lodash.differenceBy" { + const differenceBy: typeof _.differenceBy; + export = differenceBy; +} + + +declare module "lodash.differenceWith" { + const differenceWith: typeof _.differenceWith; + export = differenceWith; +} + + +declare module "lodash.drop" { + const drop: typeof _.drop; + export = drop; +} + + +declare module "lodash.dropRight" { + const dropRight: typeof _.dropRight; + export = dropRight; +} + + +declare module "lodash.dropRightWhile" { + const dropRightWhile: typeof _.dropRightWhile; + export = dropRightWhile; +} + + +declare module "lodash.dropWhile" { + const dropWhile: typeof _.dropWhile; + export = dropWhile; +} + + +declare module "lodash.fill" { + const fill: typeof _.fill; + export = fill; +} + + +declare module "lodash.filter" { + const filter: typeof _.filter; + export = filter; +} + + +declare module "lodash.flatMap" { + const flatMap: typeof _.flatMap; + export = flatMap; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.flatMapDeep" { + const flatMapDeep: typeof _.flatMapDeep; + export = flatMapDeep; +} +*/ +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.flatMapDepth" { + const flatMapDepth: typeof _.flatMapDepth; + export = flatMapDepth; +} +*/ + +declare module "lodash.flatten" { + const flatten: typeof _.flatten; + export = flatten; +} + + +declare module "lodash.flattenDeep" { + const flattenDeep: typeof _.flattenDeep; + export = flattenDeep; +} + +declare module "lodash.flattenDepth" { + const flattenDepth: typeof _.flattenDepth; + export = flattenDepth; +} + +declare module "lodash.flip" { + const flip: typeof _.flip; + export = flip; +} + + +declare module "lodash.flow" { + const flow: typeof _.flow; + export = flow; +} + + +declare module "lodash.flowRight" { + const flowRight: typeof _.flowRight; + export = flowRight; +} + + +declare module "lodash.fromPairs" { + const fromPairs: typeof _.fromPairs; + export = fromPairs; +} + + +declare module "lodash.functions" { + const functions: typeof _.functions; + export = functions; +} + + +declare module "lodash.functionsIn" { + const functionsIn: typeof _.functionsIn; + export = functionsIn; +} + + +declare module "lodash.groupBy" { + const groupBy: typeof _.groupBy; + export = groupBy; +} + + +declare module "lodash.initial" { + const initial: typeof _.initial; + export = initial; +} + + +declare module "lodash.intersection" { + const intersection: typeof _.intersection; + export = intersection; +} + + +declare module "lodash.intersectionBy" { + const intersectionBy: typeof _.intersectionBy; + export = intersectionBy; +} + + +declare module "lodash.intersectionWith" { + const intersectionWith: typeof _.intersectionWith; + export = intersectionWith; +} + + +declare module "lodash.invert" { + const invert: typeof _.invert; + export = invert; +} + + +declare module "lodash.invertBy" { + const invertBy: typeof _.invertBy; + export = invertBy; +} + + +declare module "lodash.invokeMap" { + const invokeMap: typeof _.invokeMap; + export = invokeMap; +} + + +declare module "lodash.iteratee" { + const iteratee: typeof _.iteratee; + export = iteratee; +} + + +declare module "lodash.keyBy" { + const keyBy: typeof _.keyBy; + export = keyBy; +} + + +declare module "lodash.keys" { + const keys: typeof _.keys; + export = keys; +} + + +declare module "lodash.keysIn" { + const keysIn: typeof _.keysIn; + export = keysIn; +} + + +declare module "lodash.map" { + const map: typeof _.map; + export = map; +} + + +declare module "lodash.mapKeys" { + const mapKeys: typeof _.mapKeys; + export = mapKeys; +} + + +declare module "lodash.mapValues" { + const mapValues: typeof _.mapValues; + export = mapValues; +} + + +declare module "lodash.matches" { + const matches: typeof _.matches; + export = matches; +} + + +declare module "lodash.matchesProperty" { + const matchesProperty: typeof _.matchesProperty; + export = matchesProperty; +} + + +declare module "lodash.memoize" { + const memoize: typeof _.memoize; + export = memoize; +} + + +declare module "lodash.merge" { + const merge: typeof _.merge; + export = merge; +} + + +declare module "lodash.mergeWith" { + const mergeWith: typeof _.mergeWith; + export = mergeWith; +} + + +declare module "lodash.method" { + const method: typeof _.method; + export = method; +} + + +declare module "lodash.methodOf" { + const methodOf: typeof _.methodOf; + export = methodOf; +} + + +declare module "lodash.mixin" { + const mixin: typeof _.mixin; + export = mixin; +} + + +declare module "lodash.negate" { + const negate: typeof _.negate; + export = negate; +} + + +declare module "lodash.nthArg" { + const nthArg: typeof _.nthArg; + export = nthArg; +} + + +declare module "lodash.omit" { + const omit: typeof _.omit; + export = omit; +} + + +declare module "lodash.omitBy" { + const omitBy: typeof _.omitBy; + export = omitBy; +} + + +declare module "lodash.once" { + const once: typeof _.once; + export = once; +} + + +declare module "lodash.orderBy" { + const orderBy: typeof _.orderBy; + export = orderBy; +} + + +declare module "lodash.over" { + const over: typeof _.over; + export = over; +} + + +declare module "lodash.overArgs" { + const overArgs: typeof _.overArgs; + export = overArgs; +} + + +declare module "lodash.overEvery" { + const overEvery: typeof _.overEvery; + export = overEvery; +} + + +declare module "lodash.overSome" { + const overSome: typeof _.overSome; + export = overSome; +} + + +declare module "lodash.partial" { + const partial: typeof _.partial; + export = partial; +} + + +declare module "lodash.partialRight" { + const partialRight: typeof _.partialRight; + export = partialRight; +} + + +declare module "lodash.partition" { + const partition: typeof _.partition; + export = partition; +} + + +declare module "lodash.pick" { + const pick: typeof _.pick; + export = pick; +} + + +declare module "lodash.pickBy" { + const pickBy: typeof _.pickBy; + export = pickBy; +} + + +declare module "lodash.property" { + const property: typeof _.property; + export = property; +} + + +declare module "lodash.propertyOf" { + const propertyOf: typeof _.propertyOf; + export = propertyOf; +} + + +declare module "lodash.pull" { + const pull: typeof _.pull; + export = pull; +} + + +declare module "lodash.pullAll" { + const pullAll: typeof _.pullAll; + export = pullAll; +} + + +declare module "lodash.pullAllBy" { + const pullAllBy: typeof _.pullAllBy; + export = pullAllBy; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.pullAllWith" { + const pullAllWith: typeof _.pullAllWith; + export = pullAllWith; +} +*/ + +declare module "lodash.pullAt" { + const pullAt: typeof _.pullAt; + export = pullAt; +} + + +declare module "lodash.range" { + const range: typeof _.range; + export = range; +} + + +declare module "lodash.rangeRight" { + const rangeRight: typeof _.rangeRight; + export = rangeRight; +} + + +declare module "lodash.rearg" { + const rearg: typeof _.rearg; + export = rearg; +} + + +declare module "lodash.reject" { + const reject: typeof _.reject; + export = reject; +} + + +declare module "lodash.remove" { + const remove: typeof _.remove; + export = remove; +} + + +declare module "lodash.rest" { + const rest: typeof _.rest; + export = rest; +} + + +declare module "lodash.reverse" { + const reverse: typeof _.reverse; + export = reverse; +} + + +declare module "lodash.sampleSize" { + const sampleSize: typeof _.sampleSize; + export = sampleSize; +} + + +declare module "lodash.set" { + const set: typeof _.set; + export = set; +} + + +declare module "lodash.setWith" { + const setWith: typeof _.setWith; + export = setWith; +} + + +declare module "lodash.shuffle" { + const shuffle: typeof _.shuffle; + export = shuffle; +} + + +declare module "lodash.slice" { + const slice: typeof _.slice; + export = slice; +} + + +declare module "lodash.sortBy" { + const sortBy: typeof _.sortBy; + export = sortBy; +} + + +declare module "lodash.sortedUniq" { + const sortedUniq: typeof _.sortedUniq; + export = sortedUniq; +} + + +declare module "lodash.sortedUniqBy" { + const sortedUniqBy: typeof _.sortedUniqBy; + export = sortedUniqBy; +} + + +declare module "lodash.split" { + const split: typeof _.split; + export = split; +} + + +declare module "lodash.spread" { + const spread: typeof _.spread; + export = spread; +} + + +declare module "lodash.tail" { + const tail: typeof _.tail; + export = tail; +} + + +declare module "lodash.take" { + const take: typeof _.take; + export = take; +} + + +declare module "lodash.takeRight" { + const takeRight: typeof _.takeRight; + export = takeRight; +} + + +declare module "lodash.takeRightWhile" { + const takeRightWhile: typeof _.takeRightWhile; + export = takeRightWhile; +} + + +declare module "lodash.takeWhile" { + const takeWhile: typeof _.takeWhile; + export = takeWhile; +} + + +declare module "lodash.tap" { + const tap: typeof _.tap; + export = tap; +} + + +declare module "lodash.throttle" { + const throttle: typeof _.throttle; + export = throttle; +} + + +declare module "lodash.thru" { + const thru: typeof _.thru; + export = thru; +} + + +declare module "lodash.toArray" { + const toArray: typeof _.toArray; + export = toArray; +} + + +declare module "lodash.toPairs" { + const toPairs: typeof _.toPairs; + export = toPairs; +} + + +declare module "lodash.toPairsIn" { + const toPairsIn: typeof _.toPairsIn; + export = toPairsIn; +} + + +declare module "lodash.toPath" { + const toPath: typeof _.toPath; + export = toPath; +} + + +declare module "lodash.toPlainObject" { + const toPlainObject: typeof _.toPlainObject; + export = toPlainObject; +} + + +declare module "lodash.transform" { + const transform: typeof _.transform; + export = transform; +} + + +declare module "lodash.unary" { + const unary: typeof _.unary; + export = unary; +} + + +declare module "lodash.union" { + const union: typeof _.union; + export = union; +} + + +declare module "lodash.unionBy" { + const unionBy: typeof _.unionBy; + export = unionBy; +} + + +declare module "lodash.unionWith" { + const unionWith: typeof _.unionWith; + export = unionWith; +} + + +declare module "lodash.uniq" { + const uniq: typeof _.uniq; + export = uniq; +} + + +declare module "lodash.uniqBy" { + const uniqBy: typeof _.uniqBy; + export = uniqBy; +} + + +declare module "lodash.uniqWith" { + const uniqWith: typeof _.uniqWith; + export = uniqWith; +} + + +declare module "lodash.unset" { + const unset: typeof _.unset; + export = unset; +} + + +declare module "lodash.unzip" { + const unzip: typeof _.unzip; + export = unzip; +} + + +declare module "lodash.unzipWith" { + const unzipWith: typeof _.unzipWith; + export = unzipWith; +} + + +declare module "lodash.update" { + const update: typeof _.update; + export = update; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.updateWith" { + const updateWith: typeof _.updateWith; + export = updateWith; +} +*/ + +declare module "lodash.values" { + const values: typeof _.values; + export = values; +} + + +declare module "lodash.valuesIn" { + const valuesIn: typeof _.valuesIn; + export = valuesIn; +} + + +declare module "lodash.without" { + const without: typeof _.without; + export = without; +} + + +declare module "lodash.words" { + const words: typeof _.words; + export = words; +} + + +declare module "lodash.wrap" { + const wrap: typeof _.wrap; + export = wrap; +} + + +declare module "lodash.xor" { + const xor: typeof _.xor; + export = xor; +} + + +declare module "lodash.xorBy" { + const xorBy: typeof _.xorBy; + export = xorBy; +} + + +declare module "lodash.xorWith" { + const xorWith: typeof _.xorWith; + export = xorWith; +} + + +declare module "lodash.zip" { + const zip: typeof _.zip; + export = zip; +} + + +declare module "lodash.zipObject" { + const zipObject: typeof _.zipObject; + export = zipObject; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.zipObjectDeep" { + const zipObjectDeep: typeof _.zipObjectDeep; + export = zipObjectDeep; +} +*/ + + +declare module "lodash.zipWith" { + const zipWith: typeof _.zipWith; + export = zipWith; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.entries" { + const entries: typeof _.entries; + export = entries; +} +*/ +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.entriesIn" { + const entriesIn: typeof _.entriesIn; + export = entriesIn; +} +*/ + + +declare module "lodash.extend" { + const extend: typeof _.extend; + export = extend; +} + + +declare module "lodash.extendWith" { + const extendWith: typeof _.extendWith; + export = extendWith; +} + + +declare module "lodash.add" { + const add: typeof _.add; + export = add; +} + + +declare module "lodash.attempt" { + const attempt: typeof _.attempt; + export = attempt; +} + + +declare module "lodash.camelCase" { + const camelCase: typeof _.camelCase; + export = camelCase; +} + + +declare module "lodash.capitalize" { + const capitalize: typeof _.capitalize; + export = capitalize; +} + + +declare module "lodash.ceil" { + const ceil: typeof _.ceil; + export = ceil; +} + + +declare module "lodash.clamp" { + const clamp: typeof _.clamp; + export = clamp; +} + + +declare module "lodash.clone" { + const clone: typeof _.clone; + export = clone; +} + + +declare module "lodash.cloneDeep" { + const cloneDeep: typeof _.cloneDeep; + export = cloneDeep; +} + + +declare module "lodash.cloneDeepWith" { + const cloneDeepWith: typeof _.cloneDeepWith; + export = cloneDeepWith; +} + + +declare module "lodash.cloneWith" { + const cloneWith: typeof _.cloneWith; + export = cloneWith; +} + + +declare module "lodash.deburr" { + const deburr: typeof _.deburr; + export = deburr; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.divide" { + const divide: typeof _.divide; + export = divide; +} +*/ + +declare module "lodash.endsWith" { + const endsWith: typeof _.endsWith; + export = endsWith; +} + + +declare module "lodash.eq" { + const eq: typeof _.eq; + export = eq; +} + + +declare module "lodash.escape" { + const escape: typeof _.escape; + export = escape; +} + + +declare module "lodash.escapeRegExp" { + const escapeRegExp: typeof _.escapeRegExp; + export = escapeRegExp; +} + + +declare module "lodash.every" { + const every: typeof _.every; + export = every; +} + + +declare module "lodash.find" { + const find: typeof _.find; + export = find; +} + + +declare module "lodash.findIndex" { + const findIndex: typeof _.findIndex; + export = findIndex; +} + + +declare module "lodash.findKey" { + const findKey: typeof _.findKey; + export = findKey; +} + + +declare module "lodash.findLast" { + const findLast: typeof _.findLast; + export = findLast; +} + + +declare module "lodash.findLastIndex" { + const findLastIndex: typeof _.findLastIndex; + export = findLastIndex; +} + + +declare module "lodash.findLastKey" { + const findLastKey: typeof _.findLastKey; + export = findLastKey; +} + + +declare module "lodash.floor" { + const floor: typeof _.floor; + export = floor; +} + + +declare module "lodash.forEach" { + const forEach: typeof _.forEach; + export = forEach; +} + + +declare module "lodash.forEachRight" { + const forEachRight: typeof _.forEachRight; + export = forEachRight; +} + + +declare module "lodash.forIn" { + const forIn: typeof _.forIn; + export = forIn; +} + + +declare module "lodash.forInRight" { + const forInRight: typeof _.forInRight; + export = forInRight; +} + + +declare module "lodash.forOwn" { + const forOwn: typeof _.forOwn; + export = forOwn; +} + + +declare module "lodash.forOwnRight" { + const forOwnRight: typeof _.forOwnRight; + export = forOwnRight; +} + + +declare module "lodash.get" { + const get: typeof _.get; + export = get; +} + + +declare module "lodash.gt" { + const gt: typeof _.gt; + export = gt; +} + + +declare module "lodash.gte" { + const gte: typeof _.gte; + export = gte; +} + + +declare module "lodash.has" { + const has: typeof _.has; + export = has; +} + + +declare module "lodash.hasIn" { + const hasIn: typeof _.hasIn; + export = hasIn; +} + + +declare module "lodash.head" { + const head: typeof _.head; + export = head; +} + + +declare module "lodash.identity" { + const identity: typeof _.identity; + export = identity; +} + + +declare module "lodash.includes" { + const includes: typeof _.includes; + export = includes; +} + + +declare module "lodash.indexOf" { + const indexOf: typeof _.indexOf; + export = indexOf; +} + + +declare module "lodash.inRange" { + const inRange: typeof _.inRange; + export = inRange; +} + + +declare module "lodash.invoke" { + const invoke: typeof _.invoke; + export = invoke; +} + + +declare module "lodash.isArguments" { + const isArguments: typeof _.isArguments; + export = isArguments; +} + + +declare module "lodash.isArray" { + const isArray: typeof _.isArray; + export = isArray; +} + + +declare module "lodash.isArrayBuffer" { + const isArrayBuffer: typeof _.isArrayBuffer; + export = isArrayBuffer; +} + + +declare module "lodash.isArrayLike" { + const isArrayLike: typeof _.isArrayLike; + export = isArrayLike; +} + + +declare module "lodash.isArrayLikeObject" { + const isArrayLikeObject: typeof _.isArrayLikeObject; + export = isArrayLikeObject; +} + + +declare module "lodash.isBoolean" { + const isBoolean: typeof _.isBoolean; + export = isBoolean; +} + + +declare module "lodash.isBuffer" { + const isBuffer: typeof _.isBuffer; + export = isBuffer; +} + + +declare module "lodash.isDate" { + const isDate: typeof _.isDate; + export = isDate; +} + + +declare module "lodash.isElement" { + const isElement: typeof _.isElement; + export = isElement; +} + + +declare module "lodash.isEmpty" { + const isEmpty: typeof _.isEmpty; + export = isEmpty; +} + + +declare module "lodash.isEqual" { + const isEqual: typeof _.isEqual; + export = isEqual; +} + + +declare module "lodash.isEqualWith" { + const isEqualWith: typeof _.isEqualWith; + export = isEqualWith; +} + + +declare module "lodash.isError" { + const isError: typeof _.isError; + export = isError; +} + + +declare module "lodash.isFinite" { + const isFinite: typeof _.isFinite; + export = isFinite; +} + + +declare module "lodash.isFunction" { + const isFunction: typeof _.isFunction; + export = isFunction; +} + + +declare module "lodash.isInteger" { + const isInteger: typeof _.isInteger; + export = isInteger; +} + + +declare module "lodash.isLength" { + const isLength: typeof _.isLength; + export = isLength; +} + + +declare module "lodash.isMap" { + const isMap: typeof _.isMap; + export = isMap; +} + + +declare module "lodash.isMatch" { + const isMatch: typeof _.isMatch; + export = isMatch; +} + + +declare module "lodash.isMatchWith" { + const isMatchWith: typeof _.isMatchWith; + export = isMatchWith; +} + + +declare module "lodash.isNaN" { + const isNaN: typeof _.isNaN; + export = isNaN; +} + + +declare module "lodash.isNative" { + const isNative: typeof _.isNative; + export = isNative; +} + + +declare module "lodash.isNil" { + const isNil: typeof _.isNil; + export = isNil; +} + + +declare module "lodash.isNull" { + const isNull: typeof _.isNull; + export = isNull; +} + + +declare module "lodash.isNumber" { + const isNumber: typeof _.isNumber; + export = isNumber; +} + + +declare module "lodash.isObject" { + const isObject: typeof _.isObject; + export = isObject; +} + + +declare module "lodash.isObjectLike" { + const isObjectLike: typeof _.isObjectLike; + export = isObjectLike; +} + + +declare module "lodash.isPlainObject" { + const isPlainObject: typeof _.isPlainObject; + export = isPlainObject; +} + + +declare module "lodash.isRegExp" { + const isRegExp: typeof _.isRegExp; + export = isRegExp; +} + + +declare module "lodash.isSafeInteger" { + const isSafeInteger: typeof _.isSafeInteger; + export = isSafeInteger; +} + + +declare module "lodash.isSet" { + const isSet: typeof _.isSet; + export = isSet; +} + + +declare module "lodash.isString" { + const isString: typeof _.isString; + export = isString; +} + + +declare module "lodash.isSymbol" { + const isSymbol: typeof _.isSymbol; + export = isSymbol; +} + + +declare module "lodash.isTypedArray" { + const isTypedArray: typeof _.isTypedArray; + export = isTypedArray; +} + + +declare module "lodash.isUndefined" { + const isUndefined: typeof _.isUndefined; + export = isUndefined; +} + + +declare module "lodash.isWeakMap" { + const isWeakMap: typeof _.isWeakMap; + export = isWeakMap; +} + + +declare module "lodash.isWeakSet" { + const isWeakSet: typeof _.isWeakSet; + export = isWeakSet; +} + + +declare module "lodash.join" { + const join: typeof _.join; + export = join; +} + + +declare module "lodash.kebabCase" { + const kebabCase: typeof _.kebabCase; + export = kebabCase; +} + + +declare module "lodash.last" { + const last: typeof _.last; + export = last; +} + + +declare module "lodash.lastIndexOf" { + const lastIndexOf: typeof _.lastIndexOf; + export = lastIndexOf; +} + + +declare module "lodash.lowerCase" { + const lowerCase: typeof _.lowerCase; + export = lowerCase; +} + + +declare module "lodash.lowerFirst" { + const lowerFirst: typeof _.lowerFirst; + export = lowerFirst; +} + + +declare module "lodash.lt" { + const lt: typeof _.lt; + export = lt; +} + + +declare module "lodash.lte" { + const lte: typeof _.lte; + export = lte; +} + + +declare module "lodash.max" { + const max: typeof _.max; + export = max; +} + + +declare module "lodash.maxBy" { + const maxBy: typeof _.maxBy; + export = maxBy; +} + + +declare module "lodash.mean" { + const mean: typeof _.mean; + export = mean; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.meanBy" { + const meanBy: typeof _.meanBy; + export = meanBy; +} +*/ + +declare module "lodash.min" { + const min: typeof _.min; + export = min; +} + + +declare module "lodash.minBy" { + const minBy: typeof _.minBy; + export = minBy; +} + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.multiply" { + const multiply: typeof _.multiply; + export = multiply; +} +*/ + +/** +* uncoment it if definition exists +*/ +/* +declare module "lodash.nth" { + const nth: typeof _.nth; + export = nth; +} +*/ + +declare module "lodash.noConflict" { + const noConflict: typeof _.noConflict; + export = noConflict; +} + + +declare module "lodash.noop" { + const noop: typeof _.noop; + export = noop; +} + + +declare module "lodash.now" { + const now: typeof _.now; + export = now; +} + + +declare module "lodash.pad" { + const pad: typeof _.pad; + export = pad; +} + + +declare module "lodash.padEnd" { + const padEnd: typeof _.padEnd; + export = padEnd; +} + + +declare module "lodash.padStart" { + const padStart: typeof _.padStart; + export = padStart; +} + + +declare module "lodash.parseInt" { + const parseInt: typeof _.parseInt; + export = parseInt; +} + + +declare module "lodash.random" { + const random: typeof _.random; + export = random; +} + + +declare module "lodash.reduce" { + const reduce: typeof _.reduce; + export = reduce; +} + + +declare module "lodash.reduceRight" { + const reduceRight: typeof _.reduceRight; + export = reduceRight; +} + + +declare module "lodash.repeat" { + const repeat: typeof _.repeat; + export = repeat; +} + + +declare module "lodash.replace" { + const replace: typeof _.replace; + export = replace; +} + + +declare module "lodash.result" { + const result: typeof _.result; + export = result; +} + + +declare module "lodash.round" { + const round: typeof _.round; + export = round; +} + + +declare module "lodash.runInContext" { + const runInContext: typeof _.runInContext; + export = runInContext; +} + + +declare module "lodash.sample" { + const sample: typeof _.sample; + export = sample; +} + + +declare module "lodash.size" { + const size: typeof _.size; + export = size; +} + + +declare module "lodash.snakeCase" { + const snakeCase: typeof _.snakeCase; + export = snakeCase; +} + + +declare module "lodash.some" { + const some: typeof _.some; + export = some; +} + + +declare module "lodash.sortedIndex" { + const sortedIndex: typeof _.sortedIndex; + export = sortedIndex; +} + + +declare module "lodash.sortedIndexBy" { + const sortedIndexBy: typeof _.sortedIndexBy; + export = sortedIndexBy; +} + + +declare module "lodash.sortedIndexOf" { + const sortedIndexOf: typeof _.sortedIndexOf; + export = sortedIndexOf; +} + + +declare module "lodash.sortedLastIndex" { + const sortedLastIndex: typeof _.sortedLastIndex; + export = sortedLastIndex; +} + + +declare module "lodash.sortedLastIndexBy" { + const sortedLastIndexBy: typeof _.sortedLastIndexBy; + export = sortedLastIndexBy; +} + + +declare module "lodash.sortedLastIndexOf" { + const sortedLastIndexOf: typeof _.sortedLastIndexOf; + export = sortedLastIndexOf; +} + + +declare module "lodash.startCase" { + const startCase: typeof _.startCase; + export = startCase; +} + + +declare module "lodash.startsWith" { + const startsWith: typeof _.startsWith; + export = startsWith; +} + + +declare module "lodash.subtract" { + const subtract: typeof _.subtract; + export = subtract; +} + + +declare module "lodash.sum" { + const sum: typeof _.sum; + export = sum; +} + + +declare module "lodash.sumBy" { + const sumBy: typeof _.sumBy; + export = sumBy; +} + + +declare module "lodash.template" { + const template: typeof _.template; + export = template; +} + + +declare module "lodash.times" { + const times: typeof _.times; + export = times; +} + + +declare module "lodash.toInteger" { + const toInteger: typeof _.toInteger; + export = toInteger; +} + + +declare module "lodash.toLength" { + const toLength: typeof _.toLength; + export = toLength; +} + + +declare module "lodash.toLower" { + const toLower: typeof _.toLower; + export = toLower; +} + + +declare module "lodash.toNumber" { + const toNumber: typeof _.toNumber; + export = toNumber; +} + + +declare module "lodash.toSafeInteger" { + const toSafeInteger: typeof _.toSafeInteger; + export = toSafeInteger; +} + + +declare module "lodash.toString" { + const toString: typeof _.toString; + export = toString; +} + + +declare module "lodash.toUpper" { + const toUpper: typeof _.toUpper; + export = toUpper; +} + + +declare module "lodash.trim" { + const trim: typeof _.trim; + export = trim; +} + + +declare module "lodash.trimEnd" { + const trimEnd: typeof _.trimEnd; + export = trimEnd; +} + + +declare module "lodash.trimStart" { + const trimStart: typeof _.trimStart; + export = trimStart; +} + + +declare module "lodash.truncate" { + const truncate: typeof _.truncate; + export = truncate; +} + + +declare module "lodash.unescape" { + const unescape: typeof _.unescape; + export = unescape; +} + + +declare module "lodash.uniqueId" { + const uniqueId: typeof _.uniqueId; + export = uniqueId; +} + + +declare module "lodash.upperCase" { + const upperCase: typeof _.upperCase; + export = upperCase; +} + + +declare module "lodash.upperFirst" { + const upperFirst: typeof _.upperFirst; + export = upperFirst; +} + + +declare module "lodash.each" { + const each: typeof _.each; + export = each; +} + + +declare module "lodash.eachRight" { + const eachRight: typeof _.eachRight; + export = eachRight; +} + + +declare module "lodash.first" { + const first: typeof _.first; + export = first; +} + // Backward compatibility with --target es5 interface Set {} interface Map {} diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 0e5c4a3d07..2c60fdb17d 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -141,6 +141,14 @@ result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3, 4]).splice(1); result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3, 4]).splice(1, 2, 5, 6); result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3, 4]).unshift(5, 6); +result = <_.LoDashExplicitObjectWrapper>_.chain([1, 2, 3, 4]).pop(); +result = <_.LoDashExplicitArrayWrapper>_.chain([1, 2, 3, 4]).push(5, 6, 7); +result = <_.LoDashExplicitObjectWrapper>_.chain([1, 2, 3, 4]).shift(); +result = <_.LoDashExplicitArrayWrapper>_.chain([1, 2, 3, 4]).sort((a, b) => 1); +result = <_.LoDashExplicitArrayWrapper>_.chain([1, 2, 3, 4]).splice(1); +result = <_.LoDashExplicitArrayWrapper>_.chain([1, 2, 3, 4]).splice(1, 2, 5, 6); +result = <_.LoDashExplicitArrayWrapper>_.chain([1, 2, 3, 4]).unshift(5, 6); + /********* * Array * *********/ @@ -673,6 +681,7 @@ namespace TestFindIndex { let array: TResult[]; let list: _.List; let predicateFn: (value: TResult, index?: number, collection?: _.List) => boolean; + let fromIndex: number; { let result: number; @@ -681,21 +690,25 @@ namespace TestFindIndex { result = _.findIndex(array, predicateFn); result = _.findIndex(array, ''); result = _.findIndex<{a: number}, TResult>(array, {a: 42}); + result = _.findIndex(array, predicateFn, fromIndex); result = _.findIndex(list); result = _.findIndex(list, predicateFn); result = _.findIndex(list, ''); result = _.findIndex<{a: number}, TResult>(list, {a: 42}); + result = _.findIndex(list, predicateFn, fromIndex); result = _(array).findIndex(); result = _(array).findIndex(predicateFn); result = _(array).findIndex(''); result = _(array).findIndex<{a: number}>({a: 42}); + result = _(array).findIndex(predicateFn, fromIndex); result = _(list).findIndex(); result = _(list).findIndex(predicateFn); result = _(list).findIndex(''); result = _(list).findIndex<{a: number}>({a: 42}); + result = _(list).findIndex(predicateFn, fromIndex); } { @@ -705,11 +718,13 @@ namespace TestFindIndex { result = _(array).chain().findIndex(predicateFn); result = _(array).chain().findIndex(''); result = _(array).chain().findIndex<{a: number}>({a: 42}); + result = _(array).chain().findIndex(predicateFn, fromIndex); result = _(list).chain().findIndex(); result = _(list).chain().findIndex(predicateFn); result = _(list).chain().findIndex(''); result = _(list).chain().findIndex<{a: number}>({a: 42}); + result = _(list).chain().findIndex(predicateFn, fromIndex); } } @@ -719,6 +734,7 @@ namespace TestFindLastIndex { let list: _.List; let predicateFn: (value: TResult, index?: number, collection?: _.List) => boolean; + let fromIndex: number; { let result: number; @@ -727,21 +743,25 @@ namespace TestFindLastIndex { result = _.findLastIndex(array, predicateFn); result = _.findLastIndex(array, ''); result = _.findLastIndex<{a: number}, TResult>(array, {a: 42}); + result = _.findLastIndex(array, predicateFn, fromIndex); result = _.findLastIndex(list); result = _.findLastIndex(list, predicateFn); result = _.findLastIndex(list, ''); result = _.findLastIndex<{a: number}, TResult>(list, {a: 42}); + result = _.findLastIndex(list, predicateFn, fromIndex); result = _(array).findLastIndex(); result = _(array).findLastIndex(predicateFn); result = _(array).findLastIndex(''); result = _(array).findLastIndex<{a: number}>({a: 42}); + result = _(array).findLastIndex(predicateFn, fromIndex); result = _(list).findLastIndex(); result = _(list).findLastIndex(predicateFn); result = _(list).findLastIndex(''); result = _(list).findLastIndex<{a: number}>({a: 42}); + result = _(list).findLastIndex(predicateFn, fromIndex); } { @@ -751,11 +771,13 @@ namespace TestFindLastIndex { result = _(array).chain().findLastIndex(predicateFn); result = _(array).chain().findLastIndex(''); result = _(array).chain().findLastIndex<{a: number}>({a: 42}); + result = _(array).chain().findLastIndex(predicateFn, fromIndex); result = _(list).chain().findLastIndex(); result = _(list).chain().findLastIndex(predicateFn); result = _(list).chain().findLastIndex(''); result = _(list).chain().findLastIndex<{a: number}>({a: 42}); + result = _(list).chain().findLastIndex(predicateFn, fromIndex); } } @@ -3727,12 +3749,16 @@ result = _.findLast([1, 2, 3, 4], function (num) { result = _.findLast(foodsCombined, { 'type': 'vegetable' }); result = _.findLast(foodsCombined, 'organic'); +result = _.findLast(foodsCombined, 'organic', 1); + result = _([1, 2, 3, 4]).findLast(function (num) { return num % 2 == 0; }); result = _(foodsCombined).findLast({ 'type': 'vegetable' }); result = _(foodsCombined).findLast('organic'); +result = _(foodsCombined).findLast('organic', 1); + // _.flatMap namespace TestFlatMap { let numArray: (number|number[])[] = [1, [2, 3]]; @@ -5864,12 +5890,18 @@ namespace TestMemoize { result = _(memoizeFn).chain().memoize(memoizeResolverFn); } - _.memoize.Cache = { - delete: key => false, - get: key => undefined, - has: key => false, - set(key, value) { return this; } - }; + interface MemoizeCache { + delete(key: K): boolean; + get(key: K): V; + has(key: K): boolean; + set(key: K, value: V): this; + } + interface MemoizeCacheConstructor { + new (): MemoizeCache; + } + let MemoizeCache: MemoizeCacheConstructor + + _.memoize.Cache = MemoizeCache; } // _.overArgs @@ -11097,6 +11129,125 @@ namespace TestConstant { } } +// _.defaultTo +namespace TestDefaultTo { + { + let result: number; + result = _.defaultTo(42, 42); + result = _.defaultTo(undefined, 42); + result = _.defaultTo(null, 42); + result = _.defaultTo(NaN, 42); + } + + { + let result: string; + result = _.defaultTo('a', 'default'); + result = _.defaultTo(undefined, 'default'); + result = _.defaultTo(null, 'default'); + } + + { + let result: boolean; + result = _.defaultTo(true, true); + result = _.defaultTo(undefined, true); + result = _.defaultTo(null, true); + } + + { + let result: string[]; + result = _.defaultTo(['a'], ['default']); + result = _.defaultTo(undefined, ['default']); + result = _.defaultTo(null, ['default']); + } + + { + let result: {a: string}; + result = _.defaultTo<{a: string}>({a: 'a'}, {a: 'a'}); + result = _.defaultTo<{a: string}>(undefined, {a: 'a'}); + result = _.defaultTo<{a: string}>(null, {a: 'a'}); + } + + { + let result: _.LoDashImplicitObjectWrapper; + result = _(42).defaultTo(42); + result = _(undefined).defaultTo(42); + result = _(null).defaultTo(42); + result = _(NaN).defaultTo(42); + } + + { + let result: _.LoDashImplicitObjectWrapper; + result = _('a').defaultTo('default'); + result = _(null).defaultTo('default'); + result = _(NaN).defaultTo('default'); + } + + { + let result: _.LoDashImplicitObjectWrapper; + result = _(true).defaultTo(true); + result = _(undefined).defaultTo(true); + result = _(null).defaultTo(true); + result = _(NaN).defaultTo(true); + } + + { + let result: _.LoDashImplicitObjectWrapper; + result = _(['a']).defaultTo(['default']); + result = _(undefined).defaultTo(['default']); + result = _(null).defaultTo(['default']); + result = _(NaN).defaultTo(['default']); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: string }>; + result = _({ a: 'a' }).defaultTo({a : 'a'}); + result = _(undefined).defaultTo({a : 'a'}); + result = _(null).defaultTo({a : 'a'}); + result = _(NaN).defaultTo({a : 'a'}); + } + + { + let result: _.LoDashExplicitObjectWrapper; + result = _(42).chain().defaultTo(42); + result = _(undefined).chain().defaultTo(42); + result = _(null).chain().defaultTo(42); + result = _(NaN).chain().defaultTo(42); + } + + { + let result: _.LoDashExplicitObjectWrapper; + result = _('a').chain().defaultTo('default'); + result = _(undefined).chain().defaultTo('default'); + result = _(null).chain().defaultTo('default'); + result = _(NaN).chain().defaultTo('default'); + } + + { + let result: _.LoDashExplicitObjectWrapper; + result = _(true).chain().defaultTo(true); + result = _(undefined).chain().defaultTo(true); + result = _(null).chain().defaultTo(true); + result = _(NaN).chain().defaultTo(true); + } + + { + let result: _.LoDashExplicitObjectWrapper; + result = _(['a']).chain().defaultTo(['default']); + result = _(undefined).chain().defaultTo(['default']); + result = _(null).chain().defaultTo(['default']); + result = _(NaN).chain().defaultTo(['default']); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: string }>; + result = _({ a: 'a' }).chain().defaultTo({a : 'a'}); + result = _(undefined).chain().defaultTo({a : 'a'}); + result = _(null).chain().defaultTo({a : 'a'}); + result = _(NaN).chain().defaultTo({a : 'a'}); + } + +} + // _.identity namespace TestIdentity { { @@ -11893,3 +12044,578 @@ result = <_.TemplateSettings>_.templateSettings; res1___ = _.partialRight(func4, "foo", true, 100); res____ = _.partialRight(func4, 42, "foo", true, 100); } + +/*************************** + * method_modules_tests * + ***************************/ + +import afterFunc = require("lodash.after"); +import aryFunc = require("lodash.ary"); +import assignFunc = require("lodash.assign"); +import assignInFunc = require("lodash.assignIn"); +import assignInWithFunc = require("lodash.assignInWith"); +import assignWithFunc = require("lodash.assignWith"); +import atFunc = require("lodash.at"); +import beforeFunc = require("lodash.before"); +import bindFunc = require("lodash.bind"); +import bindAllFunc = require("lodash.bindAll"); +import bindKeyFunc = require("lodash.bindKey"); +import castArrayFunc = require("lodash.castArray"); +import chainFunc = require("lodash.chain"); +import chunkFunc = require("lodash.chunk"); +import compactFunc = require("lodash.compact"); +import concatFunc = require("lodash.concat"); +import constantFunc = require("lodash.constant"); +import countByFunc = require("lodash.countBy"); +import createFunc = require("lodash.create"); +import curryFunc = require("lodash.curry"); +import curryRightFunc = require("lodash.curryRight"); +import debounceFunc = require("lodash.debounce"); +import defaultsFunc = require("lodash.defaults"); +import defaultsDeepFunc = require("lodash.defaultsDeep"); +import deferFunc = require("lodash.defer"); +import delayFunc = require("lodash.delay"); +import differenceFunc = require("lodash.difference"); +import differenceByFunc = require("lodash.differenceBy"); +import differenceWithFunc = require("lodash.differenceWith"); +import dropFunc = require("lodash.drop"); +import dropRightFunc = require("lodash.dropRight"); +import dropRightWhileFunc = require("lodash.dropRightWhile"); +import dropWhileFunc = require("lodash.dropWhile"); +import fillFunc = require("lodash.fill"); +import filterFunc = require("lodash.filter"); +import flatMapFunc = require("lodash.flatMap"); +import flattenFunc = require("lodash.flatten"); +import flattenDeepFunc = require("lodash.flattenDeep"); +import flattenDepthFunc = require("lodash.flattenDepth"); +import flipFunc = require("lodash.flip"); +import flowFunc = require("lodash.flow"); +import flowRightFunc = require("lodash.flowRight"); +import fromPairsFunc = require("lodash.fromPairs"); +import functionsFunc = require("lodash.functions"); +import functionsInFunc = require("lodash.functionsIn"); +import groupByFunc = require("lodash.groupBy"); +import initialFunc = require("lodash.initial"); +import intersectionFunc = require("lodash.intersection"); +import intersectionByFunc = require("lodash.intersectionBy"); +import intersectionWithFunc = require("lodash.intersectionWith"); +import invertFunc = require("lodash.invert"); +import invertByFunc = require("lodash.invertBy"); +import invokeMapFunc = require("lodash.invokeMap"); +import iterateeFunc = require("lodash.iteratee"); +import keyByFunc = require("lodash.keyBy"); +import keysFunc = require("lodash.keys"); +import keysInFunc = require("lodash.keysIn"); +import mapFunc = require("lodash.map"); +import mapKeysFunc = require("lodash.mapKeys"); +import mapValuesFunc = require("lodash.mapValues"); +import matchesFunc = require("lodash.matches"); +import matchesPropertyFunc = require("lodash.matchesProperty"); +import memoizeFunc = require("lodash.memoize"); +import mergeFunc = require("lodash.merge"); +import mergeWithFunc = require("lodash.mergeWith"); +import methodFunc = require("lodash.method"); +import methodOfFunc = require("lodash.methodOf"); +import mixinFunc = require("lodash.mixin"); +import negateFunc = require("lodash.negate"); +import nthArgFunc = require("lodash.nthArg"); +import omitFunc = require("lodash.omit"); +import omitByFunc = require("lodash.omitBy"); +import onceFunc = require("lodash.once"); +import orderByFunc = require("lodash.orderBy"); +import overFunc = require("lodash.over"); +import overArgsFunc = require("lodash.overArgs"); +import overEveryFunc = require("lodash.overEvery"); +import overSomeFunc = require("lodash.overSome"); +import partialFunc = require("lodash.partial"); +import partialRightFunc = require("lodash.partialRight"); +import partitionFunc = require("lodash.partition"); +import pickFunc = require("lodash.pick"); +import pickByFunc = require("lodash.pickBy"); +import propertyFunc = require("lodash.property"); +import propertyOfFunc = require("lodash.propertyOf"); +import pullFunc = require("lodash.pull"); +import pullAllFunc = require("lodash.pullAll"); +import pullAllByFunc = require("lodash.pullAllBy"); +import pullAtFunc = require("lodash.pullAt"); +import rangeFunc = require("lodash.range"); +import rangeRightFunc = require("lodash.rangeRight"); +import reargFunc = require("lodash.rearg"); +import rejectFunc = require("lodash.reject"); +import removeFunc = require("lodash.remove"); +import restFunc = require("lodash.rest"); +import reverseFunc = require("lodash.reverse"); +import sampleSizeFunc = require("lodash.sampleSize"); +import setFunc = require("lodash.set"); +import setWithFunc = require("lodash.setWith"); +import shuffleFunc = require("lodash.shuffle"); +import sliceFunc = require("lodash.slice"); +import sortByFunc = require("lodash.sortBy"); +import sortedUniqFunc = require("lodash.sortedUniq"); +import sortedUniqByFunc = require("lodash.sortedUniqBy"); +import splitFunc = require("lodash.split"); +import spreadFunc = require("lodash.spread"); +import tailFunc = require("lodash.tail"); +import takeFunc = require("lodash.take"); +import takeRightFunc = require("lodash.takeRight"); +import takeRightWhileFunc = require("lodash.takeRightWhile"); +import takeWhileFunc = require("lodash.takeWhile"); +import tapFunc = require("lodash.tap"); +import throttleFunc = require("lodash.throttle"); +import thruFunc = require("lodash.thru"); +import toArrayFunc = require("lodash.toArray"); +import toPairsFunc = require("lodash.toPairs"); +import toPairsInFunc = require("lodash.toPairsIn"); +import toPathFunc = require("lodash.toPath"); +import toPlainObjectFunc = require("lodash.toPlainObject"); +import transformFunc = require("lodash.transform"); +import unaryFunc = require("lodash.unary"); +import unionFunc = require("lodash.union"); +import unionByFunc = require("lodash.unionBy"); +import unionWithFunc = require("lodash.unionWith"); +import uniqFunc = require("lodash.uniq"); +import uniqByFunc = require("lodash.uniqBy"); +import uniqWithFunc = require("lodash.uniqWith"); +import unsetFunc = require("lodash.unset"); +import unzipFunc = require("lodash.unzip"); +import unzipWithFunc = require("lodash.unzipWith"); +import updateFunc = require("lodash.update"); +import valuesFunc = require("lodash.values"); +import valuesInFunc = require("lodash.valuesIn"); +import withoutFunc = require("lodash.without"); +import wordsFunc = require("lodash.words"); +import wrapFunc = require("lodash.wrap"); +import xorFunc = require("lodash.xor"); +import xorByFunc = require("lodash.xorBy"); +import xorWithFunc = require("lodash.xorWith"); +import zipFunc = require("lodash.zip"); +import zipObjectFunc = require("lodash.zipObject"); +import zipWithFunc = require("lodash.zipWith"); +import extendFunc = require("lodash.extend"); +import extendWithFunc = require("lodash.extendWith"); +import addFunc = require("lodash.add"); +import attemptFunc = require("lodash.attempt"); +import camelCaseFunc = require("lodash.camelCase"); +import capitalizeFunc = require("lodash.capitalize"); +import ceilFunc = require("lodash.ceil"); +import clampFunc = require("lodash.clamp"); +import cloneFunc = require("lodash.clone"); +import cloneDeepFunc = require("lodash.cloneDeep"); +import cloneDeepWithFunc = require("lodash.cloneDeepWith"); +import cloneWithFunc = require("lodash.cloneWith"); +import deburrFunc = require("lodash.deburr"); +import endsWithFunc = require("lodash.endsWith"); +import eqFunc = require("lodash.eq"); +import escapeFunc = require("lodash.escape"); +import escapeRegExpFunc = require("lodash.escapeRegExp"); +import everyFunc = require("lodash.every"); +import findFunc = require("lodash.find"); +import findIndexFunc = require("lodash.findIndex"); +import findKeyFunc = require("lodash.findKey"); +import findLastFunc = require("lodash.findLast"); +import findLastIndexFunc = require("lodash.findLastIndex"); +import findLastKeyFunc = require("lodash.findLastKey"); +import floorFunc = require("lodash.floor"); +import forEachFunc = require("lodash.forEach"); +import forEachRightFunc = require("lodash.forEachRight"); +import forInFunc = require("lodash.forIn"); +import forInRightFunc = require("lodash.forInRight"); +import forOwnFunc = require("lodash.forOwn"); +import forOwnRightFunc = require("lodash.forOwnRight"); +import getFunc = require("lodash.get"); +import gtFunc = require("lodash.gt"); +import gteFunc = require("lodash.gte"); +import hasFunc = require("lodash.has"); +import hasInFunc = require("lodash.hasIn"); +import headFunc = require("lodash.head"); +import identityFunc = require("lodash.identity"); +import includesFunc = require("lodash.includes"); +import indexOfFunc = require("lodash.indexOf"); +import inRangeFunc = require("lodash.inRange"); +import invokeFunc = require("lodash.invoke"); +import isArgumentsFunc = require("lodash.isArguments"); +import isArrayFunc = require("lodash.isArray"); +import isArrayBufferFunc = require("lodash.isArrayBuffer"); +import isArrayLikeFunc = require("lodash.isArrayLike"); +import isArrayLikeObjectFunc = require("lodash.isArrayLikeObject"); +import isBooleanFunc = require("lodash.isBoolean"); +import isBufferFunc = require("lodash.isBuffer"); +import isDateFunc = require("lodash.isDate"); +import isElementFunc = require("lodash.isElement"); +import isEmptyFunc = require("lodash.isEmpty"); +import isEqualFunc = require("lodash.isEqual"); +import isEqualWithFunc = require("lodash.isEqualWith"); +import isErrorFunc = require("lodash.isError"); +import isFiniteFunc = require("lodash.isFinite"); +import isFunctionFunc = require("lodash.isFunction"); +import isIntegerFunc = require("lodash.isInteger"); +import isLengthFunc = require("lodash.isLength"); +import isMapFunc = require("lodash.isMap"); +import isMatchFunc = require("lodash.isMatch"); +import isMatchWithFunc = require("lodash.isMatchWith"); +import isNaNFunc = require("lodash.isNaN"); +import isNativeFunc = require("lodash.isNative"); +import isNilFunc = require("lodash.isNil"); +import isNullFunc = require("lodash.isNull"); +import isNumberFunc = require("lodash.isNumber"); +import isObjectFunc = require("lodash.isObject"); +import isObjectLikeFunc = require("lodash.isObjectLike"); +import isPlainObjectFunc = require("lodash.isPlainObject"); +import isRegExpFunc = require("lodash.isRegExp"); +import isSafeIntegerFunc = require("lodash.isSafeInteger"); +import isSetFunc = require("lodash.isSet"); +import isStringFunc = require("lodash.isString"); +import isSymbolFunc = require("lodash.isSymbol"); +import isTypedArrayFunc = require("lodash.isTypedArray"); +import isUndefinedFunc = require("lodash.isUndefined"); +import isWeakMapFunc = require("lodash.isWeakMap"); +import isWeakSetFunc = require("lodash.isWeakSet"); +import joinFunc = require("lodash.join"); +import kebabCaseFunc = require("lodash.kebabCase"); +import lastFunc = require("lodash.last"); +import lastIndexOfFunc = require("lodash.lastIndexOf"); +import lowerCaseFunc = require("lodash.lowerCase"); +import lowerFirstFunc = require("lodash.lowerFirst"); +import ltFunc = require("lodash.lt"); +import lteFunc = require("lodash.lte"); +import maxFunc = require("lodash.max"); +import maxByFunc = require("lodash.maxBy"); +import meanFunc = require("lodash.mean"); +import minFunc = require("lodash.min"); +import minByFunc = require("lodash.minBy"); +import noConflictFunc = require("lodash.noConflict"); +import noopFunc = require("lodash.noop"); +import nowFunc = require("lodash.now"); +import padFunc = require("lodash.pad"); +import padEndFunc = require("lodash.padEnd"); +import padStartFunc = require("lodash.padStart"); +import parseIntFunc = require("lodash.parseInt"); +import randomFunc = require("lodash.random"); +import reduceFunc = require("lodash.reduce"); +import reduceRightFunc = require("lodash.reduceRight"); +import repeatFunc = require("lodash.repeat"); +import replaceFunc = require("lodash.replace"); +import resultFunc = require("lodash.result"); +import roundFunc = require("lodash.round"); +import runInContextFunc = require("lodash.runInContext"); +import sampleFunc = require("lodash.sample"); +import sizeFunc = require("lodash.size"); +import snakeCaseFunc = require("lodash.snakeCase"); +import someFunc = require("lodash.some"); +import sortedIndexFunc = require("lodash.sortedIndex"); +import sortedIndexByFunc = require("lodash.sortedIndexBy"); +import sortedIndexOfFunc = require("lodash.sortedIndexOf"); +import sortedLastIndexFunc = require("lodash.sortedLastIndex"); +import sortedLastIndexByFunc = require("lodash.sortedLastIndexBy"); +import sortedLastIndexOfFunc = require("lodash.sortedLastIndexOf"); +import startCaseFunc = require("lodash.startCase"); +import startsWithFunc = require("lodash.startsWith"); +import subtractFunc = require("lodash.subtract"); +import sumFunc = require("lodash.sum"); +import sumByFunc = require("lodash.sumBy"); +import templateFunc = require("lodash.template"); +import timesFunc = require("lodash.times"); +import toIntegerFunc = require("lodash.toInteger"); +import toLengthFunc = require("lodash.toLength"); +import toLowerFunc = require("lodash.toLower"); +import toNumberFunc = require("lodash.toNumber"); +import toSafeIntegerFunc = require("lodash.toSafeInteger"); +import toStringFunc = require("lodash.toString"); +import toUpperFunc = require("lodash.toUpper"); +import trimFunc = require("lodash.trim"); +import trimEndFunc = require("lodash.trimEnd"); +import trimStartFunc = require("lodash.trimStart"); +import truncateFunc = require("lodash.truncate"); +import unescapeFunc = require("lodash.unescape"); +import uniqueIdFunc = require("lodash.uniqueId"); +import upperCaseFunc = require("lodash.upperCase"); +import upperFirstFunc = require("lodash.upperFirst"); +import eachFunc = require("lodash.each"); +import eachRightFunc = require("lodash.eachRight"); +import firstFunc = require("lodash.first"); +namespace method_modules_tests { + _.after = afterFunc; + _.ary = aryFunc; + _.assign = assignFunc; + _.assignIn = assignInFunc; + _.assignInWith = assignInWithFunc; + _.assignWith = assignWithFunc; + _.at = atFunc; + _.before = beforeFunc; + _.bind = bindFunc; + _.bindAll = bindAllFunc; + _.bindKey = bindKeyFunc; + _.castArray = castArrayFunc; + _.chain = chainFunc; + _.chunk = chunkFunc; + _.compact = compactFunc; + _.concat = concatFunc; + _.constant = constantFunc; + _.countBy = countByFunc; + _.create = createFunc; + _.curry = curryFunc; + _.curryRight = curryRightFunc; + _.debounce = debounceFunc; + _.defaults = defaultsFunc; + _.defaultsDeep = defaultsDeepFunc; + _.defer = deferFunc; + _.delay = delayFunc; + _.difference = differenceFunc; + _.differenceBy = differenceByFunc; + _.differenceWith = differenceWithFunc; + _.drop = dropFunc; + _.dropRight = dropRightFunc; + _.dropRightWhile = dropRightWhileFunc; + _.dropWhile = dropWhileFunc; + _.fill = fillFunc; + _.filter = filterFunc; + _.flatMap = flatMapFunc; + _.flatten = flattenFunc; + _.flattenDeep = flattenDeepFunc; + _.flattenDepth = flattenDepthFunc; + _.flip = flipFunc; + _.flow = flowFunc; + _.flowRight = flowRightFunc; + _.fromPairs = fromPairsFunc; + _.functions = functionsFunc; + _.functionsIn = functionsInFunc; + _.groupBy = groupByFunc; + _.initial = initialFunc; + _.intersection = intersectionFunc; + _.intersectionBy = intersectionByFunc; + _.intersectionWith = intersectionWithFunc; + _.invert = invertFunc; + _.invertBy = invertByFunc; + _.invokeMap = invokeMapFunc; + _.iteratee = iterateeFunc; + _.keyBy = keyByFunc; + _.keys = keysFunc; + _.keysIn = keysInFunc; + _.map = mapFunc; + _.mapKeys = mapKeysFunc; + _.mapValues = mapValuesFunc; + _.matches = matchesFunc; + _.matchesProperty = matchesPropertyFunc; + _.memoize = memoizeFunc; + _.merge = mergeFunc; + _.mergeWith = mergeWithFunc; + _.method = methodFunc; + _.methodOf = methodOfFunc; + _.mixin = mixinFunc; + _.negate = negateFunc; + _.nthArg = nthArgFunc; + _.omit = omitFunc; + _.omitBy = omitByFunc; + _.once = onceFunc; + _.orderBy = orderByFunc; + _.over = overFunc; + _.overArgs = overArgsFunc; + _.overEvery = overEveryFunc; + _.overSome = overSomeFunc; + _.partial = partialFunc; + _.partialRight = partialRightFunc; + _.partition = partitionFunc; + _.pick = pickFunc; + _.pickBy = pickByFunc; + _.property = propertyFunc; + _.propertyOf = propertyOfFunc; + _.pull = pullFunc; + _.pullAll = pullAllFunc; + _.pullAllBy = pullAllByFunc; + _.pullAt = pullAtFunc; + _.range = rangeFunc; + _.rangeRight = rangeRightFunc; + _.rearg = reargFunc; + _.reject = rejectFunc; + _.remove = removeFunc; + _.rest = restFunc; + _.reverse = reverseFunc; + _.sampleSize = sampleSizeFunc; + _.set = setFunc; + _.setWith = setWithFunc; + _.shuffle = shuffleFunc; + _.slice = sliceFunc; + _.sortBy = sortByFunc; + _.sortedUniq = sortedUniqFunc; + _.sortedUniqBy = sortedUniqByFunc; + _.split = splitFunc; + _.spread = spreadFunc; + _.tail = tailFunc; + _.take = takeFunc; + _.takeRight = takeRightFunc; + _.takeRightWhile = takeRightWhileFunc; + _.takeWhile = takeWhileFunc; + _.tap = tapFunc; + _.throttle = throttleFunc; + _.thru = thruFunc; + _.toArray = toArrayFunc; + _.toPairs = toPairsFunc; + _.toPairsIn = toPairsInFunc; + _.toPath = toPathFunc; + _.toPlainObject = toPlainObjectFunc; + _.transform = transformFunc; + _.unary = unaryFunc; + _.union = unionFunc; + _.unionBy = unionByFunc; + _.unionWith = unionWithFunc; + _.uniq = uniqFunc; + _.uniqBy = uniqByFunc; + _.uniqWith = uniqWithFunc; + _.unset = unsetFunc; + _.unzip = unzipFunc; + _.unzipWith = unzipWithFunc; + _.update = updateFunc; + _.values = valuesFunc; + _.valuesIn = valuesInFunc; + _.without = withoutFunc; + _.words = wordsFunc; + _.wrap = wrapFunc; + _.xor = xorFunc; + _.xorBy = xorByFunc; + _.xorWith = xorWithFunc; + _.zip = zipFunc; + _.zipObject = zipObjectFunc; + _.zipWith = zipWithFunc; + _.extend = extendFunc; + _.extendWith = extendWithFunc; + _.add = addFunc; + _.attempt = attemptFunc; + _.camelCase = camelCaseFunc; + _.capitalize = capitalizeFunc; + _.ceil = ceilFunc; + _.clamp = clampFunc; + _.clone = cloneFunc; + _.cloneDeep = cloneDeepFunc; + _.cloneDeepWith = cloneDeepWithFunc; + _.cloneWith = cloneWithFunc; + _.deburr = deburrFunc; + _.endsWith = endsWithFunc; + _.eq = eqFunc; + _.escape = escapeFunc; + _.escapeRegExp = escapeRegExpFunc; + _.every = everyFunc; + _.find = findFunc; + _.findIndex = findIndexFunc; + _.findKey = findKeyFunc; + _.findLast = findLastFunc; + _.findLastIndex = findLastIndexFunc; + _.findLastKey = findLastKeyFunc; + _.floor = floorFunc; + _.forEach = forEachFunc; + _.forEachRight = forEachRightFunc; + _.forIn = forInFunc; + _.forInRight = forInRightFunc; + _.forOwn = forOwnFunc; + _.forOwnRight = forOwnRightFunc; + _.get = getFunc; + _.gt = gtFunc; + _.gte = gteFunc; + _.has = hasFunc; + _.hasIn = hasInFunc; + _.head = headFunc; + _.identity = identityFunc; + _.includes = includesFunc; + _.indexOf = indexOfFunc; + _.inRange = inRangeFunc; + _.invoke = invokeFunc; + _.isArguments = isArgumentsFunc; + _.isArray = isArrayFunc; + _.isArrayBuffer = isArrayBufferFunc; + _.isArrayLike = isArrayLikeFunc; + _.isArrayLikeObject = isArrayLikeObjectFunc; + _.isBoolean = isBooleanFunc; + _.isBuffer = isBufferFunc; + _.isDate = isDateFunc; + _.isElement = isElementFunc; + _.isEmpty = isEmptyFunc; + _.isEqual = isEqualFunc; + _.isEqualWith = isEqualWithFunc; + _.isError = isErrorFunc; + _.isFinite = isFiniteFunc; + _.isFunction = isFunctionFunc; + _.isInteger = isIntegerFunc; + _.isLength = isLengthFunc; + _.isMap = isMapFunc; + _.isMatch = isMatchFunc; + _.isMatchWith = isMatchWithFunc; + _.isNaN = isNaNFunc; + _.isNative = isNativeFunc; + _.isNil = isNilFunc; + _.isNull = isNullFunc; + _.isNumber = isNumberFunc; + _.isObject = isObjectFunc; + _.isObjectLike = isObjectLikeFunc; + _.isPlainObject = isPlainObjectFunc; + _.isRegExp = isRegExpFunc; + _.isSafeInteger = isSafeIntegerFunc; + _.isSet = isSetFunc; + _.isString = isStringFunc; + _.isSymbol = isSymbolFunc; + _.isTypedArray = isTypedArrayFunc; + _.isUndefined = isUndefinedFunc; + _.isWeakMap = isWeakMapFunc; + _.isWeakSet = isWeakSetFunc; + _.join = joinFunc; + _.kebabCase = kebabCaseFunc; + _.last = lastFunc; + _.lastIndexOf = lastIndexOfFunc; + _.lowerCase = lowerCaseFunc; + _.lowerFirst = lowerFirstFunc; + _.lt = ltFunc; + _.lte = lteFunc; + _.max = maxFunc; + _.maxBy = maxByFunc; + _.mean = meanFunc; + _.min = minFunc; + _.minBy = minByFunc; + _.noConflict = noConflictFunc; + _.noop = noopFunc; + _.now = nowFunc; + _.pad = padFunc; + _.padEnd = padEndFunc; + _.padStart = padStartFunc; + _.parseInt = parseIntFunc; + _.random = randomFunc; + _.reduce = reduceFunc; + _.reduceRight = reduceRightFunc; + _.repeat = repeatFunc; + _.replace = replaceFunc; + _.result = resultFunc; + _.round = roundFunc; + _.runInContext = runInContextFunc; + _.sample = sampleFunc; + _.size = sizeFunc; + _.snakeCase = snakeCaseFunc; + _.some = someFunc; + _.sortedIndex = sortedIndexFunc; + _.sortedIndexBy = sortedIndexByFunc; + _.sortedIndexOf = sortedIndexOfFunc; + _.sortedLastIndex = sortedLastIndexFunc; + _.sortedLastIndexBy = sortedLastIndexByFunc; + _.sortedLastIndexOf = sortedLastIndexOfFunc; + _.startCase = startCaseFunc; + _.startsWith = startsWithFunc; + _.subtract = subtractFunc; + _.sum = sumFunc; + _.sumBy = sumByFunc; + _.template = templateFunc; + _.times = timesFunc; + _.toInteger = toIntegerFunc; + _.toLength = toLengthFunc; + _.toLower = toLowerFunc; + _.toNumber = toNumberFunc; + _.toSafeInteger = toSafeIntegerFunc; + _.toString = toStringFunc; + _.toUpper = toUpperFunc; + _.trim = trimFunc; + _.trimEnd = trimEndFunc; + _.trimStart = trimStartFunc; + _.truncate = truncateFunc; + _.unescape = unescapeFunc; + _.uniqueId = uniqueIdFunc; + _.upperCase = upperCaseFunc; + _.upperFirst = upperFirstFunc; + _.each = eachFunc; + _.eachRight = eachRightFunc; + _.first = firstFunc; +} diff --git a/lowlight/lowlight-tests.ts b/lowlight/lowlight-tests.ts new file mode 100644 index 0000000000..0160093785 --- /dev/null +++ b/lowlight/lowlight-tests.ts @@ -0,0 +1,82 @@ +/// + +import { highlight, highlightAuto, registerLanguage } from 'lowlight'; +import * as core from 'lowlight/lib/core'; + +function highlighter(hljs: any): any { + return { + aliases: ['cmake.in'], + case_insensitive: true, + keywords: { + keyword: + 'forall all exists exist only m M i e 1 2 3 4 5 6 7 8 9 0 - + * / \ % ! . , ; : | lim limsup liminf infinity not' + }, + contains: [ + { + className: 'variable', + begin: '(', end: ')' + }, + ] + }; +} + +registerLanguage('math', highlighter); + +console.log(highlight('typescript', +`class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + + public version(): string { + return this.version; + } +} +` +)); + +console.info(highlightAuto( +`class CPP { + private year: number; + public constructor(private version: string) { + this.year = Number(version.match(/.+\d+$/)); + } + + public version(): string { + return this.version; + } +} +` +)); + +core.registerLanguage('math', highlighter); + +console.log(core.highlight('javascript', +`class CPP { + constructor(version) { + this.version = version; + this.year = Number(version.match(/.+\d+$/)); + } + + version(){ + return this.version; + } +} +` +, { prefix: 'core-' })); + + +console.info(core.highlightAuto( +`class CPP { + constructor(version) { + this.version = version; + this.year = Number(version.match(/.+\d+$/)); + } + + version(){ + return this.version; + } +} +` +, { prefix: 'core-', subset: ['purescript', 'javascript', 'typescript', 'coffeescript'] })); \ No newline at end of file diff --git a/lowlight/lowlight.d.ts b/lowlight/lowlight.d.ts new file mode 100644 index 0000000000..589c9b50fd --- /dev/null +++ b/lowlight/lowlight.d.ts @@ -0,0 +1,99 @@ +// Type definitions for lowlight +// Project: https://github.com/wooorm/lowlight +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'lowlight' { + export { highlight, highlightAuto, registerLanguage } from 'lowlight/lib/core'; +} + +declare module 'lowlight/lib/core' { + export function highlight(language: string, value: string, options?: lowlight.HighlightOptions): lowlight.HighlightResult; + export function highlightAuto(value: string, options?: lowlight.HighlightAutoOptions): lowlight.HighlightAutoResult; + export function registerLanguage(name: string, syntax: Function): void; +} + +declare namespace lowlight { + namespace AST { + namespace Unist { + interface Data { + [index: string]: any; + } + + interface Position { + line: number; + column: number; + offset?: number; + } + + interface Location { + start: Position; + end: Position; + indent?: Array; + } + + export interface Node { + type: string; + data?: Data; + position?: Location; + } + + export interface Parent extends Node { + children: Array; + } + + export interface Text extends Node { + value: string; + } + } + + interface Properties { + [index: string]: any; + } + + export interface Root extends Unist.Parent { + type: 'root'; + } + + export interface Element extends Unist.Parent { + type: 'element'; + tagName: string; + properties: Properties; + } + + export interface Doctype extends Unist.Node { + type: 'doctype'; + name: string; + public?: string; + system?: string; + } + + export interface Comment extends Unist.Text { + type: 'comment'; + } + + export interface Text extends Unist.Text { + type: 'text'; + } + } + + type HastNode = AST.Root | AST.Element | AST.Doctype | AST.Comment | AST.Text; + + interface HighlightOptions { + prefix?: string; + } + + interface HighlightAutoOptions extends HighlightOptions { + subset?: Array; + } + + interface HighlightResult { + relevance: number; + language: string; + value: Array; + } + + interface HighlightAutoResult extends HighlightResult { + secondBest?: HighlightAutoResult; + } +} \ No newline at end of file diff --git a/mapbox-gl/mapbox-gl-0.25.1.d.ts b/mapbox-gl/mapbox-gl-0.25.1.d.ts new file mode 100644 index 0000000000..2ee8d30949 --- /dev/null +++ b/mapbox-gl/mapbox-gl-0.25.1.d.ts @@ -0,0 +1,936 @@ +// Type definitions for Mapbox GL JS v0.24.0 +// Project: https://github.com/mapbox/mapbox-gl-js +// Definitions by: Dominik Bruderer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace mapboxgl { + let accessToken: string; + let version: string; + export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; + + /** + * Map + */ + export class Map extends Evented { + constructor(options?: MapboxOptions); + + addControl(control: Control): this; + + addClass(klass: string, options?: mapboxgl.StyleOptions): this; + + removeClass(klass: string, options?: mapboxgl.StyleOptions): this; + + setClasses(klasses: string[], options?: mapboxgl.StyleOptions): this; + + hasClass(klass: string): boolean; + + getClasses(): string[]; + + resize(): this; + + getBounds(): mapboxgl.LngLatBounds; + + setMaxBounds(lnglatbounds?: mapboxgl.LngLatBounds | number[][]): this; + + setMinZoom(minZoom?: number): this; + + setMaxZoom(maxZoom?: number): this; + + project(lnglat: mapboxgl.LngLat | number[]): mapboxgl.Point; + + unproject(point: mapboxgl.Point | number[]): mapboxgl.LngLat; + + queryRenderedFeatures(pointOrBox?: mapboxgl.Point|number[]|mapboxgl.Point[]|number[][], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; + + querySourceFeatures(sourceID: string, parameters: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + + setStyle(style: mapboxgl.Style | string): this; + + getStyle(): mapboxgl.Style; + + addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + + removeSource(id: string): this; + + getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + + addLayer(layer: mapboxgl.Layer, before?: string): this; + + removeLayer(id: string): this; + + getLayer(id: string): mapboxgl.Layer; + + setFilter(layer: string, filter: any[]): this; + + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; + + getFilter(layer: string): any[]; + + setPaintProperty(layer: string, name: string, value: any, klass?: string): this; + + getPaintProperty(layer: string, name: string, klass?: string): any; + + setLayoutProperty(layer: string, name: string, value: any): this; + + getLayoutProperty(layer: string, name: string, klass?: string): any; + + getContainer(): HTMLElement; + + getCanvasContainer(): HTMLElement; + + getCanvas(): HTMLCanvasElement; + + loaded(): boolean; + + remove(): void; + + onError(): void; + + showTileBoundaries: boolean; + + showCollisionBoxes: boolean; + + repaint: boolean; + + getCenter(): mapboxgl.LngLat; + + setCenter(center: LngLat|number[], eventData?: mapboxgl.EventData): this; + + panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + panTo(lnglat: mapboxgl.LngLat, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; + + getZoom(): number; + + setZoom(zoom: number, eventData?: mapboxgl.EventData): this; + + zoomTo(zoom: number, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + zoomIn(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + zoomOut(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + getBearing(): number; + + setBearing(bearing: number, eventData?: mapboxgl.EventData): this; + + rotateTo(bearing: number, options?: mapboxgl.AnimationOptions, eventData?: EventData): this; + + resetNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + snapToNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + getPitch(): number; + + setPitch(pitch: number, eventData?: EventData): this; + + fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number, offset?: Point|number[],maxZoom?: number }): this; + + jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; + + easeTo(options: mapboxgl.CameraOptions | mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; + + stop(): this; + + scrollZoom: ScrollZoomHandler; + + boxZoom: BoxZoomHandler; + + dragRotate: DragRotateHandler; + + dragPan: DragPanHandler; + + keyboard: KeyboardHandler; + + doublClickZoom: DoubleClickZoomHandler; + + touchZoomRotate: TouchZoomRotateHandler; + } + + export interface MapboxOptions { + /** If true, an attribution control will be added to the map. */ + attributionControl?: boolean; + + bearing?: number; + + /** Snap to north threshold in degrees. */ + bearingSnap?: number; + + /** If true, enable the "box zoom" interaction (see BoxZoomHandler) */ + boxZoom?: boolean; + + /** initial map center */ + center?: mapboxgl.LngLat | number[]; + + /** Style class names with which to initialize the map */ + classes?: string[]; + + /** ID of the container element */ + container?: string | Element; + + /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ + dragPan?: boolean; + + /** If true, enable the "drag to rotate" interaction (see DragRotateHandler). */ + dragRotate?: boolean; + + /** If true, enable the "double click to zoom" interaction (see DoubleClickZoomHandler). */ + doubleClickZoom?: boolean; + + /** If true, the map will track and update the page URL according to map position */ + hash?: boolean; + + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ + failIfMayorPerformanceCaveat?: boolean; + + /** If false, no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input */ + interactive?: boolean; + + /** If true, enable keyboard shortcuts (see KeyboardHandler). */ + keyboard?: boolean; + + /** If set, the map is constrained to the given bounds. */ + maxBounds?: mapboxgl.LngLatBounds | number[][]; + + /** Maximum zoom of the map */ + maxZoom?: number; + + /** Minimum zoom of the map */ + minZoom?: number; + + /** If true, The maps canvas can be exported to a PNG using map.getCanvas().toDataURL();. This is false by default as a performance optimization. */ + preserveDrawingBuffer?: boolean; + + pitch?: number; + + /** If true, enable the "scroll to zoom" interaction */ + scrollZoom?: boolean; + + /** stylesheet location */ + style?: mapboxgl.Style | string; + + /** If true, the map will automatically resize when the browser window resizes */ + trackResize?: boolean; + + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ + touchZoomRotate?: boolean; + + /** Initial zoom level */ + zoom?: number; + } + + /** + * BoxZoomHandler + */ + export class BoxZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * ScrollZoomHandler + */ + export class ScrollZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DragPenHandler + */ + export class DragPanHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DragRotateHandler + */ + export class DragRotateHandler { + constructor(map: mapboxgl.Map, options?: {bearingSnap?: number, pitchWithRotate?: boolean}); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * KeyboardHandler + */ + export class KeyboardHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DoubleClickZoomHandler + */ + export class DoubleClickZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * TouchZoomRotateHandler + */ + export class TouchZoomRotateHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + + disableRotation(): void; + + enableRotation(): void; + } + + /** + * Control + */ + export class Control extends Evented { + addTo(map: mapboxgl.Map): this; + + remove(): this; + } + + /** + * ControlOptions + */ + export interface ControlOptions { + position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; + } + + /** + * Navigation + */ + export class Navigation extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Geolocate + */ + export class Geolocate extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Attribution + */ + export class Attribution extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Scale + */ + export class Scale extends Control { + constructor(options?: {position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left', maxWidth?: number, unit?: string}) + } + + /** + * Popup + */ + export class Popup extends Evented { + constructor(options?: mapboxgl.PopupOptions); + + addTo(map: mapboxgl.Map): this; + + isOpen(): boolean; + + remove(): this; + + getLngLat(): mapboxgl.LngLat; + + setLngLat(lnglat: mapboxgl.LngLat | number[]): this; + + setText(text: string): this; + + setHTML(html: string): this; + + setDOMContent(htmlNode: Node): this; + } + + export interface PopupOptions { + closeButton?: boolean; + + closeOnClick?: boolean; + + anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + + offset?: number | Point | number[] | { [key:string]: Point | number[];}; + } + + export interface Style { + bearing?: number; + center?: number[]; + glyphs?: string; + layers?: Layer[]; + metadata?: any; + name?: string; + pitch?: number; + sources?: any; + sprite?: string; + transition?: Transition; + version: number; + zoom?: number; + } + + export interface Transition { + delay?: number; + duration?: number; + } + + export interface Source { + type: "vector" | "raster" | "geojson" | "image" | "video"; + } + + /** + * GeoJSONSource + */ + + export interface GeoJSONSourceRaw extends Source, GeoJSONSourceOptions { + type: "geojson"; + } + + export class GeoJSONSource implements GeoJSONSourceRaw { + type: "geojson"; + + constructor(options?: mapboxgl.GeoJSONSourceOptions); + + setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + } + + export interface GeoJSONSourceOptions { + data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; + + maxzoom?: number; + + buffer?: number; + + tolerance?: number; + + cluster?: number | boolean; + + clusterRadius?: number; + + clusterMaxZoom?: number; + } + + /** + * VideoSource + */ + export class VideoSource implements Source, VideoSourceOptions { + type: "video"; + + constructor(options?: mapboxgl.VideoSourceOptions); + + getVideo(): HTMLVideoElement; + + setCoordinates(coordinates: number[][]): this; + } + + export interface VideoSourceOptions { + urls?: string[]; + + coordinates?: number[][]; + } + + /** + * ImageSource + */ + export class ImageSource implements Source, ImageSourceOptions { + type: "image"; + + constructor(options?: mapboxgl.ImageSourceOptions); + + setCoordinates(coordinates: number[][]): this; + } + + export interface ImageSourceOptions { + url?: string; + + coordinates?: number[][]; + } + + interface VectorSource extends Source { + type: "vector"; + url?: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + } + + interface RasterSource extends Source { + type: "raster"; + url: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + } + + /** + * LngLat + */ + export class LngLat { + lng: number; + lat: number; + + constructor(lng: number, lat: number); + + /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ + wrap(): mapboxgl.LngLat; + + /** Return a LngLat as an array */ + toArray(): number[]; + + /** Return a LngLat as a string */ + toString(): string; + + static convert(input: number[]|mapboxgl.LngLat): mapboxgl.LngLat; + } + + /** + * LngLatBounds + */ + export class LngLatBounds { + sw: LngLat | number[]; + ne: LngLat | number[]; + constructor(sw?: LngLat, ne?: LngLat); + + /** Extend the bounds to include a given LngLat or LngLatBounds. */ + extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; + + /** Get the point equidistant from this box's corners */ + getCenter(): mapboxgl.LngLat; + + /** Get southwest corner */ + getSouthWest(): mapboxgl.LngLat; + + /** Get northeast corner */ + getNorthEast(): mapboxgl.LngLat; + + /** Get northwest corner */ + getNorthWest(): mapboxgl.LngLat; + + /** Get southeast corner */ + getSouthEast(): mapboxgl.LngLat; + + /** Get west edge longitude */ + getWest(): number; + + /** Get south edge latitude */ + getSouth(): number; + + /** Get east edge longitude */ + getEast(): number; + + /** Get north edge latitude */ + getNorth(): number; + + /** Returns a LngLatBounds as an array */ + toArray(): number[][]; + + /** Return a LngLatBounds as a string */ + toString(): string; + + /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ + static convert(input: mapboxgl.LngLatBounds | number[] | number[][]): mapboxgl.LngLatBounds; + } + + /** + * Point + */ + // Todo: Pull out class to seperate definition for Module "point-geometry" + export class Point { + constructor(options?: Object); + + clone(): Point; + + add(p: number): Point; + + sub(p: number): Point; + + mult(k: number): Point; + + div(k: number): Point; + + rotate(a: number): Point; + + matMult(m: number): Point; + + unit(): Point; + + perp(): Point; + + round(): Point; + + mag(): number; + + equals(): boolean; + + dist(): number; + + distSqr(): number; + + angle(): number; + + angleTo(): number; + + angleWidth(): number; + + angleWidthSep(): number; + } + + export class Marker { + constructor(element?: HTMLElement, options?: { offset?: Point | number[] }); + + addTo(map: Map): this; + + remove(): this; + + getLngLat(): LngLat; + + setLngLat(lngLat: LngLat | number[]): this; + + setPopup(popup?: Popup): this; + + getPopup(): Popup; + + togglePopup(): this; + } + + /** + * Evented + */ + export class Evented { + on(type: string, listener: Function): this; + + off(type?: string | any, listener?: Function): this; + + once(type: string, listener: Function): this; + + fire(type: string, data?: mapboxgl.EventData | Object): this; + + listens(type: string): boolean; + } + + /** + * StyleOptions + */ + export interface StyleOptions { + transition?: boolean; + } + + /** + * EventData + */ + export class EventData { + type: string; + target: Map; + originalEvent: Event; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapMouseEvent { + type: string; + target: Map; + originalEvent: MouseEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapTouchEvent { + type: string; + target: Map; + originalEvent: TouchEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + points: Point[]; + lngLats: LngLat[]; + } + + export class MapBoxZoomEvent { + originalEvent: MouseEvent; + boxZoomBounds: LngLatBounds; + } + + /** + * AnimationOptions + */ + export interface AnimationOptions { + /** Number in milliseconds */ + duration?: number; + easing?: Function; + /** point, origin of movement relative to map center */ + offset?: Point | number[]; + /** When set to false, no animation happens */ + animate?: boolean; + } + + /** + * CameraOptions + */ + export interface CameraOptions { + /** Map center */ + center?: mapboxgl.LngLat | number[]; + /** Map zoom level */ + zoom?: number; + /** Map rotation bearing in degrees counter-clockwise from north */ + bearing?: number; + /** Map angle in degrees at which the camera is looking at the ground */ + pitch?: number; + /** If zooming, the zoom center (defaults to map center) */ + around?: mapboxgl.LngLat | number[]; + } + + /** + * FlyToOptions + */ + export interface FlyToOptions extends AnimationOptions, CameraOptions { + curve?: number; + minZoom?: number; + speed?: number; + screenSpeed?: number; + easing?: Function; + } + + /** + * MapEvent + */ + export interface MapEvent { + webglcontextlost?: {originalEvent: WebGLContextEvent}; + webglcontextrestored?: {originalEvent: WebGLContextEvent}; + render?: void; + contextmenu?: {data: mapboxgl.MapMouseEvent}; + dblclick?: {data: mapboxgl.MapMouseEvent}; + click?: {data: mapboxgl.MapMouseEvent}; + touchcancel?: {data: mapboxgl.MapTouchEvent}; + touchmove?: {data: mapboxgl.MapTouchEvent}; + touchend?: {data: mapboxgl.MapTouchEvent}; + touchstart?: {data: mapboxgl.MapTouchEvent}; + mousemove?: {data: mapboxgl.MapMouseEvent}; + mouseup?: {data: mapboxgl.MapMouseEvent}; + mousedown?: {data: mapboxgl.MapMouseEvent}; + moveend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + move?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + movestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + mouseout?:{data: mapboxgl.MapMouseEvent}; + load?: void; + zoomend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + zoom?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + zoomstart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + boxzoomcancel?: {data: mapboxgl.MapBoxZoomEvent}; + boxzoomstart?: {data: mapboxgl.MapBoxZoomEvent}; + boxzoomend?: {data: mapboxgl.MapBoxZoomEvent}; + rotate?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + rotatestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + rotateend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + drag?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + dragend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + pitch?: {data: mapboxgl.EventData}; + } + + export interface Layer { + id: string; + type?: "fill" | "line" | "symbol" | "circle" | "raster" | "background" | string; //TODO: Ideally we wouldn't accept string here, just these specific strings + + metadata?: any; + ref?: string; + + source?: string; + + "source-layer"?: string; + + minzoom?: number; + maxzoom?: number; + + interactive?: boolean; + + filter?: any[]; + layout?: BackgroundLayout | FillLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout; + paint?: BackgroundPaint | FillPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint; + } + + export interface StyleFunction { + stops: any[][]; + property?: string; + base?: number; + type?: "continuous" | "interval" | "categorical"; + } + + export interface BackgroundLayout { + visibility?: "visible" | "none"; + } + export interface BackgroundPaint { + "background-color"?: string; + "background-pattern"?: string; + "background-opacity"?: number; + } + + export interface FillLayout { + visibility?: "visible" | "none"; + } + export interface FillPaint { + "fill-antialias"?: boolean; + "fill-opacity"?: number | StyleFunction; + "fill-color"?: string | StyleFunction; + "fill-outline-color": string | StyleFunction; + "fill-translate"?: number[]; + "fill-translate-anchor"?: "map" | "viewport"; + "fill-pattern"?: "string"; + } + + export interface LineLayout { + visibility?: "visible" | "none"; + + "line-cap"?: "butt" | "round" | "square"; + "line-join"?: "bevel" | "round" | "miter"; + "line-miter-limit"?: number; + "line-round-limit"?: number; + } + export interface LinePaint { + "line-opacity"?: number; + "line-color"?: string| StyleFunction; + "line-translate"?: number[]; + "line-translate-anchor"?: "map" | "viewport"; + "line-width"?: number; + "line-gap-width"?: number; + "line-offset"?: number; + "line-blur"?: number; + "line-dasharray"?: number[]; + "line-dasharray-transition"?: Transition; + "line-pattern"?: string; + } + + export interface SymbolLayout { + visibility?: "visible" | "none"; + + "symbol-placement"?: "point" | "line"; + "symbol-spacing"?: number; + "symbol-avoid-edges"?: boolean; + "icon-allow-overlap"?: boolean; + "icon-ignore-placement"?: boolean; + "icon-optional"?: boolean; + "icon-rotation-alignment"?: "map" | "viewport" | "auto"; + "icon-size"?: number; + "icon-text-fit"?: "none" | "both" | "width" | "height"; + "icon-text-fit-padding"?: number[]; + "icon-image"?: string; + "icon-rotate"?: number | StyleFunction; + "icon-padding"?: number; + "icon-keep-upright"?: boolean; + "icon-offset"?: number[]; + "text-pitch-alignment"?: "map" | "viewport" | "auto"; + "text-rotation-alignment"?: "map" | "viewport" | "auto"; + "text-field"?: string; + "text-font"?: string | string[]; + "text-size"?: number; + "text-max-width"?: number; + "text-line-height"?: number; + "text-letter-spacing"?: number; + "text-justify"?: "left" | "center" | "right"; + "text-anchor"?: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; + "text-max-angle"?: number; + "text-rotate"?: number; + "text-padding"?: number; + "text-keep-upright"?: boolean; + "text-transform"?: "none" | "uppercase" | "lowercase"; + "text-offset"?: number[]; + "text-allow-overlap"?: boolean; + "text-ignore-placement"?: boolean; + "text-optional"?: boolean; + + } + export interface SymbolPaint { + "icon-opacity"?: number; + "icon-color"?: string; + "icon-halo-color"?: string; + "icon-halo-width"?: number; + "icon-halo-blur"?: number; + "icon-translate"?: number[]; + "icon-translate-anchor"?: "map" | "viewport"; + "text-opacity"?: number; + "text-color"?: "string"; + "text-halo-color"?: "string"; + "text-halo-width"?: number; + "text-halo-blur"?: number; + "text-translate"?: number[]; + "text-translate-anchor"?: "map" | "viewport"; + } + + export interface RasterLayout { + visibility?: "visible" | "none"; + } + + export interface RasterPaint { + "raster-opacity"?: number; + "raster-hue-rotate"?: number; + "raster-brightness-min"?: number; + "raster-brightness-max"?: number; + "raster-saturation"?: number; + "raster-contrast"?: number; + "raster-fade-duration"?: number; + } + + export interface CircleLayout { + visibility?: "visible" | "none"; + } + + export interface CirclePaint { + "circle-radius"?: number | StyleFunction; + "circle-radius-transition"?: Transition; + "circle-color"?: number | StyleFunction; + "circle-blur"?: number | StyleFunction; + "circle-opacity"?: number | StyleFunction; + "circle-translate"?: number[]; + "circle-translate-anchor"?: "map" | "viewport"; + "circle-pitch-scale"?: "map" | "viewport"; + } +} + +declare module 'mapbox-gl' { + export = mapboxgl; +} diff --git a/mapbox-gl/mapbox-gl.d.ts b/mapbox-gl/mapbox-gl.d.ts index 2ee8d30949..ddb6344cbd 100644 --- a/mapbox-gl/mapbox-gl.d.ts +++ b/mapbox-gl/mapbox-gl.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.24.0 +// Type definitions for Mapbox GL JS v0.26.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -343,28 +343,28 @@ declare namespace mapboxgl { /** * Navigation */ - export class Navigation extends Control { + export class NavigationControl extends Control { constructor(options?: mapboxgl.ControlOptions); } /** * Geolocate */ - export class Geolocate extends Control { + export class GeolocateControl extends Control { constructor(options?: mapboxgl.ControlOptions); } /** * Attribution */ - export class Attribution extends Control { + export class AttributionControl extends Control { constructor(options?: mapboxgl.ControlOptions); } /** * Scale */ - export class Scale extends Control { + export class ScaleControl extends Control { constructor(options?: {position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left', maxWidth?: number, unit?: string}) } @@ -697,6 +697,11 @@ declare namespace mapboxgl { boxZoomBounds: LngLatBounds; } + export class MapDataEvent { + type: string; + dataType: "source" | "style" | "tile"; + } + /** * AnimationOptions */ @@ -741,8 +746,12 @@ declare namespace mapboxgl { * MapEvent */ export interface MapEvent { + resize?: void; webglcontextlost?: {originalEvent: WebGLContextEvent}; webglcontextrestored?: {originalEvent: WebGLContextEvent}; + remove?: void; + dataloading?: {data: mapboxgl.MapDataEvent}; + data?: {data: mapboxgl.MapDataEvent}; render?: void; contextmenu?: {data: mapboxgl.MapMouseEvent}; dblclick?: {data: mapboxgl.MapMouseEvent}; @@ -798,7 +807,8 @@ declare namespace mapboxgl { stops: any[][]; property?: string; base?: number; - type?: "continuous" | "interval" | "categorical"; + type?: "identity" | "exponential" | "interval" | "categorical"; + "colorSpace"?: "rgb" | "lab" | "interval"; } export interface BackgroundLayout { @@ -821,6 +831,8 @@ declare namespace mapboxgl { "fill-translate"?: number[]; "fill-translate-anchor"?: "map" | "viewport"; "fill-pattern"?: "string"; + "fill-extrude-height"?: number; + "fill-extrude-base"?: number; } export interface LineLayout { diff --git a/material-ui/legacy/material-ui-0.15.1-tests.tsx b/material-ui/legacy/material-ui-0.15.1-tests.tsx new file mode 100644 index 0000000000..a3cd559123 --- /dev/null +++ b/material-ui/legacy/material-ui-0.15.1-tests.tsx @@ -0,0 +1,4953 @@ +/// +/// +/// +/// + +import * as React from 'react'; +import {Component, PropTypes} from 'react'; +import * as ReactDOM from 'react-dom'; + +import getMuiTheme from 'material-ui/styles/getMuiTheme'; +import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; +import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; +import muiThemeable from 'material-ui/styles/muiThemeable'; +import {MuiTheme} from 'material-ui/styles' + +import AppBar from 'material-ui/AppBar'; +import AutoComplete from 'material-ui/AutoComplete'; +import Avatar from 'material-ui/Avatar'; +import Badge from 'material-ui/Badge'; +import Checkbox from 'material-ui/Checkbox'; +import Chip from 'material-ui/Chip'; +import CircularProgress from 'material-ui/CircularProgress'; +import DatePicker from 'material-ui/DatePicker'; +import Dialog from 'material-ui/Dialog'; +import Divider from 'material-ui/Divider'; +import Drawer from 'material-ui/Drawer'; +import DropDownMenu from 'material-ui/DropDownMenu'; +import FlatButton from 'material-ui/FlatButton'; +import FloatingActionButton from 'material-ui/FloatingActionButton'; +import FontIcon from 'material-ui/FontIcon'; +import IconButton from 'material-ui/IconButton'; +import IconMenu from 'material-ui/IconMenu'; +import LinearProgress from 'material-ui/LinearProgress'; +import List from 'material-ui/List/List'; +import ListItem from 'material-ui/List/ListItem'; +import MenuItem from 'material-ui/MenuItem'; +import Paper from 'material-ui/Paper'; +import RaisedButton from 'material-ui/RaisedButton'; +import RefreshIndicator from 'material-ui/RefreshIndicator'; +import SelectField from 'material-ui/SelectField'; +import Slider from 'material-ui/Slider'; +import Snackbar from 'material-ui/Snackbar'; +import Subheader from 'material-ui/Subheader'; +import SvgIcon from 'material-ui/SvgIcon'; +import TextField from 'material-ui/TextField'; +import TimePicker from 'material-ui/TimePicker'; +import Toggle from 'material-ui/Toggle'; +import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; +import {GridList, GridTile} from 'material-ui/GridList'; +import {MakeSelectable} from 'material-ui/List'; +import {Menu} from 'material-ui/Menu'; +import {Popover, PopoverAnimationVertical} from 'material-ui/Popover'; +import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton'; +import {Step, Stepper, StepLabel, StepContent, StepButton} from 'material-ui/Stepper'; +import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, TableFooter} from 'material-ui/Table'; +import {Tabs, Tab} from 'material-ui/Tabs'; +import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar'; + +import ActionAndroid from 'material-ui/svg-icons/action/android'; +import ActionAssignment from 'material-ui/svg-icons/action/assignment'; +import ActionFavorite from 'material-ui/svg-icons/action/favorite'; +import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border'; +import ActionFlightTakeoff from 'material-ui/svg-icons/action/flight-takeoff'; +import ActionGrade from 'material-ui/svg-icons/action/grade'; +import ActionHome from 'material-ui/svg-icons/action/home'; +import ActionInfo from 'material-ui/svg-icons/action/info'; +import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right'; +import CommunicationCall from 'material-ui/svg-icons/communication/call'; +import CommunicationChatBubble from 'material-ui/svg-icons/communication/chat-bubble'; +import CommunicationEmail from 'material-ui/svg-icons/communication/email'; +import ContentAdd from 'material-ui/svg-icons/content/add'; +import ContentCopy from 'material-ui/svg-icons/content/content-copy'; +import ContentDrafts from 'material-ui/svg-icons/content/drafts'; +import ContentFilter from 'material-ui/svg-icons/content/filter-list'; +import ContentInbox from 'material-ui/svg-icons/content/inbox'; +import ContentLink from 'material-ui/svg-icons/content/link'; +import ContentSend from 'material-ui/svg-icons/content/send'; +import Delete from 'material-ui/svg-icons/action/delete'; +import Download from 'material-ui/svg-icons/file/file-download'; +import EditorInsertChart from 'material-ui/svg-icons/editor/insert-chart'; +import FileCloudDownload from 'material-ui/svg-icons/file/cloud-download'; +import FileFileDownload from 'material-ui/svg-icons/file/file-download'; +import FileFolder from 'material-ui/svg-icons/file/folder'; +import FolderIcon from 'material-ui/svg-icons/file/folder-open'; +import HardwareVideogameAsset from 'material-ui/svg-icons/hardware/videogame-asset'; +import MapsPersonPin from 'material-ui/svg-icons/maps/person-pin'; +import MapsPlace from 'material-ui/svg-icons/maps/place'; +import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; +import NavigationClose from 'material-ui/svg-icons/navigation/close'; +import NavigationExpandMoreIcon from 'material-ui/svg-icons/navigation/expand-more'; +import NotificationsIcon from 'material-ui/svg-icons/social/notifications'; +import PersonAdd from 'material-ui/svg-icons/social/person-add'; +import RemoveRedEye from 'material-ui/svg-icons/image/remove-red-eye'; +import StarBorder from 'material-ui/svg-icons/toggle/star-border'; +import UploadIcon from 'material-ui/svg-icons/file/cloud-upload'; +import WarningIcon from 'material-ui/svg-icons/alert/warning'; + +import {cyan500, cyan700, + grey100, grey300, grey400, grey500, + pinkA200, + white, darkBlack, fullBlack, + blue300, + indigo900, + orange200, + deepOrange300, + pink400, + purple500, + fullWhite, + blue500, red500, greenA200, yellow500, + transparent, yellow600, indigo500, lightBlack, + orange500, +} from 'material-ui/styles/colors'; +import {fade} from 'material-ui/utils/colorManipulator'; + +import {SMALL, MEDIUM, LARGE, default as withWidth} from 'material-ui/utils/withWidth'; + + +import injectTapEventPlugin = require('react-tap-event-plugin'); + +// Needed for onTouchTap +// Check this repo: +// https://github.com/zilverline/react-tap-event-plugin +injectTapEventPlugin(); + +function handleTouchTap() { + alert('onTouchTap triggered on the title component'); +} + +const styles = { + title: { + cursor: 'pointer', + }, + exampleImageInput: { + cursor: 'pointer', + position: 'absolute', + top: 0, + bottom: 0, + right: 0, + left: 0, + width: '100%', + opacity: 0, + }, + button: { + margin: 12, + }, + chip: { + margin: 4 + }, + smallIcon: { + width: 36, + height: 36, + }, + mediumIcon: { + width: 48, + height: 48, + }, + largeIcon: { + width: 60, + height: 60, + }, + small: { + width: 72, + height: 72, + padding: 16, + }, + medium: { + width: 96, + height: 96, + padding: 24, + }, + large: { + width: 120, + height: 120, + padding: 30, + }, + radioButton: { + marginTop: 16, + }, + root: { + display: 'flex', + flexWrap: 'wrap', + justifyContent: 'space-around', + }, + gridList: { + width: 500, + height: 500, + overflowY: 'auto', + marginBottom: 24, + }, + paper: { + display: 'inline-block', + float: 'left', + margin: '16px 32px 16px 0', + }, + rightIcon: { + textAlign: 'center', + lineHeight: '24px', + }, + customWidth: { + width: 200, + }, + h3: { + marginTop: 20, + fontWeight: 400, + }, + block: { + display: 'flex', + maxWidth: 250, + }, + block2: { + margin: 10, + }, + container: { + position: 'relative', + }, + refresh: { + display: 'inline-block', + position: 'relative', + }, + checkbox: { + marginBottom: 16, + }, + toggle: { + marginBottom: 16, + }, + propContainer: { + width: 200, + overflow: 'hidden', + margin: '20px auto 0', + }, + propToggleHeader: { + margin: '20px auto 10px', + }, + headline: { + fontSize: 24, + paddingTop: 16, + marginBottom: 12, + fontWeight: 400, + }, + errorStyle: { + color: orange500, + }, + underlineStyle: { + borderColor: orange500, + }, + floatingLabelStyle: { + color: orange500, + }, + floatingLabelFocusStyle: { + color: blue500, + }, +}; + +const style = { + marginRight: 20, + marginLeft: 20, + display: 'inline-block', + margin: '16px 32px 16px 0', +}; + +const customContentStyle = { + width: '100%', + maxWidth: 'none', +}; + +const iconStyles = { + marginRight: 24, +}; + +// "http://www.material-ui.com/#/customization/themes" + +// This replaces the textColor value on the palette +// and then update the keys for each component that depends on it. +// More on Colors: http://www.material-ui.com/#/customization/colors +const muiTheme = getMuiTheme({ + palette: { + textColor: cyan500, + }, + appBar: { + height: 50, + }, +}); + +const darkMuiTheme = getMuiTheme(darkBaseTheme); + +const lightBaseTheme = { + spacing: { + iconSize: 24, + desktopGutter: 24, + desktopGutterMore: 32, + desktopGutterLess: 16, + desktopGutterMini: 8, + desktopKeylineIncrement: 64, + desktopDropDownMenuItemHeight: 32, + desktopDropDownMenuFontSize: 15, + desktopDrawerMenuItemHeight: 48, + desktopSubheaderHeight: 48, + desktopToolbarHeight: 56, + }, + fontFamily: 'Roboto, sans-serif', + palette: { + primary1Color: cyan500, + primary2Color: cyan700, + primary3Color: grey400, + accent1Color: pinkA200, + accent2Color: grey100, + accent3Color: grey500, + textColor: darkBlack, + alternateTextColor: white, + canvasColor: white, + borderColor: grey300, + disabledColor: fade(darkBlack, 0.3), + pickerHeaderColor: cyan500, + clockCircleColor: fade(darkBlack, 0.07), + shadowColor: fullBlack, + }, +}; + +const lightMuiTheme = getMuiTheme(lightBaseTheme); + + +class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}, {}> { + static propTypes: React.ValidationMap = { + muiTheme: React.PropTypes.object.isRequired, + }; + + render() { + return ( + + Hello World! + + ); + } +} + + +// "http://www.material-ui.com/#/customization/inline-styles" +const InlineStylesCheckbox = () => ( + +); + + +// "http://www.material-ui.com/#/components/app-bar" +const AppBarExampleIcon = () => ( + +); + +const AppBarExampleIconButton = () => ( + Title} + onTitleTouchTap={handleTouchTap} + iconElementLeft={} + iconElementRight={} + /> +); + +const AppBarExampleIconMenu = () => ( + } + iconElementRight={ + + } + targetOrigin={{horizontal: 'right', vertical: 'top'}} + anchorOrigin={{horizontal: 'right', vertical: 'top'}} + > + + + + + } + /> +); + +// "http://www.material-ui.com/#/components/auto-complete" +export class AutoCompleteExampleSimple extends React.Component<{}, {dataSource: string[]}> { + + constructor(props) { + super(props); + + this.state = { + dataSource: [], + }; + } + + handleUpdateInput = (value) => { + this.setState({ + dataSource: [ + value, + value + value, + value + value + value, + ], + }); + }; + + render() { + return ( +
+ + +
+ ); + } +} + +const dataSource1 = [ + { + text: 'text-value1', + value: ( + + ), + }, + { + text: 'text-value2', + value: ( + + ), + }, +]; + +const dataSource2 = ['12345', '23456', '34567']; + +const dataSource3 = [ + {text: 'Some Text', value: 'someFirstValue'}, + {text: 'Some Text', value: 'someSecondValue'}, +]; + +const AutoCompleteExampleNoFilter = () => ( +
+
+
+ +
+); + +const colors = [ + 'Red', + 'Orange', + 'Yellow', + 'Green', + 'Blue', + 'Purple', + 'Black', + 'White', +]; + +const fruit = [ + 'Apple', 'Apricot', 'Avocado', + 'Banana', 'Bilberry', 'Blackberry', 'Blackcurrant', 'Blueberry', + 'Boysenberry', 'Blood Orange', + 'Cantaloupe', 'Currant', 'Cherry', 'Cherimoya', 'Cloudberry', + 'Coconut', 'Cranberry', 'Clementine', + 'Damson', 'Date', 'Dragonfruit', 'Durian', + 'Elderberry', + 'Feijoa', 'Fig', + 'Goji berry', 'Gooseberry', 'Grape', 'Grapefruit', 'Guava', + 'Honeydew', 'Huckleberry', + 'Jabouticaba', 'Jackfruit', 'Jambul', 'Jujube', 'Juniper berry', + 'Kiwi fruit', 'Kumquat', + 'Lemon', 'Lime', 'Loquat', 'Lychee', + 'Nectarine', + 'Mango', 'Marion berry', 'Melon', 'Miracle fruit', 'Mulberry', 'Mandarine', + 'Olive', 'Orange', + 'Papaya', 'Passionfruit', 'Peach', 'Pear', 'Persimmon', 'Physalis', 'Plum', 'Pineapple', + 'Pumpkin', 'Pomegranate', 'Pomelo', 'Purple Mangosteen', + 'Quince', + 'Raspberry', 'Raisin', 'Rambutan', 'Redcurrant', + 'Salal berry', 'Satsuma', 'Star fruit', 'Strawberry', 'Squash', 'Salmonberry', + 'Tamarillo', 'Tamarind', 'Tomato', 'Tangerine', + 'Ugli fruit', + 'Watermelon', +]; + +const AutoCompleteExampleFilters = () => ( +
+ +
+ +
+); + +// "http://www.material-ui.com/#/components/avatar" +const AvatarExampleSimple = () => ( + + + } + > + Image Avatar + + + } + > + Image Avatar with custom size + + } /> + } + > + FontIcon Avatar + + } + color={blue300} + backgroundColor={indigo900} + size={30} + style={style} + /> + } + > + FontIcon Avatar with custom colors and size + + } /> + } + > + SvgIcon Avatar + + } + color={orange200} + backgroundColor={pink400} + size={30} + style={style} + /> + } + > + SvgIcon Avatar with custom colors and size + + A} + > + Letter Avatar + + + A + + } + > + Letter Avatar with custom colors and size + + +); + + +// "http://www.material-ui.com/#/components/badge" +const BadgeExampleSimple = () => ( +
+ + + + + + + + +
+); + +const BadgeExampleContent = () => ( +
+ } + > + + + + Company Name + +
+); + + +// "http://www.material-ui.com/#/components/flat-button" +const FlatButtonExampleSimple = () => ( +
+ + + + +
+); + +const FlatButtonExampleComplex = () => ( +
+ + + + + Label before} + labelPosition="before" + primary={true} + style={styles.button} + icon={} + /> + + } + /> + +
+); + +const FlatButtonExampleIcon = () => ( +
+ } + style={style} + /> + } + style={style} + /> + } + style={style} + /> +
+); + + +// "http://www.material-ui.com/#/components/raised-button" +const RaisedButtonExampleSimple = () => ( +
+ + + + +
+); + +const RaisedButtonExampleComplex = () => ( +
+ + + + Label before} + labelPosition="before" + primary={true} + icon={} + style={styles.button} + /> + } + /> +
+); + +const RaisedButtonExampleIcon = () => ( +
+ } + style={style} + /> + } + style={style} + /> + } + style={style} + /> +
+); + + +// "http://www.material-ui.com/#/components/floating-action-button" +const FloatingActionButtonExampleSimple = () => ( +
+ + + + + + + + + + + + + + + + + + + + + + + +
+); + + +// "http://www.material-ui.com/#/components/icon-button" +const IconButtonExampleSimple = () => ( +
+ + +
+); + +const IconButtonExampleComplex = () => ( +
+ + + + + + + + + + home + +
+); + +const IconButtonExampleSize = () => ( +
+ + + + + + + + + + + + + + + +
+); + +const IconButtonExampleTooltip = () => ( +
+ + + + + + +
+); + +const IconButtonExampleTouch = () => ( +
+ + + + + + + + + + + + + + + + + + +
+); + + +// "http://www.material-ui.com/#/components/card" +const CardExampleWithAvatar = () => ( + + + } + > + + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. + Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. + Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. + + + + + + +); + +const CardExampleWithoutAvatar = () => ( + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. + Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. + Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. + + + + + + +); + +class CardExampleControlled extends React.Component<{}, {expanded: boolean}> { + + constructor(props) { + super(props); + this.state = { + expanded: false, + }; + } + + handleExpandChange = (expanded) => { + this.setState({expanded: expanded}); + }; + + handleToggle = (event, toggle) => { + this.setState({expanded: toggle}); + }; + + handleExpand = () => { + this.setState({expanded: true}); + }; + + handleReduce = () => { + this.setState({expanded: false}); + }; + + render() { + return ( + + + + + + } + > + + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi. + Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque. + Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. + + + + + + + ); + } +} + +// "http://www.material-ui.com/#/components/chip" +const ChipExampleSimple = () => ( +
+ Basic Chip + Blue Background + Blue Label Color + UI Avatar + Styled +
+); + +class ChipExampleComplex extends React.Component<{}, {}>{ + handleRequestDelete = () => { + alert('You clicked the delete button.'); + } + + handleTouchTap = () => { + alert('You clicked the Chip.'); + } + + render() { + return ( +
+ Click Me +
+ ); + } +} + + +// "http://www.material-ui.com/#/components/date-picker" +const DatePickerExampleSimple = () => ( +
+ + + +
+); + +const DatePickerExampleInline = () => ( +
+ + +
+); + +const optionsStyle = { + maxWidth: 255, + marginRight: 'auto', +}; + +interface DatePickerExampleToggleState { + minDate?: Date; + maxDate?: Date; + autoOk?: boolean; + disableYearSelection?: boolean; +} + +class DatePickerExampleToggle extends React.Component<{}, DatePickerExampleToggleState> { + constructor(props) { + super(props); + + const minDate = new Date(); + const maxDate = new Date(); + minDate.setFullYear(minDate.getFullYear() - 1); + minDate.setHours(0, 0, 0, 0); + maxDate.setFullYear(maxDate.getFullYear() + 1); + maxDate.setHours(0, 0, 0, 0); + + this.state = { + minDate: minDate, + maxDate: maxDate, + autoOk: false, + disableYearSelection: false, + }; + } + + handleChangeMinDate = (event, date) => { + this.setState({ + minDate: date, + }); + }; + + handleChangeMaxDate = (event, date) => { + this.setState({ + maxDate: date, + }); + }; + + handleToggle = (event, toggled) => { + this.setState({ + [event.target.name]: toggled, + }); + }; + + render() { + return ( +
+ +
+ + + + +
+
+ ); + } +} + +class DatePickerExampleControlled extends React.Component<{}, {controlledDate?: Date}> { + + constructor(props) { + super(props); + + this.state = { + controlledDate: null, + }; + } + + handleChange = (event, date) => { + this.setState({ + controlledDate: date, + }); + }; + + render() { + return ( + + ); + } +} + +function disableWeekends(date) { + return date.getDay() === 0 || date.getDay() === 6; +} +function disableRandomDates() { + return Math.random() > 0.7; +} +const DatePickerExampleDisableDates = () => ( +
+ + +
+); + +let DateTimeFormat = new Intl.DateTimeFormat('fr'); +const DatePickerExampleInternational = () => ( +
+ + + +
+); + + + +// "http://material-ui.com/#/components/dialog" +class DialogExampleSimple extends React.Component<{}, {open?: boolean}> { + state = { + open: false, + }; + + handleOpen = () => { + this.setState({open: true}); + }; + + handleClose = () => { + this.setState({open: false}); + }; + + render() { + const actions = [ + , + , + ]; + + return ( +
+ + + The actions in this window were passed in as an array of React objects. + +
+ ); + } +} + +class DialogExampleModal extends React.Component<{}, {open?: boolean}> { + state = { + open: false, + }; + + handleOpen = () => { + this.setState({open: true}); + }; + + handleClose = () => { + this.setState({open: false}); + }; + + render() { + const actions = [ + , + , + ]; + + return ( +
+ + + Only actions can close this dialog. + +
+ ); + } +} + +class DialogExampleCustomWidth extends React.Component<{}, {open?: boolean}> { + state = { + open: false, + }; + + handleOpen = () => { + this.setState({open: true}); + }; + + handleClose = () => { + this.setState({open: false}); + }; + + render() { + const actions = [ + , + , + ]; + + return ( +
+ + + This dialog spans the entire width of the screen. + +
+ ); + } +} + +class DialogExampleDialogDatePicker extends React.Component<{}, {open?: boolean}> { + state = { + open: false, + }; + + handleOpen = () => { + this.setState({open: true}); + }; + + handleClose = () => { + this.setState({open: false}); + }; + + render() { + const actions = [ + , + ]; + + return ( +
+ + + Open a Date Picker dialog from within a dialog. + + +
+ ); + } +} + +class DialogExampleScrollable extends React.Component<{}, {open?: boolean}> { + state = { + open: false, + }; + + handleOpen = () => { + this.setState({open: true}); + }; + + handleClose = () => { + this.setState({open: false}); + }; + + render() { + const actions = [ + , + , + ]; + + const radios = []; + for (let i = 0; i < 30; i++) { + radios.push( + + ); + } + + return ( +
+ + + + {radios} + + +
+ ); + } +} + +class DialogExampleAlert extends React.Component<{}, {open?: boolean}> { + state = { + open: false, + }; + + handleOpen = () => { + this.setState({open: true}); + }; + + handleClose = () => { + this.setState({open: false}); + }; + + render() { + const actions = [ + , + , + ]; + + return ( +
+ + + Discard draft? + +
+ ); + } +} + + +// "http://www.material-ui.com/#/components/divider" +const DividerExampleForm = () => ( + + + + + + + + + + +); + +const DividerExampleList = () => ( + + + + + + + + + + + +); + +const DividerExampleMenu = () => ( + + + + + + +); + + +// "http://www.material-ui.com/#/components/drawer" +class DrawerSimpleExample extends React.Component<{}, {open?: boolean}> { + + constructor(props) { + super(props); + this.state = {open: false}; + } + + handleToggle = () => this.setState({open: !this.state.open}); + + render() { + return ( +
+ + + Menu Item + Menu Item 2 + +
+ ); + } +} + +class DrawerUndockedExample extends React.Component<{}, {open?: boolean}> { + + constructor(props) { + super(props); + this.state = {open: false}; + } + + handleToggle = () => this.setState({open: !this.state.open}); + + handleClose = () => this.setState({open: false}); + + render() { + return ( +
+ + this.setState({open})} + > + Menu Item + Menu Item 2 + +
+ ); + } +} + +class DrawerOpenRightExample extends React.Component<{}, {open?: boolean}> { + + constructor(props) { + super(props); + this.state = {open: false}; + } + + handleToggle = () => this.setState({open: !this.state.open}); + + render() { + return ( +
+ + + + +
+ ); + } +} + + +// "http://www.material-ui.com/#/components/grid-list" +const tilesData: {img: string, title: string, author: string, featured?: boolean}[] = [ + { + img: 'images/grid-list/00-52-29-429_640.jpg', + title: 'Breakfast', + author: 'jill111', + featured: true, + }, + { + img: 'images/grid-list/burger-827309_640.jpg', + title: 'Tasty burger', + author: 'pashminu', + }, + { + img: 'images/grid-list/camera-813814_640.jpg', + title: 'Camera', + author: 'Danson67', + }, + { + img: 'images/grid-list/morning-819362_640.jpg', + title: 'Morning', + author: 'fancycrave1', + }, + { + img: 'images/grid-list/hats-829509_640.jpg', + title: 'Hats', + author: 'Hans', + }, + { + img: 'images/grid-list/honey-823614_640.jpg', + title: 'Honey', + author: 'fancycravel', + }, + { + img: 'images/grid-list/vegetables-790022_640.jpg', + title: 'Vegetables', + author: 'jill111', + }, + { + img: 'images/grid-list/water-plant-821293_640.jpg', + title: 'Water plant', + author: 'BkrmadtyaKarki', + }, +]; + +const GridListExampleSimple = () => ( +
+ + December + {tilesData.map((tile) => ( + by {tile.author}} + actionIcon={} + > + + + ))} + +
+); + +const GridListExampleComplex = () => ( +
+ + {tilesData.map((tile) => ( + } + actionPosition="left" + titlePosition="top" + titleBackground="linear-gradient(to bottom, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)" + cols={tile.featured ? 2 : 1} + rows={tile.featured ? 2 : 1} + > + + + ))} + +
+); + + +// "http://www.material-ui.com/#/components/font-icon" +const FontIconExampleSimple = () => ( +
+ + + + + +
+); + +const FontIconExampleIcons = () => ( +
+ home + flight_takeoff + cloud_download + videogame_asset +
+); + + +// "http://www.material-ui.com/#/components/svg-icon" +const HomeIcon = (props) => ( + + + +); + +const SvgIconExampleSimple = () => ( +
+ + + +
+); + +const SvgIconExampleIcons = () => ( +
+ + + + +
+); + + +// "http://material-ui.com/#/components/lists" +const ListExampleSimple = () => ( + + + } /> + } /> + } /> + } /> + } /> + + + + } /> + } /> + } /> + } /> + + +); + +const ListExampleChat = () => ( + + + Recent chats + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + + + + Previous chats + } + /> + } + /> + + +); + +const ListExampleContacts = () => ( + + + } + rightAvatar={} + /> + } + /> + } + /> + } + /> + + + + + A + + } + rightAvatar={} + /> + } + /> + } + /> + } + /> + + +); + +const ListExampleFolder = () => ( + + + Folders + } />} + rightIcon={} + primaryText="Photos" + secondaryText="Jan 9, 2014" + /> + } />} + rightIcon={} + primaryText="Recipes" + secondaryText="Jan 17, 2014" + /> + } />} + rightIcon={} + primaryText="Work" + secondaryText="Jan 28, 2014" + /> + + + + Files + } backgroundColor={blue500} />} + rightIcon={} + primaryText="Vacation itinerary" + secondaryText="Jan 20, 2014" + /> + } backgroundColor={yellow600} />} + rightIcon={} + primaryText="Kitchen remodel" + secondaryText="Jan 10, 2014" + /> + + +); + +const ListExampleNested = () => ( + + + Nested List Items + } /> + } /> + } + initiallyOpen={true} + primaryTogglesNestedList={true} + nestedItems={[ + } + />, + } + disabled={true} + nestedItems={[ + } />, + ]} + />, + ]} + /> + + +); + +const ListExampleSettings = () => ( +
+ + + General + + + + + + Hangout Notifications + } + primaryText="Notifications" + secondaryText="Allow notifications" + /> + } + primaryText="Sounds" + secondaryText="Hangouts message" + /> + } + primaryText="Video sounds" + secondaryText="Hangouts video call" + /> + + + + + + + + + Priority Interruptions + } /> + } /> + } /> + + + + Hangout Notifications + } /> + } /> + } /> + + +
+); + +const ListExamplePhone = () => ( + + + } + rightIcon={} + primaryText="(650) 555 - 1234" + secondaryText="Mobile" + /> + } + primaryText="(323) 555 - 6789" + secondaryText="Work" + /> + + + + } + primaryText="aliconnors@example.com" + secondaryText="Personal" + /> + + + +); + +const iconButtonElement = ( + + + +); + +const rightIconMenu = ( + + Reply + Forward + Delete + +); + +const ListExampleMessages = () => ( +
+ + + Today + } + primaryText="Brunch this weekend?" + secondaryText={ +

+ Brendan Lim -- + I'll be in your neighborhood doing errands this weekend. Do you want to grab brunch? +

+ } + secondaryTextLines={2} + /> + + } + primaryText={ +

Summer BBQ  4

+ } + secondaryText={ +

+ to me, Scott, Jennifer -- + Wish I could come, but I'm out of town this weekend. +

+ } + secondaryTextLines={2} + /> + + } + primaryText="Oui oui" + secondaryText={ +

+ Grace Ng -- + Do you have Paris recommendations? Have you ever been? +

+ } + secondaryTextLines={2} + /> + + } + primaryText="Birdthday gift" + secondaryText={ +

+ Kerem Suer -- + Do you have any ideas what we can get Heidi for her birthday? How about a pony? +

+ } + secondaryTextLines={2} + /> + + } + primaryText="Recipe to try" + secondaryText={ +

+ Raquel Parrado -- + We should eat this: grated squash. Corn and tomatillo tacos. +

+ } + secondaryTextLines={2} + /> +
+
+ + + Today + } + rightIconButton={rightIconMenu} + primaryText="Brendan Lim" + secondaryText={ +

+ Brunch this weekend?
+ I'll be in your neighborhood doing errands this weekend. Do you want to grab brunch? +

+ } + secondaryTextLines={2} + /> + + } + rightIconButton={rightIconMenu} + primaryText="me, Scott, Jennifer" + secondaryText={ +

+ Summer BBQ
+ Wish I could come, but I'm out of town this weekend. +

+ } + secondaryTextLines={2} + /> + + } + rightIconButton={rightIconMenu} + primaryText="Grace Ng" + secondaryText={ +

+ Oui oui
+ Do you have any Paris recs? Have you ever been? +

+ } + secondaryTextLines={2} + /> + + } + rightIconButton={rightIconMenu} + primaryText="Kerem Suer" + secondaryText={ +

+ Birthday gift
+ Do you have any ideas what we can get Heidi for her birthday? How about a pony? +

+ } + secondaryTextLines={2} + /> + + } + rightIconButton={rightIconMenu} + primaryText="Raquel Parrado" + secondaryText={ +

+ Recipe to try
+ We should eat this: grated squash. Corn and tomatillo tacos. +

+ } + secondaryTextLines={2} + /> +
+
+
+); + +function wrapState(ComposedComponent: React.ComponentClass<__MaterialUI.List.SelectableProps>) { + return class SelectableList extends Component<{defaultValue: number}, {selectedIndex: number}> { + static propTypes = { + children: PropTypes.node.isRequired, + defaultValue: PropTypes.number.isRequired, + }; + + componentWillMount() { + this.setState({ + selectedIndex: this.props.defaultValue, + }); + } + + handleRequestChange = (event, index) => { + this.setState({ + selectedIndex: index, + }); + }; + + render() { + return ( + + {this.props.children} + + ); + } + }; +} + +let SelectableList = wrapState(MakeSelectable(List)); + +const ListExampleSelectable = () => ( + + + Selectable Contacts + } + nestedItems={[ + } + />, + ]} + /> + } + /> + } + /> + } + /> + + +); + + +// "http://www.material-ui.com/#/components/menu" +const MenuExampleSimple = () => ( +
+ + + + + + + + + + + + + + + + +
+); + +const MenuExampleDisable = () => ( +
+ + + + + + + + + + + + + + + + + + + + +
+); + +const MenuExampleIcons = () => ( +
+ + + } /> + } /> + } /> + + } /> + } /> + + } /> + + + + + + } /> + settings} /> + settings + } + /> + ¶} /> + §} /> + + +
+); + +const MenuExampleSecondary = () => ( +
+ + + + + + + + + + } /> + } /> + } /> + } /> + } /> + + + + + + + + + + + + + + + + + + +
+); + +const MenuExampleNested = () => ( +
+ + + + + + } + menuItems={[ + } + menuItems={[ + , + , + , + , + ]} + />, + , + , + , + ]} + /> + + + + + + + +
+); + + +// "http://www.material-ui.com/#/components/icon-menu" +const IconMenuExampleSimple = () => ( +
+ } + anchorOrigin={{horizontal: 'left', vertical: 'top'}} + targetOrigin={{horizontal: 'left', vertical: 'top'}} + > + + + + + + + } + anchorOrigin={{horizontal: 'left', vertical: 'bottom'}} + targetOrigin={{horizontal: 'left', vertical: 'bottom'}} + > + + + + + + + } + anchorOrigin={{horizontal: 'right', vertical: 'bottom'}} + targetOrigin={{horizontal: 'right', vertical: 'bottom'}} + > + + + + + + + } + anchorOrigin={{horizontal: 'right', vertical: 'top'}} + targetOrigin={{horizontal: 'right', vertical: 'top'}} + > + + + + + + +
+); + +interface IconMenuExampleControlledState { + valueSingle?: string; + valueMultiple?: string[]; + openMenu?: boolean; +} + +class IconMenuExampleControlled extends React.Component<{}, IconMenuExampleControlledState> { + constructor(props) { + super(props); + + this.state = { + valueSingle: '3', + valueMultiple: ['3', '5'], + }; + } + + handleChangeSingle = (event, value) => { + this.setState({ + valueSingle: value, + }); + }; + + handleChangeMultiple = (event, value) => { + this.setState({ + valueMultiple: value, + }); + }; + + handleOpenMenu = () => { + this.setState({ + openMenu: true, + }); + } + + handleOnRequestChange = (value) => { + this.setState({ + openMenu: value, + }); + } + + render() { + return ( +
+ } + onChange={this.handleChangeSingle} + value={this.state.valueSingle} + > + + + + + + + } + onChange={this.handleChangeMultiple} + value={this.state.valueMultiple} + multiple={true} + > + + + + + + + + } + open={this.state.openMenu} + onRequestChange={this.handleOnRequestChange} + > + + + + + + +
+ ); + } +} + +const IconMenuExampleScrollable = () => ( + } + anchorOrigin={{horizontal: 'left', vertical: 'top'}} + targetOrigin={{horizontal: 'left', vertical: 'top'}} + maxHeight={272} + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +); + +const IconMenuExampleNested = () => ( +
+ } + anchorOrigin={{horizontal: 'left', vertical: 'top'}} + targetOrigin={{horizontal: 'left', vertical: 'top'}} + > + } + menuItems={[ + , + , + , + , + ]} + /> + + } + menuItems={[ + , + , + , + , + ]} + /> + + } /> + + + + +
+); + + +// "http://www.material-ui.com/#/components/dropdown-menu" +class DropDownMenuSimpleExample extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: 1}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( +
+ + + + + + + +
+ + + + + + + +
+ ); + } +} + +class DropDownMenuOpenImmediateExample extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: 2}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( + + + + + + + + ); + } +} + +const items: React.ReactElement<__MaterialUI.Menus.MenuItemProps>[] = []; +for (let i = 0; i < 100; i++ ) { + items.push(); +} + +class DropDownMenuLongMenuExample extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: 10}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( + + {items} + + ); + } +} + +class DropDownMenuLabeledExample extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: 2}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( + + + + + + + ); + } +} + + +// "http://material-ui.com/#/components/paper" +const PaperExampleSimple = () => ( +
+ + + + + +
+); + +const PaperExampleRounded = () => ( +
+ + + + + +
+); + +const PaperExampleCircle = () => ( +
+ + + + + +
+); + + +// "http://www.material-ui.com/#/components/popover" +class PopoverExampleSimple extends React.Component<{}, {open?: boolean, anchorEl?: React.ReactInstance}> { + + constructor(props) { + super(props); + + this.state = { + open: false, + }; + } + + handleTouchTap = (event) => { + // This prevents ghost click. + event.preventDefault(); + + this.setState({ + open: true, + anchorEl: event.currentTarget, + }); + }; + + handleRequestClose = () => { + this.setState({ + open: false, + }); + }; + + render() { + return ( +
+ + + + + + + + + +
+ ); + } +} + +class PopoverExampleAnimation extends React.Component<{}, {open?: boolean, anchorEl?: React.ReactInstance}> { + + constructor(props) { + super(props); + + this.state = { + open: false, + }; + } + + handleTouchTap = (event) => { + // This prevents ghost click. + event.preventDefault(); + this.setState({ + open: true, + anchorEl: event.currentTarget, + }); + }; + + handleRequestClose = () => { + this.setState({ + open: false, + }); + }; + + render() { + return ( +
+ + + + + + + + + +
+ ); + } +} + +interface PopoverExampleConfigurableState { + open?: boolean; + anchorOrigin?: __MaterialUI.propTypes.origin; + targetOrigin?: __MaterialUI.propTypes.origin; + anchorEl?: React.ReactInstance; +} + +class PopoverExampleConfigurable extends React.Component<{}, PopoverExampleConfigurableState> { + + constructor(props) { + super(props); + + this.state = { + open: false, + anchorOrigin: { + horizontal: 'left', + vertical: 'bottom', + }, + targetOrigin: { + horizontal: 'left', + vertical: 'top', + }, + }; + } + + handleTouchTap = (event) => { + // This prevents ghost click. + event.preventDefault(); + this.setState({ + open: true, + anchorEl: event.currentTarget, + }); + }; + + handleRequestClose = () => { + this.setState({ + open: false, + }); + }; + + setAnchor = (positionElement, position) => { + const {anchorOrigin} = this.state; + anchorOrigin[positionElement] = position; + + this.setState({ + anchorOrigin: anchorOrigin, + }); + }; + + setTarget = (positionElement, position) => { + const {targetOrigin} = this.state; + targetOrigin[positionElement] = position; + + this.setState({ + targetOrigin: targetOrigin, + }); + }; + + render() { + return ( +
+ +

Current Settings

+
+          anchorOrigin: {JSON.stringify(this.state.anchorOrigin)}
+          
+ targetOrigin: {JSON.stringify(this.state.targetOrigin)} +
+

Position Options

+

Use the settings below to toggle the positioning of the popovers above

+

Anchor Origin

+
+
+ Vertical + + + +
+
+ Horizontal + + + +
+
+

Target Origin

+
+
+ Vertical + + + +
+
+ Horizontal + + + +
+
+ + + + + + + + +
+ ); + } +} + + +// "http://www.material-ui.com/#/components/circular-progress" +const CircularProgressExampleSimple = () => ( +
+ + + +
+); + +class CircularProgressExampleDeterminate extends React.Component<{}, {completed?: number}> { + private timer: number; + + constructor(props) { + super(props); + + this.state = { + completed: 0, + }; + } + + componentDidMount() { + this.timer = setTimeout(() => this.progress(5), 1000); + } + + componentWillUnmount() { + clearTimeout(this.timer); + } + + progress(completed) { + if (completed > 100) { + this.setState({completed: 100}); + } else { + this.setState({completed}); + const diff = Math.random() * 10; + this.timer = setTimeout(() => this.progress(completed + diff), 1000); + } + } + + render() { + return ( +
+ + + +
+ ); + } +} + + +// "http://www.material-ui.com/#/components/linear-progress" +const LinearProgressExampleSimple = () => ( + +); + +class LinearProgressExampleDeterminate extends React.Component<{}, {completed?: number}> { + private timer: number; + + constructor(props) { + super(props); + + this.state = { + completed: 0, + }; + } + + componentDidMount() { + this.timer = setTimeout(() => this.progress(5), 1000); + } + + componentWillUnmount() { + clearTimeout(this.timer); + } + + progress(completed) { + if (completed > 100) { + this.setState({completed: 100}); + } else { + this.setState({completed}); + const diff = Math.random() * 10; + this.timer = setTimeout(() => this.progress(completed + diff), 1000); + } + } + + render() { + return ( + + ); + } +} + + +// "http://www.material-ui.com/#/components/refresh-indicator" +const RefreshIndicatorExampleSimple = () => ( +
+ + + + +
+); + +const RefreshIndicatorExampleLoading = () => ( +
+ + +
+); + + +// "http://www.material-ui.com/#/components/select-field" +class SelectFieldExampleSimple extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: 1}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( +
+ + + + + + + +
+ + + + +
+ + + + + + + +
+ + + + + + + +
+ ); + } +} + +class SelectFieldLongMenuExample extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: 10}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( + + {items} + + ); + } +} + +class SelectFieldExampleCustomLabel extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: 1}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( + + + + + + + ); + } +} + +const itemsPeriod = [ + , + , + , + , + , +]; + +export default class SelectFieldExampleFloatingLabel extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: null}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( +
+ + {itemsPeriod} + +
+ + {itemsPeriod} + +
+ ); + } +} + +class SelectFieldExampleError extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = {value: null}; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + const {value} = this.state; + + const night = value === 2 || value === 3; + + return ( +
+ + {itemsPeriod} + +
+ + {itemsPeriod} + +
+ ); + } +} + + +// "http://www.material-ui.com/#/components/slider" +const SliderExampleSimple = () => ( +
+ + + +
+); + +const SliderExampleDisabled = () => ( +
+ + + +
+); + +const SliderExampleStep = () => ( + +); + +class SliderExampleControlled extends React.Component<{}, {firstSlider?: number, secondSlider?: number}> { + + state = { + firstSlider: 0.5, + secondSlider: 50, + } + + handleFirstSlider(event, value) { + this.setState({firstSlider: value}); + } + + handleSecondSlider(event, value) { + this.setState({secondSlider: value}); + } + + render() { + return ( +
+ +

+ {'The value of this slider is: '} + {this.state.firstSlider} + {' from a range of 0 to 1 inclusive'} +

+ +

+ {'The value of this slider is: '} + {this.state.secondSlider} + {' from a range of 0 to 100 inclusive'} +

+
+ ); + } +} + + +// "http://www.material-ui.com/#/components/checkbox" +const CheckboxExampleSimple = () => ( +
+ + + } + uncheckedIcon={} + label="Custom icon" + style={styles.checkbox} + /> + + + +
+); + + +// "http://www.material-ui.com/#/components/radio-button" +const RadioButtonExampleSimple = () => ( +
+ + + + } + uncheckedIcon={} + style={styles.radioButton} + /> + + + + + + + + +
+); + + +// "http://www.material-ui.com/#/components/toggle" +const ToggleExampleSimple = () => ( +
+ + + + +
+); + + +// "http://material-ui.com/#/components/snackbar" +class SnackbarExampleSimple extends React.Component<{}, {open?: boolean}> { + + constructor(props) { + super(props); + this.state = { + open: false, + }; + } + + handleTouchTap = () => { + this.setState({ + open: true, + }); + }; + + handleRequestClose = () => { + this.setState({ + open: false, + }); + }; + + render() { + return ( +
+ + +
+ ); + } +} + +class SnackbarExampleAction extends React.Component<{}, {open?: boolean, autoHideDuration?: number, message?: string}> { + + constructor(props) { + super(props); + this.state = { + autoHideDuration: 4000, + message: 'Event added to your calendar', + open: false, + }; + } + + handleTouchTap = () => { + this.setState({ + open: true, + }); + }; + + handleActionTouchTap = () => { + this.setState({ + open: false, + }); + alert('Event removed from your calendar.'); + }; + + handleChangeDuration = (event) => { + const value = event.target.value; + this.setState({ + autoHideDuration: value.length > 0 ? parseInt(value) : 0, + }); + }; + + handleRequestClose = () => { + this.setState({ + open: false, + }); + }; + + render() { + return ( +
+ +
+ + +
+ ); + } +} + +class SnackbarExampleTwice extends React.Component<{}, {open?: boolean, message?: string}> { + + private timer: number; + + constructor(props) { + super(props); + this.state = { + message: 'Event 1 added to your calendar', + open: false, + }; + this.timer = undefined; + } + + componentWillUnMount() { + clearTimeout(this.timer); + } + + handleTouchTap = () => { + this.setState({ + open: true, + }); + + this.timer = setTimeout(() => { + this.setState({ + message: `Event ${Math.round(Math.random() * 100)} added to your calendar`, + }); + }, 1500); + }; + + handleRequestClose = () => { + this.setState({ + open: false, + }); + }; + + render() { + return ( +
+ + +
+ ); + } +} + + +// "http://www.material-ui.com/#/components/stepper" +class HorizontalLinearStepper extends React.Component<{}, {stepIndex?: number, finished?: boolean}> { + + state = { + finished: false, + stepIndex: 0, + }; + + handleNext = () => { + const {stepIndex} = this.state; + this.setState({ + stepIndex: stepIndex + 1, + finished: stepIndex >= 2, + }); + }; + + handlePrev = () => { + const {stepIndex} = this.state; + if (stepIndex > 0) { + this.setState({stepIndex: stepIndex - 1}); + } + }; + + getStepContent(stepIndex) { + switch (stepIndex) { + case 0: + return 'Select campaign settings...'; + case 1: + return 'What is an ad group anyways?'; + case 2: + return 'This is the bit I really care about!'; + default: + return 'You\'re a long way from home sonny jim!'; + } + } + + render() { + const {finished, stepIndex} = this.state; + const contentStyle = {margin: '0 16px'}; + + return ( +
+ + + Select campaign settings + + + Create an ad group + + + Create an ad + + +
+ {finished ? ( +

+ { + event.preventDefault(); + this.setState({stepIndex: 0, finished: false}); + }} + > + Click here + to reset the example. +

+ ) : ( +
+

{this.getStepContent(stepIndex)}

+
+ + +
+
+ )} +
+
+ ); + } +} + +class VerticalLinearStepper extends React.Component<{}, {stepIndex?: number, finished?: boolean}> { + + state = { + finished: false, + stepIndex: 0, + }; + + handleNext = () => { + const {stepIndex} = this.state; + this.setState({ + stepIndex: stepIndex + 1, + finished: stepIndex >= 2, + }); + }; + + handlePrev = () => { + const {stepIndex} = this.state; + if (stepIndex > 0) { + this.setState({stepIndex: stepIndex - 1}); + } + }; + + renderStepActions(step) { + const {stepIndex} = this.state; + + return ( +
+ + {step > 0 && ( + + )} +
+ ); + } + + render() { + const {finished, stepIndex} = this.state; + + return ( +
+ + + Select campaign settings + +

+ For each ad campaign that you create, you can control how much + you're willing to spend on clicks and conversions, which networks + and geographical locations you want your ads to show on, and more. +

+ {this.renderStepActions(0)} +
+
+ + Create an ad group + +

An ad group contains one or more ads which target a shared set of keywords.

+ {this.renderStepActions(1)} +
+
+ + Create an ad + +

+ Try out different ad text to see what brings in the most customers, + and learn how to enhance your ads using features like ad extensions. + If you run into any problems with your ads, find out how to tell if + they're running and how to resolve approval issues. +

+ {this.renderStepActions(2)} +
+
+
+ {finished && ( +

+ { + event.preventDefault(); + this.setState({stepIndex: 0, finished: false}); + }} + > + Click here + to reset the example. +

+ )} +
+ ); + } +} + +class HorizontalNonLinearStepper extends React.Component<{}, {stepIndex?: number}> { + + state = { + stepIndex: 0, + }; + + handleNext = () => { + const {stepIndex} = this.state; + if (stepIndex < 2) { + this.setState({stepIndex: stepIndex + 1}); + } + }; + + handlePrev = () => { + const {stepIndex} = this.state; + if (stepIndex > 0) { + this.setState({stepIndex: stepIndex - 1}); + } + }; + + getStepContent(stepIndex) { + switch (stepIndex) { + case 0: + return 'Select campaign settings...'; + case 1: + return 'What is an ad group anyways?'; + case 2: + return 'This is the bit I really care about!'; + default: + return 'You\'re a long way from home sonny jim!'; + } + } + + render() { + const {stepIndex} = this.state; + const contentStyle = {margin: '0 16px'}; + + return ( +
+ + + this.setState({stepIndex: 0})}> + Select campaign settings + + + + this.setState({stepIndex: 1})}> + Create an ad group + + + + this.setState({stepIndex: 2})}> + Create an ad + + + +
+

{this.getStepContent(stepIndex)}

+
+ + +
+
+
+ ); + } +} + +class VerticalNonLinear extends React.Component<{}, {stepIndex?: number}> { + + state = { + stepIndex: 0, + }; + + handleNext = () => { + const {stepIndex} = this.state; + if (stepIndex < 2) { + this.setState({stepIndex: stepIndex + 1}); + } + }; + + handlePrev = () => { + const {stepIndex} = this.state; + if (stepIndex > 0) { + this.setState({stepIndex: stepIndex - 1}); + } + }; + + renderStepActions(step) { + return ( +
+ + {step > 0 && ( + + )} +
+ ); + } + + render() { + const {stepIndex} = this.state; + + return ( +
+ + + this.setState({stepIndex: 0})}> + Select campaign settings + + +

+ For each ad campaign that you create, you can control how much + you're willing to spend on clicks and conversions, which networks + and geographical locations you want your ads to show on, and more. +

+ {this.renderStepActions(0)} +
+
+ + this.setState({stepIndex: 1})}> + Create an ad group + + +

An ad group contains one or more ads which target a shared set of keywords.

+ {this.renderStepActions(1)} +
+
+ + this.setState({stepIndex: 2})}> + Create an ad + + +

+ Try out different ad text to see what brings in the most customers, + and learn how to enhance your ads using features like ad extensions. + If you run into any problems with your ads, find out how to tell if + they're running and how to resolve approval issues. +

+ {this.renderStepActions(2)} +
+
+
+
+ ); + } +} + +const getStyles = () => { + return { + root: { + width: '100%', + maxWidth: 700, + margin: 'auto', + }, + content: { + margin: '0 16px', + }, + actions: { + marginTop: 12, + }, + backButton: { + marginRight: 12, + }, + }; +}; + +class GranularControlStepper extends React.Component<{}, {stepIndex?: number, visited?: number[]}> { + + state = { + stepIndex: null, + visited: [], + }; + + componentWillMount() { + const {stepIndex, visited} = this.state; + this.setState({visited: visited.concat(stepIndex)}); + } + + componentWillUpdate(nextProps, nextState) { + const {stepIndex, visited} = nextState; + if (visited.indexOf(stepIndex) === -1) { + this.setState({visited: visited.concat(stepIndex)}); + } + } + + handleNext = () => { + const {stepIndex} = this.state; + if (stepIndex < 2) { + this.setState({stepIndex: stepIndex + 1}); + } + }; + + handlePrev = () => { + const {stepIndex} = this.state; + if (stepIndex > 0) { + this.setState({stepIndex: stepIndex - 1}); + } + }; + + getStepContent(stepIndex) { + switch (stepIndex) { + case 0: + return 'Select campaign settings...'; + case 1: + return 'What is an ad group anyways?'; + case 2: + return 'This is the bit I really care about!'; + default: + return 'Click a step to get started.'; + } + } + + render() { + const {stepIndex, visited} = this.state; + const styles = getStyles(); + + return ( +
+

+ { + event.preventDefault(); + this.setState({stepIndex: null, visited: []}); + }} + > + Click here + to reset the example. +

+ + + this.setState({stepIndex: 0})}> + Select campaign settings + + + + this.setState({stepIndex: 1})}> + Create an ad group + + + + this.setState({stepIndex: 2})}> + Create an ad + + + +
+

{this.getStepContent(stepIndex)}

+ {stepIndex !== null && ( +
+ + +
+ )} +
+
+ ); + } +} + +class CustomIcon extends React.Component<{}, {stepIndex?: number}> { + + state = { + stepIndex: 0, + }; + + handleNext = () => { + const {stepIndex} = this.state; + if (stepIndex < 2) { + this.setState({stepIndex: stepIndex + 1}); + } + }; + + handlePrev = () => { + const {stepIndex} = this.state; + if (stepIndex > 0) { + this.setState({stepIndex: stepIndex - 1}); + } + }; + + getStepContent(stepIndex) { + switch (stepIndex) { + case 0: + return 'Select campaign settings...'; + case 1: + return 'What is an ad group anyways?'; + case 2: + return 'This is the bit I really care about!'; + default: + return 'You\'re a long way from home sonny jim!'; + } + } + + render() { + return ( +
+ + + + Select campaign settings + + + + } + style={{color: red500}} + > + Create an ad group + + + + + Create an ad + + + +
+ ); + } +} + + +// "http://www.material-ui.com/#/components/subheader" +// Included in ListExampleChat and ListExampleFolder + +// "http://www.material-ui.com/#/components/table" +const TableExampleSimple = () => ( + + + + ID + Name + Status + + + + + 1 + John Smith + Employed + + + 2 + Randal White + Unemployed + + + 3 + Stephanie Sanders + Employed + + + 4 + Steve Brown + Employed + + +
+); + +const tableData: {name: string, status: string, selected?: boolean}[] = [ + { + name: 'John Smith', + status: 'Employed', + selected: true, + }, + { + name: 'Randal White', + status: 'Unemployed', + }, + { + name: 'Stephanie Sanders', + status: 'Employed', + selected: true, + }, + { + name: 'Steve Brown', + status: 'Employed', + }, + { + name: 'Joyce Whitten', + status: 'Employed', + }, + { + name: 'Samuel Roberts', + status: 'Employed', + }, + { + name: 'Adam Moore', + status: 'Employed', + }, +]; + +interface TableExampleComplexState { + fixedHeader?: boolean, + fixedFooter?: boolean, + stripedRows?: boolean, + showRowHover?: boolean, + selectable?: boolean, + multiSelectable?: boolean, + enableSelectAll?: boolean, + deselectOnClickaway?: boolean, + showCheckboxes?: boolean, + height?: string, +} + +class TableExampleComplex extends React.Component<{}, TableExampleComplexState> { + + constructor(props) { + super(props); + + this.state = { + fixedHeader: true, + fixedFooter: true, + stripedRows: false, + showRowHover: false, + selectable: true, + multiSelectable: false, + enableSelectAll: false, + deselectOnClickaway: true, + showCheckboxes: true, + height: '300px', + }; + } + + handleToggle = (event, toggled) => { + this.setState({ + [event.target.name]: toggled, + }); + }; + + handleChange = (event) => { + this.setState({height: event.target.value}); + }; + + render() { + return ( +
+ + + + + Super Header + + + + ID + Name + Status + + + + {tableData.map( (row, index) => ( + + {index} + {row.name} + {row.status} + + ))} + + + + ID + Name + Status + + + + Super Footer + + + +
+ +
+

Table Properties

+ + + + + + +

TableBody Properties

+ + + +

Multiple Properties

+ +
+
+ ); + } +} + +// "http://www.material-ui.com/#/components/tabs" +function handleActive(tab) { + alert(`A tab with this value property ${tab.props.value} was activated.`); +} + +const TabsExampleSimple = () => ( + + +
+

Tab One

+

+ This is an example tab. +

+

+ You can put any sort of HTML or react component in here. It even keeps the component state! +

+ +
+
+ +
+

Tab Two

+

+ This is another example tab. +

+
+
+ +
+

Tab Three

+

+ This is a third example tab. +

+
+
+
+); + +class TabsExampleControlled extends React.Component<{}, {value?: string}> { + + constructor(props) { + super(props); + this.state = { + value: 'a', + }; + } + + handleChange = (value) => { + this.setState({ + value: value, + }); + }; + + render() { + return ( + + +
+

Controllable Tab A

+

+ Tabs are also controllable if you want to programmatically pass them their values. + This allows for more functionality in Tabs such as not + having any Tab selected or assigning them different values. +

+
+
+ +
+

Controllable Tab B

+

+ This is another example of a controllable tab. Remember, if you + use controllable Tabs, you need to give all of your tabs values or else + you wont be able to select them. +

+
+
+
+ ); + } +} + +const TabsExampleIcon = () => ( + + } /> + } /> + favorite} /> + +); + +const TabsExampleIconText = () => ( + + phone} + label="RECENTS" + /> + favorite} + label="FAVORITES" + /> + } + label="NEARBY" + /> + +); + + +// "http://www.material-ui.com/#/components/text-field" +const TextFieldExampleSimple = () => ( +
+
+
+
+
+
+
+
+
+
+ +
+); + +const TextFieldExampleError = () => ( +
+
+
+
+
+
+); + +const TextFieldExampleCustomize = () => ( +
+
+
+
+
+ +
+); + +const TextFieldExampleDisabled = () => ( +
+
+
+
+ +
+); + +class TextFieldExampleControlled extends React.Component<{}, {value?: string}> { + + constructor(props) { + super(props); + + this.state = { + value: 'Property Value', + }; + } + + handleChange = (event) => { + this.setState({ + value: event.target.value, + }); + }; + + render() { + return ( +
+ +
+ ); + } +} + +// "http://www.material-ui.com/#/components/time-picker" +const TimePickerExampleSimple = () => ( +
+ + + +
+); + +class TimePickerExampleComplex extends React.Component<{}, {value24?: Date, value12?: Date}> { + + constructor(props) { + super(props); + this.state = {value24: null, value12: null}; + } + + handleChangeTimePicker24 = (event, date) => { + this.setState({value24: date}); + }; + + handleChangeTimePicker12 = (event, date) => { + this.setState({value12: date}); + }; + + render() { + return ( +
+ + +
+ ); + } +} + +const TimePickerInternational = () => ( +
+ +
+); + + +// "http://www.material-ui.com/#/components/toolbar" +class ToolbarExamplesSimple extends React.Component<{}, {value?: number}> { + + constructor(props) { + super(props); + this.state = { + value: 3, + }; + } + + handleChange = (event, index, value) => this.setState({value}); + + render() { + return ( + + + + + + + + + + + + + + + + + + + + + } + > + + + + + + ); + } +} + +const componentWithWidth = withWidth()(ToolbarExamplesSimple); + + +interface MaterialUiTestsState { +} + +class MaterialUiTests extends React.Component<{}, MaterialUiTestsState> { + + render () { + return ( + + + + + ); + } +} + +// "http://www.material-ui.com/#/get-started/usage" +ReactDOM.render( + , + document.getElementById('app') +); diff --git a/material-ui/legacy/material-ui-0.15.1-tests.tsx.tscparams b/material-ui/legacy/material-ui-0.15.1-tests.tsx.tscparams new file mode 100644 index 0000000000..855355b85f --- /dev/null +++ b/material-ui/legacy/material-ui-0.15.1-tests.tsx.tscparams @@ -0,0 +1 @@ +--experimentalDecorators \ No newline at end of file diff --git a/material-ui/legacy/material-ui-0.15.1.d.ts b/material-ui/legacy/material-ui-0.15.1.d.ts new file mode 100644 index 0000000000..b5ec61b14b --- /dev/null +++ b/material-ui/legacy/material-ui-0.15.1.d.ts @@ -0,0 +1,8630 @@ +// Type definitions for material-ui v0.15.1 +// Project: https://github.com/callemall/material-ui +// Definitions by: Nathan Brown , Oliver Herrmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "material-ui" { + export import AppBar = __MaterialUI.AppBar; + export import AutoComplete = __MaterialUI.AutoComplete; + export import Avatar = __MaterialUI.Avatar; + export import Badge = __MaterialUI.Badge; + export import Card = __MaterialUI.Card.Card; + export import CardActions = __MaterialUI.Card.CardActions; + export import CardHeader = __MaterialUI.Card.CardHeader; + export import CardMedia = __MaterialUI.Card.CardMedia; + export import CardText = __MaterialUI.Card.CardText; + export import CardTitle = __MaterialUI.Card.CardTitle; + export import Checkbox = __MaterialUI.Switches.Checkbox; + export import Chip = __MaterialUI.Chip; + export import CircularProgress = __MaterialUI.CircularProgress; + export import DatePicker = __MaterialUI.DatePicker.DatePicker; + export import Dialog = __MaterialUI.Dialog; + export import Divider = __MaterialUI.Divider; + export import Drawer = __MaterialUI.Drawer; + export import DropDownMenu = __MaterialUI.Menus.DropDownMenu; + export import FlatButton = __MaterialUI.FlatButton; + export import FloatingActionButton = __MaterialUI.FloatingActionButton; + export import FontIcon = __MaterialUI.FontIcon; + export import GridList = __MaterialUI.GridList.GridList; + export import GridTile = __MaterialUI.GridList.GridTile; + export import IconButton = __MaterialUI.IconButton; + export import IconMenu = __MaterialUI.Menus.IconMenu; + export import LinearProgress = __MaterialUI.LinearProgress; + export import List = __MaterialUI.List.List; + export import ListItem = __MaterialUI.List.ListItem; + export import MakeSelectable = __MaterialUI.List.MakeSelectable; + export import Menu = __MaterialUI.Menus.Menu; + export import MenuItem = __MaterialUI.Menus.MenuItem; + export import Paper = __MaterialUI.Paper; + export import Popover = __MaterialUI.Popover.Popover; + export import RadioButton = __MaterialUI.Switches.RadioButton; + export import RadioButtonGroup = __MaterialUI.Switches.RadioButtonGroup; + export import RaisedButton = __MaterialUI.RaisedButton; + export import RefreshIndicator = __MaterialUI.RefreshIndicator; + export import SelectField = __MaterialUI.SelectField; + export import Slider = __MaterialUI.Slider; + export import Subheader = __MaterialUI.Subheader; + export import SvgIcon = __MaterialUI.SvgIcon; + export import Step = __MaterialUI.Stepper.Step; + export import StepButton = __MaterialUI.Stepper.StepButton; + export import StepContent = __MaterialUI.Stepper.StepContent; + export import StepLabel = __MaterialUI.Stepper.StepLabel; + export import Stepper = __MaterialUI.Stepper; + export import Snackbar = __MaterialUI.Snackbar; + export import Tab = __MaterialUI.Tabs.Tab; + export import Tabs = __MaterialUI.Tabs.Tabs; + export import Table = __MaterialUI.Table.Table; + export import TableBody = __MaterialUI.Table.TableBody; + export import TableFooter = __MaterialUI.Table.TableFooter; + export import TableHeader = __MaterialUI.Table.TableHeader; + export import TableHeaderColumn = __MaterialUI.Table.TableHeaderColumn; + export import TableRow = __MaterialUI.Table.TableRow; + export import TableRowColumn = __MaterialUI.Table.TableRowColumn; + export import TextField = __MaterialUI.TextField; + export import TimePicker = __MaterialUI.TimePicker; + export import Toggle = __MaterialUI.Switches.Toggle; + export import Toolbar = __MaterialUI.Toolbar.Toolbar; + export import ToolbarGroup = __MaterialUI.Toolbar.ToolbarGroup; + export import ToolbarSeparator = __MaterialUI.Toolbar.ToolbarSeparator; + export import ToolbarTitle = __MaterialUI.Toolbar.ToolbarTitle; + + // export type definitions + export type TouchTapEvent = __MaterialUI.TouchTapEvent; + export type TouchTapEventHandler = __MaterialUI.TouchTapEventHandler; +} + +declare namespace __MaterialUI { + export import React = __React; + + // ReactLink is from "react/addons" + interface ReactLink { + value: T; + requestChange(newValue: T): void; + } + + // What's common between React.TouchEvent and React.MouseEvent + interface TouchTapEvent extends React.SyntheticEvent { + altKey: boolean; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + shiftKey: boolean; + } + + // What's common between React.TouchEventHandler and React.MouseEventHandler + interface TouchTapEventHandler extends React.EventHandler { } + + interface ThemeWrapperProps extends React.Props { + theme: Styles.MuiTheme; + } + export class ThemeWrapper extends React.Component { + } + + export namespace Styles { + interface Spacing { + iconSize?: number; + + desktopGutter?: number; + desktopGutterMore?: number; + desktopGutterLess?: number; + desktopGutterMini?: number; + desktopKeylineIncrement?: number; + desktopDropDownMenuItemHeight?: number; + desktopDropDownMenuFontSize?: number; + desktopLeftNavMenuItemHeight?: number; + desktopSubheaderHeight?: number; + desktopToolbarHeight?: number; + } + export var Spacing: Spacing; + + interface ThemePalette { + primary1Color?: string; + primary2Color?: string; + primary3Color?: string; + accent1Color?: string; + accent2Color?: string; + accent3Color?: string; + textColor?: string; + alternateTextColor?: string; + canvasColor?: string; + borderColor?: string; + disabledColor?: string; + pickerHeaderColor?: string; + clockCircleColor?: string; + shadowColor?: string; + } + export var ThemePalette: ThemePalette; + interface MuiTheme { + spacing?: Spacing; + fontFamily?: string; + palette?: ThemePalette; + isRtl?: boolean; + userAgent?: string; + zIndex?: zIndex; + baseTheme?: RawTheme; + rawTheme?: RawTheme; + appBar?: { + color?: string; + textColor?: string; + height?: number; + titleFontWeight?: number; + padding?: number; + }; + avatar?: { + color?: string; + backgroundColor?: string; + borderColor?: string; + }; + badge?: { + color?: string; + textColor?: string; + primaryColor?: string; + primaryTextColor?: string; + secondaryColor?: string; + secondaryTextColor?: string; + fontWeight?: number; + }; + button?: { + height?: number; + minWidth?: number; + iconButtonSize?: number; + }; + card?: { + titleColor?: string; + subtitleColor?: string; + fontWeight?: number; + }; + cardMedia?: { + color?: string; + overlayContentBackground?: string; + titleColor?: string; + subtitleColor?: string; + }; + cardText?: { + textColor?: string; + }; + checkbox?: { + boxColor?: string; + checkedColor?: string; + requiredColor?: string; + disabledColor?: string; + labelColor?: string; + labelDisabledColor?: string; + }; + chip?: { + backgroundColor?: string; + deleteIconColor?: string; + textColor?: string; + fontSize?: number; + fontWeight?: number; + shadow?: string; + }; + datePicker?: { + color?: string; + textColor?: string; + calendarTextColor?: string; + selectColor?: string; + selectTextColor?: string; + calendarYearBackgroundColor?: string; + }; + dialog?: { + titleFontSize?: number; + bodyFontSize?: number; + bodyColor?: string; + }; + dropDownMenu?: { + accentColor?: string; + }; + enhancedButton?: { + tapHighlightColor?: string; + }; + flatButton?: { + color?: string; + buttonFilterColor?: string; + disabledTextColor?: string; + textColor?: string; + primaryTextColor?: string; + secondaryTextColor?: string; + fontSize?: number; + fontWeight?: number; + }; + floatingActionButton?: { + buttonSize?: number; + miniSize?: number; + color?: string; + iconColor?: string; + secondaryColor?: string; + secondaryIconColor?: string; + disabledTextColor?: string; + disabledColor?: string; + }; + gridTile?: { + textColor?: string; + }; + icon?: { + color?: string; + backgroundColor?: string; + }; + inkBar?: { + backgroundColor?: string; + }; + drawer?: { + width?: number; + color?: string; + }; + listItem?: { + nestedLevelDepth?: number; + secondaryTextColor?: string; + leftIconColor?: string; + rightIconColor?: string; + }; + menu?: { + backgroundColor?: string; + containerBackgroundColor?: string; + }; + menuItem?: { + dataHeight?: number; + height?: number; + hoverColor?: string; + padding?: number; + selectedTextColor?: string; + rightIconDesktopFill?: string; + }; + menuSubheader?: { + padding?: number; + borderColor?: string; + textColor?: string; + }; + overlay?: { + backgroundColor?: string; + }; + paper?: { + color?: string; + backgroundColor?: string; + zDepthShadows?: string[]; + }; + radioButton?: { + borderColor?: string; + backgroundColor?: string; + checkedColor?: string; + requiredColor?: string; + disabledColor?: string; + size?: number; + labelColor?: string; + labelDisabledColor?: string; + }; + raisedButton?: { + color?: string; + textColor?: string; + primaryColor?: string; + primaryTextColor?: string; + secondaryColor?: string; + secondaryTextColor?: string; + disabledColor?: string; + disabledTextColor?: string; + fontSize?: number; + fontWeight?: number; + }; + refreshIndicator?: { + strokeColor?: string; + loadingStrokeColor?: string; + }; + ripple?: { + color?: string; + }; + slider?: { + trackSize?: number; + trackColor?: string; + trackColorSelected?: string; + handleSize?: number; + handleSizeDisabled?: number; + handleSizeActive?: number; + handleColorZero?: string; + handleFillColor?: string; + selectionColor?: string; + rippleColor?: string; + }; + snackbar?: { + textColor?: string; + backgroundColor?: string; + actionColor?: string; + }; + subheader?: { + color?: string; + fontWeight?: number; + }; + stepper?: { + backgroundColor?: string; + hoverBackgroundColor?: string; + iconColor?: string; + hoveredIconColor?: string; + inactiveIconColor?: string; + textColor?: string; + disabledTextColor?: string; + connectorLineColor?: string; + }; + svgIcon?: { + color?: string, + }; + table?: { + backgroundColor?: string; + }; + tableFooter?: { + borderColor?: string; + textColor?: string; + }; + tableHeader?: { + borderColor?: string; + }; + tableHeaderColumn?: { + textColor?: string; + height?: number; + spacing?: number; + }; + tableRow?: { + hoverColor?: string; + stripeColor?: string; + selectedColor?: string; + textColor?: string; + borderColor?: string; + height?: number; + }; + tableRowColumn?: { + height?: number; + spacing?: number; + }; + tabs?: { + backgroundColor?: string; + textColor?: string; + selectedTextColor?: string; + }; + textField?: { + textColor?: string; + hintColor?: string; + floatingLabelColor?: string; + disabledTextColor?: string; + errorColor?: string; + focusColor?: string; + backgroundColor?: string; + borderColor?: string; + }; + timePicker?: { + color?: string; + textColor?: string; + accentColor?: string; + clockColor?: string; + clockCircleColor?: string; + headerColor?: string; + selectColor?: string; + selectTextColor?: string; + }; + toggle?: { + thumbOnColor?: string; + thumbOffColor?: string; + thumbDisabledColor?: string; + thumbRequiredColor?: string; + trackOnColor?: string; + trackOffColor?: string; + trackDisabledColor?: string; + labelColor?: string; + labelDisabledColor?: string; + trackRequiredColor?: string; + }; + toolbar?: { + color?: string; + hoverColor?: string; + backgroundColor?: string; + height?: number; + titleFontSize?: number; + iconColor?: string; + separatorColor?: string; + menuHoverColor?: string; + }; + tooltip?: { + color?: string; + rippleBackgroundColor?: string; + }; + } + + interface zIndex { + menu: number; + appBar: number; + drawerOverlay: number; + drawer: number; + dialogOverlay: number; + dialog: number; + layer: number; + popover: number; + snackbar: number; + tooltip: number; + } + export var zIndex: zIndex; + + interface RawTheme { + spacing?: Spacing; + fontFamily?: string; + palette?: ThemePalette; + } + var lightBaseTheme: RawTheme; + var darkBaseTheme: RawTheme; + + export function muiThemeable, P, S>(): (component: TComponent) => TComponent; + + //** @deprecated use MuiThemeProvider instead **/ + export function themeDecorator(muiTheme: Styles.MuiTheme): (Component: TFunction) => TFunction; + + interface MuiThemeProviderProps extends React.Props { + muiTheme?: Styles.MuiTheme; + } + export class MuiThemeProvider extends React.Component{ + } + + export function getMuiTheme(...muiTheme: MuiTheme[]): MuiTheme; + + interface ThemeManager { + //** @deprecated ThemeManager is deprecated. please import getMuiTheme directly from "material-ui/styles/getMuiTheme" **/ + getMuiTheme(baseTheme: RawTheme, muiTheme?: MuiTheme): MuiTheme; + + //** @deprecated modifyRawThemeSpacing is deprecated. please use getMuiTheme to modify your theme directly. http://www.material-ui.com/#/customization/themes **/ + modifyRawThemeSpacing(muiTheme: MuiTheme, newSpacing: Spacing): MuiTheme; + + //** @deprecated modifyRawThemePalette is deprecated. please use getMuiTheme to modify your theme directly. http://www.material-ui.com/#/customization/themes **/ + modifyRawThemePalette(muiTheme: MuiTheme, newPaletteKeys: ThemePalette): MuiTheme; + + //** @deprecated modifyRawThemeFontFamily is deprecated. please use getMuiTheme to modify your theme directly. http://www.material-ui.com/#/customization/themes **/ + modifyRawThemeFontFamily(muiTheme: MuiTheme, newFontFamily: string): MuiTheme; + } + export var ThemeManager: ThemeManager; + + interface Transitions { + easeOut(duration?: string, property?: string | string[], delay?: string, easeFunction?: string): string; + create(duration?: string, property?: string, delay?: string, easeFunction?: string): string; + easeOutFunction: string; + easeInOutFunction: string; + } + export var Transitions: Transitions; + + interface Typography { + textFullBlack: string; + textDarkBlack: string; + textLightBlack: string; + textMinBlack: string; + textFullWhite: string; + textDarkWhite: string; + textLightWhite: string; + + // font weight + fontWeightLight: number; + fontWeightNormal: number; + fontWeightMedium: number; + + fontStyleButtonFontSize: number; + } + export var Typography: Typography; + + //** @deprecated use darkBaseTheme instead **/ + export var DarkRawTheme: RawTheme; + + //** @deprecated use lightBaseTheme instead **/ + export var LightRawTheme: RawTheme; + } + + interface AppBarProps extends React.Props { + className?: string; + iconClassNameLeft?: string; + iconClassNameRight?: string; + iconElementLeft?: React.ReactElement; + iconElementRight?: React.ReactElement; + iconStyleRight?: React.CSSProperties; + iconStyleLeft?: React.CSSProperties; + onLeftIconButtonTouchTap?: TouchTapEventHandler; + onRightIconButtonTouchTap?: TouchTapEventHandler; + onTitleTouchTap?: TouchTapEventHandler; + showMenuIconButton?: boolean; + style?: React.CSSProperties; + title?: React.ReactNode; + titleStyle?: React.CSSProperties; + zDepth?: number; + } + export class AppBar extends React.Component{ + } + + interface AppCanvasProps extends React.Props { + } + export class AppCanvas extends React.Component { + } + + namespace propTypes { + type horizontal = 'left' | 'middle' | 'right'; + type vertical = 'top' | 'center' | 'bottom'; + type direction = 'left' | 'right' | 'up' | 'down'; + + interface origin { + horizontal: horizontal; + vertical: vertical; + } + + type corners = 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'; + type cornersAndCenter = 'bottom-center' | 'bottom-left' | 'bottom-right' | 'top-center' | 'top-left' | 'top-right'; + } + + type AutoCompleteDataItem = { text: string, value: React.ReactNode } | string; + type AutoCompleteDataSource = { text: string, value: React.ReactNode }[] | string[]; + interface AutoCompleteProps extends React.Props { + anchorOrigin?: propTypes.origin; + animated?: boolean; + dataSource: AutoCompleteDataSource; + disableFocusRipple?: boolean; + errorStyle?: React.CSSProperties; + errorText?: string; + filter?: (searchText: string, key: string, item: AutoCompleteDataItem) => boolean; + floatingLabelText?: React.ReactNode; + fullWidth?: boolean; + hintText?: string; + listStyle?: React.CSSProperties; + maxSearchResults?: number; + menuCloseDelay?: number; + menuProps?: any; + menuStyle?: React.CSSProperties; + onBlur?: React.FocusEventHandler; + onFocus?: React.FocusEventHandler; + onKeyDown?: React.KeyboardEventHandler; + onNewRequest?: (chosenRequest: string, index: number) => void; + onUpdateInput?: (searchText: string, dataSource: AutoCompleteDataSource) => void; + open?: boolean; + openOnFocus?: boolean; + searchText?: string; + style?: React.CSSProperties; + targetOrigin?: propTypes.origin; + /** @deprecated Instead, use openOnFocus */ + triggerUpdateOnFocus?: boolean; + } + export class AutoComplete extends React.Component { + static noFilter: () => boolean; + static defaultFilter: (searchText: string, key: string) => boolean; + static caseSensitiveFilter: (searchText: string, key: string) => boolean; + static caseInsensitiveFilter: (searchText: string, key: string) => boolean; + static levenshteinDistanceFilter(distanceLessThan: number): (searchText: string, key: string) => boolean; + static fuzzyFilter: (searchText: string, key: string) => boolean; + static Item: Menus.MenuItem; + static Divider: Divider; + } + + interface AvatarProps extends React.Props { + backgroundColor?: string; + className?: string; + color?: string; + icon?: React.ReactElement; + size?: number; + src?: string; + style?: React.CSSProperties; + } + export class Avatar extends React.Component { + } + + interface BadgeProps extends React.Props { + badgeContent: React.ReactNode; + badgeStyle?: React.CSSProperties; + className?: string; + primary?: boolean; + secondary?: boolean; + style?: React.CSSProperties; + } + export class Badge extends React.Component { + } + + interface BeforeAfterWrapperProps extends React.Props { + afterElementType?: string; + afterStyle?: React.CSSProperties; + beforeElementType?: string; + beforeStyle?: React.CSSProperties; + elementType?: string; + style?: React.CSSProperties; + } + export class BeforeAfterWrapper extends React.Component { + } + + // non generally overridden elements of EnhancedButton + interface SharedEnhancedButtonProps extends React.Props { + centerRipple?: boolean; + disableFocusRipple?: boolean; + disableKeyboardFocus?: boolean; + disableTouchRipple?: boolean; + focusRippleColor?: string; + focusRippleOpacity?: number; + keyboardFocused?: boolean; + linkButton?: boolean; + onBlur?: React.FocusEventHandler; + onFocus?: React.FocusEventHandler; + onKeyboardFocus?: (e: React.FocusEvent, isKeyboardFocused: boolean) => void; + onKeyDown?: React.KeyboardEventHandler; + onKeyUp?: React.KeyboardEventHandler; + onTouchTap?: TouchTapEventHandler; + onClick?: React.MouseEventHandler; + style?: React.CSSProperties; + tabIndex?: number; + touchRippleColor?: string; + touchRippleOpacity?: number; + type?: string; + containerElement?: React.ReactNode | string; + } + + interface EnhancedButtonProps extends React.HTMLAttributes, SharedEnhancedButtonProps { + // container element,