diff --git a/.gitignore b/.gitignore index 4f0152028d..858238c5bf 100644 --- a/.gitignore +++ b/.gitignore @@ -30,10 +30,12 @@ _infrastructure/tests/build *.iml *.js.map !*.js/ +!scripts/new-package.js +!scripts/lint.js node_modules .sublimets .settings/launch.json - .vscode +yarn.lock \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 48704282ad..4db6a14a5b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - 4 + - 6.9.1 sudo: false diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 44f0d8e9a0..8b263f19ae 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) 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..d3e6c0e27c 100644 --- a/README.md +++ b/README.md @@ -4,36 +4,217 @@ > 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 paste inside of `declarations.d.ts` and follow the steps below. -* See [CONTRIBUTORS.md](CONTRIBUTORS.md) -## Requested definitions +#### Test a new package + +* Add a new file `declarations.d.ts` to your project. +* Add it to the compilation, through `"includes"` or `"files"` in your [tsconfig](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html), +or through a `/// ` declaration in your code. +* Inside `declarations.d.ts`, write `declare module "foo" { }`, then write the module declaration inside. +* Test that your code works. +* *Then*, once you've tested your definitions, make a PR contributing the definition. + + +### 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/rails-actioncable/rails-actioncable-tests.ts b/actioncable/actioncable-tests.ts similarity index 100% rename from rails-actioncable/rails-actioncable-tests.ts rename to actioncable/actioncable-tests.ts diff --git a/rails-actioncable/index.d.ts b/actioncable/index.d.ts similarity index 100% rename from rails-actioncable/index.d.ts rename to actioncable/index.d.ts diff --git a/rails-actioncable/tsconfig.json b/actioncable/tsconfig.json similarity index 90% rename from rails-actioncable/tsconfig.json rename to actioncable/tsconfig.json index 01da174ddf..6767b44330 100644 --- a/rails-actioncable/tsconfig.json +++ b/actioncable/tsconfig.json @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "rails-actioncable-tests.ts" + "actioncable-tests.ts" ] } \ No newline at end of file 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/amqplib/amqplib-0.3.d.ts b/amqplib/amqplib-0.3.d.ts new file mode 100644 index 0000000000..3138f7494e --- /dev/null +++ b/amqplib/amqplib-0.3.d.ts @@ -0,0 +1,219 @@ +// Type definitions for amqplib 0.3.x +// Project: https://github.com/squaremo/amqp.node +// Definitions by: Michael Nahkies , Ab Reitsma +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "amqplib/properties" { + namespace Replies { + interface Empty { + } + interface AssertQueue { + queue: string; + messageCount: number; + consumerCount: number; + } + interface PurgeQueue { + messageCount: number; + } + interface DeleteQueue { + messageCount: number; + } + interface AssertExchange { + exchange: string; + } + interface Consume { + consumerTag: string; + } + } + + namespace Options { + interface AssertQueue { + exclusive?: boolean; + durable?: boolean; + autoDelete?: boolean; + arguments?: any; + messageTtl?: number; + expires?: number; + deadLetterExchange?: string; + deadLetterRoutingKey?: string; + maxLength?: number; + } + interface DeleteQueue { + ifUnused?: boolean; + ifEmpty?: boolean; + } + interface AssertExchange { + durable?: boolean; + internal?: boolean; + autoDelete?: boolean; + alternateExchange?: string; + arguments?: any; + } + interface DeleteExchange { + ifUnused?: boolean; + } + interface Publish { + expiration?: string; + userId?: string; + CC?: string | string[]; + + mandatory?: boolean; + persistent?: boolean; + deliveryMode?: boolean | number; + BCC?: string | string[]; + + contentType?: string; + contentEncoding?: string; + headers?: any; + priority?: number; + correlationId?: string; + replyTo?: string; + messageId?: string; + timestamp?: number; + type?: string; + appId?: string; + } + interface Consume { + consumerTag?: string; + noLocal?: boolean; + noAck?: boolean; + exclusive?: boolean; + priority?: number; + arguments?: any; + } + interface Get { + noAck?: boolean; + } + } + + interface Message { + content: Buffer; + fields: any; + properties: any; + } +} + +declare module "amqplib" { + + import events = require("events"); + import when = require("when"); + import shared = require("amqplib/properties") + export import Replies = shared.Replies; + export import Options = shared.Options; + export import Message = shared.Message; + + interface Connection extends events.EventEmitter { + close(): when.Promise; + createChannel(): when.Promise; + createConfirmChannel(): when.Promise; + } + + interface Channel extends events.EventEmitter { + close(): when.Promise; + + assertQueue(queue: string, options?: Options.AssertQueue): when.Promise; + checkQueue(queue: string): when.Promise; + + deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise; + purgeQueue(queue: string): when.Promise; + + bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; + unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; + + assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise; + checkExchange(exchange: string): when.Promise; + + deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise; + + bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; + unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; + + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; + + consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise; + + cancel(consumerTag: string): when.Promise; + get(queue: string, options?: Options.Get): when.Promise; + + ack(message: Message, allUpTo?: boolean): void; + ackAll(): void; + + nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; + nackAll(requeue?: boolean): void; + reject(message: Message, requeue?: boolean): void; + + prefetch(count: number, global?: boolean): when.Promise; + recover(): when.Promise; + } + + function connect(url: string, socketOptions?: any): when.Promise; +} + +declare module "amqplib/callback_api" { + + import events = require("events"); + import shared = require("amqplib/properties") + export import Replies = shared.Replies; + export import Options = shared.Options; + export import Message = shared.Message; + + interface Connection extends events.EventEmitter { + close(callback?: (err: any) => void): void; + createChannel(callback: (err: any, channel: Channel) => void): void; + createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void; + } + + interface Channel extends events.EventEmitter { + close(callback: (err: any) => void): void; + + assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err:any, ok: Replies.AssertQueue) => void): void; + checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void; + + deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err:any, ok: Replies.DeleteQueue) => void): void; + purgeQueue(queue: string, callback?: (err:any, ok: Replies.PurgeQueue) => void): void; + + bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + + assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void; + checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void; + + deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void; + + bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; + + consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void; + + cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void; + get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void; + + ack(message: Message, allUpTo?: boolean): void; + ackAll(): void; + + nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; + nackAll(requeue?: boolean): void; + reject(message: Message, requeue?: boolean): void; + + prefetch(count: number, global?: boolean): void; + recover(callback?: (err: any, ok: Replies.Empty) => void): void; + } + + interface ConfirmChannel extends Channel { + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; + + waitForConfirms(callback?: (err: any) => void): void; + } + + function connect(callback: (err: any, connection: Connection) => void): void; + function connect(url: string, callback: (err: any, connection: Connection) => void): void; + function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void; +} diff --git a/amqplib/amqplib-tests.ts b/amqplib/amqplib-tests.ts index 07b9ec5402..b17128653a 100644 --- a/amqplib/amqplib-tests.ts +++ b/amqplib/amqplib-tests.ts @@ -1,44 +1,42 @@ - - // promise api tests -import amqp = require("amqplib"); +import amqp = require('amqplib'); -var msg = "Hello World"; +var msg = 'Hello World'; // test promise api -amqp.connect("amqp://localhost") +amqp.connect('amqp://localhost') .then(connection => { return connection.createChannel() - .tap(channel => channel.checkQueue("myQueue")) - .then(channel => channel.sendToQueue("myQueue", new Buffer(msg))) - .ensure(() => connection.close()); + .tap(channel => channel.checkQueue('myQueue')) + .then(channel => channel.sendToQueue('myQueue', new Buffer(msg))) + .finally(() => connection.close()); }); -amqp.connect("amqp://localhost") +amqp.connect('amqp://localhost') .then(connection => { return connection.createChannel() - .tap(channel => channel.checkQueue("myQueue")) - .then(channel => channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString()))) - .ensure(() => connection.close()); + .tap(channel => channel.checkQueue('myQueue')) + .then(channel => channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString()))) + .finally(() => connection.close()); }); // test promise api properties var amqpMessage: amqp.Message; -amqpMessage.properties.contentType = "application/json"; +amqpMessage.properties.contentType = 'application/json'; var amqpAssertExchangeOptions: amqp.Options.AssertExchange; var anqpAssertExchangeReplies: amqp.Replies.AssertExchange; // callback api tests -import amqpcb = require("amqplib/callback_api"); +import amqpcb = require('amqplib/callback_api'); -amqpcb.connect("amqp://localhost", (err, connection) => { +amqpcb.connect('amqp://localhost', (err, connection) => { if(!err) { connection.createChannel((err, channel) => { if (!err) { - channel.assertQueue("myQueue", {}, (err, ok) => { + channel.assertQueue('myQueue', {}, (err, ok) => { if(!err) { - channel.sendToQueue("myQueue", new Buffer(msg)); + channel.sendToQueue('myQueue', new Buffer(msg)); } }); } @@ -46,13 +44,13 @@ amqpcb.connect("amqp://localhost", (err, connection) => { } }); -amqpcb.connect("amqp://localhost", (err, connection) => { +amqpcb.connect('amqp://localhost', (err, connection) => { if(!err) { connection.createChannel((err, channel) => { if (!err) { - channel.assertQueue("myQueue", {}, (err, ok) => { + channel.assertQueue('myQueue', {}, (err, ok) => { if(!err) { - channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString())); + channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString())); } }); } @@ -62,6 +60,6 @@ amqpcb.connect("amqp://localhost", (err, connection) => { // test callback api properties var amqpcbMessage: amqpcb.Message; -amqpcbMessage.properties.contentType = "application/json"; +amqpcbMessage.properties.contentType = 'application/json'; var amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange; -var anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange; \ No newline at end of file +var anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange; diff --git a/amqplib/index.d.ts b/amqplib/index.d.ts index 3138f7494e..b406e00ac0 100644 --- a/amqplib/index.d.ts +++ b/amqplib/index.d.ts @@ -1,13 +1,76 @@ -// Type definitions for amqplib 0.3.x +// Type definitions for amqplib 0.5.x // Project: https://github.com/squaremo/amqp.node -// Definitions by: Michael Nahkies , Ab Reitsma +// Definitions by: Michael Nahkies , Ab Reitsma , Nicolás Fantone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// /// -declare module "amqplib/properties" { - namespace Replies { +declare module 'amqplib' { + import * as Promise from 'bluebird'; + import * as events from 'events'; + import shared = require('amqplib/properties'); + + export import Replies = shared.Replies; + export import Options = shared.Options; + export import Message = shared.Message; + + export interface Connection extends events.EventEmitter { + close(): Promise; + createChannel(): Promise; + createConfirmChannel(): Promise; + } + + export interface Channel extends events.EventEmitter { + close(): Promise; + + assertQueue(queue: string, options?: Options.AssertQueue): Promise; + checkQueue(queue: string): Promise; + + deleteQueue(queue: string, options?: Options.DeleteQueue): Promise; + purgeQueue(queue: string): Promise; + + bindQueue(queue: string, source: string, pattern: string, args?: any): Promise; + unbindQueue(queue: string, source: string, pattern: string, args?: any): Promise; + + assertExchange(exchange: string, type: string, options?: Options.AssertExchange): Promise; + checkExchange(exchange: string): Promise; + + deleteExchange(exchange: string, options?: Options.DeleteExchange): Promise; + + bindExchange(destination: string, source: string, pattern: string, args?: any): Promise; + unbindExchange(destination: string, source: string, pattern: string, args?: any): Promise; + + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; + + consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise; + + cancel(consumerTag: string): Promise; + get(queue: string, options?: Options.Get): Promise; + + ack(message: Message, allUpTo?: boolean): void; + ackAll(): void; + + nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; + nackAll(requeue?: boolean): void; + reject(message: Message, requeue?: boolean): void; + + prefetch(count: number, global?: boolean): Promise; + recover(): Promise; + } + + export interface ConfirmChannel extends Channel { + publish(exchange:string, routingKey:string, content:Buffer, options?:Options.Publish, callback?:(err:any, ok:Replies.Empty) => void):boolean; + sendToQueue(queue:string, content:Buffer, options?:Options.Publish, callback?:(err:any, ok:Replies.Empty) => void):boolean; + + waitForConfirms(): Promise; + } + + export function connect(url: string, socketOptions?: any): Promise; +} + +declare module 'amqplib/properties' { + export namespace Replies { interface Empty { } interface AssertQueue { @@ -29,7 +92,7 @@ declare module "amqplib/properties" { } } - namespace Options { + export namespace Options { interface AssertQueue { exclusive?: boolean; durable?: boolean; @@ -40,6 +103,7 @@ declare module "amqplib/properties" { deadLetterExchange?: string; deadLetterRoutingKey?: string; maxLength?: number; + maxPriority?: number; } interface DeleteQueue { ifUnused?: boolean; @@ -56,7 +120,7 @@ declare module "amqplib/properties" { ifUnused?: boolean; } interface Publish { - expiration?: string; + expiration?: string | number; userId?: string; CC?: string | string[]; @@ -89,92 +153,35 @@ declare module "amqplib/properties" { } } - interface Message { + export interface Message { content: Buffer; fields: any; properties: any; } } -declare module "amqplib" { +declare module 'amqplib/callback_api' { + import events = require('events'); + import shared = require('amqplib/properties') - import events = require("events"); - import when = require("when"); - import shared = require("amqplib/properties") export import Replies = shared.Replies; export import Options = shared.Options; export import Message = shared.Message; - interface Connection extends events.EventEmitter { - close(): when.Promise; - createChannel(): when.Promise; - createConfirmChannel(): when.Promise; - } - - interface Channel extends events.EventEmitter { - close(): when.Promise; - - assertQueue(queue: string, options?: Options.AssertQueue): when.Promise; - checkQueue(queue: string): when.Promise; - - deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise; - purgeQueue(queue: string): when.Promise; - - bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; - unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; - - assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise; - checkExchange(exchange: string): when.Promise; - - deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise; - - bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; - unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; - - publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; - sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - - consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise; - - cancel(consumerTag: string): when.Promise; - get(queue: string, options?: Options.Get): when.Promise; - - ack(message: Message, allUpTo?: boolean): void; - ackAll(): void; - - nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; - nackAll(requeue?: boolean): void; - reject(message: Message, requeue?: boolean): void; - - prefetch(count: number, global?: boolean): when.Promise; - recover(): when.Promise; - } - - function connect(url: string, socketOptions?: any): when.Promise; -} - -declare module "amqplib/callback_api" { - - import events = require("events"); - import shared = require("amqplib/properties") - export import Replies = shared.Replies; - export import Options = shared.Options; - export import Message = shared.Message; - - interface Connection extends events.EventEmitter { + export interface Connection extends events.EventEmitter { close(callback?: (err: any) => void): void; createChannel(callback: (err: any, channel: Channel) => void): void; createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void; } - interface Channel extends events.EventEmitter { + export interface Channel extends events.EventEmitter { close(callback: (err: any) => void): void; - assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err:any, ok: Replies.AssertQueue) => void): void; + assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err: any, ok: Replies.AssertQueue) => void): void; checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void; - deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err:any, ok: Replies.DeleteQueue) => void): void; - purgeQueue(queue: string, callback?: (err:any, ok: Replies.PurgeQueue) => void): void; + deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err: any, ok: Replies.DeleteQueue) => void): void; + purgeQueue(queue: string, callback?: (err: any, ok: Replies.PurgeQueue) => void): void; bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; @@ -206,14 +213,14 @@ declare module "amqplib/callback_api" { recover(callback?: (err: any, ok: Replies.Empty) => void): void; } - interface ConfirmChannel extends Channel { + export interface ConfirmChannel extends Channel { publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; waitForConfirms(callback?: (err: any) => void): void; } - function connect(callback: (err: any, connection: Connection) => void): void; - function connect(url: string, callback: (err: any, connection: Connection) => void): void; - function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void; + export function connect(callback: (err: any, connection: Connection) => void): void; + export function connect(url: string, callback: (err: any, connection: Connection) => void): void; + export function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void; } diff --git a/analytics-node/analytics-node-tests.ts b/analytics-node/analytics-node-tests.ts index 594c15fae6..5207fe560b 100644 --- a/analytics-node/analytics-node-tests.ts +++ b/analytics-node/analytics-node-tests.ts @@ -1,8 +1,8 @@ -import AnalyticsNode = require("analytics-node"); -var analytics: AnalyticsNode.Analytics; +import Analytics = require("analytics-node"); +var analytics: Analytics; function testConfig(): void { - analytics = new AnalyticsNode.Analytics('YOUR_WRITE_KEY', { + analytics = new Analytics('YOUR_WRITE_KEY', { flushAt: 20, flushAfter: 10000 }); diff --git a/analytics-node/index.d.ts b/analytics-node/index.d.ts index 455b13c92b..fa0b8d6426 100644 --- a/analytics-node/index.d.ts +++ b/analytics-node/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andrew Fong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = AnalyticsNode; +export = AnalyticsNode.Analytics; declare namespace AnalyticsNode { diff --git a/angular-animate/tsconfig.json b/angular-animate/tsconfig.json index 81f1a4a364..a76d9cbdb5 100644 --- a/angular-animate/tsconfig.json +++ b/angular-animate/tsconfig.json @@ -13,6 +13,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-clipboard/angular-clipboard-tests.ts b/angular-clipboard/angular-clipboard-tests.ts new file mode 100644 index 0000000000..ccb1c7ce9a --- /dev/null +++ b/angular-clipboard/angular-clipboard-tests.ts @@ -0,0 +1,14 @@ +/// +/// + +import * as angular from "angular"; +import {ClipboardService} from "angular-clipboard"; + +const app = angular.module('testModule', ['angular-clipboard']); +app.controller('TestController', ($scope: ng.IScope, clipboard: ClipboardService) => { + $scope['testCopy'] = () => { + if (clipboard.supported) { + clipboard.copyText('hiiiiiii'); + } + }; +}); diff --git a/angular-clipboard/index.d.ts b/angular-clipboard/index.d.ts new file mode 100644 index 0000000000..bb2d93ce49 --- /dev/null +++ b/angular-clipboard/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for angular-clipboard v1.5 +// Project: https://github.com/omichelsen/angular-clipboard +// Definitions by: Bradford Wagner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Definition of the Clipboard Service + */ +export interface ClipboardService { + /** + * tells us whether or not angular-clipboard is supported + */ + supported: boolean; + + /** + * copies text to a clipboard + * @param text the text to be copied to the clipboard + */ + copyText(text: string): void; +} diff --git a/angular-clipboard/tsconfig.json b/angular-clipboard/tsconfig.json new file mode 100644 index 0000000000..1f69b1e8fa --- /dev/null +++ b/angular-clipboard/tsconfig.json @@ -0,0 +1,19 @@ +{ + "files": [ + "index.d.ts", + "angular-clipboard-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/angular-cookies/tsconfig.json b/angular-cookies/tsconfig.json index 81f1a4a364..a76d9cbdb5 100644 --- a/angular-cookies/tsconfig.json +++ b/angular-cookies/tsconfig.json @@ -13,6 +13,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-deferred-bootstrap/tsconfig.json b/angular-deferred-bootstrap/tsconfig.json index aa3c166f61..cd3ad35519 100644 --- a/angular-deferred-bootstrap/tsconfig.json +++ b/angular-deferred-bootstrap/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-gettext/index.d.ts b/angular-gettext/index.d.ts index 380ef1d8b7..224f5032e0 100644 --- a/angular-gettext/index.d.ts +++ b/angular-gettext/index.d.ts @@ -1,73 +1,79 @@ -// Type definitions for angular-gettext v2.1.0 +// Type definitions for angular-gettext v2.1.0 // Project: https://angular-gettext.rocketeer.be/ // Definitions by: Ákos Lukács // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare namespace angular.gettext { - interface gettextCatalog { - ////////////// - /// Fields /// - ////////////// - - /** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ - debug: boolean; - /** (default: [MISSING]:): Custom prefix for untranslated strings. */ - debugPrefix: string; - /** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */ - showTranslatedMarkers: boolean; - /** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */ - translatedMarkerPrefix: string; - /** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */ - translatedMarkerSuffix: string; - /** An object of loaded translation strings.Shouldn't be used directly. */ - strings: {}; - /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated - * @deprecreated - */ - baseLanguage: string; +import * as angular from 'angular'; - /////////////// - /// Methods /// - /////////////// +declare module 'angular' { + export namespace gettext { + interface gettextCatalog { - /** Sets the current language and makes sure that all translations get updated correctly. */ - setCurrentLanguage(lang: string): void; + ////////////// + /// Fields /// + ////////////// - /** Returns the current language. */ - getCurrentLanguage(): string; + /** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ + debug: boolean; + /** (default: [MISSING]:): Custom prefix for untranslated strings. */ + debugPrefix: string; + /** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */ + showTranslatedMarkers: boolean; + /** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */ + translatedMarkerPrefix: string; + /** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */ + translatedMarkerSuffix: string; + /** An object of loaded translation strings.Shouldn't be used directly. */ + strings: {}; + /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated + * @deprecreated + */ + baseLanguage: string; - /** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ - * @param language A language code. - * @param strings A dictionary of strings. The format of this dictionary is: - * - Keys: Singular English strings (as defined in the source files) - * - Values: Either a single string for signular-only strings or an array of plural forms. - */ - setStrings(language: string, strings: { [key: string]: string|string[] }): void; - /** Get the correct pluralized (but untranslated) string for the value of n. */ - getStringForm(string: string, n: number): string; + /////////////// + /// Methods /// + /////////////// - /** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect: - * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); - * // var hello will be "Hallo Ruben!" in Dutch. - * The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. - */ - getString(string: string, scope?: any, context?: string): string; + /** Sets the current language and makes sure that all translations get updated correctly. */ + setCurrentLanguage(lang: string): void; - /** Translate a plural string with the given context. */ - getPlural(n: number, string: string, stringPlural: string, context?: any): string; + /** Returns the current language. */ + getCurrentLanguage(): string; - /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ - loadRemote(url: string): ng.IHttpPromise; - } + /** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ + * @param language A language code. + * @param strings A dictionary of strings. The format of this dictionary is: + * - Keys: Singular English strings (as defined in the source files) + * - Values: Either a single string for signular-only strings or an array of plural forms. + */ + setStrings(language: string, strings: { [key: string]: string|string[] }): void; - /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ - interface gettextFunction { - (dummyString: string): string; + /** Get the correct pluralized (but untranslated) string for the value of n. */ + getStringForm(string: string, n: number): string; + + /** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect: + * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); + * // var hello will be "Hallo Ruben!" in Dutch. + * The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. + */ + getString(string: string, scope?: any, context?: string): string; + + /** Translate a plural string with the given context. */ + getPlural(n: number, string: string, stringPlural: string, context?: any): string; + + /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ + loadRemote(url: string): ng.IHttpPromise; + } + + /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ + interface gettextFunction { + (dummyString: string): string; + } } } diff --git a/angular-google-analytics/angular-google-analytics-service.d.ts b/angular-google-analytics/angular-google-analytics-service.d.ts deleted file mode 100644 index 9801280740..0000000000 --- a/angular-google-analytics/angular-google-analytics-service.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Type definitions for angular-google-analytics v1.1.0 -// Project: https://github.com/revolunet/angular-google-analytics -// Definitions by: Matt Wheatley -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace angular.google.analytics { - interface AnalyticsService { - /** - * @summary If logging is enabled then all outbound calls are accessible via an in-memory array. - * This is useful for troubleshooting and seeing the order of outbound calls with parameters. - */ - log: Array; - - /** - * @summary If in offline mode then all calls are queued to an in-memory array for future processing. - * All calls queued to the offlineQueue are not outbound calls yet and hence do not show up in the log. - */ - offlineQueue: Array; - - /** - * @summary Returns the current URL that would be sent if a `trackPage` call was made. - * @return {string} The URL - */ - getUrl: () => string; - - /** - * @summary Manually create classic analytics (ga.js) script tag - */ - createScriptTag: () => void; - - /** - * @summary Manually create universal analytics (analytics.js) script tag - */ - createAnalyticsScriptTag: () => void; - - /** - * @summary Allows for advanced configuration and definitions in univeral analytics only. This is a no-op when using classic analytics. - */ - set: (key: string, value: any, accountName?: string) => void; - - /** - * @summary Creates a new page view event - * @param {string} pageURL URL of page view - * @param {string} title Page Title - * @param {Object} dimensions Additional dimensions and metrics - */ - trackPage: (pageURL: string, title?: string, dimensions?: { [expr: string]: any }) => void; - - /** - * @summary Create a new event - */ - trackEvent: (category: string, action: string, label: string, value?: any, nonInteractionFlag?: boolean, dimensions?: { [expr: string]: any }) => void; - - trackException: (descrption: string, isFatal: boolean) => void; - - /** - * @summary While in offline mode, no calls to the ga function or pushes to the gaq array are made. - * This will queue all calls for later sending once offline mode is reset to false. - */ - offline: (offlineMode: boolean) => void; - } -} diff --git a/angular-google-analytics/index.d.ts b/angular-google-analytics/index.d.ts index 20663bec30..d83753a7b7 100644 --- a/angular-google-analytics/index.d.ts +++ b/angular-google-analytics/index.d.ts @@ -4,171 +4,232 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +import * as angular from 'angular'; -declare namespace angular.google.analytics { +declare module 'angular' { + export namespace google.analytics { + /** + * @summary Interface for {@link AnalyticsService}. + * @interface + */ + interface AnalyticsService { + /** + * @summary If logging is enabled then all outbound calls are accessible via an in-memory array. + * This is useful for troubleshooting and seeing the order of outbound calls with parameters. + */ + log: Array; + + /** + * @summary If in offline mode then all calls are queued to an in-memory array for future processing. + * All calls queued to the offlineQueue are not outbound calls yet and hence do not show up in the log. + */ + offlineQueue: Array; + + /** + * @summary Returns the current URL that would be sent if a `trackPage` call was made. + * @return {string} The URL + */ + getUrl: () => string; + + /** + * @summary Manually create classic analytics (ga.js) script tag + */ + createScriptTag: () => void; + + /** + * @summary Manually create universal analytics (analytics.js) script tag + */ + createAnalyticsScriptTag: () => void; + + /** + * @summary Allows for advanced configuration and definitions in univeral analytics only. This is a no-op when using classic analytics. + */ + set: (key: string, value: any, accountName?: string) => void; + + /** + * @summary Creates a new page view event + * @param {string} pageURL URL of page view + * @param {string} title Page Title + * @param {Object} dimensions Additional dimensions and metrics + */ + trackPage: (pageURL: string, title?: string, dimensions?: { [expr: string]: any }) => void; + + /** + * @summary Create a new event + */ + trackEvent: (category: string, action: string, label: string, value?: any, nonInteractionFlag?: boolean, dimensions?: { [expr: string]: any }) => void; + + trackException: (descrption: string, isFatal: boolean) => void; + + /** + * @summary While in offline mode, no calls to the ga function or pushes to the gaq array are made. + * This will queue all calls for later sending once offline mode is reset to false. + */ + offline: (offlineMode: boolean) => void; + } /** * @summary Interface for {@link AnalysticsProvider}. * @interface */ interface AnalyticsProvider { - /** - * @summary Use Delay Script Tag Insertion. - * @param {boolean} val If true, the delay script tag is inserted. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - delayScriptTag(val: boolean): AnalyticsProvider; + /** + * @summary Use Delay Script Tag Insertion. + * @param {boolean} val If true, the delay script tag is inserted. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + delayScriptTag(val: boolean): AnalyticsProvider; - /** - * @summary Activates the test mode. - */ - enterTestMode(): void; + /** + * @summary Activates the test mode. + */ + enterTestMode(): void; - /** - * @summary Gets the global cookie configuration. - * @return {Object} The global cookie configuration. - */ - getCookieConfig(): Object; + /** + * @summary Gets the global cookie configuration. + * @return {Object} The global cookie configuration. + */ + getCookieConfig(): Object; - /** - * @summary Ignore first page view. - * @param {boolean} val If true, the first page view is ignored. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - ignoreFirstPageLoad(val: boolean): AnalyticsProvider; + /** + * @summary Ignore first page view. + * @param {boolean} val If true, the first page view is ignored. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + ignoreFirstPageLoad(val: boolean): AnalyticsProvider; - /** - * @summary Enable Service Logging. - * @param {boolean} val If true, log all outbound calls to an in-memory array accessible. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - logAllCalls(val: boolean): AnalyticsProvider; + /** + * @summary Enable Service Logging. + * @param {boolean} val If true, log all outbound calls to an in-memory array accessible. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + logAllCalls(val: boolean): AnalyticsProvider; - /** - * @summary Set Google Analytics Accounts. - * @param {Object} tracker The account identifier(s). - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setAccount(tracker: string|Object|Array): AnalyticsProvider; + /** + * @summary Set Google Analytics Accounts. + * @param {Object} tracker The account identifier(s). + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setAccount(tracker: string | Object | Array): AnalyticsProvider; - /** - * @summary Set Cookie Configuration. - * @param {Object} config The custom cookie parameters. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - * @deprecated - */ - setCookieConfig(config: Object): AnalyticsProvider; + /** + * @summary Set Cookie Configuration. + * @param {Object} config The custom cookie parameters. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + * @deprecated + */ + setCookieConfig(config: Object): AnalyticsProvider; - /** - * @summary Set cross-linked domains. - * @param {Array} domains The domains. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setCrossLinkDomains(domains: Array): AnalyticsProvider; + /** + * @summary Set cross-linked domains. + * @param {Array} domains The domains. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setCrossLinkDomains(domains: Array): AnalyticsProvider; - /** - * @summary Set currency. - * @param {string} currencyCode The currency code. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setCurrency(currencyCode: string): AnalyticsProvider; + /** + * @summary Set currency. + * @param {string} currencyCode The currency code. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setCurrency(currencyCode: string): AnalyticsProvider; - /** - * @summary Set Domain Name. - * @param {string} domain The domain name. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setDomainName(domain: string): AnalyticsProvider; + /** + * @summary Set Domain Name. + * @param {string} domain The domain name. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setDomainName(domain: string): AnalyticsProvider; - /** - * @summary Enable Experiment (universal analytics only). - * @param {string} id The experiment identifier. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setExperimentId(id: string): AnalyticsProvider; + /** + * @summary Enable Experiment (universal analytics only). + * @param {string} id The experiment identifier. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setExperimentId(id: string): AnalyticsProvider; - /** - * @summary Support Hybrid Mobile Applications. - * @param {boolean} val If true, each account object will disable protocol checking and all injected scripts will use the HTTPS protocol. - */ - setHybridMobileSupport(val: boolean): AnalyticsProvider; + /** + * @summary Support Hybrid Mobile Applications. + * @param {boolean} val If true, each account object will disable protocol checking and all injected scripts will use the HTTPS protocol. + */ + setHybridMobileSupport(val: boolean): AnalyticsProvider; - /** - * @summary Set the default page event name. - * @param {string} name The default page event name. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setPageEvent(name: string): AnalyticsProvider; + /** + * @summary Set the default page event name. + * @param {string} name The default page event name. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setPageEvent(name: string): AnalyticsProvider; - /** - * @summary Sets the regex to scrub location before sending to analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - * @param {RegExp} regex The regex. - */ - setRemoveRegExp(regex: RegExp): AnalyticsProvider; + /** + * @summary Sets the regex to scrub location before sending to analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + * @param {RegExp} regex The regex. + */ + setRemoveRegExp(regex: RegExp): AnalyticsProvider; - /** - * @summary Starts the offline mode. - * @param {boolean} val If true, the offline mode is started. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - startOffline(val: boolean): AnalyticsProvider; + /** + * @summary Starts the offline mode. + * @param {boolean} val If true, the offline mode is started. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + startOffline(val: boolean): AnalyticsProvider; - /** - * @summary Track all routes. - * @param {boolean} val If true, all routes are tracked. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - trackPages(doTrack: boolean): AnalyticsProvider; + /** + * @summary Track all routes. + * @param {boolean} val If true, all routes are tracked. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + trackPages(doTrack: boolean): AnalyticsProvider; - /** - * @summary Sets the URL prefix. - * @param {string} prefix The URL prefix. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - trackPrefix(prefix: string): AnalyticsProvider; + /** + * @summary Sets the URL prefix. + * @param {string} prefix The URL prefix. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + trackPrefix(prefix: string): AnalyticsProvider; - /** - * @summary Track all URL query parameters. - * @param {boolean} val If true, all URL query parameters are tracked. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - trackUrlParams(val: boolean): AnalyticsProvider; + /** + * @summary Track all URL query parameters. + * @param {boolean} val If true, all URL query parameters are tracked. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + trackUrlParams(val: boolean): AnalyticsProvider; - /** - * @summary Use Classic Analytics. - * @param {boolean} val If true, use classic analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useAnalytics(val: boolean): AnalyticsProvider; + /** + * @summary Use Classic Analytics. + * @param {boolean} val If true, use classic analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useAnalytics(val: boolean): AnalyticsProvider; - /** - * @summary Use Cross Domain Linking. - * @param {boolean} val If true, the cross-linked domains are registered with Google Analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useCrossDomainLinker(val: boolean): AnalyticsProvider; + /** + * @summary Use Cross Domain Linking. + * @param {boolean} val If true, the cross-linked domains are registered with Google Analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useCrossDomainLinker(val: boolean): AnalyticsProvider; - /** - * @summary Use Display Features. - * @param {boolean} val If true, the display features module is loaded with Google Analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useDisplayFeatures(val: boolean): AnalyticsProvider; + /** + * @summary Use Display Features. + * @param {boolean} val If true, the display features module is loaded with Google Analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useDisplayFeatures(val: boolean): AnalyticsProvider; - /** - * @summary Enable enhanced e-commerce module. - * @param {boolean} val If true, the enhanced e-commerce module is enabled. - * @param {boolean} enhanced If true, the "ec.js" file is used, otherwises, the "ecommerce.js" is used. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useECommerce(val: boolean, enhanced: boolean): AnalyticsProvider; + /** + * @summary Enable enhanced e-commerce module. + * @param {boolean} val If true, the enhanced e-commerce module is enabled. + * @param {boolean} enhanced If true, the "ec.js" file is used, otherwises, the "ecommerce.js" is used. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useECommerce(val: boolean, enhanced: boolean): AnalyticsProvider; - /** - * @summary Use Enhanced Link Attribution. - * @param {boolean} val If true, the enhanced link attribution module is loaded with Google Analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useEnhancedLinkAttribution(val: boolean): AnalyticsProvider; + /** + * @summary Use Enhanced Link Attribution. + * @param {boolean} val If true, the enhanced link attribution module is loaded with Google Analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useEnhancedLinkAttribution(val: boolean): AnalyticsProvider; } + } } diff --git a/angular-material/index.d.ts b/angular-material/index.d.ts index d4020a8c2a..7895732ada 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 { @@ -335,6 +336,7 @@ declare module 'angular' { onRemoving?: Function; onDomRemoved?: Function; origin?: string | JQuery | Element; + onCloseSuccess?: ((panel: IPanelRef, closeReason: string) => any); } interface IPanelRef { @@ -407,6 +409,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-mocks/index.d.ts b/angular-mocks/index.d.ts index e3ef7bad18..3c24ed1cf6 100644 --- a/angular-mocks/index.d.ts +++ b/angular-mocks/index.d.ts @@ -107,7 +107,7 @@ declare module 'angular' { interface IComponentControllerService { // TBinding is an interface exposed by a component as per John Papa's style guide // https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top - (componentName: string, locals: { $scope: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T; + (componentName: string, locals: { $scope?: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T; } diff --git a/angular-mocks/tsconfig.json b/angular-mocks/tsconfig.json index b53af4d397..68a8f53b3c 100644 --- a/angular-mocks/tsconfig.json +++ b/angular-mocks/tsconfig.json @@ -15,6 +15,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-permission/angular-permission-tests.ts b/angular-permission/angular-permission-tests.ts index 4f3a35f5df..051ace69b8 100644 --- a/angular-permission/angular-permission-tests.ts +++ b/angular-permission/angular-permission-tests.ts @@ -66,7 +66,7 @@ angular PermissionStore.removePermissionDefinition('user'); - let permissions: Array = PermissionStore.getStore(); + let permissions = PermissionStore.getStore(); }); @@ -90,5 +90,5 @@ angular RoleStore.removeRoleDefinition('user'); - let roles: Array = RoleStore.getStore(); + let roles = RoleStore.getStore(); }); diff --git a/angular-permission/index.d.ts b/angular-permission/index.d.ts index 0b8d06f32a..28781cb5df 100644 --- a/angular-permission/index.d.ts +++ b/angular-permission/index.d.ts @@ -30,8 +30,8 @@ declare module 'angular' { * @param validationFunction {Function} Function used to validate if permission is valid */ definePermission( - name: string, - validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise + permissionName: string, + validationFunction: PermissionValidationFunction ): void; /** @@ -43,10 +43,14 @@ declare module 'angular' { * @param validationFunction {Function} Function used to validate if permission is valid */ defineManyPermissions( - permissions: string[], - validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise + permissionNames: string[], + validationFunction: PermissionValidationFunction ): void; + /** + * Removes all permissions + * @method + */ clearStore(): void; /** @@ -55,7 +59,7 @@ declare module 'angular' { * * @param permissionName {String} Name of defined permission */ - removePermissionDefinition(permission: string): void; + removePermissionDefinition(permissionName: string): void; /** * Checks if permission exists @@ -66,13 +70,21 @@ declare module 'angular' { */ hasPermissionDefinition(permissionName: string): boolean; + /** + * Returns permission by it's name + * @method + * + * @returns {permission.Permission} Permissions definition object + */ + getPermissionDefinition(permissionName: string): Permission; + /** * Returns all permissions * @method * * @returns {Object} Permissions collection */ - getStore(): Permission[]; + getStore(): { [permissionName: string]: Permission }; } export interface RoleStore { @@ -85,8 +97,8 @@ declare module 'angular' { * @param [validationFunction] {Function} Function used to validate if permissions in role are valid */ defineRole( - role: string, - permissions: Array, + roleName: string, + permissions: string[], validationFunction: RoleValidationFunction ): void; @@ -97,7 +109,10 @@ declare module 'angular' { * @param roleName {String} Name of defined role * @param permissions {Array} Set of permission names */ - defineRole(role: string, permissions: Array): void; + defineRole( + roleName: string, + permissions: string[] + ): void; /** * Checks if role is defined in store @@ -106,7 +121,7 @@ declare module 'angular' { * @param roleName {String} Name of role * @returns {Boolean} */ - hasRoleDefinition(role: string): boolean; + hasRoleDefinition(roleName: string): boolean; /** * Returns role definition object by it's name @@ -136,27 +151,31 @@ declare module 'angular' { * * @returns {Object} Defined roles collection */ - getStore(): Role[]; + getStore(): { [roleName: string]: Role }; } export interface Role { roleName: string; permissionNames: string[]; validationFunction?: RoleValidationFunction; + validateRole: () => angular.IPromise; } export interface Permission { permissionName: string; validationFunction?: PermissionValidationFunction; + validatePermission: () => angular.IPromise; } - interface RoleValidationFunction { - (permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; - } + export type RoleValidationFunction = ( + roleName?: string, + transitionProperties?: TransitionProperties + ) => boolean | angular.IPromise; - interface PermissionValidationFunction { - (permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; - } + export type PermissionValidationFunction = ( + permissionName?: string, + transitionProperties?: TransitionProperties + ) => boolean | angular.IPromise; export interface IPermissionState extends angular.ui.IState { data?: any | DataWithPermissions; @@ -164,8 +183,8 @@ declare module 'angular' { export interface DataWithPermissions { permissions?: { - only?: (() => void) | Array | angular.IPromise; - except?: (() => void) | Array | angular.IPromise; + only?: (() => void) | string | string[] | angular.IPromise; + except?: (() => void) | string | string[] | angular.IPromise; redirectTo: string | (() => string) | (() => PermissionRedirectConfigation) | { [index: string]: PermissionRedirectConfigation } }; } diff --git a/angular-promise-tracker/angular-promise-tracker-tests.ts b/angular-promise-tracker/angular-promise-tracker-tests.ts new file mode 100644 index 0000000000..82f9e66c06 --- /dev/null +++ b/angular-promise-tracker/angular-promise-tracker-tests.ts @@ -0,0 +1,20 @@ +angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker', + ($q: angular.IQService, promiseTracker: angular.promisetracker.PromiseTrackerService) => { + const trackerWithoutOptions = promiseTracker(); + + const options = { + activationDelay: 10, + minDuration: 500 + } as angular.promisetracker.PromiseTrackerOptions; + const trackerWithOptions = promiseTracker(options); + + const isActive: boolean = trackerWithOptions.active(); + const tracking: boolean = trackerWithOptions.tracking(); + const trackingCount: number = trackerWithOptions.trackingCount(); + trackerWithOptions.cancel(); + + const createdPromise: angular.IDeferred = trackerWithOptions.createPromise(); + + const promiseToAdd = $q.defer().promise; + const addedPromise: angular.IDeferred = trackerWithOptions.addPromise(promiseToAdd); +}]); diff --git a/angular-promise-tracker/index.d.ts b/angular-promise-tracker/index.d.ts new file mode 100644 index 0000000000..c00f36e77c --- /dev/null +++ b/angular-promise-tracker/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for angular-promise-tracker 2.2.2 +// Project: https://github.com/ajoslin/angular-promise-tracker +// Definitions by: Rufus Linke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as angular from 'angular'; + +declare module 'angular' { + export namespace promisetracker { + interface PromiseTrackerOptions { + activationDelay: number; + minDuration: number; + } + + interface PromiseTracker { + active(): boolean; + tracking(): boolean; + trackingCount(): number; + addPromise(promise: angular.IPromise): angular.IDeferred; + createPromise(): angular.IDeferred; + cancel(): void; + } + + interface PromiseTrackerService { + (options?: PromiseTrackerOptions): PromiseTracker; + } + } +} diff --git a/angular-promise-tracker/tsconfig.json b/angular-promise-tracker/tsconfig.json new file mode 100644 index 0000000000..266a8adf90 --- /dev/null +++ b/angular-promise-tracker/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-promise-tracker-tests.ts" + ] +} diff --git a/angular-q-spread/tsconfig.json b/angular-q-spread/tsconfig.json index 90110b0e9f..3461eaa2db 100644 --- a/angular-q-spread/tsconfig.json +++ b/angular-q-spread/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-resource/tsconfig.json b/angular-resource/tsconfig.json index fe51bc7293..6bff757b93 100644 --- a/angular-resource/tsconfig.json +++ b/angular-resource/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-route/tsconfig.json b/angular-route/tsconfig.json index 96c224daaf..3301b843a3 100644 --- a/angular-route/tsconfig.json +++ b/angular-route/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-sanitize/tsconfig.json b/angular-sanitize/tsconfig.json index c029bece36..96bc483afb 100644 --- a/angular-sanitize/tsconfig.json +++ b/angular-sanitize/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file 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..95229f68cd --- /dev/null +++ b/angular-ui-router-default/angular-ui-router-default-tests.ts @@ -0,0 +1,40 @@ +import * as angular from "angular"; +import { ui } from "angular"; + +angular.module("test", [ + "ui.router", + "ui.router.default" +]) + .config(function($stateProvider: 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/index.d.ts b/angular-ui-router-default/index.d.ts new file mode 100644 index 0000000000..76e4db23e0 --- /dev/null +++ b/angular-ui-router-default/index.d.ts @@ -0,0 +1,19 @@ +// 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 + +import * as aur from "angular-ui-router"; + +declare module "angular" { + namespace 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-default/tsconfig.json b/angular-ui-router-default/tsconfig.json new file mode 100644 index 0000000000..b4a462b3c9 --- /dev/null +++ b/angular-ui-router-default/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-ui-router-default-tests.ts" + ] +} \ No newline at end of file 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..2ca6e18806 --- /dev/null +++ b/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts @@ -0,0 +1,28 @@ +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/index.d.ts b/angular-ui-router-uib-modal/index.d.ts new file mode 100644 index 0000000000..29e963fc6e --- /dev/null +++ b/angular-ui-router-uib-modal/index.d.ts @@ -0,0 +1,14 @@ +// 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 + +import * as auir from "angular-ui-router"; + +declare module "angular" { + namespace ui { + interface IState { + modal?: boolean | string[]; + } + } +} diff --git a/angular-ui-router-uib-modal/tsconfig.json b/angular-ui-router-uib-modal/tsconfig.json new file mode 100644 index 0000000000..08dbd4d4cf --- /dev/null +++ b/angular-ui-router-uib-modal/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-ui-router-uib-modal-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-websocket/tsconfig.json b/angular-websocket/tsconfig.json index 7579a1591c..a340f7ffbd 100644 --- a/angular-websocket/tsconfig.json +++ b/angular-websocket/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/angular-xeditable/tsconfig.json b/angular-xeditable/tsconfig.json index e9a9c10c51..e81407b730 100644 --- a/angular-xeditable/tsconfig.json +++ b/angular-xeditable/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file 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 713e959d51..d07777d2cf 100644 --- a/angular/index.d.ts +++ b/angular/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.5 // Project: http://angularjs.org -// Definitions by: Diego Vilar +// Definitions by: Diego Vilar , Georgii Dolzhykov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -984,9 +984,7 @@ declare namespace angular { * See http://docs.angularjs.org/api/ng/service/$q */ interface IQService { - new (resolver: (resolve: IQResolveReject) => any): IPromise; new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; - (resolver: (resolve: IQResolveReject) => any): IPromise; (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; /** @@ -1043,6 +1041,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. */ @@ -1228,6 +1227,11 @@ declare namespace angular { (scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery; // If one argument is provided, then it's assumed to be the cloneAttachFn. (cloneAttachFn?: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery; + + /** + * Returns true if the specified slot contains content (i.e. one or more DOM nodes) + */ + isSlotFilled(slotName: string): boolean; } /////////////////////////////////////////////////////////////////////////// @@ -1379,12 +1383,12 @@ declare namespace angular { */ url: string; /** - * Event listeners to be bound to the XMLHttpRequest object. + * Event listeners to be bound to the XMLHttpRequest object. * To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block. */ eventHandlers?: { [type: string]: EventListenerOrEventListenerObject }; /** - * Event listeners to be bound to the XMLHttpRequest upload object. + * Event listeners to be bound to the XMLHttpRequest upload object. * To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block. */ uploadEventHandlers?: { [type: string]: EventListenerOrEventListenerObject }; @@ -1708,7 +1712,7 @@ declare namespace angular { (new (...args: any[]) => IController) | // Instead of classes, plain functions are often used as controller constructors, especially in examples. ((...args: any[]) => (void | IController)); - + /** * Directive controllers have a well-defined lifecycle. Each controller can implement "lifecycle hooks". These are methods that * will be called by Angular at certain points in the life cycle of the directive. @@ -1771,7 +1775,7 @@ declare namespace angular { /////////////////////////////////////////////////////////////////////////// interface IDirectiveFactory { - (...args: any[]): IDirective; + (...args: any[]): IDirective | IDirectiveLinkFn; } interface IDirectiveLinkFn { @@ -1779,8 +1783,8 @@ declare namespace angular { scope: IScope, instanceElement: JQuery, instanceAttributes: IAttributes, - controller: {}, - transclude: ITranscludeFunction + controller?: IController | IController[] | {[key: string]: IController}, + transclude?: ITranscludeFunction ): void; } @@ -1808,7 +1812,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/angular/tsconfig.json b/angular/tsconfig.json index ea2099d486..e0d792766a 100644 --- a/angular/tsconfig.json +++ b/angular/tsconfig.json @@ -14,6 +14,6 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": false + "forceConsistentCasingInFileNames": true } } \ No newline at end of file diff --git a/anybar/anybar-tests.ts b/anybar/anybar-tests.ts new file mode 100644 index 0000000000..6b4ea8ef89 --- /dev/null +++ b/anybar/anybar-tests.ts @@ -0,0 +1,5 @@ +import * as anybar from 'anybar' + +anybar('red', { port: 123 }) + +anybar('green') diff --git a/anybar/index.d.ts b/anybar/index.d.ts new file mode 100644 index 0000000000..4972f29756 --- /dev/null +++ b/anybar/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for anybar 2.0.1 +// Project: https://github.com/sindresorhus/anybar +// Definitions by: Chris Khoo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace anybar { } + +declare function anybar(color: string, options?: { port: number }): void + +export = anybar diff --git a/anybar/tsconfig.json b/anybar/tsconfig.json new file mode 100644 index 0000000000..f23e5a828f --- /dev/null +++ b/anybar/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "anybar-tests.ts" + ] +} diff --git a/arbiter/Arbiter-tests.ts b/arbiter/arbiter-tests.ts similarity index 100% rename from arbiter/Arbiter-tests.ts rename to arbiter/arbiter-tests.ts 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..f11d0070ef 100644 --- a/archiver/index.d.ts +++ b/archiver/index.d.ts @@ -18,24 +18,32 @@ import * as FS from 'fs'; import * as STREAM from 'stream'; -interface nameInterface { - name?: string; -} -interface Archiver extends STREAM.Transform { - pipe(writeStream: FS.WriteStream): void; - append(source: FS.ReadStream | Buffer | string, name: nameInterface): void; - finalize(): void; -} - -interface Options { - -} - -declare function archiver(format: string, options?: Options): Archiver; +declare function archiver(format: string, options?: archiver.Options): archiver.Archiver; declare namespace archiver { - function create(format: string, options?: Options): Archiver; + + export function create(format: string, options?: Options): Archiver; + + + export interface nameInterface { + name?: string; + } + + export 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; + } + + export interface Options { + + } } export = archiver; diff --git a/array-foreach/array-foreach-tests.ts b/array-foreach/array-foreach-tests.ts new file mode 100644 index 0000000000..cc75ff25ae --- /dev/null +++ b/array-foreach/array-foreach-tests.ts @@ -0,0 +1,39 @@ +import arrayForEach = require('array-foreach'); + +const array: Array = [1, 2, 3, 4]; +const result: Array = []; + +arrayForEach(array, (i: number) => { + result.push(i); +}); + +arrayForEach(array, (i: number, index: number) => { + result.push(i + index); +}); + +arrayForEach(array, (i: number, index: number, array: Array) => { + result.push(array[i]); +}); + +const resultThis: Array<{i: number, that: string}> = []; + +arrayForEach(array, (i: number) => { + resultThis.push({ + i: i, + that: this.that + }); +}, { that: 'jeff' }); + +arrayForEach(array, (i: number, index: number) => { + resultThis.push({ + i: i + index, + that: this.that + }); +}, { that: 'jeff' }); + +arrayForEach(array, (i: number, index: number, array: Array) => { + resultThis.push({ + i: array[i], + that: this.that + }); +}, { that: 'jeff' }); \ No newline at end of file diff --git a/array-foreach/index.d.ts b/array-foreach/index.d.ts new file mode 100644 index 0000000000..6493ebd3ec --- /dev/null +++ b/array-foreach/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for array-foreach +// Project: https://www.npmjs.com/package/array-foreach +// Definitions by: Steve Jenkins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** +* Performs the specified action for each element in an array. +* @param arr Array of items to iterate over +* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. +* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. +*/ +declare function forEach(arr: Array, callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; + +/** +* Performs the specified action for each element in an array. +* @param arr Nodelist of items to iterate over +* @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. +* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. +*/ +declare function forEach(arr: NodeListOf, callbackfn: (value: T, index: number, array: ReadonlyArray) => void, thisArg?: any): void; +export = forEach; diff --git a/array-foreach/tsconfig.json b/array-foreach/tsconfig.json new file mode 100644 index 0000000000..23766723b4 --- /dev/null +++ b/array-foreach/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "array-foreach-tests.ts" + ] +} \ No newline at end of file diff --git a/asn1js/asn1js-tests.ts b/asn1js/asn1js-tests.ts new file mode 100644 index 0000000000..992ef2bbb1 --- /dev/null +++ b/asn1js/asn1js-tests.ts @@ -0,0 +1,52 @@ +import { LocalLengthBlock, Null } from "asn1js"; +import { OctetString } from "asn1js"; +import { ObjectIdentifier } from "asn1js"; +import { UTCTime } from "asn1js"; + +let t = new LocalLengthBlock(); + +{ + // Null + let testNull = new Null(); + let json = testNull.toJSON(); + + testNull.toBER(); + testNull.fromBER(new Uint8Array(0).buffer, 0, 0); +} + +{ + // OctetString + let test = new OctetString(); + let json = test.toJSON(); + + test.toBER(); + test.fromBER(new Uint8Array(0).buffer, 0, 0); + test.isEqual(test); + OctetString.blockName() === "name"; +} + +{ + // ObjectIdentifier + let test = new ObjectIdentifier(); + let json = test.toJSON(); + + test.toBER(); + test.fromBER(new Uint8Array(0).buffer, 0, 0); + OctetString.blockName() === "name"; +} + +{ + // UTCTime + let test = new UTCTime(); + test = new UTCTime({ + value: "" + }); + test = new UTCTime({ + valueDate: new Date() + }); + let json = test.toJSON(); + + test.toBER(); + test.fromBER(new Uint8Array(0).buffer, 0, 0); + OctetString.blockName() === "name"; +} diff --git a/asn1js/index.d.ts b/asn1js/index.d.ts new file mode 100644 index 0000000000..7eced899b2 --- /dev/null +++ b/asn1js/index.d.ts @@ -0,0 +1,675 @@ +// Type definitions for asn1js +// Project: https://github.com/PeculiarVentures/ASN1.js +// Definitions by: Stepan Miroshin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +import { getParametersValue, padNumber, isEqualBuffer, bufferToHexCodes, checkBufferParams, utilToBase, utilFromBase, utilEncodeTC, utilDecodeTC, utilConcatBuf, nearestPowerOf2 } from "pvutils"; + +export = Asn1js; + +declare namespace Asn1js { + + interface LocalBaseBlockParams { + blockLength?: number; + error?: string; + warnings?: string[]; + valueBeforeDecode?: ArrayBuffer; + } + + interface JsonLocalBaseBlock { + blockName: string; + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + } + + class LocalBaseBlock { + blockLength: number; + error: string; + warnings: string[]; + valueBeforeDecode: ArrayBuffer; + + constructor(params?: LocalBaseBlockParams); + /** + * Aux function, need to get a block name. Need to have it here for inhiritence + * + * @static + * @returns {string} + * + * @memberOf LocalBaseBlock + */ + static blockName(): string; + /** + * Convertion for the block to JSON object + * + * @returns {JsonLocalBaseBlock} + * + * @memberOf LocalBaseBlock + */ + toJSON(): JsonLocalBaseBlock; + } + + interface LocalHexBlockParams extends LocalBaseBlockParams { + isHexOnly?: boolean; + valueHex?: ArrayBuffer; + } + + interface ILocalHexBlock { + isHexOnly: boolean; + valueHex: ArrayBuffer; + /** + * Base function for converting block from BER encoded array of bytes + * + * @param {ArrayBuffer} inputBuffer ASN.1 BER encoded array + * @param {number} inputOffset Offset in ASN.1 BER encoded array where decoding should be started + * @param {number} inputLength Maximum length of array of bytes which can be using in this function + * @returns {number} Offset after least decoded byte + * + * @memberOf LocalHexBlockMixin + */ + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (BER rules) + * + * @param {boolean} [sizeOnly=false] Flag that we need only a size of encoding, not a real array of bytes + * @returns {ArrayBuffer} + * + * @memberOf LocalHexBlockMixin + */ + toBER(sizeOnly?: boolean): ArrayBuffer; + /** + * Convertion for the block to JSON object + * @returns {*} + */ + toJSON(): any; + } + + class LocalHexBlock implements ILocalHexBlock { + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params: any); + /** + * Aux function, need to get a block name. Need to have it here for inhiritence + * + * @static + * @returns {string} + * + * @memberOf LocalHexBlockMixin + */ + static blockName(): string; + /** + * Base function for converting block from BER encoded array of bytes + * + * @param {ArrayBuffer} inputBuffer ASN.1 BER encoded array + * @param {number} inputOffset Offset in ASN.1 BER encoded array where decoding should be started + * @param {number} inputLength Maximum length of array of bytes which can be using in this function + * @returns {number} Offset after least decoded byte + * + * @memberOf LocalHexBlockMixin + */ + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (BER rules) + * + * @param {boolean} [sizeOnly=false] Flag that we need only a size of encoding, not a real array of bytes + * @returns {ArrayBuffer} + * + * @memberOf LocalHexBlockMixin + */ + toBER(sizeOnly?: boolean): ArrayBuffer; + /** + * Convertion for the block to JSON object + * @returns {*} + */ + toJSON(): any; + } + + interface LocalIdentificationBlockParams { + idBlock?: LocalHexBlockParams & { + isConstructed?: boolean; + tagClass?: number; + tagNumber?: number; + }; + } + + class LocalIdentificationBlock extends LocalBaseBlock implements ILocalHexBlock { + isConstructed: boolean; + tagClass: number; + tagNumber: number; + + constructor(params?: LocalIdentificationBlockParams); + + // ILocalHexBlock implementation + isHexOnly: boolean; + valueHex: ArrayBuffer; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalLengthBlockParams { + lenBlock?: { + isIndefiniteForm?: boolean; + longFormUsed?: boolean; + length: number; + } + } + + class LocalLengthBlock extends LocalBaseBlock { + isIndefiniteForm: boolean; + longFormUsed: boolean; + length: number; + constructor(params?: LocalLengthBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): void; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + class LocalValueBlock extends LocalBaseBlock { + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): void; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface BaseBlockParams extends LocalBaseBlockParams { + name?: string; + optional?: boolean; + primitiveSchema?: Object; + } + + class BaseBlock extends LocalBaseBlock { + constructor(parameters?: BaseBlockParams, valueBlockType?: typeof LocalValueBlock); + idBlock: LocalIdentificationBlock; + lenBlock: LocalLengthBlock; + valueBlock: T; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalPrimitiveValueBlockParams extends LocalBaseBlockParams { + valueHex?: ArrayBuffer; + isHexOnly?: boolean; + } + class LocalPrimitiveValueBlock extends LocalValueBlock { + valueHex: ArrayBuffer; + isHexOnly: boolean; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + class Primitive extends BaseBlock { + } + + interface LocalConstructedValueBlockParams extends LocalBaseBlockParams { + value?: LocalValueBlock; + isIndefiniteForm?: boolean; + } + + class LocalConstructedValueBlock extends LocalValueBlock { + value: LocalValueBlock[]; + isIndefiniteForm: boolean; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + class Constructed extends BaseBlock { } + + interface LocalEndOfContentValueBlockParams extends LocalBaseBlockParams { } + + class LocalEndOfContentValueBlock extends LocalValueBlock { + constructor(params?: LocalEndOfContentValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + export class EndOfContent extends BaseBlock { } + + interface LocalBooleanValueBlockParams extends LocalBaseBlockParams { + value?: boolean; + isHexOnly?: boolean; + valueHex?: ArrayBuffer; + } + class LocalBooleanValueBlock extends LocalValueBlock { + value: boolean; + isHexOnly: boolean; + valueHex: ArrayBuffer; + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + class Boolean extends BaseBlock { } + + class Sequence extends Constructed { } + class Set extends Constructed { } + class Null extends BaseBlock { } + + interface LocalOctetStringValueBlockParams extends LocalConstructedValueBlockParams, LocalHexBlockParams { + isConstructed?: boolean; + } + + class LocalOctetStringValueBlock extends LocalConstructedValueBlock implements ILocalHexBlock { + isConstructed: boolean; + isHexOnly: boolean; + valueHex: ArrayBuffer; + + constructor(params?: LocalOctetStringValueBlockParams); + } + + export class OctetString extends BaseBlock { + constructor(params?: LocalOctetStringValueBlockParams); + /** + * Checking that two OCTETSTRINGs are equal + * + * @param {OctetString} octetString + * @returns {boolean} + * + * @memberOf OctetString + */ + isEqual(octetString: OctetString): boolean; + } + + interface LocalBitStringValueBlockParams extends LocalConstructedValueBlockParams, LocalHexBlockParams { + unusedBits?: number; + isConstructed?: boolean; + blockLength?: number; + } + + class LocalBitStringValueBlock extends LocalConstructedValueBlock implements LocalHexBlock { + unusedBits: number; + isConstructed: boolean; + blockLength: number; + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params?: LocalBitStringValueBlockParams); + } + + class BitString extends BaseBlock { + constructor(params?: LocalBitStringValueBlockParams); + /** + * Checking that two BITSTRINGs are equal + * @param {BitString} bitString + */ + isEqual(bitString: BitString): boolean; + } + + interface LocalIntegerValueBlockParams extends LocalBaseBlockParams, LocalHexBlockParams { + } + + class LocalIntegerValueBlock extends LocalValueBlock implements LocalHexBlock { + valueDec: number; + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params?: LocalIntegerValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + /** + * Base function for converting block from DER encoded array of bytes + * + * @param {ArrayBuffer} inputBuffer ASN.1 DER encoded array + * @param {number} inputOffset Offset in ASN.1 DER encoded array where decoding should be started + * @param {number} inputLength Maximum length of array of bytes which can be using in this function + * @param {number} [expectedLength=0] Expected length of converted "valueHex" buffer + * @returns {number} Offset after least decoded byte + */ + fromDER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, expectedLength?: number): number; + /** + * Encoding of current ASN.1 block into ASN.1 encoded array (DER rules) + * + * @param {boolean} [sizeOnly=false] Flag that we need only a size of encoding, not a real array of bytes + * @returns {ArrayBuffer} + */ + toDER(sizeOnly?: boolean): ArrayBuffer; + } + + interface IntegerParams { + value?: number; + } + export class Integer extends BaseBlock { + constructor(params?: IntegerParams) + /** + * Compare two Integer object, or Integer and ArrayBuffer objects + * + * @param {(Integer | ArrayBuffer)} otherValue + * @returns {boolean} + * + * @memberOf Integer + */ + isEqual(otherValue: Integer | ArrayBuffer): boolean; + /** + * Convert current Integer value from BER into DER format + * + * @returns {Integer} + */ + convertToDER(): Integer; + /** + * Convert current Integer value from DER to BER format + * @returns {Integer} + */ + convertFromDER(): Integer; + } + + class Enumerated extends Integer { } + + interface LocalSidValueBlockParams extends LocalBaseBlockParams, LocalHexBlockParams { + valueDec?: number; + isFirstSid?: boolean; + } + + class LocalSidValueBlock extends LocalBaseBlock implements LocalHexBlock { + valueDec: number; + isFirstSid: boolean; + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params?: LocalSidValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toString(): string; + } + + interface LocalObjectIdentifierValueBlockParams extends LocalBaseBlockParams { + value?: string; + } + + class LocalObjectIdentifierValueBlock extends LocalValueBlock { + constructor(params?: LocalObjectIdentifierValueBlockParams); + + /** + * Create "LocalObjectIdentifierValueBlock" class from string + * + * @param {string} string Input string to convert from + * @returns {boolean} + */ + fromString(data: string): boolean; + /** + * Converts "LocalObjectIdentifierValueBlock" class to string + * + * @returns {string} + * + * @memberOf LocalObjectIdentifierValueBlock + */ + toString(): string; + } + + export class ObjectIdentifier extends BaseBlock { + constructor(params?: LocalObjectIdentifierValueBlockParams); + } + + interface LocalUtf8StringValueBlockParams extends LocalBaseBlockParams, LocalHexBlock { + } + + class LocalUtf8StringValueBlock extends LocalBaseBlock implements LocalHexBlock { + isHexOnly: boolean; + valueHex: ArrayBuffer; + constructor(params?: LocalSidValueBlockParams); + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + toString(): string; + } + + interface Utf8StringParams { + value?: string; + } + + class Utf8String extends BaseBlock { + constructor(params?: Utf8StringParams); + /** + * Function converting ArrayBuffer into ASN.1 internal string + * + * @param {ArrayBuffer} inputBuffer ASN.1 BER encoded array + * + * @memberOf Utf8String + */ + fromBuffer(inputBuffer: ArrayBuffer): void; + /** + * Function converting JavaScript string into ASN.1 internal class + * + * @param {string} inputString ASN.1 BER encoded array + * + * @memberOf Utf8String + */ + fromString(inputString: string): void; + } + + interface LocalBmpStringValueBlockParams extends LocalHexBlockParams, LocalBaseBlockParams { + } + + class LocalBmpStringValueBlock extends LocalBaseBlock implements LocalHexBlock { + value: string; + isHexOnly: boolean; + valueHex: ArrayBuffer; + + constructor(params?: LocalBmpStringValueBlockParams); + + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface BmpStringParams { + value?: string; + } + + export class BmpString extends BaseBlock { + constructor(params?: BmpStringParams); + /** + * Function converting ArrayBuffer into ASN.1 internal string + * + * @param {ArrayBuffer} inputBuffer ASN.1 BER encoded array + * + * @memberOf BmpString + */ + fromBuffer(inputBuffer: ArrayBuffer): void; + /** + * Function converting JavaScript string into ASN.1 internal class + * + * @param {string} inputString ASN.1 BER encoded array + * + * @memberOf BmpString + */ + fromString(inputString: string): void; + } + + interface LocalUniversalStringValueParams extends LocalHexBlockParams, LocalBaseBlockParams { + } + + class LocalUniversalStringValueBlock extends LocalBaseBlock implements LocalHexBlock { + value: string; + isHexOnly: boolean; + valueHex: ArrayBuffer; + + constructor(params?: LocalUniversalStringValueParams); + + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface UniversalStringParams { + value?: string; + } + + export class UniversalString extends BaseBlock { + constructor(params?: UniversalStringParams); + /** + * Function converting ArrayBuffer into ASN.1 internal string + * + * @param {ArrayBuffer} inputBuffer ASN.1 BER encoded array + * + * @memberOf UniversalString + */ + fromBuffer(inputBuffer: ArrayBuffer): void; + /** + * Function converting JavaScript string into ASN.1 internal class + * + * @param {string} inputString ASN.1 BER encoded array + * + * @memberOf UniversalString + */ + fromString(inputString: string): void; + } + interface LocalSimpleLocalSimpleStringValueBlockParams extends LocalHexBlockParams, LocalBaseBlockParams { + } + + class LocalSimpleLocalSimpleStringValueBlock extends LocalBaseBlock implements LocalHexBlock { + value: string; + isHexOnly: boolean; + valueHex: ArrayBuffer; + + constructor(params?: LocalSimpleLocalSimpleStringValueBlockParams); + + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + interface LocalSimpleStringBlockParams { + value?: string; + } + export class LocalSimpleStringBlock extends BaseBlock { + constructor(params?: LocalSimpleStringBlockParams); + /** + * Function converting ArrayBuffer into ASN.1 internal string + * + * @param {ArrayBuffer} inputBuffer ASN.1 BER encoded array + * + * @memberOf LocalSimpleStringBlock + */ + fromBuffer(inputBuffer: ArrayBuffer): void; + /** + * Function converting JavaScript string into ASN.1 internal class + * + * @param {string} inputString ASN.1 BER encoded array + * + * @memberOf LocalSimpleStringBlock + */ + fromString(inputString: string): void; + } + + export class NumericString extends LocalSimpleStringBlock { } + export class PrintableString extends LocalSimpleStringBlock { } + export class TeletexString extends LocalSimpleStringBlock { } + export class VideotexString extends LocalSimpleStringBlock { } + export class IA5String extends LocalSimpleStringBlock { } + export class GraphicString extends LocalSimpleStringBlock { } + export class VisibleString extends LocalSimpleStringBlock { } + export class GeneralString extends LocalSimpleStringBlock { } + export class CharacterString extends LocalSimpleStringBlock { } + + interface UTCTimeParams extends LocalSimpleLocalSimpleStringValueBlockParams { + value?: string; + valueDate?: Date; + } + + export class UTCTime extends VisibleString { + year: number; + month: number; + day: number; + hour: number; + minute: number; + second: number; + constructor(params?: UTCTimeParams); + /** + * Function converting ASN.1 internal string into ArrayBuffer + * + * @returns {ArrayBuffer} + * + * @memberOf UTCTime + */ + toBuffer(): ArrayBuffer; + /** + * Function converting "Date" object into ASN.1 internal string + * + * @param {Date} inputDate JavaScript "Date" object + * + * @memberOf UTCTime + */ + fromDate(inputDate: Date): void; + /** + * Function converting ASN.1 internal string into "Date" object + * + * @returns {Date} + * + * @memberOf UTCTime + */ + toDate(): Date; + } + + class GeneralizedTime extends UTCTime { + millisecond: number; + } + + class DATE extends Utf8String { } + class TimeOfDay extends Utf8String { } + class DateTime extends Utf8String { } + class Duration extends Utf8String { } + class TIME extends Utf8String { } + + interface ChoiceParams { + value?: LocalValueBlock[]; + optional?: boolean; + } + + class Choice { + value: LocalValueBlock[]; + optional: boolean; + constructor(params?: ChoiceParams); + } + + interface AnyParams { + name?: string; + optional?: boolean; + } + class Any { + name: string; + optional: boolean; + constructor(params?: AnyParams); + } + + interface RepeatedParams { + name?: string; + optional?: boolean; + value?: Any; + local?: boolean; + } + class Repeated { + name: string; + optional: boolean; + value: Any; + local: boolean; + constructor(params?: RepeatedParams); + } + interface RawDataParams { + data?: ArrayBuffer; + } + class RawData { + data: ArrayBuffer; + + constructor(params?: RawDataParams); + + fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number; + toBER(sizeOnly?: boolean): ArrayBuffer; + } + + /** + * Major function for decoding ASN.1 BER array into internal library structuries + * + * @param {ArrayBuffer} inputBuffer ASN.1 BER encoded array of bytes + * @returns {{ offset: number; result: LocalBaseBlock }} + */ + function fromBER(inputBuffer: ArrayBuffer): { offset: number; result: LocalBaseBlock }; + + /** + * Compare of two ASN.1 object trees + * + * @param {*} root Root of input ASN.1 object tree + * @param {*} inputData Input ASN.1 object tree + * @param {*} inputSchema Input ASN.1 schema to compare with + * @returns {{ verified: boolean, result?: any }} + */ + function compareSchema(root: any, inputData: any, inputSchema: any): { verified: boolean, result?: any }; + + /** + * ASN.1 schema verification for ArrayBuffer data + * + * @param {ArrayBuffer} inputBuffer Input BER-encoded ASN.1 data + * @param {*} inputSchema Input ASN.1 schema to verify against to + * @returns {{ verified: boolean, result?: any }} + */ + function verifySchema(inputBuffer: ArrayBuffer, inputSchema: any): { verified: boolean, result?: any }; + +} \ No newline at end of file diff --git a/asn1js/tsconfig.json b/asn1js/tsconfig.json new file mode 100644 index 0000000000..8934574c23 --- /dev/null +++ b/asn1js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "asn1js-tests.ts" + ] +} diff --git a/async-polling/async-polling-tests.ts b/async-polling/async-polling-tests.ts new file mode 100644 index 0000000000..82adc0299e --- /dev/null +++ b/async-polling/async-polling-tests.ts @@ -0,0 +1,62 @@ +import AsyncPolling = require("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/index.d.ts b/async-polling/index.d.ts new file mode 100644 index 0000000000..640c863874 --- /dev/null +++ b/async-polling/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for AsyncPolling +// Project: https://github.com/cGuille/async-polling +// Definitions by: Zlatko Andonovski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace AsyncPolling { + export type EventName = "run"|"start"|"error"|"result"|"end"|"schedule"|"stop"; +} + +declare 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-polling/tsconfig.json b/async-polling/tsconfig.json new file mode 100644 index 0000000000..0611af7c76 --- /dev/null +++ b/async-polling/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "async-polling-tests.ts" + ] +} \ No newline at end of file diff --git a/async/async-tests.ts b/async/async-tests.ts index b724582368..c4a3506415 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -1,9 +1,10 @@ /// import fs = require("fs"); +import process = require("process"); -var path: { - exists: (path: string, callback?: (err: string, exists: boolean) => any) => void; +declare var path: { + exists: (path: string, callback?: (err: Error, exists: boolean) => any) => void; }; function callback() { } @@ -33,8 +34,8 @@ async.series([ function () { } ]); -var data = []; -function asyncProcess(item, callback) { } +var data: any[] = []; +function asyncProcess(item: any, callback: (err: Error, result: any) => void) { } async.map(data, asyncProcess, function (err, results) { console.log(results); }); @@ -49,11 +50,11 @@ var saveFile = function () { } async.each(openFiles, saveFile, function (err) { }); async.eachSeries(openFiles, saveFile, function (err) { }); -var documents, requestApi; +var documents: any, requestApi: any; async.eachLimit(documents, 20, requestApi, function (err) { }); // forEachOf* functions. May accept array or object. -function forEachOfIterator(item, key, forEachOfIteratorCallback) { +function forEachOfIterator(item: string, key: string, forEachOfIteratorCallback: any) { console.log("ForEach: item=" + item + ", key=" + key); forEachOfIteratorCallback(); } @@ -64,9 +65,8 @@ async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { }); async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { }); async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { }); -var process; var numArray = [1, 2, 3]; -function reducer(memo, item, callback) { +function reducer(memo: any, item: any, callback: any) { process.nextTick(function () { callback(null, memo + item) }); @@ -103,20 +103,20 @@ async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { async.series([ function (callback) { - callback(null, 'one'); + callback(undefined, 'one'); }, function (callback) { - callback(null, 'two'); + callback(undefined, 'two'); }, ], function (err, results) { }); async.series([ function (callback) { - callback(null, 'one'); + callback(undefined, 'one'); }, function (callback) { - callback(null, 'two'); + callback(undefined, 'two'); }, ], function (err, results) { }); @@ -124,12 +124,12 @@ function (err, results) { }); async.series({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, @@ -138,25 +138,25 @@ function (err, results) { }); async.series({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, function (err, results) { }); async.times(5, function(n, next) { - next(null, n) + next(undefined as any, n) }, function(err, results) { console.log(results) }) async.timesSeries(5, function(n, next) { - next(null, n) + next(undefined as any, n) }, function(err, results) { console.log(results) }) @@ -164,12 +164,12 @@ async.timesSeries(5, function(n, next) { async.parallel([ function (callback) { setTimeout(function () { - callback(null, 'one'); + callback(undefined, 'one'); }, 200); }, function (callback) { setTimeout(function () { - callback(null, 'two'); + callback(undefined, 'two'); }, 100); }, ], @@ -178,12 +178,12 @@ function (err, results) { }); async.parallel([ function (callback) { setTimeout(function () { - callback(null, 'one'); + callback(undefined, 'one'); }, 200); }, function (callback) { setTimeout(function () { - callback(null, 'two'); + callback(undefined, 'two'); }, 100); }, ], @@ -193,12 +193,12 @@ function (err, results) { }); async.parallel({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, @@ -207,12 +207,12 @@ function (err, results) { }); async.parallel({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, @@ -221,12 +221,12 @@ async.parallel({ async.parallelLimit({ one: function (callback) { setTimeout(function () { - callback(null, 1); + callback(undefined, 1); }, 200); }, two: function (callback) { setTimeout(function () { - callback(null, 2); + callback(undefined, 2); }, 100); }, }, @@ -235,7 +235,7 @@ async.parallelLimit({ ); -function whileFn(callback) { +function whileFn(callback: any) { count++; setTimeout(callback, 1000); } @@ -258,19 +258,19 @@ async.forever(function (errBack) { ); async.waterfall([ - function (callback) { + function (callback: any) { callback(null, 'one', 'two'); }, - function (arg1, arg2, callback) { + function (arg1: any, arg2: any, callback: any) { callback(null, 'three'); }, - function (arg1, callback) { + function (arg1: any, callback: any) { callback(null, 'done'); } ], function (err, result) { }); -var q = async.queue(function (task: any, callback) { +var q = async.queue(function (task: any, callback: any) { console.log('hello ' + task.name); callback(); }, 2); @@ -323,7 +323,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: any) { console.log('Task: ' + task); callback(); }, 1); @@ -358,26 +358,26 @@ var cargo = async.cargo(function (tasks, callback) { // add some items -cargo.push({ name: 'foo' }, function (err) { +cargo.push({ name: 'foo' }, function (err: Error) { console.log('finished processing foo'); }); -cargo.push({ name: 'bar' }, function (err) { +cargo.push({ name: 'bar' }, function (err: Error) { console.log('finished processing bar'); }); -cargo.push({ name: 'baz' }, function (err) { +cargo.push({ name: 'baz' }, function (err: Error) { console.log('finished processing baz'); }); var filename = ''; async.auto({ - get_data: function (callback) { }, - make_folder: function (callback) { }, + get_data: function (callback: any) { }, + make_folder: function (callback: any) { }, //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback) { + write_file: ['get_data', 'make_folder', function (callback: any) { callback(null, filename); }], //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback, results) { }] + email_link: ['write_file', function (callback: any, results: any) { }] }); async.retry(3, function (callback, results) { }, function (err, result) { }); @@ -411,13 +411,13 @@ async.parallel([ }, ]); -var call_order = []; +var call_order: string[] = []; async.nextTick(function () { call_order.push('two'); }); call_order.push('one'); -var slow_fn = function (name, callback) { +var slow_fn = function (name: string, callback: any) { callback(null, 123); }; var fn = async.memoize(slow_fn); @@ -427,15 +427,369 @@ async.ensureAsync(function () { }); async.constant(42); async.asyncify(function () { }); -async.log(function (name, callback) { +async.log(function (name: any, callback: any) { setTimeout(function () { callback(null, 'hello ' + name); }, 0); }, "world" ); -async.dir(function (name, callback) { +async.dir(function (name: string, callback: any) { setTimeout(function () { 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(undefined as any, 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(undefined as any, 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(undefined as any, 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(undefined as any, 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(undefined as any, 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(undefined as any, 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(undefined as any, 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(undefined as any, [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(undefined as any, 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(undefined as any, 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(undefined as any, 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..8b564fbd80 100644 --- a/async/index.d.ts +++ b/async/index.d.ts @@ -1,11 +1,13 @@ // 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 AsyncWaterfallCallback { (err: Error, ...args: any[]): void; } +interface AsyncBooleanResultCallback { (err: Error, truthValue: boolean): void; } interface AsyncResultCallback { (err: Error, result: T): void; } interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } @@ -15,7 +17,7 @@ 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 AsyncBooleanIterator { (item: T, callback: AsyncBooleanResultCallback): void; } interface AsyncWorker { (task: T, callback: ErrorCallback): void; } interface AsyncVoidFunction { (callback: ErrorCallback): void; } @@ -89,52 +91,74 @@ interface Async { // Collections each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; - eachSeries(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; - forEachOf(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, 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; - 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; + forEachOf(obj: Dictionary, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfSeries: typeof async.forEachOf; 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; + 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; @@ -143,14 +167,14 @@ interface Async { 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; + 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. @@ -158,19 +182,15 @@ interface Async { 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; + 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)[]; diff --git a/async/tsconfig.json b/async/tsconfig.json index c655cc101a..5c890605cd 100644 --- a/async/tsconfig.json +++ b/async/tsconfig.json @@ -2,8 +2,8 @@ "compilerOptions": { "module": "commonjs", "target": "es6", - "noImplicitAny": false, - "strictNullChecks": false, + "noImplicitAny": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/auth0-lock/index.d.ts b/auth0-lock/index.d.ts index 5d53fd8dc3..e9d7420917 100644 --- a/auth0-lock/index.d.ts +++ b/auth0-lock/index.d.ts @@ -122,5 +122,5 @@ interface Auth0LockStatic { declare var Auth0Lock: Auth0LockStatic; declare module "auth0-lock" { - export = Auth0Lock; + export default Auth0Lock; } diff --git a/awesomplete/awesomplete-tests.ts b/awesomplete/awesomplete-tests.ts new file mode 100644 index 0000000000..11abfdcba0 --- /dev/null +++ b/awesomplete/awesomplete-tests.ts @@ -0,0 +1,55 @@ +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/index.d.ts b/awesomplete/index.d.ts new file mode 100644 index 0000000000..d39389f008 --- /dev/null +++ b/awesomplete/index.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/awesomplete/tsconfig.json b/awesomplete/tsconfig.json new file mode 100644 index 0000000000..d76ee637ec --- /dev/null +++ b/awesomplete/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "awesomplete-tests.ts" + ] +} \ No newline at end of file diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index 72c443fab1..f54c3cc2d4 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -1,17 +1,18 @@ -import lambda = require('aws-lambda'); +/// -var str: string; -var date: Date; -var anyObj: any; -var num: number; -var identity: lambda.CognitoIdentity; -var error: Error; -var b: boolean; -var clientCtx: lambda.ClientContext; +var str: string = "any string"; +var date: Date = new Date(); +var anyObj: any = { abc: 123 }; +var num: number = 5; +var error: Error = new Error(); +var b: boolean = true; +var clientCtx: AWSLambda.ClientContext; +var clientContextEnv: AWSLambda.ClientContextEnv; +var clientContextClient: AWSLambda.ClientContextClient; +var context: AWSLambda.Context; +var identity: AWSLambda.CognitoIdentity; /* Context */ -var context: lambda.Context; - b = context.callbackWaitsForEmptyEventLoop; str = context.functionName; str = context.functionVersion; @@ -24,15 +25,41 @@ identity = context.identity; clientCtx = context.clientContext; /* CognitoIdentity */ -var identity: lambda.CognitoIdentity; - str = identity.cognitoIdentityId; str = identity.cognitoIdentityPoolId; +/* ClientContext */ +clientContextClient = clientCtx.client; +anyObj = clientCtx.Custom; +clientContextEnv = clientCtx.env; + +/* ClientContextEnv */ +str = clientContextEnv.locale; +str = clientContextEnv.make; +str = clientContextEnv.model; +str = clientContextEnv.platform; +str = clientContextEnv.platformVersion; + +/* ClientContextClient */ +str = clientContextClient.appPackageName; +str = clientContextClient.appTitle; +str = clientContextClient.appVersionCode; +str = clientContextClient.appVersionName; +str = clientContextClient.installationId; + /* Callback */ -function callback(cb: lambda.Callback) { +function callback(cb: AWSLambda.Callback) { cb(); 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..a5086eaadf 100644 --- a/aws-lambda/index.d.ts +++ b/aws-lambda/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - // Context // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html interface Context { @@ -23,7 +22,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; @@ -64,4 +65,6 @@ interface ClientContextEnv { * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. */ -export type Callback = (error?: Error, result?: any) => void; \ No newline at end of file +export type Callback = (error?: Error, result?: any) => void; + +export as namespace AWSLambda; \ No newline at end of file diff --git a/aws-sdk/aws-sdk-tests.ts b/aws-sdk/aws-sdk-tests.ts index 7d3b7a5c2c..5188a3e725 100644 --- a/aws-sdk/aws-sdk-tests.ts +++ b/aws-sdk/aws-sdk-tests.ts @@ -381,3 +381,42 @@ dynamoDBDocClient.query( else console.log(data); // successful response } ); + +var kinesis = new AWS.Kinesis(); + +var putRecordParam = { + Data: new Buffer('...') || 'STRING_VALUE', /* required */ + PartitionKey: 'STRING_VALUE', /* required */ + StreamName: 'STRING_VALUE', /* required */ + ExplicitHashKey: 'STRING_VALUE', + SequenceNumberForOrdering: 'STRING_VALUE' +}; +kinesis.putRecord(putRecordParam, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response +}); + +var putRecordParams = { + Records: [ /* required */ + { + Data: new Buffer('...') || 'STRING_VALUE', /* required */ + PartitionKey: 'STRING_VALUE', /* required */ + ExplicitHashKey: 'STRING_VALUE' + }, + /* more items */ + ], + StreamName: 'STRING_VALUE' /* required */ +}; +kinesis.putRecords(putRecordParams, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response +}); + +var increaseStreamRetentionPeriodParams = { + RetentionPeriodHours: 0, /* required */ + StreamName: 'STRING_VALUE' /* required */ +}; +kinesis.increaseStreamRetentionPeriod(increaseStreamRetentionPeriodParams, function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response +}); \ No newline at end of file diff --git a/aws-sdk/index.d.ts b/aws-sdk/index.d.ts index 83ecb93f53..fbee8f926c 100644 --- a/aws-sdk/index.d.ts +++ b/aws-sdk/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for aws-sdk // Project: https://github.com/aws/aws-sdk-js -// Definitions by: midknight41 +// Definitions by: midknight41 , Casper Skydt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Imported from: https://github.com/soywiz/typescript-node-definitions/aws-sdk.d.ts @@ -335,6 +335,56 @@ export declare class SNS { publish(request: Sns.PublishRequest, callback: (err: any, data: any) => void): void; } +export class Kinesis { + constructor(options?: any); + endpoint: Endpoint; + + putRecord(params: KINESIS.PutRecordParams, callback: (error: Error, data: KINESIS.PutRecordResult) => void): void; + putRecords(params: KINESIS.PutRecordsParams, callback: (error: Error, data: KINESIS.PutRecordsResult) => void): void; + increaseStreamRetentionPeriod(params: KINESIS.IncreaseStreamRetentionPeriodParams, callback: (error: Error, data: any) => void): void; + } + + export module KINESIS { + export interface Record { + Data: Buffer | string | Blob; + PartitionKey: string; + ExplicitHashKey?: string; + } + + export interface RecordResult { + SequenceNumber: string; + ShardId: string; + ErrorCode: string; + ErrorMessage: string; + } + + export interface PutRecordParams extends Record { + StreamName: string; + SequenceNumberForOrdering?: string; + } + + export interface PutRecordResult { + ShardId: string; + SequenceNumber: string; + } + + export interface PutRecordsParams { + StreamName: string; + Records: Record[]; + } + + export interface PutRecordsResult { + FailedRecordCount: number; + Records: RecordResult[] + } + + export interface IncreaseStreamRetentionPeriodParams { + RetentionPeriodHours: number; + StreamName: string; + } + } + + export declare class SWF { constructor(options?: any); endpoint: Endpoint; @@ -378,7 +428,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; @@ -522,7 +573,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 @@ -615,8 +667,8 @@ export module CloudFormation { ResourceTypes?: string[]; OnFailure?: string[]; // cannot specify both DisableRollback and OnFailure // DO_NOTHING | ROLLBACK | DELETE - StackPolicyBody?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL - StackPolicyURL?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL + StackPolicyBody?: string; // cannot specify both StackPolicyBody and StackPolicyURL + StackPolicyURL?: string; // cannot specify both StackPolicyBody and StackPolicyURL Tags?: CloudFormation.Tag[]; } @@ -2252,6 +2304,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..c46056ed25 --- /dev/null +++ b/aws-serverless-express/aws-serverless-express-tests.ts @@ -0,0 +1,28 @@ +/// + +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/index.d.ts b/aws-serverless-express/index.d.ts new file mode 100644 index 0000000000..e4601e6ccd --- /dev/null +++ b/aws-serverless-express/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for aws-serverless-express +// Project: https://github.com/awslabs/aws-serverless-express +// Definitions by: Ben Speakman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +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; \ No newline at end of file diff --git a/aws-serverless-express/tsconfig.json b/aws-serverless-express/tsconfig.json new file mode 100644 index 0000000000..7b42b1f538 --- /dev/null +++ b/aws-serverless-express/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aws-serverless-express-tests.ts" + ] +} \ No newline at end of file diff --git a/aws4/aws4-tests.ts b/aws4/aws4-tests.ts new file mode 100644 index 0000000000..b611951e45 --- /dev/null +++ b/aws4/aws4-tests.ts @@ -0,0 +1,24 @@ +/// + +import * as aws4 from "."; + +let requestSigner = new aws4.RequestSigner({}, {}); +requestSigner.matchHost(""); +requestSigner.isSingleRegion(); +requestSigner.createHost(); +requestSigner.prepareRequest(); +requestSigner.sign(); +requestSigner.getDateTime(); +requestSigner.getDate(); +requestSigner.authHeader(); +requestSigner.signature(); +requestSigner.stringToSign(); +requestSigner.canonicalString(); +requestSigner.canonicalHeaders(); +requestSigner.signedHeaders(); +requestSigner.credentialString(); +requestSigner.defaultCredentials(); +requestSigner.parsePath(); +requestSigner.formatPath(); + +aws4.sign({}, {}); diff --git a/aws4/index.d.ts b/aws4/index.d.ts new file mode 100644 index 0000000000..88f54f2a3f --- /dev/null +++ b/aws4/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for aws4 1.5.0 +// Project: https://github.com/mhart/aws4 +// Definitions by: Andrew Crites +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class RequestSigner { + constructor(request?: any, credentials?: any); + request: any; + credentials: any; + service: any; + region: any; + isCodeCommitGit: any; + + matchHost(host?: string): string; + isSingleRegion(): boolean; + createHost(): string; + prepareRequest(): void; + sign(): any; + getDateTime(): string; + getDate(): string; + authHeader(): string; + signature(): string; + stringToSign(): string; + canonicalString(): string; + canonicalHeaders(): string; + signedHeaders(): string; + credentialString(): string; + defaultCredentials(): any; + parsePath(): any; + formatPath(): string; +} + +export function sign(options?: any, credentials?: any): RequestSigner; diff --git a/aws4/tsconfig.json b/aws4/tsconfig.json new file mode 100644 index 0000000000..fb9528a526 --- /dev/null +++ b/aws4/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aws4-tests.ts" + ] +} 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/base64-js/base64-js-tests.ts b/base64-js/base64-js-tests.ts index 6852ddb626..13c3f705b5 100644 --- a/base64-js/base64-js-tests.ts +++ b/base64-js/base64-js-tests.ts @@ -1,6 +1,5 @@ -/// +import * as base64js from "base64-js"; -import * as base64js from 'base64-js'; - -const bytes: Uint8Array = base64js.toByteArray('shemp'); +const length: number = base64js.byteLength(""); +const bytes: Uint8Array = base64js.toByteArray(""); const decoded: string = base64js.fromByteArray(new Uint8Array(0)); diff --git a/base64-js/index.d.ts b/base64-js/index.d.ts index a029f384c3..7a38667368 100644 --- a/base64-js/index.d.ts +++ b/base64-js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for base64-js v1.1.2 +// Type definitions for base64-js 1.2 // Project: https://github.com/beatgammit/base64-js // Definitions by: Peter Safranek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export function byteLength(encoded: string): number; export function toByteArray(encoded: string): Uint8Array; -export function fromByteArray(bytes: Uint8Array): string; \ No newline at end of file +export function fromByteArray(bytes: Uint8Array): string; diff --git a/base64-js/tsconfig.json b/base64-js/tsconfig.json index dc8ef6a70a..0d0c14d324 100644 --- a/base64-js/tsconfig.json +++ b/base64-js/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "base64-js-test.ts" + "base64-js-tests.ts" ] } \ No newline at end of file diff --git a/base64-js/tslint.json b/base64-js/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/base64-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/bases/bases-tests.ts b/bases/bases-tests.ts new file mode 100644 index 0000000000..85aa71406e --- /dev/null +++ b/bases/bases-tests.ts @@ -0,0 +1,9 @@ +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/index.d.ts b/bases/index.d.ts new file mode 100644 index 0000000000..2111daddf6 --- /dev/null +++ b/bases/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for bases 0.2.1 +// Project: https://github.com/aseemk/bases.js +// Definitions by: Hari Krishna +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +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/bases/tsconfig.json b/bases/tsconfig.json new file mode 100644 index 0000000000..a8df7c46d9 --- /dev/null +++ b/bases/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bases-tests.ts" + ] +} \ No newline at end of file diff --git a/bind-ponyfill/bind-ponyfill-tests.ts b/bind-ponyfill/bind-ponyfill-tests.ts new file mode 100644 index 0000000000..8c5ba7ec05 --- /dev/null +++ b/bind-ponyfill/bind-ponyfill-tests.ts @@ -0,0 +1,8 @@ +import ponyBind = require('bind-ponyfill'); + +let boundFn: Function; + +boundFn = ponyBind(() => { console.log(this); }, 'Hello world!'); +boundFn = ponyBind((...args: Array) => { console.log(this, ...args); }, 'Hello world!', 'arg1'); +boundFn = ponyBind((...args: Array) => { console.log(this, ...args); }, 'Hello world!', 'arg1', 'arg2'); +boundFn = ponyBind((arg1: string, arg2: number) => { console.log(this, arg1, arg2); }, 'Hello world!', 'arg1', 2); \ No newline at end of file diff --git a/bind-ponyfill/index.d.ts b/bind-ponyfill/index.d.ts new file mode 100644 index 0000000000..8fb2227627 --- /dev/null +++ b/bind-ponyfill/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for bind-ponyfill 0.1.0 +// Project: https://www.npmjs.com/package/bind-ponyfill +// Definitions by: Steve Jenkins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function ponyBind(fn: Function, that: any, ...args: Array): Function; +export = ponyBind; \ No newline at end of file diff --git a/bind-ponyfill/tsconfig.json b/bind-ponyfill/tsconfig.json new file mode 100644 index 0000000000..44c1eca54a --- /dev/null +++ b/bind-ponyfill/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bind-ponyfill-tests.ts" + ] +} diff --git a/bit-array/bit-array-tests.ts b/bit-array/bit-array-tests.ts index 5e072967d9..7c1ff57b1b 100644 --- a/bit-array/bit-array-tests.ts +++ b/bit-array/bit-array-tests.ts @@ -1,3 +1,4 @@ +/// import BitArray = require("bit-array"); diff --git a/bonjour/bonjour-tests.ts b/bonjour/bonjour-tests.ts new file mode 100644 index 0000000000..1ae8a218fe --- /dev/null +++ b/bonjour/bonjour-tests.ts @@ -0,0 +1,20 @@ +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/index.d.ts b/bonjour/index.d.ts new file mode 100644 index 0000000000..0eb5b584c0 --- /dev/null +++ b/bonjour/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for bonjour v3.5.0 +// Project: https://github.com/watson/bonjour +// Definitions by: Quentin Lampin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +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/bonjour/tsconfig.json b/bonjour/tsconfig.json new file mode 100644 index 0000000000..07715bfe01 --- /dev/null +++ b/bonjour/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bonjour-tests.ts" + ] +} \ No newline at end of file diff --git a/bookshelf/bookshelf-tests.ts b/bookshelf/bookshelf-tests.ts index 8c59b88413..5b743bef71 100644 --- a/bookshelf/bookshelf-tests.ts +++ b/bookshelf/bookshelf-tests.ts @@ -2,6 +2,7 @@ import * as Knex from 'knex'; import * as Bookshelf from 'bookshelf'; import * as assert from 'assert'; import * as express from 'express'; +import * as _ from "lodash"; /** * The examples/tests below follow Bookshelf documentation chapter after chapter: http://bookshelfjs.org/ @@ -296,7 +297,7 @@ class Account extends bookshelf.Model { } { var checkit = require('checkit'); - + //todo: make sure this works with BlueBird 3.0 var bcrypt:any; // = Promise.promisifyAll(require('bcrypt')); 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..a692b663bb 100644 --- a/bootstrap-datepicker/index.d.ts +++ b/bootstrap-datepicker/index.d.ts @@ -12,7 +12,7 @@ * “w” (week), “m” (month), and “y” (year). * * See online docs for more info: - * http://bootstrap-datepicker.readthedocs.org/en/release/options.html + * https://bootstrap-datepicker.readthedocs.io/en/latest/options.html */ interface DatepickerOptions { format?: string | DatepickerCustomFormatOptions; @@ -36,6 +36,12 @@ interface DatepickerOptions { multidateSeparator?: string; orientation?: string; assumeNearbyYear?: any; + viewMode?: string; + templates?: any; + zIndexOffset?: number; + showOnFocus?: boolean; + immediateUpdates?: boolean; + title?: string; } interface DatepickerCustomFormatOptions { diff --git a/bootstrap-select/bootstrap-select-tests.ts b/bootstrap-select/bootstrap-select-tests.ts new file mode 100644 index 0000000000..e2e8c88560 --- /dev/null +++ b/bootstrap-select/bootstrap-select-tests.ts @@ -0,0 +1,40 @@ +/// + +$(".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/index.d.ts b/bootstrap-select/index.d.ts new file mode 100644 index 0000000000..5f511685ba --- /dev/null +++ b/bootstrap-select/index.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-select/tsconfig.json b/bootstrap-select/tsconfig.json new file mode 100644 index 0000000000..366216ab7f --- /dev/null +++ b/bootstrap-select/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bootstrap-select-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap-table/bootstrap-table-tests.ts b/bootstrap-table/bootstrap-table-tests.ts new file mode 100644 index 0000000000..6336ba4f8d --- /dev/null +++ b/bootstrap-table/bootstrap-table-tests.ts @@ -0,0 +1 @@ +$().bootstrapTable({}); diff --git a/bootstrap-table/index.d.ts b/bootstrap-table/index.d.ts new file mode 100644 index 0000000000..5ed1b5e529 --- /dev/null +++ b/bootstrap-table/index.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/bootstrap-table/tsconfig.json b/bootstrap-table/tsconfig.json new file mode 100644 index 0000000000..ad183f608a --- /dev/null +++ b/bootstrap-table/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bootstrap-table-tests.ts" + ] +} \ No newline at end of file diff --git a/braintree-web/braintree-web-tests.ts b/braintree-web/braintree-web-tests.ts index fb7e6325c5..c9aee724c0 100644 --- a/braintree-web/braintree-web-tests.ts +++ b/braintree-web/braintree-web-tests.ts @@ -48,10 +48,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/index.d.ts b/braintree-web/index.d.ts index 2cf2d89467..e58cf7455b 100644 --- a/braintree-web/index.d.ts +++ b/braintree-web/index.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 ` element to use. - */ - target?: (elem: Element) => Element; - - /** - * Returns the explicit text to copy. - * @param {Element} elem Current element - * @returns {String} Text to be copied. - */ - text?: (elem: Element) => string; -} - -interface ClipboardEvent { - action: string; - text: string; - trigger: Element; - clearSelection(): void; -} - declare module 'clipboard' { + class Clipboard { + constructor(selector: (string | Element | NodeListOf), options?: Clipboard.Options); + + /** + * Subscribes to events that indicate the result of a copy/cut operation. + * @param type {String} Event type ('success' or 'error'). + * @param handler Callback function. + */ + on(type: "success", handler: (e: Clipboard.Event) => void): this; + on(type: "error", handler: (e: Clipboard.Event) => void): this; + on(type: string, handler: (e: Clipboard.Event) => void): this; + + /** + * Clears all event bindings. + */ + destroy(): void; + } + + namespace Clipboard { + interface Options { + /** + * Overwrites default command ('cut' or 'copy'). + * @param {Element} elem Current element + * @returns {String} Only 'cut' or 'copy'. + */ + action?: (elem: Element) => string; + + /** + * Overwrites default target input element. + * @param {Element} elem Current element + * @returns {Element} element to use. + */ + target?: (elem: Element) => Element; + + /** + * Returns the explicit text to copy. + * @param {Element} elem Current element + * @returns {String} Text to be copied. + */ + text?: (elem: Element) => string; + } + + interface Event { + action: string; + text: string; + trigger: Element; + clearSelection(): void; + } + } + export = Clipboard; } diff --git a/code/code-tests.ts b/code/code-tests.ts new file mode 100644 index 0000000000..ea956c6c2c --- /dev/null +++ b/code/code-tests.ts @@ -0,0 +1,162 @@ +import { expect, settings, fail, count, incomplete, thrownAt } from "code"; + +expect(10).to.be.above(5); +expect("abc").to.be.a.string(); +expect([1, 2]).to.be.an.array(); +expect(20).to.be.at.least(20); +expect("abc").to.have.length(3); +expect("abc").to.be.a.string().and.contain(["a", "b"]); +expect(6).to.be.in.range(5, 6); + +expect(10).to.not.be.above(20); +expect([1, 2, 3]).to.shallow.include(3); +expect([1, 1, 2]).to.only.include([1, 2]); +expect([1, 2]).to.once.include([1, 2]); +expect([1, 2, 3]).to.part.include([1, 4]); + +expect(10, "Age").to.be.above(5); + +const func = function () { return arguments; }; +expect(func()).to.be.arguments(); + +expect([1, 2]).to.be.an.array(); + +expect(true).to.be.a.boolean(); + +expect(new Date()).to.be.a.date(); + +const err = new Error("Oops an error occured."); +expect(err).to.be.an.error(); +expect(err).to.be.an.error(Error); +expect(err).to.be.an.error("Oops an error occured."); +expect(err).to.be.an.error(Error, /occured/); + +expect(function () { }).to.be.a.function(); + +expect(123).to.be.a.number(); + +expect(/abc/).to.be.a.regexp(); + +expect("abc").to.be.a.string(); + +expect({ a: "1" }).to.be.an.object(); + +expect(true).to.be.true(); + +expect(false).to.be.false(); + +expect(null).to.be.null(); + +expect(undefined).to.be.undefined(); + +expect("abc").to.include("ab"); +expect("abc").to.only.include("abc"); +expect("aaa").to.only.include("a"); +expect("abc").to.once.include("b"); +expect("abc").to.include(["a", "c"]); +expect("abc").to.part.include(["a", "d"]); + +expect([1, 2, 3]).to.include(1); +expect([{ a: 1 }]).to.include({ a: 1 }); +expect([1, 2, 3]).to.include([1, 2]); +expect([{ a: 1 }]).to.include([{ a: 1 }]); +expect([1, 1, 2]).to.only.include([1, 2]); +expect([1, 2]).to.once.include([1, 2]); +expect([1, 2, 3]).to.part.include([1, 4]); +expect([[1], [2]]).to.include([[1]]); + +interface TestType { + a: number; + b?: number; + c?: number; + d?: number; +} + +interface TestType2 { + a: number[]; + b?: number[]; + c: number[]; +} + +expect({ a: 1, b: 2, c: 3 }).to.include("a"); +expect({ a: 1, b: 2, c: 3 }).to.include(["a", "c"]); +expect({ a: 1, b: 2, c: 3 }).to.only.include(["a", "b", "c"]); +expect({ a: 1, b: 2, c: 3 }).to.include({ a: 1 }); +expect({ a: 1, b: 2, c: 3 }).to.include({ a: 1 }); +expect({ a: 1, b: 2, c: 3 }).to.include({ a: 1, c: 3 }); +expect({ a: 1, b: 2, c: 3 }).to.part.include({ a: 1, d: 4 }); +expect({ a: 1, b: 2, c: 3 }).to.part.include({ a: 1, d: 4 }); +expect({ a: 1, b: 2, c: 3 }).to.only.include({ a: 1, b: 2, c: 3 }); +expect({ a: [1], b: [2], c: [3] }).to.include({ a: [1], c: [3] }); +expect({ a: [1], b: [2], c: [3] }).to.include({ a: [1], c: [3] }); + +expect("https://example.org/secure").to.startWith("https://"); + +expect("http://example.org/relative").to.endWith("/relative"); + +expect(4).to.exist(); +expect(null).to.not.exist(); + +expect("abc").to.be.empty(); + +expect("abcd").to.have.length(4); + +expect(5).to.equal(5); +expect({ a: 1 }).to.equal({ a: 1 }); + +expect(Object.create(null)).to.equal({}, { prototype: false }); + +expect(5).to.shallow.equal(5); +expect({ a: 1 }).to.shallow.equal({ a: 1 }); + +expect(10).to.be.above(5); + +expect(10).to.be.at.least(10); + +expect(10).to.be.below(20); + +expect(10).to.be.at.most(10); + +expect(10).to.be.within(10, 20); +expect(20).to.be.within(10, 20); + +expect(15).to.be.between(10, 20); + +expect(10).to.be.about(9, 1); + +expect(new Date()).to.be.an.instanceof(Date); + +expect("a5").to.match(/\w\d/); +expect(["abc", "def"]).to.match(/^[\w\d,]*$/); +expect(1).to.match(/^\d$/); + +expect("x").to.satisfy(value => value === "x"); + +class CustomError extends Error { + call: (message: string) => Error; +} + +const throws = function () { + + throw new CustomError("Oh no!"); +}; + +expect(throws).to.throw(CustomError, "Oh no!"); + +fail("This should not occur"); + +expect(count()).to.be.a.number(); + +expect(incomplete()).to.be.null().and.not.be.an.array(); + +const error = thrownAt(new Error("oops")); +expect(error).to.not.be.undefined(); +expect(error.column).to.exist(); + +const foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; +settings.truncateMessages = false; +expect(foo).to.equal([]); + +const bar = Object.create(null); +settings.comparePrototypes = false; +expect(bar).to.equal({}); diff --git a/code/index.d.ts b/code/index.d.ts new file mode 100644 index 0000000000..174215f5d8 --- /dev/null +++ b/code/index.d.ts @@ -0,0 +1,188 @@ +// Type definitions for code 4.0.0 +// Project: https://github.com/hapijs/code +// Definitions by: Prashant Tiwari +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Generates an assertion object. */ +export function expect(value: T | T[], prefix?: string): AssertionChain; +/** Makes the test fail with the given message. */ +export function fail(message: string): void; +/** Returns the total number of assertions created using the expect() method. */ +export function count(): number; +/** Returns an array of the locations where incomplete assertions were declared or null if no incomplete assertions found. */ +export function incomplete(): Array | null; +/** Returns the filename, line number, and column number of where the error was created. */ +export function thrownAt(error?: Error): CodeError; +/** Configure code. */ +export const settings: Settings; + +type AssertionChain = Assertion & Expectation; + +interface Assertion extends Grammar, Flags { } + +interface Expectation extends Types, Values { } + +interface Grammar { + /** Connecting word. */ + a: AssertionChain; + /** Connecting word. */ + an: AssertionChain; + /** Connecting word. */ + and: AssertionChain; + /** Connecting word. */ + at: AssertionChain; + /** Connecting word. */ + be: AssertionChain; + /** Connecting word. */ + have: AssertionChain; + /** Connecting word. */ + in: AssertionChain; + /** Connecting word. */ + to: AssertionChain; +} + +interface Flags { + /** Inverses the expected result of any assertion */ + not: AssertionChain; + /** + * Requires that inclusion matches appear only once in the provided value. + * Used by include(). + */ + once: AssertionChain; + /** + * Requires that only the provided elements appear in the provided value. + * Used by include(). + */ + only: AssertionChain; + /** + * Allows a partial match when asserting inclusion + * Used by include(). Defaults to false. + */ + part: AssertionChain; + /** + * Performs a comparison using strict equality (===). + * Code defaults to deep comparison. Used by equal() and include(). + */ + shallow: AssertionChain; +} + +interface Types { + /** Asserts that the reference value is an arguments object. */ + arguments(): AssertionChain; + /** Asserts that the reference value is an Array. */ + array(): AssertionChain; + /** Asserts that the reference value is a boolean. */ + boolean(): AssertionChain; + /** Asserts that the reference value is a Buffer. */ + buffer(): AssertionChain; + /** Asserts that the reference value is a Date. */ + date(): AssertionChain; + /** Asserts that the reference value is an error. */ + error(type?: Object, message?: string | RegExp): AssertionChain; + /** Asserts that the reference value is a function. */ + function(): AssertionChain; + /** Asserts that the reference value is a number. */ + number(): AssertionChain; + /** Asserts that the reference value is a RegExp. */ + regexp(): AssertionChain; + /** Asserts that the reference value is a string. */ + string(): AssertionChain; + /** Asserts that the reference value is an object (excluding array, buffer, or other native objects). */ + object(): AssertionChain; +} + +interface Values { + /** Asserts that the reference value is true. */ + true(): AssertionChain; + /** Asserts that the reference value is false. */ + false(): AssertionChain; + /** Asserts that the reference value is null. */ + null(): AssertionChain; + /** Asserts that the reference value is undefined. */ + undefined(): AssertionChain; + /** Asserts that the reference value (a string, array, or object) includes the provided values. */ + include(values: string | string[] | T | T[]): AssertionChain; + /** Asserts that the reference value (a string, array, or object) includes the provided values. */ + includes(values: string | string[] | T | T[]): AssertionChain; + /** Asserts that the reference value (a string, array, or object) includes the provided values. */ + contain(values: string | string[] | T | T[]): AssertionChain; + /** Asserts that the reference value (a string, array, or object) includes the provided values. */ + contains(values: string | string[] | T | T[]): AssertionChain; + /** Asserts that the reference value (a string) starts with the provided value. */ + startWith(value: string): AssertionChain; + /** Asserts that the reference value (a string) starts with the provided value. */ + startsWith(value: string): AssertionChain; + /** Asserts that the reference value (a string) ends with the provided value. */ + endWith(value: string): AssertionChain; + /** Asserts that the reference value (a string) ends with the provided value. */ + endsWith(value: string): AssertionChain; + /** Asserts that the reference value exists (not null or undefined). */ + exist(): AssertionChain; + /** Asserts that the reference value exists (not null or undefined). */ + exists(): AssertionChain; + /** Asserts that the reference value has a length property equal to zero or an object with no keys. */ + empty(): AssertionChain; + /** Asserts that the reference value has a length property matching the provided size or an object with the specified number of keys. */ + length(size: number): AssertionChain; + /** Asserts that the reference value equals the provided value. */ + equal(value: T, options?: any): AssertionChain; + /** Asserts that the reference value equals the provided value. */ + equals(value: T, options?: any): AssertionChain; + /** Asserts that the reference value is greater than (>) the provided value. */ + above(value: T): AssertionChain; + /** Asserts that the reference value is greater than (>) the provided value. */ + greaterThan(value: T): AssertionChain; + /** Asserts that the reference value is at least (>=) the provided value. */ + least(value: T): AssertionChain; + /** Asserts that the reference value is at least (>=) the provided value. */ + min(value: T): AssertionChain; + /** Asserts that the reference value is less than (<) the provided value. */ + below(value: T): AssertionChain; + /** Asserts that the reference value is less than (<) the provided value. */ + lessThan(value: T): AssertionChain; + /** Asserts that the reference value is at most (<=) the provided value. */ + most(value: T): AssertionChain; + /** Asserts that the reference value is at most (<=) the provided value. */ + max(value: T): AssertionChain; + /** Asserts that the reference value is within (from <= value <= to) the provided values. */ + within(from: T, to: T): AssertionChain; + /** Asserts that the reference value is within (from <= value <= to) the provided values. */ + range(from: T, to: T): AssertionChain; + /** Asserts that the reference value is between but not equal (from < value < to) the provided values. */ + between(from: T, to: T): AssertionChain; + /** Asserts that the reference value is about the provided value within a delta margin of difference. */ + about(value: number, delta: number): AssertionChain; + /** Asserts that the reference value has the provided instanceof value. */ + instanceof(type: Object): AssertionChain; + /** Asserts that the reference value has the provided instanceof value. */ + instanceOf(type: Object): AssertionChain; + /** Asserts that the reference value's toString() representation matches the provided regular expression. */ + match(regex: RegExp): AssertionChain; + /** Asserts that the reference value's toString() representation matches the provided regular expression. */ + matches(regex: RegExp): AssertionChain; + /** Asserts that the reference value satisfies the provided validator function. */ + satisfy(validator: (value: T) => boolean): AssertionChain; + /** Asserts that the reference value satisfies the provided validator function. */ + satisfies(validator: (value: T) => boolean): AssertionChain; + /** Asserts that the function reference value throws an exception when called. */ + throw(type: Object, message: string | RegExp): AssertionChain; +} + +interface Settings { + /** + * Truncate long assertion error messages for readability? + * Defaults to true. + */ + truncateMessages?: boolean; + /** + * Ignore object prototypes when doing a deep comparison? + * Defaults to false. + */ + comparePrototypes?: boolean; +} + +interface CodeError { + filename: string; + line: string; + column: string; +} diff --git a/code/tsconfig.json b/code/tsconfig.json new file mode 100644 index 0000000000..d0299c6345 --- /dev/null +++ b/code/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "code-tests.ts" + ] +} \ No newline at end of file diff --git a/codemirror/index.d.ts b/codemirror/index.d.ts index fbbf2d84fd..83c45e93ab 100644 --- a/codemirror/index.d.ts +++ b/codemirror/index.d.ts @@ -393,8 +393,8 @@ declare namespace CodeMirror { /** Fired whenever a line is (re-)rendered to the DOM. Fired right after the DOM element is built, before it is added to the document. The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor. */ - on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; - off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; + on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: CodeMirror.LineHandle, element: HTMLElement) => void ): void; + off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: CodeMirror.LineHandle, element: HTMLElement) => void ): void; /** Expose the state object, so that the Editor.state.completionActive property is reachable*/ state: any; @@ -430,7 +430,7 @@ declare namespace CodeMirror { /** Replace the part of the document between from and to with the given string. from and to must be {line, ch} objects. to can be left off to simply insert the string at position from. */ - replaceRange(replacement: string, from: CodeMirror.Position, to: CodeMirror.Position): void; + replaceRange(replacement: string, from: CodeMirror.Position, to?: CodeMirror.Position): void; /** Get the content of line n. */ getLine(n: number): string; @@ -1240,4 +1240,3 @@ declare namespace CodeMirror { } } } - diff --git a/color/color-tests.ts b/color/color-tests.ts new file mode 100644 index 0000000000..1b2d9369e0 --- /dev/null +++ b/color/color-tests.ts @@ -0,0 +1,79 @@ +import * as Color from "color" + +var color: Color.Color = Color("white") +var colorOther: Color.Color = Color("black") + +var colorRGB: Color.Color = color.rgb(0, 0, 0) +var colorRGB: Color.Color = color.rgb([0, 0, 0]) +var rgb: Color.RGBColor = color.rgb() + +var colorHSL: Color.Color = color.hsl([0, 0, 0]) +var hsl: Color.HSLColor = color.hsl() + +var colorHSV: Color.Color = color.hsv([0, 0, 0]) +var hsv: Color.HSVColor = color.hsv() + +var colorHBW: Color.Color = color.hbw([0, 0, 0]) +var hbw: Color.HBWColor = color.hbw() + +var colorCMYK: Color.Color = color.cmyk([0, 0, 0, 0]) +var cmyk: Color.CMYKColor = color.cmyk() + +var hex: string = color.hexString() +var percent: string = color.percentString() +var keyword: string | void = color.keyword() +var alpha: number = color.alpha() +var red: number = color.red() +var green: number = color.green() +var blue: number = color.blue() +var hue: number = color.hue() +var saturation: number = color.saturation() +var lightness: number = color.lightness() +var saturationv: number = color.saturationv() +var value: number = color.value() +var whiteness: number = color.whiteness() +var blackness: number = color.blackness() +var cyan: number = color.cyan() +var magenta: number = color.magenta() +var yellow: number = color.yellow() +var black: number = color.black() +var luminosity: number = color.luminosity() +var contrast: number = color.contrast(colorOther) +var dark: boolean = color.dark() +var light: boolean = color.light() +var level: string = color.level(colorOther) + +var chain: Color.Color = color + .rgb(0, 0, 0) + .hsl([0, 0, 0]) + .hsv([0, 0, 0]) + .hbw([0, 0, 0]) + .cmyk([0, 0, 0 ,0]) + .alpha(0) + .red(0) + .green(0) + .blue(0) + .hue(0) + .saturation(0) + .lightness(0) + .saturationv(0) + .value(0) + .whiteness(0) + .blackness(0) + .cyan(0) + .magenta(0) + .yellow(0) + .black(0) + .negate() + .lighten(0) + .darken(0) + .saturate(0) + .desaturate(0) + .greyscale() + .whiten(0) + .blacken(0) + .clearer(0) + .opaquer(0) + .rotate(0) + .mix(colorOther, 0) + .clone() diff --git a/color/index.d.ts b/color/index.d.ts new file mode 100644 index 0000000000..0395cd1bf9 --- /dev/null +++ b/color/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for color v0.12.0 +// Project: https://github.com/qix-/color +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Color { + + interface RGBColor { + r: number + g: number + b: number + a?: number + } + + interface FullRGBColor { + red: number + green: number + blue: number + alpha?: number + } + + interface HSLColor { + h: number + s: number + l: number + a?: number + } + + interface FullHSLColor { + hue: number + saturation: number + lightness: number + alpha?: number + } + + interface HSVColor { + h: number + s: number + v: number + } + + interface FullHSVColor { + hue: number + saturation: number + value: number + } + + interface HBWColor { + h: number + b: number + w: number + } + + interface FullHBWColor { + hue: number + whiteness: number + blackness: number + } + + interface CMYKColor { + c: number + m: number + y: number + k: number + } + + interface FullCMYKColor { + cyan: number + magenta: number + yellow: number + black: number + } + + type ColorParam = string | RGBColor | FullRGBColor | HSLColor | FullHSLColor | HSVColor + | FullHSVColor | HBWColor | FullHBWColor | CMYKColor | FullCMYKColor + + interface Color { + (color: ColorParam | Color) : Color + rgb(values: Array): Color + rgb(r: number, g: number, b: number, a?: number): Color + rgb(values: RGBColor): Color + rgb(values: FullRGBColor): Color + rgb(): RGBColor + rgbArray(): Array + rgbString(): string + rgbaString(): string + rgbNumber(): number + hsl(values: Array): Color + hsl(): HSLColor + hslArray(): Array + hslString(): string + hslaString(): string + hsv(values: Array): Color + hsv(): HSVColor + hsvArray(): Array + hsvString(): string + hbw(values: Array): Color + hbw(): HBWColor + hbwArray(): Array + hbwString(): string + cmyk(values: Array): Color + cmyk(): CMYKColor + cmykArray(): Array + cmykString(): string + hexString(): string + percentString(): string + keyword(): string | void + alpha(alpha: number): Color + alpha(): number + red(red: number): Color + red(): number + green(green: number): Color + green(): number + blue(blue: number): Color + blue(): number + hue(hue: number): Color + hue(): number + saturation(saturation: number): Color + saturation(): number + lightness(lightness: number): Color + lightness(): number + saturationv(saturationv: number): Color + saturationv(): number + value(value: number): Color + value(): number + whiteness(whiteness: number): Color + whiteness(): number + blackness(blackness: number): Color + blackness(): number + cyan(cyan: number): Color + cyan(): number + magenta(magenta: number): Color + magenta(): number + yellow(yellow: number): Color + yellow(): number + black(black: number): Color + black(): number + luminosity(): number + contrast(color: Color): number + dark(): boolean + light(): boolean + negate(): Color + lighten(value: number): Color + darken(value: number): Color + saturate(value: number): Color + desaturate(value: number): Color + greyscale(): Color + whiten(value: number): Color + blacken(value: number): Color + clearer(value: number): Color + opaquer(value: number): Color + rotate(value: number): Color + mix(color: Color, value?: number): Color + level(color: Color): string + clone(): Color + } +} + +declare const Color: Color.Color; +export = Color; +export as namespace Color; diff --git a/color/tsconfig.json b/color/tsconfig.json new file mode 100644 index 0000000000..860f35d441 --- /dev/null +++ b/color/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-tests.ts" + ] +} \ No newline at end of file diff --git a/com.darktalker.cordova.screenshot/com.darktalker.cordova.screenshot-tests.ts b/com.darktalker.cordova.screenshot/com.darktalker.cordova.screenshot-tests.ts new file mode 100644 index 0000000000..f7ed9d8b59 --- /dev/null +++ b/com.darktalker.cordova.screenshot/com.darktalker.cordova.screenshot-tests.ts @@ -0,0 +1,6 @@ +navigator.screenshot.save(() => {/**/}); +navigator.screenshot.save(() => {/**/}, 'jpg', 50); +navigator.screenshot.save(() => {/**/}, 'jpg', 50, 'myScreenShot'); + +navigator.screenshot.URI(() => {/**/}); +navigator.screenshot.URI(() => {/**/}, 50); diff --git a/com.darktalker.cordova.screenshot/index.d.ts b/com.darktalker.cordova.screenshot/index.d.ts new file mode 100644 index 0000000000..b2df93b22b --- /dev/null +++ b/com.darktalker.cordova.screenshot/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for com.darktalker.cordova.screenshot v0.1.5 +// Project: https://github.com/gitawego/cordova-screenshot +// Definitions by: Ivana Dolezalova +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace com.darktalker.cordova.screenshot { + interface Plugin { + /** + * Takes a screenshot, saves it to device as JPG and provides a path to the file. + * + * @param saveCallback callback function, holds results + * @param format format of to be taken image, possible values are 'jpg' and 'png' ('jpg' is default) + * @param quality custom quality of to be taken image in percentage (100 is default) + * @param filename custom filename of to be taken image, ('screenshot_.' is default) + */ + save(saveCallback: (errorMessage: string, successObject: {success: boolean, filePath: string}) => void, + format?: string, + quality?: number, + filename?: string): void; + + /** + * Takes a screenshot and provides it trough data URI as JPG. No data are saved in the device. + * + * @param uriCallback callback function, holds results + * @param quality custom quality of to be taken image in percentage (100 is default) + */ + URI(uriCallback: (errorMessage: string, successObject: {URI: string}) => void, + quality?: number): void; + } +} + +interface Navigator { + screenshot: com.darktalker.cordova.screenshot.Plugin; +} diff --git a/com.darktalker.cordova.screenshot/tsconfig.json b/com.darktalker.cordova.screenshot/tsconfig.json new file mode 100644 index 0000000000..0b1d4ae264 --- /dev/null +++ b/com.darktalker.cordova.screenshot/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "com.darktalker.cordova.screenshot-tests.ts" + ] +} diff --git a/content-type/content-type-tests.ts b/content-type/content-type-tests.ts index 0e5eb2c048..f173a1efbb 100644 --- a/content-type/content-type-tests.ts +++ b/content-type/content-type-tests.ts @@ -15,3 +15,5 @@ obj = contentType.parse(res); var str: string = contentType.format({type: 'image/svg+xml'}); +var media: contentType.MediaType; +contentType.format(media); diff --git a/content-type/index.d.ts b/content-type/index.d.ts index 0095367565..3dd39182f4 100644 --- a/content-type/index.d.ts +++ b/content-type/index.d.ts @@ -3,10 +3,10 @@ // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare var x: ContentType.StaticFunctions; -export = x; +declare var ct: ct.StaticFunctions; +export = ct; -declare namespace ContentType { +declare namespace ct { interface StaticFunctions { parse(string: string): MediaType; parse(req: { headers: any; }): MediaType; diff --git a/convert-source-map/index.d.ts b/convert-source-map/index.d.ts index 22fda2b62b..cc870fed66 100644 --- a/convert-source-map/index.d.ts +++ b/convert-source-map/index.d.ts @@ -1,26 +1,27 @@ -// Type definitions for convert-source-map +// Type definitions for convert-source-map v1.3.0 // Project: https://github.com/thlorenz/convert-source-map -// Definitions by: Andrew Gaspar +// Definitions by: Andrew Gaspar , Melvin Groenhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - export interface SourceMapConverter { toObject(): any; toJSON(space?: any): string; toBase64(): string; - toComment(): string; - - addProperty(key: string, value: any): SourceMapConverter; - setProperty(key: string, value: any): SourceMapConverter; - + toComment(options?: { multiline?: boolean; }): string; + addProperty(key: string, value: any): this; + setProperty(key: string, value: any): this; getProperty(key: string): any; } -export declare function removeComments(src: string): string; -export declare var commentRegex: RegExp; - export declare function fromObject(obj: any): SourceMapConverter; export declare function fromJSON(json: string): SourceMapConverter; export declare function fromBase64(base64: string): SourceMapConverter; export declare function fromComment(comment: string): SourceMapConverter; -export declare function fromSource(source: string): SourceMapConverter; +export declare function fromMapFileComment(comment: string, mapFileDir: string): SourceMapConverter; +export declare function fromSource(source: string, largeSource?: boolean): SourceMapConverter | null; +export declare function fromMapFileSource(source: string, mapFileDir: string): SourceMapConverter | null; +export declare function removeComments(src: string): string; +export declare function removeMapFileComments(src: string): string; +export declare function generateMapFileComment(file: string, options?: { multiline?: boolean; }): string; +export declare var commentRegex: RegExp; +export declare var mapFileCommentRegex: RegExp; diff --git a/cookiejs/tsconfig.json b/cookiejs/tsconfig.json index 49aa749ae4..76d537c57c 100644 --- a/cookiejs/tsconfig.json +++ b/cookiejs/tsconfig.json @@ -5,11 +5,11 @@ "noImplicitAny": true, "strictNullChecks": false, "baseUrl": "../", - "typesSearchPaths": [ + "typeRoots": [ "../" ], + "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true }, "files": [ diff --git a/copy-webpack-plugin/copy-webpack-plugin-tests.ts b/copy-webpack-plugin/copy-webpack-plugin-tests.ts new file mode 100644 index 0000000000..022a734261 --- /dev/null +++ b/copy-webpack-plugin/copy-webpack-plugin-tests.ts @@ -0,0 +1,72 @@ +import { Configuration } from 'webpack' +import * as CopyWebpackPlugin from 'copy-webpack-plugin' + +const c: Configuration = { + plugins: [ + new CopyWebpackPlugin([ + // {output}/file.txt + { from: 'from/file.txt' }, + + // {output}/to/file.txt + { from: 'from/file.txt', to: 'to/file.txt' }, + + // {output}/to/directory/file.txt + { from: 'from/file.txt', to: 'to/directory' }, + + // Copy directory contents to {output}/ + { from: 'from/directory' }, + + // Copy directory contents to {output}/to/directory/ + { from: 'from/directory', to: 'to/directory' }, + + // Copy glob results to /absolute/path/ + { from: 'from/directory/**/*', to: '/absolute/path' }, + + // Copy glob results (with dot files) to /absolute/path/ + { + from: { + glob:'from/directory/**/*', + dot: true, + }, + to: '/absolute/path' + }, + + // Copy glob results, relative to context + { + context: 'from/directory', + from: '**/*', + to: '/absolute/path' + }, + + // {output}/file/without/extension + { + from: 'path/to/file.txt', + to: 'file/without/extension', + toType: 'file' + }, + + // {output}/directory/with/extension.ext/file.txt + { + from: 'path/to/file.txt', + to: 'directory/with/extension.ext', + toType: 'dir' + }, + ], { + ignore: [ + // Doesn't copy any files with a txt extension + '*.txt', + + // Doesn't copy any file, even if they start with a dot + '**/*', + + // Doesn't copy any file, except if they start with a dot + { glob: '**/*', dot: false } + ], + + // By default, we only copy modified files during + // a watch or webpack-dev-server build. Setting this + // to `true` copies all files. + copyUnmodified: true, + }) + ] +} diff --git a/copy-webpack-plugin/index.d.ts b/copy-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..11a3a30dd9 --- /dev/null +++ b/copy-webpack-plugin/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for copy-webpack-plugin v4.0.0 +// Project: https://github.com/kevlened/copy-webpack-plugin +// Definitions by: flying-sheep +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin } from 'webpack' +import { IOptions } from 'minimatch' + +interface MiniMatchGlob extends IOptions { + glob: string +} + +interface CopyPattern { + /** File source path or glob */ + from: string | MiniMatchGlob + /** + * Path or webpack file-loader patterns. defaults: + * output root if `from` is file or dir. + * resolved glob path if `from` is glob. + */ + to?: string + /** + * How to interpret `to`. defaults: + * 'file' if to has extension or from is file. + * 'dir' if from is directory, to has no extension or ends in '/'. + * 'template' if to contains a template pattern. + */ + toType?: 'file' | 'dir' | 'template' + /** A path that determines how to interpret the `from` path. (default: `compiler.options.context`) */ + context?: string + /** + * Removes all directory references and only copies file names. + * + * If files have the same name, the result is non-deterministic. (default: `false`) + */ + flatten?: boolean + /** Additional globs to ignore for this pattern. (default: `[]`) */ + ignore?: Array + /** Function that modifies file contents before writing to webpack. (default: `(content, path) => content`) */ + transform?: (content: string, path: string) => string + /** Overwrites files already in `compilation.assets` (usually added by other plugins; default: `false`) */ + force?: boolean +} + +interface CopyWebpackPluginConfiguration { + /** Array of globs to ignore. (applied to from; default: `[]`) */ + ignore?: Array + /** Copies files, regardless of modification when using `watch` or `webpack-dev-server`. All files are copied on first build, regardless of this option. (default: `false`) */ + copyUnmodified?: boolean + /** Debug level. warning: only warnings, info/true: file location and read info, debug: very detailed debugging info. (default: `'warning'`) */ + debug?: 'warning' | 'info'|true | 'debug' +} + +interface CopyWebpackPlugin { + new (patterns?: CopyPattern[], options?: CopyWebpackPluginConfiguration): Plugin +} + +declare const copyWebpackPlugin: CopyWebpackPlugin +export = copyWebpackPlugin diff --git a/copy-webpack-plugin/tsconfig.json b/copy-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..1d8d63e8ac --- /dev/null +++ b/copy-webpack-plugin/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "copy-webpack-plugin-tests.ts" + ] +} diff --git a/cordova-plugin-battery-status/tsconfig.json b/cordova-plugin-battery-status/tsconfig.json index b781800488..0ba34b4eaf 100644 --- a/cordova-plugin-battery-status/tsconfig.json +++ b/cordova-plugin-battery-status/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts b/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts new file mode 100644 index 0000000000..6e4317ac9d --- /dev/null +++ b/cordova-plugin-ble-central/cordova-plugin-ble-central-tests.ts @@ -0,0 +1,119 @@ +var log = (msg : string) => {}; +var devices: BLECentralPlugin.PeripheralData[] = []; +var demoDevice :BLECentralPlugin.PeripheralData = { + "name": "Battery Demo", + "id": "20:FF:D0:FF:D1:C0", + "advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121], + "rssi": -55 +}; + +devices.push(demoDevice); +var demoExtendedData : BLECentralPlugin.PeripheralDataExtended = { + "name": "Battery Demo", + "id": "20:FF:D0:FF:D1:C0", + "advertising": [2,1,6,3,3,15,24,8,9,66,97,116,116,101,114,121], + "rssi": -55, + "services": [ + "1800", + "1801", + "180f" + ], + "characteristics": [ + { + "service": "1800", + "characteristic": "2a00", + "properties": [ + "Read" + ] + }, + { + "service": "1800", + "characteristic": "2a01", + "properties": [ + "Read" + ] + }, + { + "service": "1801", + "characteristic": "2a05", + "properties": [ + "Read" + ] + }, + { + "service": "180f", + "characteristic": "2a19", + "properties": [ + "Read" + ], + "descriptors": [ + { + "uuid": "2901" + }, + { + "uuid": "2904" + } + ] + } + ] +}; + + +//get updates about the bluethooth states +ble.startStateNotifications((state) => log(`BLE state ${state}`)); + +ble.isEnabled(()=> log(`bluetooth is enabled`), ()=>log(`bluetooth is not enabled`)); + +//here we try to enable bluetooth +ble.enable(() => log(`yes it worked, or it was already enabled `), () => log(`nope it didn't work, the user pressed cancel, or we are in iOS`)); + +ble.showBluetoothSettings(() => log(`yes it worked`), () => log(`nope it didn't work`)) + +//stop getting updates about the bluethooth states +ble.stopStateNotifications() + +//scan 5 seconds +ble.scan([], 5000, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ); + +//scan continously +ble.startScan([], (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ) + +////scan continously +ble.startScanWithOptions([], {reportDuplicates:false }, (data) => { devices.push(data); }, ()=> log('couldn\'t connect') ) + +//stop scanning +ble.stopScan(()=> log('all good'), ()=> log('couldn\'t stop scanning')); + +//are we conenected to that device? +ble.isConnected(demoDevice.id, () => log(`already connected to this device`), ()=> log(`not yet connected to that device`)); + +//connect to a specific device +var extendedData : BLECentralPlugin.PeripheralDataExtended; +ble.connect(demoDevice.id, (data)=> extendedData = data, () => log(`couldn't connect to the device`) ); + +//read some data from a characteristic +var charsOfOneOfItsServices = demoExtendedData.characteristics.filter((value) => value.service == demoExtendedData.services[0]); +ble.read(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data) => log(`we've received some data`), ()=> log(`couldn't read any data`)); + +//read the rssi +ble.readRSSI(demoDevice.id, (rssi)=>log(`Device ${demoDevice.name} has an RSSI of ${rssi}`)); + +var notificationsReceived : number = 0; +//get notified of changes for that characteristic +ble.startNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, (data)=> notificationsReceived++, ()=> log(`darn`)); + +//write some data +ble.write(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`)); +//write some data without getting notified +ble.writeWithoutResponse(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic, new ArrayBuffer(40), ()=> log(`all good`), ()=> log(`could't write`)); + +//stop getting notified of changes. +ble.stopNotification(demoDevice.id, charsOfOneOfItsServices[0].service, charsOfOneOfItsServices[0].characteristic); + +//notificationsReceived == 1 + +//just disconnect +ble.disconnect(demoDevice.id); + + + diff --git a/cordova-plugin-ble-central/index.d.ts b/cordova-plugin-ble-central/index.d.ts new file mode 100644 index 0000000000..ccf2396833 --- /dev/null +++ b/cordova-plugin-ble-central/index.d.ts @@ -0,0 +1,108 @@ +// Type definitions for cordova-plugin-ble-central 1.1.2 +// Project: https://github.com/don/cordova-plugin-ble-central +// Definitions by: Gidon Junge +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare namespace BLECentralPlugin { + + interface PeripheralCharacteristic { + service: string; + characteristic: string; + properties: string[]; + descriptors?: any[]; + } + + interface PeripheralData { + name: string; + id: string; + rssi: number + advertising: ArrayBuffer|any; + } + + + interface PeripheralDataExtended extends PeripheralData{ + services: string[]; + characteristics: PeripheralCharacteristic[] + } + + + + + interface StartScanOptions { + reportDuplicates?: boolean; + } + + export interface BLECentralPluginStatic { + scan(services: string[], seconds: number, success : (data: PeripheralData) => any): void; + scan(services: string[], seconds: number, success : (data: PeripheralData) => any, failure : () => any): void; + + startScan(services: string[], success: (data: PeripheralData) => any): void; + startScan(services: string[], success: (data: PeripheralData) => any, failure: () => any): void; + + startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any): void; + startScanWithOptions(services: string[], options: StartScanOptions, success: (data: PeripheralData) => any, failure: () => any): void; + + stopScan(): void; + stopScan(success: () => any): void; + stopScan(success: () => any, failure: () => any): void; + + connect(device_id:string, success: (data: PeripheralDataExtended) => any, failure: () => any): void; + + disconnect(device_id:string): void; + disconnect(device_id:string, success: () => any): void; + disconnect(device_id:string, success: () => any, failure: () => any): void; + + read(device_id: string, service_uuid:string, characteristic_uuid:string): void; + read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void; + read(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void; + + write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void; + write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void; + write(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void; + + /* Writes data to a characteristic without a response from the peripheral. You are not notified if the write fails in the BLE stack. + The success callback is be called when the characteristic is written.*/ + writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer): void; + writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any): void; + writeWithoutResponse(device_id: string, service_uuid:string, characteristic_uuid:string, data: ArrayBuffer, success : () => any, failure: () => any): void; + + /* Register to be notified when the value of a characteristic changes. */ + startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any): void; + startNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: (rawData: ArrayBuffer) => any, failure: () => any): void; + + stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string): void; + stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any): void; + stopNotification(device_id: string, service_uuid:string, characteristic_uuid:string, success: () => any, failure: () => any): void; + + /* Reports if bluetooth is enabled. */ + isEnabled(success: () => any , failure: () => any): void; + + /* Calls the success callback when the peripheral is connected and the failure callback when not connected. */ + isConnected(device_id: string, success: () => any): void; + isConnected(device_id: string, success: () => any, failure: () => any): void; + + startStateNotifications(success: (state: string) => any): void; + startStateNotifications(success: (state: string) => any, failure: () => any): void; + + stopStateNotifications(): void; + stopStateNotifications(success: () => any): void; + stopStateNotifications(success: () => any, failure: () => any): void; + + /* Opens the Bluetooth settings for the operating systems. + [iOS] showBluetoothSettings is not supported on iOS. */ + showBluetoothSettings(): void; + showBluetoothSettings(success: () => any): void; + showBluetoothSettings(success: () => any, failure: () => any): void; + + /* Enable Bluetooth on the device. + [iOS] enable is not supported on iOS. */ + enable(success: () => any, failure: () => any): void; + + + readRSSI(device_id:string, success: (rssi: number) => any): void; + readRSSI(device_id:string, success: (rssi: number) => any, failure: () => any): void; + } +} + +declare var ble: BLECentralPlugin.BLECentralPluginStatic; \ No newline at end of file diff --git a/cordova-plugin-ble-central/tsconfig.json b/cordova-plugin-ble-central/tsconfig.json new file mode 100644 index 0000000000..cfff519c0b --- /dev/null +++ b/cordova-plugin-ble-central/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-ble-central-tests.ts" + ] +} \ No newline at end of file diff --git a/cordova-plugin-camera/tsconfig.json b/cordova-plugin-camera/tsconfig.json index fd82d2283c..4bcb17e701 100644 --- a/cordova-plugin-camera/tsconfig.json +++ b/cordova-plugin-camera/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-contacts/tsconfig.json b/cordova-plugin-contacts/tsconfig.json index 150cbbc01b..e7622317a1 100644 --- a/cordova-plugin-contacts/tsconfig.json +++ b/cordova-plugin-contacts/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-device-motion/tsconfig.json b/cordova-plugin-device-motion/tsconfig.json index 38d054da74..8fdea1bb00 100644 --- a/cordova-plugin-device-motion/tsconfig.json +++ b/cordova-plugin-device-motion/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-device-orientation/cordova-plugin-media-device-orientation-tests.ts b/cordova-plugin-device-orientation/cordova-plugin-device-orientation-tests.ts similarity index 100% rename from cordova-plugin-device-orientation/cordova-plugin-media-device-orientation-tests.ts rename to cordova-plugin-device-orientation/cordova-plugin-device-orientation-tests.ts diff --git a/cordova-plugin-device-orientation/tsconfig.json b/cordova-plugin-device-orientation/tsconfig.json index 8af4fd1451..cbbd8fcb7c 100644 --- a/cordova-plugin-device-orientation/tsconfig.json +++ b/cordova-plugin-device-orientation/tsconfig.json @@ -2,9 +2,15 @@ "compilerOptions": { "module": "commonjs", "target": "es6", - "noImplicitAny": false, - "strictNullChecks": false, - "noEmit": true + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-device/tsconfig.json b/cordova-plugin-device/tsconfig.json index 2382a3c48b..a7004ed713 100644 --- a/cordova-plugin-device/tsconfig.json +++ b/cordova-plugin-device/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-dialogs/tsconfig.json b/cordova-plugin-dialogs/tsconfig.json index 8a06fc75a3..66e676d30c 100644 --- a/cordova-plugin-dialogs/tsconfig.json +++ b/cordova-plugin-dialogs/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-file/tsconfig.json b/cordova-plugin-file/tsconfig.json index 62e93d809e..52446e1912 100644 --- a/cordova-plugin-file/tsconfig.json +++ b/cordova-plugin-file/tsconfig.json @@ -9,7 +9,8 @@ "../" ], "types": [], - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-globalization/tsconfig.json b/cordova-plugin-globalization/tsconfig.json index c743a2a3ee..1f61009199 100644 --- a/cordova-plugin-globalization/tsconfig.json +++ b/cordova-plugin-globalization/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-inappbrowser/tsconfig.json b/cordova-plugin-inappbrowser/tsconfig.json index 171d99407e..d26ba0222f 100644 --- a/cordova-plugin-inappbrowser/tsconfig.json +++ b/cordova-plugin-inappbrowser/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-keyboard/tsconfig.json b/cordova-plugin-keyboard/tsconfig.json index 00a8c3f7c5..d2f26294bc 100644 --- a/cordova-plugin-keyboard/tsconfig.json +++ b/cordova-plugin-keyboard/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-media-capture/cordova-plugin-capture-tests.ts b/cordova-plugin-media-capture/cordova-plugin-media-capture-tests.ts similarity index 100% rename from cordova-plugin-media-capture/cordova-plugin-capture-tests.ts rename to cordova-plugin-media-capture/cordova-plugin-media-capture-tests.ts diff --git a/cordova-plugin-media-capture/tsconfig.json b/cordova-plugin-media-capture/tsconfig.json index 807c41c402..f3ded32580 100644 --- a/cordova-plugin-media-capture/tsconfig.json +++ b/cordova-plugin-media-capture/tsconfig.json @@ -2,12 +2,18 @@ "compilerOptions": { "module": "commonjs", "target": "es6", - "noImplicitAny": false, - "strictNullChecks": false, - "noEmit": true + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "cordova-plugin-media-capture-tests.ts" ] -} \ No newline at end of file +} diff --git a/cordova-plugin-media/tsconfig.json b/cordova-plugin-media/tsconfig.json index 7875dd04a0..d9fc3553b5 100644 --- a/cordova-plugin-media/tsconfig.json +++ b/cordova-plugin-media/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-network-information/cordova-plugin-device-motion-tests.ts b/cordova-plugin-network-information/cordova-plugin-network-information-tests.ts similarity index 100% rename from cordova-plugin-network-information/cordova-plugin-device-motion-tests.ts rename to cordova-plugin-network-information/cordova-plugin-network-information-tests.ts diff --git a/cordova-plugin-network-information/tsconfig.json b/cordova-plugin-network-information/tsconfig.json index 3c31bfbd8e..045c48e109 100644 --- a/cordova-plugin-network-information/tsconfig.json +++ b/cordova-plugin-network-information/tsconfig.json @@ -2,9 +2,15 @@ "compilerOptions": { "module": "commonjs", "target": "es6", - "noImplicitAny": false, - "strictNullChecks": false, - "noEmit": true + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-splashscreen/tsconfig.json b/cordova-plugin-splashscreen/tsconfig.json index 032aed70bc..43e60dcd63 100644 --- a/cordova-plugin-splashscreen/tsconfig.json +++ b/cordova-plugin-splashscreen/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-statusbar/tsconfig.json b/cordova-plugin-statusbar/tsconfig.json index c464e89096..99f1b831a0 100644 --- a/cordova-plugin-statusbar/tsconfig.json +++ b/cordova-plugin-statusbar/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-vibration/tsconfig.json b/cordova-plugin-vibration/tsconfig.json index 8835563a00..65aa81393a 100644 --- a/cordova-plugin-vibration/tsconfig.json +++ b/cordova-plugin-vibration/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova-plugin-websql/tsconfig.json b/cordova-plugin-websql/tsconfig.json index 36e7e41481..7bace33807 100644 --- a/cordova-plugin-websql/tsconfig.json +++ b/cordova-plugin-websql/tsconfig.json @@ -4,7 +4,8 @@ "target": "es6", "noImplicitAny": false, "strictNullChecks": false, - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts b/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts new file mode 100644 index 0000000000..fec3c119d2 --- /dev/null +++ b/cordova.plugins.diagnostic/cordova.plugins.diagnostic-tests.ts @@ -0,0 +1,532 @@ +/// + +cordova.plugins.diagnostic.isLocationAvailable(function(available){ + console.log("Location is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isWifiAvailable(function(available){ + console.log("WiFi is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isCameraAvailable(function(available){ + console.log("Camera is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isBluetoothAvailable(function(available){ + console.log("Bluetooth is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.switchToLocationSettings(); +cordova.plugins.diagnostic.switchToMobileDataSettings(); +cordova.plugins.diagnostic.switchToBluetoothSettings(); +cordova.plugins.diagnostic.switchToWifiSettings(); + +cordova.plugins.diagnostic.isWifiEnabled(function(enabled){ + console.log("WiFi is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.setWifiState(function(){ + console.log("Wifi was enabled"); + }, function(error){ + console.error("The following error occurred: "+error); + }, true +); + +cordova.plugins.diagnostic.setBluetoothState(function(){ + console.log("Bluetooth was enabled"); + }, function(error){ + console.error("The following error occurred: "+error); + }, true +); + +cordova.plugins.diagnostic.isLocationEnabled(function(enabled){ + console.log("Location setting is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isLocationAuthorized(function(enabled){ + console.log("Location authorization is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getLocationAuthorizationStatus(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission not requested"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted always"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE: + console.log("Permission granted only when in use"); + break; + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestLocationAuthorization(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission not requested"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted always"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE: + console.log("Permission granted only when in use"); + break; + } +}, function(error){ + console.error(error); +}, cordova.plugins.diagnostic.locationAuthorizationMode.ALWAYS); + +cordova.plugins.diagnostic.isCameraPresent(function(present){ + console.log("Camera is " + (present ? "present" : "absent")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isCameraAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to the camera"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getCameraAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Camera use is authorized"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestCameraAuthorization(function(status){ + console.log("Authorization request for camera use was " + (status == cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied")); +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isMicrophoneAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to the microphone"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getMicrophoneAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Microphone use is authorized"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestMicrophoneAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Microphone use is authorized"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isContactsAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to contacts"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getContactsAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Contacts use is authorized"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.requestContactsAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Contacts use is authorized"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isCalendarAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to calendar"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getCalendarAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Calendar use is authorized"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestCalendarAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Calendar use is authorized"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.switchToSettings(function(){ + console.log("Successfully switched to Settings app"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getBluetoothState(function(state){ + if(state === cordova.plugins.diagnostic.bluetoothState.POWERED_ON){ + console.log("Bluetooth is able to connect"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.registerBluetoothStateChangeHandler(function(state){ + if(state === cordova.plugins.diagnostic.bluetoothState.POWERED_ON){ + console.log("Bluetooth is able to connect"); + } +}); + +cordova.plugins.diagnostic.registerLocationStateChangeHandler(function(state){ + if((device.platform === "Android" && state !== cordova.plugins.diagnostic.locationMode.LOCATION_OFF) + || (device.platform === "iOS") && ( state === cordova.plugins.diagnostic.permissionStatus.GRANTED + || state === cordova.plugins.diagnostic.permissionStatus.GRANTED_WHEN_IN_USE + )){ + console.log("Location is available"); + } +}); + +cordova.plugins.diagnostic.getLocationMode(function(locationMode){ + switch(locationMode){ + case cordova.plugins.diagnostic.locationMode.HIGH_ACCURACY: + console.log("High accuracy"); + break; + case cordova.plugins.diagnostic.locationMode.BATTERY_SAVING: + console.log("Battery saving"); + break; + case cordova.plugins.diagnostic.locationMode.DEVICE_ONLY: + console.log("Device only"); + break; + case cordova.plugins.diagnostic.locationMode.LOCATION_OFF: + console.log("Location off"); + break; + } +},function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isGpsLocationAvailable(function(available){ + console.log("GPS location is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){ + console.log("GPS location is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isNetworkLocationAvailable(function(available){ + console.log("Network location is " + (available ? "available" : "not available")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isNetworkLocationEnabled(function(enabled){ + console.log("Network location is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getLocationMode(function(locationMode){ + switch(locationMode){ + case cordova.plugins.diagnostic.locationMode.HIGH_ACCURACY: + console.log("High accuracy"); + break; + case cordova.plugins.diagnostic.locationMode.BATTERY_SAVING: + console.log("Battery saving"); + break; + case cordova.plugins.diagnostic.locationMode.DEVICE_ONLY: + console.log("Device only"); + break; + case cordova.plugins.diagnostic.locationMode.LOCATION_OFF: + console.log("Location off"); + break; + } +},function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getPermissionAuthorizationStatus(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use the camera"); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use the camera has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use the camera - ask again?"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use the camera - guess we won't be using it then!"); + break; + } +}, function(error){ + console.error("The following error occurred: "+error); +}, cordova.plugins.diagnostic.permission.CAMERA); + +cordova.plugins.diagnostic.getPermissionsAuthorizationStatus(function(statuses){ + for (var permission in statuses){ + switch(statuses[permission]){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use "+permission); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use "+permission+" has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use "+permission+" - ask again?"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use "+permission+" - guess we won't be using it then!"); + break; + } + } +}, function(error){ + console.error("The following error occurred: "+error); +},[ + cordova.plugins.diagnostic.permission.ACCESS_FINE_LOCATION, + cordova.plugins.diagnostic.permission.ACCESS_COARSE_LOCATION +]); + +cordova.plugins.diagnostic.requestRuntimePermission(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use the camera"); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use the camera has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use the camera - ask again?"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use the camera - guess we won't be using it then!"); + break; + } +}, function(error){ + console.error("The following error occurred: "+error); +}, cordova.plugins.diagnostic.permission.CAMERA); + +cordova.plugins.diagnostic.requestRuntimePermissions(function(statuses){ + for (var permission in statuses){ + switch(statuses[permission]){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use "+permission); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use "+permission+" has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use "+permission+" - ask again?"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use "+permission+" - guess we won't be using it then!"); + break; + } + } +}, function(error){ + console.error("The following error occurred: "+error); +},[ + cordova.plugins.diagnostic.permission.ACCESS_FINE_LOCATION, + cordova.plugins.diagnostic.permission.ACCESS_COARSE_LOCATION +]); + +if(!cordova.plugins.diagnostic.isRequestingPermission()){ + console.log("Request some permissions"); +}else{ + cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(function(statuses){ + cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(null); // de-register handler after single call + console.log("Request some permissions"); + }); +} + +function onPermissionRequestComplete(statuses:any){ + console.info("Permission request complete"); + for (var permission in statuses){ + switch(statuses[permission]){ + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted to use "+permission); + break; + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission to use "+permission+" has not been requested yet"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied to use "+permission); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS: + console.log("Permission permanently denied to use "+permission); + break; + } + } + cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(null); // de-register handler +} +cordova.plugins.diagnostic.registerPermissionRequestCompleteHandler(onPermissionRequestComplete) + +cordova.plugins.diagnostic.isBluetoothEnabled(function(enabled){ + console.log("Bluetooth is " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.hasBluetoothSupport(function(supported){ + console.log("Bluetooth is " + (supported ? "supported" : "unsupported")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.hasBluetoothLESupport(function(supported){ + console.log("Bluetooth LE is " + (supported ? "supported" : "unsupported")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.hasBluetoothLEPeripheralSupport(function(supported){ + console.log("Bluetooth LE Peripheral Mode is " + (supported ? "supported" : "unsupported")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isCameraRollAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to the camera roll"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getCameraRollAuthorizationStatus(function(status){ + switch(status){ + case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED: + console.log("Permission not requested"); + break; + case cordova.plugins.diagnostic.permissionStatus.DENIED: + console.log("Permission denied"); + break; + case cordova.plugins.diagnostic.permissionStatus.GRANTED: + console.log("Permission granted"); + break; + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestCameraRollAuthorization(function(status){ + console.log("Authorization request for camera roll was " + (status == cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied")); +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isRemoteNotificationsEnabled(function(enabled){ + console.log("Remote notifications are " + (enabled ? "enabled" : "disabled")); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isRegisteredForRemoteNotifications(function(registered){ + console.log("Device " + (registered ? "is" : "isn't") + " registered for remote notifications"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getRemoteNotificationTypes(function(types){ + for(var type in types){ + console.log(type + " is " + (types[type] ? "enabled" : "disabled")); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isRemindersAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "denied") + " access to reminders"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getRemindersAuthorizationStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Reminders authorization allowed"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestRemindersAuthorization(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Reminders authorization allowed"); + } +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isBackgroundRefreshAuthorized(function(authorized){ + console.log("App is " + (authorized ? "authorized" : "not authorized") + " to perform background refresh"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.getBackgroundRefreshStatus(function(status){ + if(status === cordova.plugins.diagnostic.permissionStatus.GRANTED){ + console.log("Background refresh is allowed"); + } +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestBluetoothAuthorization(function(){ + console.log("Bluetooth authorization requested"); +}, function(error){ + console.error(error); +}); + +cordova.plugins.diagnostic.isMotionAvailable(function(available){ + console.log("Motion tracking is " + (available ? "available" : "not available") + " on this device"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.isMotionRequestOutcomeAvailable(function(available){ + console.log("Motion tracking request outcome is " + (available ? "available" : "not available") + " on this device"); +}, function(error){ + console.error("The following error occurred: "+error); +}); + +cordova.plugins.diagnostic.requestAndCheckMotionAuthorization(function(status){ + console.log("Motion authorization is " +status); +}, function(error){ + console.error(error); +}); \ No newline at end of file diff --git a/cordova.plugins.diagnostic/index.d.ts b/cordova.plugins.diagnostic/index.d.ts new file mode 100644 index 0000000000..381b61562e --- /dev/null +++ b/cordova.plugins.diagnostic/index.d.ts @@ -0,0 +1,738 @@ +// Type definitions for cordova.plugins.diagnostic v3.3.0 +// Project: https://github.com/dpa99c/cordova-diagnostic-plugin +// Definitions by: Dave Alden +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Checks whether device hardware features are enabled or available to the app, e.g. camera, GPS, wifi + */ +interface Diagnostic { + + /** + * ANDROID ONLY + * "Dangerous" permissions that need to be requested at run-time (Android 6.0/API 23 and above) + * See http://developer.android.com/guide/topics/security/permissions.html#perm-groups + * @type {Object} + */ + permission?: any; + + /** + * ANDROID ONLY + * Permission groups indicate which associated permissions will also be requested if a given permission is requested. + * See http://developer.android.com/guide/topics/security/permissions.html#perm-groups + * @type {Object} + */ + permissionGroups?: any; + + /** + * ANDROID and iOS ONLY + * Constants for requesting and reporting the various permission states. + * @type {Object} + */ + permissionStatus?: any; + + /** + * iOS ONLY + * Location authorization mode + * @type {Object} + */ + locationAuthorizationMode?: any; + + + /** + * ANDROID ONLY + * Constants for the various location modes on Android. + * @type {Object} + */ + locationMode?: any; + + /** + * ANDROID and iOS ONLY + * Constants for the various Bluetooth hardware states. + * @type {Object} + */ + bluetoothState?: any; + + + /** + * Checks if app is able to access device location. + * @param successCallback + * @param errorCallback + */ + isLocationAvailable: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * Checks if Wifi is available. + * On iOS this returns true if the device is connected to a network by WiFi. + * On Android and Windows 10 Mobile this returns true if the WiFi setting is set to enabled, and is the same as isWifiEnabled() + * @param successCallback + * @param errorCallback + */ + isWifiAvailable: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * Checks if camera is available. + * On Android & iOS this returns true if the device has a camera AND the application is authorized to use it. + * On Windows 10 Mobile this returns true if the device has a rear-facing camera. + * @param successCallback + * @param errorCallback + */ + isCameraAvailable: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * Checks if Bluetooth is available to the app. + * Returns true if the device has Bluetooth capabilities AND if Bluetooth setting is switched on (same on Android, iOS and Windows 10 Mobile) + * @param successCallback + * @param errorCallback + */ + isBluetoothAvailable: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and WINDOWS ONLY + * Displays the device location settings to allow user to enable location services/change location mode. + */ + switchToLocationSettings?: () => void; + + /** + * ANDROID and WINDOWS ONLY + * Displays mobile settings to allow user to enable mobile data. + */ + switchToMobileDataSettings?: () => void; + + /** + * ANDROID and WINDOWS ONLY + * Displays Bluetooth settings to allow user to enable Bluetooth. + */ + switchToBluetoothSettings?: () => void; + + /** + * ANDROID and WINDOWS ONLY + * Displays WiFi settings to allow user to enable WiFi. + */ + switchToWifiSettings?: () => void; + + /** + * ANDROID and WINDOWS ONLY + * Returns true if the WiFi setting is set to enabled, and is the same as isWifiAvailable() + * @param successCallback + * @param errorCallback + */ + isWifiEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and WINDOWS ONLY + * Enables/disables WiFi on the device. + * @param successCallback + * @param errorCallback + * @param state + */ + setWifiState?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void, + state: boolean + ) => void; + + /** + * ANDROID and WINDOWS ONLY + * Enables/disables Bluetooth on the device. + * @param successCallback + * @param errorCallback + * @param state + */ + setBluetoothState?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void, + state: boolean + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns true if the device setting for location is on. + * On Android this returns true if Location Mode is switched on. + * On iOS this returns true if Location Services is switched on. + * @param successCallback + * @param errorCallback + */ + isLocationEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use location. + * @param successCallback + * @param errorCallback + */ + isLocationAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the location authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getLocationAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests location authorization for the application. + * @param successCallback + * @param errorCallback + * @param mode - (iOS-only / optional) location authorization mode specified as a locationAuthorizationMode constant. If not specified, defaults to WHEN_IN_USE. + */ + requestLocationAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void, + mode?: string + ) => void; + + + /** + * ANDROID and iOS ONLY + * Checks if camera hardware is present on device. + * @param successCallback + * @param errorCallback + */ + isCameraPresent?: ( + successCallback: (present: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use the camera. + * @param successCallback + * @param errorCallback + */ + isCameraAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the camera authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getCameraAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests camera authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestCameraAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use the microphone. + * @param successCallback + * @param errorCallback + */ + isMicrophoneAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the microphone authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getMicrophoneAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests microphone authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestMicrophoneAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use contacts (address book). + * @param successCallback + * @param errorCallback + */ + isContactsAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the contacts authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getContactsAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests contacts authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestContactsAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Checks if the application is authorized to use the calendar. + * @param successCallback + * @param errorCallback + */ + isCalendarAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the calendar authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getCalendarAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Requests calendar authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestCalendarAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Opens settings page for this app. + * On Android, this opens the "App Info" page in the Settings app. + * On iOS, this opens the app settings page in the Settings app. This works only on iOS 8+ - iOS 7 and below will invoke the errorCallback. + */ + switchToSettings?: ( + successCallback: () => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Returns the state of Bluetooth on the device. + * @param successCallback + * @param errorCallback + */ + getBluetoothState?: ( + successCallback: (state: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Registers a function to be called when a change in Bluetooth state occurs. Pass in a falsey value to de-register the currently registered function. + * @param successCallback + */ + registerBluetoothStateChangeHandler?: ( + successCallback: (state: string) => void + ) => void; + + /** + * ANDROID and iOS ONLY + * Registers a function to be called when a change in Location state occurs. Pass in a falsey value to de-register the currently registered function. + * On Android, this occurs when the Location Mode is changed. + * On iOS, this occurs when location authorization status is changed. This can be triggered either by the user's response to a location permission authorization dialog, by the user turning on/off Location Services, or by the user changing the Location authorization state specifically for your app. + * @param successCallback + */ + registerLocationStateChangeHandler?: ( + successCallback: (state: string) => void + ) => void; + + + /** + * ANDROID ONLY + * Checks if high-accuracy locations are available to the app from GPS hardware. + * Returns true if Location mode is enabled and is set to "Device only" or "High accuracy" AND if the app is authorised to use location. + * @param successCallback + * @param errorCallback + */ + isGpsLocationAvailable?: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device location setting is set to return high-accuracy locations from GPS hardware. + * Returns true if Location mode is enabled and is set to either Device only or High accuracy + * @param successCallback + * @param errorCallback + */ + isGpsLocationEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if low-accuracy locations are available to the app from network triangulation/WiFi access points. + * Returns true if Location mode is enabled and is set to "Battery saving" or "High accuracy" AND if the app is authorised to use location. + * @param successCallback + * @param errorCallback + */ + isNetworkLocationAvailable?: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device location setting is set to return high-accuracy locations from GPS hardware. + * Returns true if Location mode is enabled and is set to either Battery saving or High accuracy + * @param successCallback + * @param errorCallback + */ + isNetworkLocationEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Returns the current location mode setting for the device. + * @param successCallback + * @param errorCallback + */ + getLocationMode?: ( + successCallback: (mode: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Returns the current authorisation status for a given permission. + * @param successCallback + * @param errorCallback + * @param permission + */ + getPermissionAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void, + permission: string + ) => void; + + /** + * ANDROID ONLY + * Returns the current authorisation status for multiple permissions. + * @param successCallback + * @param errorCallback + * @param permissions + */ + getPermissionsAuthorizationStatus?: ( + successCallback: (status: string[]) => void, + errorCallback: (error: string) => void, + permissions: string[] + ) => void; + + /** + * ANDROID ONLY + * Requests app to be granted authorisation for a runtime permission. + * @param successCallback + * @param errorCallback + * @param permission + */ + requestRuntimePermission?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void, + permission: string + ) => void; + + /** + * ANDROID ONLY + * Requests app to be granted authorisation for multiple runtime permissions. + * @param successCallback + * @param errorCallback + * @param permissions + */ + requestRuntimePermissions?: ( + successCallback: (status: string[]) => void, + errorCallback: (error: string) => void, + permissions: string[] + ) => void; + + /** + * ANDROID ONLY + * Indicates if the plugin is currently requesting a runtime permission via the native API. + */ + isRequestingPermission?: () => boolean; + + /** + * ANDROID ONLY + * Registers a function to be called when a runtime permission request has completed. Pass in a falsey value to de-register the currently registered function. + * @param successCallback + */ + registerPermissionRequestCompleteHandler?: ( + successCallback: (statuses: any) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device setting for Bluetooth is switched on. + * @param successCallback + * @param errorCallback + */ + isBluetoothEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device has Bluetooth capabilities. + * @param successCallback + * @param errorCallback + */ + hasBluetoothSupport?: ( + successCallback: (supported: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device has Bluetooth Low Energy (LE) capabilities. + * @param successCallback + * @param errorCallback + */ + hasBluetoothLESupport?: ( + successCallback: (supported: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * ANDROID ONLY + * Checks if the device supports Bluetooth Low Energy (LE) Peripheral mode. + * @param successCallback + * @param errorCallback + */ + hasBluetoothLEPeripheralSupport?: ( + successCallback: (supported: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if the application is authorized to use the Camera Roll in Photos app. + * @param successCallback + * @param errorCallback + */ + isCameraRollAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Returns the authorization status for the application to use the Camera Roll in Photos app. + * @param successCallback + * @param errorCallback + */ + getCameraRollAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Requests camera roll authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestCameraRollAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if remote (push) notifications are enabled. + * @param successCallback + * @param errorCallback + */ + isRemoteNotificationsEnabled?: ( + successCallback: (enabled: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Indicates if the app is registered for remote (push) notifications on the device. + * @param successCallback + * @param errorCallback + */ + isRegisteredForRemoteNotifications?: ( + successCallback: (registered: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Indicates the current setting of notification types for the app in the Settings app. + * @param successCallback + * @param errorCallback + */ + getRemoteNotificationTypes?: ( + successCallback: (types: any) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if the application is authorized to use reminders. + * @param successCallback + * @param errorCallback + */ + isRemindersAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Returns the reminders authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getRemindersAuthorizationStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Requests reminders authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestRemindersAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if the application is authorized for background refresh. + * @param successCallback + * @param errorCallback + */ + isBackgroundRefreshAuthorized?: ( + successCallback: (authorized: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Returns the background refresh authorization status for the application. + * @param successCallback + * @param errorCallback + */ + getBackgroundRefreshStatus?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Requests Bluetooth authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestBluetoothAuthorization?: ( + successCallback: () => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if motion tracking is available on the current device. + * @param successCallback + * @param errorCallback + */ + isMotionAvailable?: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Checks if it's possible to determine the outcome of a motion authorization request on the current device. + * @param successCallback + * @param errorCallback + */ + isMotionRequestOutcomeAvailable?: ( + successCallback: (available: boolean) => void, + errorCallback: (error: string) => void + ) => void; + + /** + * iOS ONLY + * Requests and checks motion authorization for the application. + * @param successCallback + * @param errorCallback + */ + requestAndCheckMotionAuthorization?: ( + successCallback: (status: string) => void, + errorCallback: (error: string) => void + ) => void; +} + +interface CordovaPlugins { + diagnostic: Diagnostic +} \ No newline at end of file diff --git a/cordova.plugins.diagnostic/tsconfig.json b/cordova.plugins.diagnostic/tsconfig.json new file mode 100644 index 0000000000..43c76ef639 --- /dev/null +++ b/cordova.plugins.diagnostic/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova.plugins.diagnostic-tests.ts" + ] +} \ No newline at end of file diff --git a/cordova/tsconfig.json b/cordova/tsconfig.json index 417dadb8b6..afe8d4ba45 100644 --- a/cordova/tsconfig.json +++ b/cordova/tsconfig.json @@ -9,7 +9,8 @@ "../" ], "types": [], - "noEmit": true + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/credit-card-type/credit-card-type-tests.ts b/credit-card-type/credit-card-type-tests.ts new file mode 100644 index 0000000000..de2c6fade4 --- /dev/null +++ b/credit-card-type/credit-card-type-tests.ts @@ -0,0 +1,5 @@ +import * as creditCardType from "credit-card-type" + +var cardTypes: Array = creditCardType("") +var cardInfo: creditCardType.CreditCardTypeInfo = creditCardType.getTypeInfo("") +var types: { [type: string]: string } = creditCardType.types diff --git a/credit-card-type/index.d.ts b/credit-card-type/index.d.ts new file mode 100644 index 0000000000..59886b5e60 --- /dev/null +++ b/credit-card-type/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for Credit Card Type v5.0.0 +// Project: https://github.com/braintree/credit-card-type +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace creditCardType { + + type CardBrand = "american-express" | "diners-club" | "discover" | "jcb" | "maestro" | "master-card" | "unionpay" | "visa" + + interface CreditCardTypeInfo { + niceType?: string + type?: CardBrand + pattern?: RegExp + gaps?: Array + lengths?: Array + code?: { + name?: string + size?: number + } + } + + interface CreditCardType { + (number: string): Array + getTypeInfo (type: string): CreditCardTypeInfo + types: { [type: string]: string } + } +} + +declare const creditCardType: creditCardType.CreditCardType +export = creditCardType diff --git a/credit-card-type/tsconfig.json b/credit-card-type/tsconfig.json new file mode 100644 index 0000000000..7b38d340d4 --- /dev/null +++ b/credit-card-type/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "credit-card-type-tests.ts" + ] +} \ No newline at end of file diff --git a/cucumber/index.d.ts b/cucumber/index.d.ts index bbf961f852..de0a8d07d3 100644 --- a/cucumber/index.d.ts +++ b/cucumber/index.d.ts @@ -9,7 +9,7 @@ declare namespace cucumber { export interface CallbackStepDefinition{ pending : () => PromiseLike; - (errror?:any, pending?: string):void; + (error?:any, pending?: string):void; } export interface TableDefinition{ diff --git a/d3-array/index.d.ts b/d3-array/index.d.ts index 998058dbf4..1d1aae3b67 100644 --- a/d3-array/index.d.ts +++ b/d3-array/index.d.ts @@ -195,10 +195,9 @@ export interface Bisector { right: (array: T[], x: U, lo?: number, hi?: number) => number; } +export function bisector(comparator: (a: T, b: U) => number): Bisector; export function bisector(accessor: (x: T) => U): Bisector; -export function bisector(comparator: (a: T, b: U) => number): Bisector - // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** * Compares two primitive values for sorting (in ascending order). diff --git a/d3-box/d3-box-tests.ts b/d3-box/d3-box-tests.ts new file mode 100644 index 0000000000..191962ff13 --- /dev/null +++ b/d3-box/d3-box-tests.ts @@ -0,0 +1,26 @@ +/// +/// + +// Inspired by http://bl.ocks.org/mbostock/4061502 + +function iqr(k: number) { + return function(d: any) { + var q1 = d.quartiles[0], + q3 = d.quartiles[2], + iqr = (q3 - q1) * k; + let i = -1, + j = d.length; + while (d[++i] < q1 - iqr); + while (d[--j] > q3 + iqr); + return [i, j]; + }; +} + +var chart = d3.box() + .whiskers(iqr(1.5)) + .width(100) + .height(100); + +chart.domain([1, 30]); + +d3.selectAll("sth.").call(chart.duration(1000)); diff --git a/d3-box/d3-box.d.ts b/d3-box/d3-box.d.ts new file mode 100644 index 0000000000..4bc837df31 --- /dev/null +++ b/d3-box/d3-box.d.ts @@ -0,0 +1,31 @@ +// Type definitions for d3-box +// Project: https://github.com/JacksonGariety/d3-box +// Definitions by: Linkun Chen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace d3 { + export function box(): Box; + + interface Box { + (sel: d3.Selection): void; + width(): number; + width(x: number): Box; + height(): number; + height(x: number): Box; + tickFormat(): (n: number) => string; + tickFormat(fun: (n: number) => string): Box; + duration(): number; + duration(x: number): Box; + domain(): () => number[]; + domain(x: number[]): Box; + value(): (d: any) => number; + value(x: (d: any) => number): Box; + whiskers(): (d: any[], i?: number) => number[]; + whiskers(x: (d: any[], i?: number) => number[]): Box; + quartiles(): (d: any[]) => number[]; + quantiles(x: (d: any[]) => number[]): Box; + } +} + diff --git a/d3-format/d3-format-tests.ts b/d3-format/d3-format-tests.ts index 818c9218ad..3fd5742997 100644 --- a/d3-format/d3-format-tests.ts +++ b/d3-format/d3-format-tests.ts @@ -64,7 +64,7 @@ num = d3Format.precisionRound(0.0005, 3000); // ---------------------------------------------------------------------- let decimal: '.' | ',' = localeDef.decimal; -let thousands: '.' | ',' = localeDef.thousands; +let thousands: '.' | ',' | '\u00a0' | "'" = localeDef.thousands; let grouping: Array = localeDef.grouping; let currency: [string, string] = localeDef.currency; diff --git a/d3-format/index.d.ts b/d3-format/index.d.ts index 65592c0d06..92197f6ab8 100644 --- a/d3-format/index.d.ts +++ b/d3-format/index.d.ts @@ -15,7 +15,7 @@ export interface FormatLocaleDefinition { * The group separator (e.g., ","). Note that the thousands property is a misnomer, as\ * the grouping definition allows groups other than thousands. */ - thousands: '.' | ','; + thousands: '.' | ',' | '\u00a0' | "'"; /** * The array of group sizes (e.g., [3]), cycled as needed. */ diff --git a/d3-geo/d3-geo-tests.ts b/d3-geo/d3-geo-tests.ts index 2e9f3e8719..3d28bb610f 100644 --- a/d3-geo/d3-geo-tests.ts +++ b/d3-geo/d3-geo-tests.ts @@ -293,6 +293,12 @@ let multiString: GeoJSON.MultiLineString = graticuleGenerator(); let lines: GeoJSON.LineString[] = graticuleGenerator.lines(); let polygon2: GeoJSON.Polygon = graticuleGenerator.outline(); +// geoGraticule10() ===================================================== + +// test convenience function: + +multiString = d3Geo.geoGraticule10(); + // ---------------------------------------------------------------------- // Raw Projections // ---------------------------------------------------------------------- @@ -360,7 +366,7 @@ let clipAngle: number = constructedProjection.clipAngle(); constructedProjection = constructedProjection.clipAngle(null); constructedProjection = constructedProjection.clipAngle(45); -let clipExtent: [[number, number], [number, number]] = constructedProjection.clipExtent(); +let clipExtent: [[number, number], [number, number]] | null = constructedProjection.clipExtent(); constructedProjection = constructedProjection.clipExtent(null); constructedProjection = constructedProjection.clipExtent([[0, 0], [1, 1]]); @@ -416,14 +422,27 @@ conicConformal = conicConformal.fitSize([960, 500], samplePolygon); // inherited // GeoPath Generator // ---------------------------------------------------------------------- +let minimalRenderingContextMockUp: d3Geo.GeoContext = { + beginPath: () => { return; }, + moveTo: (x: number, y: number) => { return; }, + lineTo: (x: number, y: number) => { return; }, + arc: (x, y, radius, startAngle, endAngle) => { return; }, + closePath: () => { return; } +}; + // Create geoPath Generator ============================================= let geoPathCanvas: d3Geo.GeoPath; geoPathCanvas = d3Geo.geoPath(); +geoPathCanvas = d3Geo.geoPath(null); +geoPathCanvas = d3Geo.geoPath(null, null); +geoPathCanvas = d3Geo.geoPath(d3Geo.geoAzimuthalEqualArea()); +geoPathCanvas = d3Geo.geoPath(d3Geo.geoAzimuthalEqualArea(), minimalRenderingContextMockUp); let geoPathSVG: d3Geo.GeoPath>; geoPathSVG = d3Geo.geoPath>(); - +geoPathSVG = d3Geo.geoPath>(d3Geo.geoAzimuthalEqualArea()); +geoPathSVG = d3Geo.geoPath>(d3Geo.geoAzimuthalEqualArea(), null); // Configure geoPath Generator ========================================== // projection(...) ------------------------------------------------------ @@ -440,14 +459,8 @@ let geoPathConicProjection: d3Geo.GeoConicProjection = geoPathSVG.projection { return; }, - moveTo: (x: number, y: number) => { return; }, - lineTo: (x: number, y: number) => { return; }, - arc: (x, y, radius, startAngle, endAngle) => { return; }, - closePath: () => { return; } -}); +// minimal context interface (mockup) +geoPathCanvas = geoPathCanvas.context(minimalRenderingContextMockUp); let geoPathContext: d3Geo.GeoContext = geoPathCanvas.context(); @@ -461,13 +474,13 @@ let canvasContext: CanvasRenderingContext2D; geoPathCanvas = geoPathCanvas.context(canvasContext); canvasContext = geoPathCanvas.context(); -// canvasContext = geoPathSimple.context(); // fails without casting to CanvasRenderingContext2D -// canvasContext = geoPathSimple.context(); // fails as SampleProperties does not extend GeoCanvas +// canvasContext = geoPathCanvas.context(); // fails without casting to CanvasRenderingContext2D +// canvasContext = geoPathCanvas.context(); // fails as SampleProperties does not extend GeoCanvas // pointRadius(...) ------------------------------------------------------ geoPathCanvas = geoPathCanvas.pointRadius(5); -let geoPathCanvasPointRadiusAccessor: (this: any, d: d3Geo.GeoPermissibleObjects, ...args: any[]) => number = geoPathCanvas.pointRadius(); +let geoPathCanvasPointRadiusAccessor: ((this: any, d: d3Geo.GeoPermissibleObjects, ...args: any[]) => number) | number = geoPathCanvas.pointRadius(); geoPathSVG = geoPathSVG.pointRadius(function (datum) { let that: SVGPathElement = this; @@ -475,9 +488,9 @@ geoPathSVG = geoPathSVG.pointRadius(function (datum) { return datum.properties.name === 'Alabama' ? 10 : 15; }); -let geoPathSVGPointRadiusAccessor: (this: SVGPathElement, d: d3Geo.ExtendedFeature, ...args: any[]) => number = geoPathSVG.pointRadius(); -// let geoPathSVGPointRadiusAccessorWrong1: (this: SVGCircleElement, d: d3Geo.ExtendedFeature, ...args: any[]) => number = geoPathSVG.pointRadius(); // fails, mismatch in this context -// let geoPathSVGPointRadiusAccessorWrong2: (this: SVGPathElement, d: d3Geo.GeoGeometryObjects, ...args: any[]) => number = geoPathSVG.pointRadius(); // fails, mismatch in object datum type +let geoPathSVGPointRadiusAccessor: number | ((this: SVGPathElement, d: d3Geo.ExtendedFeature, ...args: any[]) => number) = geoPathSVG.pointRadius(); +// let geoPathSVGPointRadiusAccessorWrong1: number | ((this: SVGCircleElement, d: d3Geo.ExtendedFeature, ...args: any[]) => number) = geoPathSVG.pointRadius(); // fails, mismatch in this context +// let geoPathSVGPointRadiusAccessorWrong2: number | ((this: SVGPathElement, d: d3Geo.GeoGeometryObjects, ...args: any[]) => number) = geoPathSVG.pointRadius(); // fails, mismatch in object datum type // Use geoPath Generator ================================================ @@ -549,33 +562,8 @@ let svgCircleWrong: Selection; // svgPathWrong.attr('d', geoPathSVG); // fails, mismatch in datum type -// ---------------------------------------------------------------------- -// geoClipExtent -// ---------------------------------------------------------------------- -let geoClipExtent: d3Geo.GeoExtent = d3Geo.geoClipExtent(); -// extent(...) ---------------------------------------------------------- - -let extent2: [[number, number], [number, number]] = geoClipExtent.extent(); -geoClipExtent = geoClipExtent.extent([[0, 0], [960, 500]]); - -// stream(...) ---------------------------------------------------------- - -let stream: d3Geo.GeoStream; -stream = geoClipExtent.stream(stream); - -// ---------------------------------------------------------------------- -// Stream interface -// ---------------------------------------------------------------------- - -stream.point(0, 0); -stream.point(0, 0, 0); -stream.lineStart(); -stream.lineEnd(); -stream.polygonStart(); -stream.polygonEnd(); -stream.sphere(); // ---------------------------------------------------------------------- // Context interface @@ -611,6 +599,66 @@ customTransformProto = { let t: { stream: (s: d3Geo.GeoStream) => (CustomTranformProto & d3Geo.GeoStream) } = d3Geo.geoTransform(customTransformProto); + +// geoIdentity() ======================================================== + +let identityTransform: d3Geo.GeoIdentityTranform; + +identityTransform = d3Geo.geoIdentity(); + +scale = identityTransform.scale(); +identityTransform = identityTransform.scale(2); + +translate = identityTransform.translate(); +identityTransform = identityTransform.translate([10, 10]); + +clipExtent = identityTransform.clipExtent(); +identityTransform = identityTransform.clipExtent(null); +identityTransform = identityTransform.clipExtent([[0, 0], [100, 100]]); + +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], samplePolygon); +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleSphere); +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleGeometryCollection); +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleExtendedGeometryCollection); +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleFeature); +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleExtendedFeature1); +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleExtendedFeature2); +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleFeatureCollection); +identityTransform = identityTransform.fitExtent([[0, 0], [960, 500]], sampleExtendedFeatureCollection); + +identityTransform = identityTransform.fitSize([960, 500], samplePolygon); +identityTransform = identityTransform.fitSize([960, 500], sampleSphere); +identityTransform = identityTransform.fitSize([960, 500], sampleGeometryCollection); +identityTransform = identityTransform.fitSize([960, 500], sampleExtendedGeometryCollection); +identityTransform = identityTransform.fitSize([960, 500], sampleFeature); +identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeature1); +identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeature2); +identityTransform = identityTransform.fitSize([960, 500], sampleFeatureCollection); +identityTransform = identityTransform.fitSize([960, 500], sampleExtendedFeatureCollection); + +let reflecting: boolean; + +identityTransform = identityTransform.reflectX(true); +// identityTransform = identityTransform.reflectX(5); // fails, wrong argument data type +reflecting = identityTransform.reflectX(); + +identityTransform = identityTransform.reflectY(true); +// identityTransform = identityTransform.reflectY(5); // fails, wrong argument data type +reflecting = identityTransform.reflectY(); + +// ---------------------------------------------------------------------- +// Stream interface +// ---------------------------------------------------------------------- +let stream: d3Geo.GeoStream; + +stream.point(0, 0); +stream.point(0, 0, 0); +stream.lineStart(); +stream.lineEnd(); +stream.polygonStart(); +stream.polygonEnd(); +stream.sphere(); + // geoStream(...) ======================================================== d3Geo.geoStream(samplePolygon, stream); diff --git a/d3-geo/index.d.ts b/d3-geo/index.d.ts index 94e48bd810..9ab3ae74cd 100644 --- a/d3-geo/index.d.ts +++ b/d3-geo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-geo module v1.2.4 +// Type definitions for D3JS d3-geo module v1.4.0 // Project: https://github.com/d3/d3-geo/ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -14,6 +14,9 @@ * beyond the GeoJSON geometries. */ export interface GeoSphere { + /** + * Sphere geometry type + */ type: 'Sphere'; } @@ -62,43 +65,165 @@ export type GeoPermissibleObjects = GeoGeometryObjects | ExtendedGeometryCollect // Spherical Math // ---------------------------------------------------------------------- -/**Returns the spherical area of the specified GeoJSON feature in steradians. */ +/** + * Returns the spherical area of the specified feature in steradians. + * (See also path.area, which computes the projected planar area.) + * + * @param feature A geographic feature supported by d3-geo (An extension of GeoJSON feature). + */ export function geoArea(feature: ExtendedFeature): number; +/** + * Returns the spherical area of the specified feature collection in steradians. + * (See also path.area, which computes the projected planar area.) + * + * @param feature A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + */ export function geoArea(feature: ExtendedFeatureCollection>): number; +/** + * Returns the spherical area of the specified GeoJson Geometry Object or GeoSphere object in steradians. + * (See also path.area, which computes the projected planar area.) + * + * @param feature A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + */ export function geoArea(feature: GeoGeometryObjects): number; +/** + * Returns the spherical area of the specified geographic geometry collection in steradians. + * (See also path.area, which computes the projected planar area.) + * + * @param feature A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ export function geoArea(feature: ExtendedGeometryCollection): number; -/**Returns the spherical bounding box for the specified GeoJSON feature. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. */ +/** + * Returns the spherical bounding box for the specified feature. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], + * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. + * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * + * @param feature A geographic feature supported by d3-geo (An extension of GeoJSON feature). + */ export function geoBounds(feature: ExtendedFeature): [[number, number], [number, number]]; +/** + * Returns the spherical bounding box for the specified feature collection. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], + * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. + * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * + * @param feature A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + */ export function geoBounds(feature: ExtendedFeatureCollection>): [[number, number], [number, number]]; +/** + * Returns the spherical bounding box for the specified GeoJson Geometry Object or GeoSphere object. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], + * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. + * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * + * @param feature A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + */ export function geoBounds(feature: GeoGeometryObjects): [[number, number], [number, number]]; +/** + * Returns the spherical bounding box for the specified geometry collection. The bounding box is represented by a two-dimensional array: [[left, bottom], [right, top]], + * where left is the minimum longitude, bottom is the minimum latitude, right is maximum longitude, and top is the maximum latitude. All coordinates are given in degrees. + * (Note that in projected planar coordinates, the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * + * @param feature A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ export function geoBounds(feature: ExtendedGeometryCollection): [[number, number], [number, number]]; -/**Returns the spherical centroid of the specified GeoJSON feature. See also path.centroid, which computes the projected planar centroid.*/ +/** + * Returns the spherical centroid of the specified feature in steradians. + * (See also path.centroid, which computes the projected planar centroid.) + * + * @param feature A geographic feature supported by d3-geo (An extension of GeoJSON feature). + */ export function geoCentroid(feature: ExtendedFeature): [number, number]; +/** + * Returns the spherical centroid of the specified feature collection in steradians. + * (See also path.centroid, which computes the projected planar centroid.) + * + * @param feature A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + */ export function geoCentroid(feature: ExtendedFeatureCollection>): [number, number]; +/** + * Returns the spherical centroid of the specified GeoJson Geometry Object or GeoSphere object in steradians. + * (See also path.centroid, which computes the projected planar centroid.) + * + * @param feature A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + */ export function geoCentroid(feature: GeoGeometryObjects): [number, number]; +/** + * Returns the spherical centroid of the specified geographic geometry collection in steradians. + * (See also path.centroid, which computes the projected planar centroid.) + * + * @param feature A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ export function geoCentroid(feature: ExtendedGeometryCollection): [number, number]; -/**Returns the great-arc distance in radians between the two points a and b. Each point must be specified as a two-element array [longitude, latitude] in degrees. */ +/** + * Returns the great-arc distance in radians between the two points a and b. + * Each point must be specified as a two-element array [longitude, latitude] in degrees. + * + * @param a Point specified as a two-element array [longitude, latitude] in degrees. + * @param b Point specified as a two-element array [longitude, latitude] in degrees. + */ export function geoDistance(a: [number, number], b: [number, number]): number; -/**Returns the great-arc length of the specified GeoJSON feature in radians.*/ +/** + * Returns the great-arc length of the specified feature in radians. + * + * @param feature A geographic feature supported by d3-geo (An extension of GeoJSON feature). + */ export function geoLength(feature: ExtendedFeature): number; +/** + * Returns the great-arc length of the specified feature collection in radians. + * + * @param feature A geographic feature collection supported by d3-geo (An extension of GeoJSON feature). + */ export function geoLength(feature: ExtendedFeatureCollection>): number; +/** + * Returns the great-arc length of the specified GeoJson Geometry Object or GeoSphere object in radians. + * +* @param feature A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + */ export function geoLength(feature: GeoGeometryObjects): number; +/** + * Returns the great-arc length of the specified geographic geometry collection in radians. + * + * @param feature A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ export function geoLength(feature: ExtendedGeometryCollection): number; -/**Returns an interpolator function given two points a and b. Each point must be specified as a two-element array [longitude, latitude] in degrees. */ +/** + * Returns an interpolator function given two points a and b. + * Each point must be specified as a two-element array [longitude, latitude] in degrees. + * + * @param a Point specified as a two-element array [longitude, latitude] in degrees. + * @param b Point specified as a two-element array [longitude, latitude] in degrees. + */ export function geoInterpolate(a: [number, number], b: [number, number]): (t: number) => [number, number]; - +/** + * A Geo Rotation + */ export interface GeoRotation { + /** + * Returns a new array [longitude, latitude] in degrees representing the rotated point of the given point. + * + * @param point The point must be specified as a two-element array [longitude, latitude] in degrees. + */ (point: [number, number]): [number, number]; + + /** + * Returns a new array [longitude, latitude] in degrees representing the point of the given rotated point; the inverse of rotation. + * + * @param point The rotated point must be specified as a two-element array [longitude, latitude] in degrees. + */ invert(point: [number, number]): [number, number]; } -/**Returns a rotation function for the given angles, which must be a two- or three-element array of numbers [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis. */ +/** + * Returns a rotation function for the given angles. + * + * @param angles A two- or three-element array of numbers [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis. + * (These correspond to yaw, pitch and roll.) If the rotation angle gamma is omitted, it defaults to 0. + */ export function geoRotation(angles: [number, number] | [number, number, number]): GeoRotation; @@ -108,251 +233,1240 @@ export function geoRotation(angles: [number, number] | [number, number, number]) // geoCircle ============================================================ +/** + * A new circle generator + * + * The first generic corresponds to the "this"-context within which the geo circle generator will be invoked. + * + * The second generic corresponds to the type of the Datum which will be passed into the geo circle generator. + */ export interface GeoCircleGenerator { - /**Returns a new GeoJSON geometry object of type “Polygon” approximating a circle on the surface of a sphere, with the current center, radius and precision. */ + /** + * Returns a new GeoJSON geometry object of type “Polygon” approximating a circle on the surface of a sphere, + * with the current center, radius and precision. Any arguments are passed to the accessors. + */ (this: This, d?: Datum, ...args: any[]): GeoJSON.Polygon; + + /** + * Returns the current center accessor, which defaults to a function returning [0, 0]. + */ center(): ((this: This, d: Datum, ...args: any[]) => [number, number]); + /** + * Sets the circle center to the specified point [longitude, latitude] in degrees, and returns this circle generator. + * + * @param center Center point specified as [longitude, latitude] in degrees. + */ center(center: [number, number]): this; + /** + * Sets the circle center to the specified center point accessor function, and returns this circle generator. + * + * @param center An accessor function which will be invoked whenever a circle is generated, being passed any arguments passed to the circle generator. + * It returns the center point specified as [longitude, latitude] in degrees. + */ center(center: ((this: This, d: Datum, ...args: any[]) => [number, number])): this; + /** + * Returns the current radius accessor, which defaults to a function returning 90. + */ radius(): ((this: This, d: Datum, ...args: any[]) => number); + /** + * Sets the circle radius to the specified angle in degrees, and returns this circle generator. + * + * @param radius Circle radius as the specified angle in degrees. + */ radius(radius: number): this; + /** + * Sets the circle radius to the specified radius accessor function, and returns this circle generator. + * + * @param radius An accessor function which will be invoked whenever a circle is generated, being passed any arguments passed to the circle generator. + * It returns the radius as the specified angle in degrees. + */ radius(radius: ((this: This, d: Datum, ...args: any[]) => number)): this; + /** + * Returns the current precision accessor, which defaults to a function returning 6. + */ precision(): ((this: This, d: Datum, ...args: any[]) => number); + /** + * Sets the circle precision to the specified angle in degrees, and returns this circle generator. + * + * Small circles do not follow great arcs and thus the generated polygon is only an approximation. + * Specifying a smaller precision angle improves the accuracy of the approximate polygon, but also increase the cost to generate and render it. + * + * @param precision Precision as specified angle in degrees. + */ precision(precision: number): this; + /** + * Sets the circle precision to the precision accessor function, and returns this circle generator. + * + * Small circles do not follow great arcs and thus the generated polygon is only an approximation. + * Specifying a smaller precision angle improves the accuracy of the approximate polygon, but also increase the cost to generate and render it. + * + * @param precision An accessor function which will be invoked whenever a circle is generated, being passed any arguments passed to the circle generator. + * It returns the precision as the specified angle in degrees. + */ precision(precision: (this: This, d: Datum, ...args: any[]) => number): this; } +/** + * Returns a new geo circle generator + */ export function geoCircle(): GeoCircleGenerator; +/** + * Returns a new geo circle generator + * + * The generic corresponds to the data type of the first argument passed into the geo circle generator and its accessor functions. + */ export function geoCircle(): GeoCircleGenerator; +/** + * Returns a new geo circle generator + * + * The first generic corresponds to the "this" context within which the geo circle generator and its accessors will be invoked. + * + * The second generic corresponds to the data type of the first argument passed into the geo circle generator and its accessor functions. + */ export function geoCircle(): GeoCircleGenerator; // geoGraticule ============================================================ +/** + * A Feature generator for graticules: a uniform grid of meridians and parallels for showing projection distortion. + * The default graticule has meridians and parallels every 10° between ±80° latitude; for the polar regions, there are meridians every 90°. + */ export interface GeoGraticuleGenerator { - /**Returns a GeoJSON MultiLineString geometry object representing all meridians and parallels for this graticule. */ + /** + * Returns a GeoJSON MultiLineString geometry object representing all meridians and parallels for this graticule. + */ (): GeoJSON.MultiLineString; + /** + * Returns an array of GeoJSON LineString geometry objects, one for each meridian or parallel for this graticule. + */ lines(): GeoJSON.LineString[]; + + /** + * Returns a GeoJSON Polygon geometry object representing the outline of this graticule, i.e. along the meridians and parallels defining its extent. + */ outline(): GeoJSON.Polygon; + + /** + * Returns the current minor extent, which defaults to ⟨⟨-180°, -80° - ε⟩, ⟨180°, 80° + ε⟩⟩. + */ extent(): [[number, number], [number, number]]; + /** + * Sets the major and minor extents of this graticule. + * + * @param extent Extent to use for major and minor extent of graticule. + */ extent(extent: [[number, number], [number, number]]): this; + + /** + * Returns the current major extent, which defaults to ⟨⟨-180°, -90° + ε⟩, ⟨180°, 90° - ε⟩⟩. + */ extentMajor(): [[number, number], [number, number]]; + /** + * Sets the major extent of this graticule. + * + * @param extent Major extent of graticule. + */ extentMajor(extent: [[number, number], [number, number]]): this; + + /** + * Returns the current minor extent, which defaults to ⟨⟨-180°, -80° - ε⟩, ⟨180°, 80° + ε⟩⟩. + */ extentMinor(): [[number, number], [number, number]]; + /** + * Sets the minor extent of this graticule. + * + * @param extent Minor extent of graticule. + */ extentMinor(extent: [[number, number], [number, number]]): this; + + /** + * Returns the current minor step, which defaults to ⟨10°, 10°⟩. + */ step(): [number, number]; + /** + * Sets the major and minor step for this graticule + * + * @param step Major and minor step to use for this graticule. + */ step(step: [number, number]): this; + + /** + * Returns the current major step, which defaults to ⟨90°, 360°⟩. + */ stepMajor(): [number, number]; + /** + * Sets the major step for this graticule. + * + * @param step Major step. + */ stepMajor(step: [number, number]): this; + + /** + * Returns the current major step, which defaults to ⟨10°, 10°⟩. + */ stepMinor(): [number, number]; + /** + * Sets the minor step for this graticule. + * + * @param step Minor step. + */ stepMinor(step: [number, number]): this; + + /** + * Returns the current precision, which defaults to 2.5°. + */ precision(): number; + /** + * Sets the precision for this graticule, in degrees. + * + * @param angle Precision in degrees. + */ precision(angle: number): this; } +/** + * Constructs a feature generator for creating graticules: a uniform grid of meridians and parallels for showing projection distortion. + * The default graticule has meridians and parallels every 10° between ±80° latitude; for the polar regions, there are meridians every 90°. + */ export function geoGraticule(): GeoGraticuleGenerator; +/** + * A convenience method for directly generating the default 10° global graticule as a GeoJSON MultiLineString geometry object. + */ +export function geoGraticule10(): GeoJSON.MultiLineString; + // ---------------------------------------------------------------------- // Projections // ---------------------------------------------------------------------- +/** + * A D3 geo stream. D3 transforms geometry using a sequence of function calls, rather than materializing intermediate representations, to minimize overhead. + * Streams must implement several methods to receive input geometry. Streams are inherently stateful; the meaning of a point depends on whether the point is inside of a line, + * and likewise a line is distinguished from a ring by a polygon. Despite the name “stream”, these method calls are currently synchronous. + */ export interface GeoStream { + /** + * Indicates the end of a line or ring. Within a polygon, indicates the end of a ring. + * Unlike GeoJSON, the redundant closing coordinate of a ring is not indicated via point, and instead is implied via lineEnd within a polygon. + */ lineEnd(): void; + + /** + * Indicates the start of a line or ring. Within a polygon, indicates the start of a ring. The first ring of a polygon is the exterior ring, and is typically clockwise. + * Any subsequent rings indicate holes in the polygon, and are typically counterclockwise. + */ lineStart(): void; + + /** + * Indicates a point with the specified coordinates x and y (and optionally z). The coordinate system is unspecified and implementation-dependent; + * for example, projection streams require spherical coordinates in degrees as input. Outside the context of a polygon or line, + * a point indicates a point geometry object (Point or MultiPoint). Within a line or polygon ring, the point indicates a control point. + * + * @param x x-coordinate of point. + * @param y y-coordinate of point. + * @param z Optional z-coordinate of point. + */ point(x: number, y: number, z?: number): void; + + /** + * Indicates the end of a polygon. + */ polygonEnd(): void; + + /** + * Indicates the start of a polygon. The first line of a polygon indicates the exterior ring, and any subsequent lines indicate interior holes. + */ polygonStart(): void; + + /** + * Indicates the sphere (the globe; the unit sphere centered at ⟨0,0,0⟩). + */ sphere?(): void; } -export interface GeoStreamWrapper { - stream(stream: GeoStream): GeoStream; -} +// geoStream(...) ======================================================= + +/** + * Streams the specified GeoJSON object to the specified projection stream. While both features and geometry objects are supported as input, + * the stream interface only describes the geometry, and thus additional feature properties are not visible to streams. + * + * @param object + * @param stream A projection stream. + */ +export function geoStream(object: ExtendedFeature, stream: GeoStream): void; + +/** + * Streams the specified GeoJSON object to the specified projection stream. While both features and geometry objects are supported as input, + * the stream interface only describes the geometry, and thus additional feature properties are not visible to streams. + * + * @param object + * @param stream A projection stream. + */ +export function geoStream(object: ExtendedFeatureCollection>, stream: GeoStream): void; + +/** + * Streams the specified GeoJSON object to the specified projection stream. While both features and geometry objects are supported as input, + * the stream interface only describes the geometry, and thus additional feature properties are not visible to streams. + * + * @param object + * @param stream A projection stream. + */ +export function geoStream(object: GeoGeometryObjects, stream: GeoStream): void; + +/** + * Streams the specified GeoJSON object to the specified projection stream. While both features and geometry objects are supported as input, + * the stream interface only describes the geometry, and thus additional feature properties are not visible to streams. + * + * @param object + * @param stream A projection stream. + */ +export function geoStream(object: ExtendedGeometryCollection, stream: GeoStream): void; + + + +// ---------------------------------------------------------------------- +// Projections +// ---------------------------------------------------------------------- + + + + +/** + * Raw projections are point transformation functions that are used to implement custom projections; they typically passed to d3.geoProjection or d3.geoProjectionMutator. + * They are exposed here to facilitate the derivation of related projections. + * Raw projections take spherical coordinates [lambda, phi] in radians (not degrees!) and return a point [x, y], typically in the unit square centered around the origin. + */ export interface GeoRawProjection { - (longitude: number, latitude: number): [number, number]; + /** + * Projects the specified point [lambda, phi] in radians, returning a new point [x, y] in unitless coordinates. + * @param lambda Spherical lambda coordinate in radians. + * @param phi Spherical phi coordinate in radians. + */ + (lambda: number, phi: number): [number, number]; + + /** + * Inverts the projected point [x, y] in unitless coordinates, returning an unprojected point in spherical coordinates [lambda, phi] in radians. + * @param x x-coordinate (unitless). + * @param y y-coordinate (unitless). + */ invert?(x: number, y: number): [number, number]; } +/** + * An object implementing a stream method + */ +export interface GeoStreamWrapper { + /** + * Returns a projection stream for the specified output stream. Any input geometry is projected before being streamed to the output stream. + * A typical projection involves several geometry transformations: the input geometry is first converted to radians, rotated on three axes, + * clipped to the small circle or cut along the antimeridian, and lastly projected to the plane with adaptive resampling, scale and translation. + * + * @param stream An input stream + */ + stream(stream: GeoStream): GeoStream; +} +/** + * A Geographic Projection to transform spherical polygonal geometry to planar polygonal geometry. + * D3 provides implementations of several classes of standard projections: + * + * - Azimuthal + * - Composite + * - Conic + * - Cylindrical + * + * For many more projections, see d3-geo-projection. You can implement custom projections using d3.geoProjection or d3.geoProjectionMutator. + */ export interface GeoProjection extends GeoStreamWrapper { - /**Returns a new array x, y representing the projected point of the given point. The point must be specified as a two-element array [longitude, latitude] in degrees. */ + /** + * Returns a new array [x, y] (typically in pixels) representing the projected point of the given point. + * The point must be specified as a two-element array [longitude, latitude] in degrees. + * May return null if the specified point has no defined projected position, such as when the point is outside the clipping bounds of the projection. + * + * @param point A point specified as a two-dimensional array [longitude, latitude] in degrees. + */ (point: [number, number]): [number, number] | null; + /** + * Returns the current center of the projection, which defaults to ⟨0°,0°⟩. + */ center(): [number, number]; + /** + * Sets the projection’s center to the specified center, + * a two-element array of longitude and latitude in degrees and returns the projection. + * The default is ⟨0°,0°⟩. + * + * @param point A point specified as a two-dimensional array [longitude, latitude] in degrees. + */ center(point: [number, number]): this; + /** + * Returns the current clip angle which defaults to null. + * + * null switches to antimeridian cutting rather than small-circle clipping. + */ clipAngle(): number | null; + /** + * Switches to antimeridian cutting rather than small-circle clipping. + * + * @param angle Set to null to switch to antimeridian cutting. + */ clipAngle(angle: null): this; + /** + * Sets the projection’s clipping circle radius to the specified angle in degrees and returns the projection. + * Small-circle clipping is independent of viewport clipping via projection.clipExtent. + * + * @param angle Angle in degrees. + */ clipAngle(angle: number): this; + /** + * Returns the current viewport clip extent which defaults to null. + */ clipExtent(): [[number, number], [number, number]] | null; + /** + * Sets the clip extent to null and returns the projection. + * With a clip extent of null, no viewport clipping is performed. + * + * Viewport clipping is independent of small-circle clipping via projection.clipAngle. + * + * @param extent Set to null to disable viewport clipping. + */ clipExtent(extent: null): this; + /** + * Sets the projection’s viewport clip extent to the specified bounds in pixels and returns the projection. + * The extent bounds are specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left-side of the viewport, y₀ is the top, x₁ is the right and y₁ is the bottom. + * + * Viewport clipping is independent of small-circle clipping via projection.clipAngle. + * + * @param extent The extent bounds are specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left-side of the viewport, y₀ is the top, x₁ is the right and y₁ is the bottom. + */ clipExtent(extent: [[number, number], [number, number]]): this; - /**Sets the projection’s scale and translate to fit the specified GeoJSON object in the center of the given extent. */ + /** + * Sets the projection’s scale and translate to fit the specified geographic feature in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection>): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry object in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + */ fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection): this; - /**A convenience method for projection.fitExtent where the top-left corner of the extent is [0,0]. */ + /** + * Sets the projection’s scale and translate to fit the specified geographic feature in the center of an extent with the given size and top-left corner of [0, 0]. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param size The size of the extent, specified as an array [width, height]. + * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). + */ fitSize(size: [number, number], object: ExtendedFeature): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of an extent with the given size and top-left corner of [0, 0]. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param size The size of the extent, specified as an array [width, height]. + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). + */ fitSize(size: [number, number], object: ExtendedFeatureCollection>): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry object in the center of an extent with the given size and top-left corner of [0, 0]. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param size The size of the extent, specified as an array [width, height]. + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + */ fitSize(size: [number, number], object: GeoGeometryObjects): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of an extent with the given size and top-left corner of [0, 0]. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param size The size of the extent, specified as an array [width, height]. + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ fitSize(size: [number, number], object: ExtendedGeometryCollection): this; - /**Returns a new array [longitude, latitude] in degrees representing the unprojected point of the given projected point. */ + /** + * Returns a new array [longitude, latitude] in degrees representing the unprojected point of the given projected point. + * May return null if the specified point has no defined projected position, such as when the point is outside the clipping bounds of the projection. + * + * @param point The projected point, specified as a two-element array [x, y] (typically in pixels). + */ invert?(point: [number, number]): [number, number] | null; + /** + * Returns the projection’s current resampling precision which defaults to square root of 0.5. + * This value corresponds to the Douglas–Peucker distance. + */ precision(): number; + /** + * Sets the threshold for the projection’s adaptive resampling to the specified value in pixels and returns the projection. + * This value corresponds to the Douglas–Peucker distance. + * + * @param precision A numeric value in pixels to use as the threshold for the projection’s adaptive resampling. + */ precision(precision: number): this; + /** + * Returns the current rotation [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis. + * (These correspond to yaw, pitch and roll.) which defaults [0, 0, 0]. + */ rotate(): [number, number, number]; + /** + * Sets the projection’s three-axis rotation to the specified angles, which must be a two- or three-element array of numbers. + * + * @param angles A two- or three-element array of numbers [lambda, phi, gamma] specifying the rotation angles in degrees about each spherical axis. + * (These correspond to yaw, pitch and roll.) If the rotation angle gamma is omitted, it defaults to 0. + */ rotate(angles: [number, number] | [number, number, number]): this; + /** + * Returns the current scale factor; the default scale is projection-specific. + * + * The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections. + */ scale(): number; + /** + * Sets the projection’s scale factor to the specified value and returns the projection. + * The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections. + * + * @param scale Scale factor to be used for the projection; the default scale is projection-specific. + */ scale(scale: number): this; + /** + * Returns the current translation offset which defaults to [480, 250] and places ⟨0°,0°⟩ at the center of a 960×500 area. + * The translation offset determines the pixel coordinates of the projection’s center. + */ translate(): [number, number]; + /** + * Sets the projection’s translation offset to the specified two-element array [tx, ty] and returns the projection. + * The translation offset determines the pixel coordinates of the projection’s center. The default translation offset places ⟨0°,0°⟩ at the center of a 960×500 area. + * + * @param point A two-element array [tx, ty] specifying the translation offset. The default translation offset of defaults to [480, 250] places ⟨0°,0°⟩ at the center of a 960×500 area. + */ translate(point: [number, number]): this; } +/** + * A Conic Projection + */ export interface GeoConicProjection extends GeoProjection { - parallels(value: [number, number]): this; + + /** + * Return the standard parallels for the conic projection in degrees. + */ parallels(): [number, number]; + /** + * Set the standard parallels for the conic projection in degrees and return the projection. + * + * @param value A two-dimensional array representing the standard parallels in degrees. + */ + parallels(value: [number, number]): this; + } // geoPath ============================================================== +/** + * A minimal rendering context for a GeoPath generator. The minimum implemented + * methods are a subset of the CanvasRenderingContext2D API. + * + * For reference to the CanvasRenderingContext2D see https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D + */ export interface GeoContext { + + /** + * Adds an arc to the path with center point (x, y) and radius r starting at startAngle and ending at endAngle. + * The arc is drawn in clockwise directio by default. + * + * @param x x-coordinate of arc center point. + * @param y y-coordinate of arc center point. + * @param radius Radius of arc. + * @param startAngle The starting angle of the arc, measured clockwise from the positive x axis and expressed in radians. + * @param endAngle The end angle of the arc, measured clockwise from the positive x axis and expressed in radians. + * @param anticlockwise Optional boolean flag, if true the arc is drawn counter-clockwise between the two angles. + */ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void; + + /** + * Start a new path by emptying the list of sub-paths. + */ beginPath(): void; + + /** + * Causes the point of the pen to move back to the start of the current sub-path. + * It tries to draw a straight line from the current point to the start. + * If the shape has already been closed or has only one point, this function does nothing. + */ closePath(): void; + + /** + * Connects the last point in the sub-path to the x, y coordinates with a straight line (but does not actually draw it). + * + * @param x The x-coordinate for the end of the line. + * @param y The y-coordinate for the end of the line. + */ lineTo(x: number, y: number): void; + + /** + * Move the starting point of a new sub-path to the (x, y) coordinates. + * + * @param x The x-coordinate for the new starting point. + * @param y The y-coordinate for the new starting point. + */ moveTo(x: number, y: number): void; } +/** + * A Geo Path generator + * + * The first generic corresponds to the "this"-context within which the geo path generator will be invoked. This could be e.g. the DOMElement bound to "this" when using selection.attr("d", ...) with the path generator. + * + * The second generic corresponds to the type of the DatumObject which will be passed into the geo path generator for rendering. + */ export interface GeoPath { - (this: This, object: DatumObject, ...args: any[]): string; + /** + * Renders the given object, which may be any GeoJSON feature or geometry object: + * + * + Point - a single position. + * + MultiPoint - an array of positions. + * + LineString - an array of positions forming a continuous line. + * + MultiLineString - an array of arrays of positions forming several lines. + * + Polygon - an array of arrays of positions forming a polygon (possibly with holes). + * + MultiPolygon - a multidimensional array of positions forming multiple polygons. + * + GeometryCollection - an array of geometry objects. + * + Feature - a feature containing one of the above geometry objects. + * + FeatureCollection - an array of feature objects. + * + * The type Sphere is also supported, which is useful for rendering the outline of the globe; a sphere has no coordinates. + * + * + * Any additional arguments are passed along to the pointRadius accessor. + * + * If the rendering context is null, the function returns an SVG Path string, otherwise the function renders to the current context. + * + * Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interation (e.g., click or mouseover). + * Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction. + * + * The first generic type of the GeoPath generator used, must correspond to the "this" context bound to the function upon invocation. + * + * @param object An object to be rendered. + */ + (this: This, object: DatumObject, ...args: any[]): string | undefined; + /** + * Returns the projected planar area (typically in square pixels) for the specified GeoJSON object. + * Point, MultiPoint, LineString and MultiLineString features have zero area. For Polygon and MultiPolygon features, + * this method first computes the area of the exterior ring, and then subtracts the area of any interior holes. + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. + * + * @param An object for which the area is to be calculated. + */ area(object: DatumObject): number; + + /** + * Returns the projected planar bounding box (typically in pixels) for the specified GeoJSON object. + * The bounding box is represented by a two-dimensional array: [[x₀, y₀], [x₁, y₁]], where x₀ is the minimum x-coordinate, y₀ is the minimum y-coordinate, + * x₁ is maximum x-coordinate, and y₁ is the maximum y-coordinate. + * + * This is handy for, say, zooming in to a particular feature. (Note that in projected planar coordinates, + * the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. + * + * @param An object for which the bounds are to be calculated. + */ bounds(object: DatumObject): [[number, number], [number, number]]; + + /** + * Returns the projected planar centroid (typically in pixels) for the specified GeoJSON object. + * This is handy for, say, labeling state or county boundaries, or displaying a symbol map. + * For example, a noncontiguous cartogram might scale each state around its centroid. + * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. + * + * @param An object for which the centroid is to be calculated. + */ centroid(object: DatumObject): [number, number]; - context(): C | null; - context(context: GeoContext | null): this; + + /** + * Returns the current render context which defaults to null. + * + * Use the generic to cast the return type of the rendering context, if it is known for a specific application. + */ + context(): C; + + /** + * Set the current rendering context to null and return the path generator. + * The path generator will return an SVG path string; + * + * @param context Null to remove the current rendering context, if any. + */ + context(context: null): this; + + /** + * Set the current rendering context and return the path generator. + * The path generator will render to the specified context. + * + * @param context Rendering context to be used by the path generator. + * The context must at least implement GeoContext, a subset of the CanvasRenderingContext2D API. + */ + context(context: GeoContext): this; /** * Get the current projection. The generic parameter can be used to cast the result to the * correct, known type of the projection, e.g. GeoProjection or GeoConicProjection. Otherwise, * the return type defaults to the minimum type requirement for a projection which * can be passed into a GeoPath. + * + * Use the generic to cast the return type of the projection, if it is known for a specific application. */ - projection

(): P | null; + projection

(): P; /** - * Set the projection to the identity projection + * Set the projection to the identity projection. + * + * @param projection Use null to set the identity projection. */ projection(projection: null): this; /** - * Set the projection to be used with the geo path generator. + * Set the current projection to be used with the geo path generator. + * + * The given projection is typically one of D3’s built-in geographic projections; + * however, any object that exposes a projection.stream function can be used, enabling the use of custom projections. + * See D3’s transforms for more examples of arbitrary geometric transformations. + * + * @param projection A projection. */ projection(projection: GeoProjection): this; /** * Set the projection to be used with the geo path generator to a custom projection. * Custom projections must minimally contain a stream method. + * + * The given projection is typically one of D3’s built-in geographic projections; + * however, any object that exposes a projection.stream function can be used, enabling the use of custom projections. + * See D3’s transforms for more examples of arbitrary geometric transformations. + * + * @param projection A wrapper object exposing, at a minimum a "stream" method to be used for custom projections. */ projection(projection: GeoStreamWrapper): this; - pointRadius(): (this: This, object: DatumObject, ...args: any[]) => number; + /** + * Returns the current radius or radius accessor used to determine the radius for the display of Point and MultiPoint features. + * The default is a constant radius of 4.5. + */ + pointRadius(): ((this: This, object: DatumObject, ...args: any[]) => number) | number; + + /** + * Sets the radius used to display Point and MultiPoint features to the specified number and return the geo path generator. + * + * @param value Fixed radius value. + */ pointRadius(value: number): this; + + /** + * Sets the radius used to display Point and MultiPoint features to use the specified radius accessor function. + * + * While the radius is commonly specified as a number constant, it may also be specified as a function which is computed per feature, + * being passed the any arguments passed to the path generator. For example, if your GeoJSON data has additional properties, + * you might access those properties inside the radius function to vary the point size; + * alternatively, you could d3.symbol and a projection for greater flexibility. + * + * @param value A value accessor function for the radius which is evaluated for each path to be rendered. The value accessor function is invoked within the "this" context in which the path generator is used. + * It is passed the object to be rendered, and any additional arguments which have been passed into the call to the render function of the path generator. + */ pointRadius(value: (this: This, object: DatumObject, ...args: any[]) => number): this; } -export function geoPath(): GeoPath; -export function geoPath(): GeoPath; -export function geoPath(): GeoPath; +/** + * Creates a new geographic path generator. + * + * The default projection is the null projection. The null projection represents the identity transformation, i.e. + * the input geometry is not projected and is instead rendered directly in raw coordinates. + * This can be useful for fast rendering of pre-projected geometry, or for fast rendering of the equirectangular projection. + * + * The default context is null, which implies that the path generator will return an SVG path string. + * + * @param projection An (optional) current projection to be used. Typically this is one of D3’s built-in geographic projections; + * however, any object that exposes a projection.stream function can be used, enabling the use of custom projections. + * See D3’s transforms for more examples of arbitrary geometric transformations. Setting the projection to "null" uses the identity projection. The default value is "null", the identity projection. + * @param context An (optional) rendering context to be used. If a context is provided, it must at least implement the interface described by GeoContext, a subset of the CanvasRenderingContext2D API. + * Setting the context to "null" means that the path generator will return an SVG path string representing the to be rendered object. The default is "null". + */ +export function geoPath(projection?: GeoProjection | GeoStreamWrapper | null, context?: GeoContext | null): GeoPath; +/** + * Creates a new geographic path generator with the default settings. + * + * The default projection is the null projection. The null projection represents the identity transformation: + * the input geometry is not projected and is instead rendered directly in raw coordinates. + * This can be useful for fast rendering of pre-projected geometry, or for fast rendering of the equirectangular projection. + * + * The default context is null, which implies that the path generator will return an SVG path string. + * + * The generic corresponds to the type of the DatumObject which will be passed into the geo path generator for rendering + * + * @param projection An (optional) current projection to be used. Typically this is one of D3’s built-in geographic projections; + * however, any object that exposes a projection.stream function can be used, enabling the use of custom projections. + * See D3’s transforms for more examples of arbitrary geometric transformations. Setting the projection to "null" uses the identity projection. The default value is "null", the identity projection. + * @param context An (optional) rendering context to be used. If a context is provided, it must at least implement the interface described by GeoContext, a subset of the CanvasRenderingContext2D API. + * Setting the context to "null" means that the path generator will return an SVG path string representing the to be rendered object. The default is "null". + */ +export function geoPath(projection?: GeoProjection | GeoStreamWrapper | null, context?: GeoContext | null): GeoPath; +/** + * Creates a new geographic path generator with the default settings. + * + * The default projection is the null projection. The null projection represents the identity transformation: + * the input geometry is not projected and is instead rendered directly in raw coordinates. + * This can be useful for fast rendering of pre-projected geometry, or for fast rendering of the equirectangular projection. + * + * The default context is null, which implies that the path generator will return an SVG path string. + * + * The first generic corresponds to the "this"-context within which the geo path generator will be invoked. This could be e.g. the DOMElement bound to "this" when using selection.attr("d", ...) with the path generator. + * + * The second generic corresponds to the type of the DatumObject which will be passed into the geo path generator for rendering. + * + * @param projection An (optional) current projection to be used. Typically this is one of D3’s built-in geographic projections; + * however, any object that exposes a projection.stream function can be used, enabling the use of custom projections. + * See D3’s transforms for more examples of arbitrary geometric transformations. Setting the projection to "null" uses the identity projection. The default value is "null", the identity projection. + * @param context An (optional) rendering context to be used. If a context is provided, it must at least implement the interface described by GeoContext, a subset of the CanvasRenderingContext2D API. + * Setting the context to "null" means that the path generator will return an SVG path string representing the to be rendered object. The default is "null". + */ +export function geoPath(projection?: GeoProjection | GeoStreamWrapper | null, context?: GeoContext | null): GeoPath; + -// Raw Projections ======================================================== -export function geoAzimuthalEqualAreaRaw(): GeoRawProjection; -export function geoAzimuthalEquidistantRaw(): GeoRawProjection; -export function geoConicConformalRaw(phi0: number, phi1: number): GeoRawProjection; -export function geoConicEqualAreaRaw(phi0: number, phi1: number): GeoRawProjection; -export function geoConicEquidistantRaw(phi0: number, phi1: number): GeoRawProjection; -export function geoEquirectangularRaw(): GeoRawProjection; -export function geoGnomonicRaw(): GeoRawProjection; -export function geoMercatorRaw(): GeoRawProjection; -export function geoOrthographicRaw(): GeoRawProjection; -export function geoStereographicRaw(): GeoRawProjection; -export function geoTransverseMercatorRaw(): GeoRawProjection; // geoProjection ========================================================== +/** + * Constructs a new projection from the specified raw projection, project. + * The project function takes the longitude and latitude of a given point in radians, + * often referred to as lambda (λ) and phi (φ), and returns a two-element array [x, y] representing its unit projection. + * The project function does not need to scale or translate the point, as these are applied automatically by projection.scale, projection.translate, and projection.center. + * Likewise, the project function does not need to perform any spherical rotation, as projection.rotate is applied prior to projection. + * + * If the project function exposes an invert method, the returned projection will also expose projection.invert. + */ export function geoProjection(project: GeoRawProjection): GeoProjection; // geoProjectionMutator ==================================================== +/** + * Constructs a new projection from the specified raw projection factory and returns a mutate function to call whenever the raw projection changes. + * The factory must return a raw projection. The returned mutate function returns the wrapped projection. + * + * When creating a mutable projection, the mutate function is typically not exposed. + */ export function geoProjectionMutator(factory: (...args: any[]) => GeoRawProjection): () => GeoProjection; -// Pre-Defined Projections ================================================= +// Pre-Defined Projections and Raw Projections ============================= -export function geoAlbers(): GeoConicProjection; -export function geoAlbersUsa(): GeoProjection; +// Azimuthal Projections --------------------------------------------------- + +/** + * The azimuthal equal-area projection. + */ export function geoAzimuthalEqualArea(): GeoProjection; + +/** + * The raw azimuthal equal-area projection. + */ +export function geoAzimuthalEqualAreaRaw(): GeoRawProjection; + +/** + * The azimuthal equidistant projection. + */ export function geoAzimuthalEquidistant(): GeoProjection; -export function geoConicConformal(): GeoConicProjection; -export function geoConicEqualArea(): GeoConicProjection; -export function geoConicEquidistant(): GeoConicProjection; -export function geoEquirectangular(): GeoProjection; +/** + * The raw azimuthal equidistant projection. + */ +export function geoAzimuthalEquidistantRaw(): GeoRawProjection; + +/** + * The gnomonic projection. + */ export function geoGnomonic(): GeoProjection; -export function geoMercator(): GeoProjection; + +/** + * The raw gnomonic projection. + */ +export function geoGnomonicRaw(): GeoRawProjection; + +/** + * The orthographic projection. + */ export function geoOrthographic(): GeoProjection; + +/** + * The raw orthographic projection. + */ +export function geoOrthographicRaw(): GeoRawProjection; + +/** + * The stereographic projection. + */ export function geoStereographic(): GeoProjection; +/** + * The raw stereographic projection. + */ +export function geoStereographicRaw(): GeoRawProjection; + +// Composite Projections --------------------------------------------------- + +/** + * A U.S.-centric composite projection of three d3.geoConicEqualArea projections: d3.geoAlbers is used for the lower forty-eight states, + * and separate conic equal-area projections are used for Alaska and Hawaii. Note that the scale for Alaska is diminished: it is projected at 0.35× its true relative area. + * + * Composite consist of several projections that are composed into a single display. The constituent projections have fixed clip, center and rotation, + * and thus composite projections do not support projection.center, projection.rotate, projection.clipAngle, or projection.clipExtent. + */ +export function geoAlbersUsa(): GeoProjection; + +// Conic Projections ------------------------------------------------------- + +/** + * The Albers’ equal area-conic projection. This is a U.S.-centric configuration of d3.geoConicEqualArea. + */ +export function geoAlbers(): GeoConicProjection; + +/** + * The conic conformal projection. The parallels default to [30°, 30°] resulting in flat top. + */ +export function geoConicConformal(): GeoConicProjection; + +/** + * The raw conic conformal projection. + */ +export function geoConicConformalRaw(phi0: number, phi1: number): GeoRawProjection; + +/** + * The Albers’ equal-area conic projection. + */ +export function geoConicEqualArea(): GeoConicProjection; + +/** + * The raw Albers’ equal-area conic projection. + */ +export function geoConicEqualAreaRaw(phi0: number, phi1: number): GeoRawProjection; + +/** + * The conic equidistant projection. + */ +export function geoConicEquidistant(): GeoConicProjection; + +/** + * The raw conic equidistant projection. + */ +export function geoConicEquidistantRaw(phi0: number, phi1: number): GeoRawProjection; + +// Cylindrical Projections ------------------------------------------------ + +/** + * The equirectangular (plate carrée) projection. + */ +export function geoEquirectangular(): GeoProjection; + +/** + * The raw equirectangular (plate carrée) projection. + */ +export function geoEquirectangularRaw(): GeoRawProjection; + +/** + * The spherical Mercator projection. + * Defines a default projection.clipExtent such that the world is projected to a square, clipped to approximately ±85° latitude. + */ +export function geoMercator(): GeoProjection; +/** + * The raw spherical Mercator projection. + */ +export function geoMercatorRaw(): GeoRawProjection; + +/** + * The transverse spherical Mercator projection. + * Defines a default projection.clipExtent such that the world is projected to a square, clipped to approximately ±85° latitude. + */ export function geoTransverseMercator(): GeoProjection; -// geoClipExtent ============================================================= - -export interface GeoExtent { - extent(): [[number, number], [number, number]]; - extent(extent: [[number, number], [number, number]]): this; - stream(stream: GeoStream): GeoStream; -} - - -export function geoClipExtent(): GeoExtent; +/** + * The raw transverse spherical Mercator projection. + */ +export function geoTransverseMercatorRaw(): GeoRawProjection; // ---------------------------------------------------------------------- -// Projection Streams +// Projection Transforms // ---------------------------------------------------------------------- // geoTransform(...) ==================================================== +/** + * A Prototype interface which serves as a template for the implementation of a geometric transform using geoTransform(...) + * It serves as a reference for the custom methods which can be passed into geoTransform as argument to crete a generalized + * transform projection. + */ export interface GeoTransformPrototype { + /** + * Indicates the end of a line or ring. Within a polygon, indicates the end of a ring. + * Unlike GeoJSON, the redundant closing coordinate of a ring is not indicated via point, and instead is implied via lineEnd within a polygon. + */ lineEnd?(this: this & { stream: GeoStream }): void; + /** + * Indicates the start of a line or ring. Within a polygon, indicates the start of a ring. The first ring of a polygon is the exterior ring, and is typically clockwise. + * Any subsequent rings indicate holes in the polygon, and are typically counterclockwise. + */ lineStart?(this: this & { stream: GeoStream }): void; + /** + * Indicates a point with the specified coordinates x and y (and optionally z). The coordinate system is unspecified and implementation-dependent; + * for example, projection streams require spherical coordinates in degrees as input. Outside the context of a polygon or line, + * a point indicates a point geometry object (Point or MultiPoint). Within a line or polygon ring, the point indicates a control point. + * + * @param x x-coordinate of point. + * @param y y-coordinate of point. + * @param z Optional z-coordinate of point. + */ point?(this: this & { stream: GeoStream }, x: number, y: number, z?: number): void; + /** + * Indicates the end of a polygon. + */ polygonEnd?(this: this & { stream: GeoStream }): void; + /** + * Indicates the start of a polygon. The first line of a polygon indicates the exterior ring, and any subsequent lines indicate interior holes. + */ polygonStart?(this: this & { stream: GeoStream }): void; + /** + * Indicates the sphere (the globe; the unit sphere centered at ⟨0,0,0⟩). + */ sphere?(this: this & { stream: GeoStream }): void; } + // TODO: Review whether GeoStreamWrapper should be included into return value union type, i.e. ({ stream: (s: GeoStream) => (T & GeoStream & GeoStreamWrapper)})? // It probably should be omitted for purposes of this API. The stream method added to (T & GeoStream) is more of a private member used internally to // implement the Transform factory -export function geoTransform(prototype: T): { stream: (s: GeoStream) => (T & GeoStream) }; -// geoStream(...) ======================================================= +/** + * Defines an arbitrary transform using the methods defined on the specified methods object. + * Any undefined methods will use pass-through methods that propagate inputs to the output stream. + * + * @param methods An object with custom method implementations, which are used to create a transform projection. + */ +export function geoTransform(methods: T): { stream: (s: GeoStream) => (T & GeoStream) }; -export function geoStream(object: ExtendedFeature, stream: GeoStream): void; -export function geoStream(object: ExtendedFeatureCollection>, stream: GeoStream): void; -export function geoStream(object: GeoGeometryObjects, stream: GeoStream): void; -export function geoStream(object: ExtendedGeometryCollection, stream: GeoStream): void; +// geoIdentity() ================================================================= + +/** + * Geo Identity Transform + */ +export interface GeoIdentityTranform extends GeoStreamWrapper { + + /** + * Returns the current viewport clip extent which defaults to null. + */ + clipExtent(): [[number, number], [number, number]] | null; + /** + * Sets the clip extent to null and returns the projection. + * With a clip extent of null, no viewport clipping is performed. + * + * Viewport clipping is independent of small-circle clipping via projection.clipAngle. + * + * @param extent Set to null to disable viewport clipping. + */ + clipExtent(extent: null): this; + /** + * Sets the projection’s viewport clip extent to the specified bounds in pixels and returns the projection. + * The extent bounds are specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left-side of the viewport, y₀ is the top, x₁ is the right and y₁ is the bottom. + * + * Viewport clipping is independent of small-circle clipping via projection.clipAngle. + * + * @param extent The extent bounds are specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left-side of the viewport, y₀ is the top, x₁ is the right and y₁ is the bottom. + */ + clipExtent(extent: [[number, number], [number, number]]): this; + + /** + * Sets the projection’s scale and translate to fit the specified geographic feature in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). + */ + fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). + */ + fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection>): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry object in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + */ + fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ + fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection): this; + + + /** + * Sets the projection’s scale and translate to fit the specified geographic feature in the center of an extent with the given size and top-left corner of [0, 0]. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param size The size of the extent, specified as an array [width, height]. + * @param object A geographic feature supported by d3-geo (An extension of GeoJSON feature). + */ + fitSize(size: [number, number], object: ExtendedFeature): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of an extent with the given size and top-left corner of [0, 0]. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param size The size of the extent, specified as an array [width, height]. + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). + */ + fitSize(size: [number, number], object: ExtendedFeatureCollection>): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry object in the center of an extent with the given size and top-left corner of [0, 0]. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param size The size of the extent, specified as an array [width, height]. + * @param object A GeoJson Geometry Object or GeoSphere object supported by d3-geo (An extension of GeoJSON). + */ + fitSize(size: [number, number], object: GeoGeometryObjects): this; + /** + * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of an extent with the given size and top-left corner of [0, 0]. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param size The size of the extent, specified as an array [width, height]. + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ + fitSize(size: [number, number], object: ExtendedGeometryCollection): this; + + /** + * Returns true if x-reflection is enabled, which defaults to false. + */ + reflectX(): boolean; + /** + * Sets whether or not the x-dimension is reflected (negated) in the output. + * + * @param reflect true = reflect x-dimension, false = do not reflect x-dimension. + */ + reflectX(reflect: boolean): this; + + /** + * Returns true if y-reflection is enabled, which defaults to false. + */ + reflectY(): boolean; + /** + * Sets whether or not the y-dimension is reflected (negated) in the output. + * + * This is especially useful for transforming from standard spatial reference systems, + * which treat positive y as pointing up, to display coordinate systems such as Canvas and SVG, + * which treat positive y as pointing down. + * + * @param reflect true = reflect y-dimension, false = do not reflect y-dimension. + */ + reflectY(reflect: boolean): this; + + /** + * Returns the current scale factor. + * + * The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections. + */ + scale(): number; + /** + * Sets the projection’s scale factor to the specified value and returns the projection. + * The scale factor corresponds linearly to the distance between projected points; however, absolute scale factors are not equivalent across projections. + * + * @param scale Scale factor to be used for the projection. + */ + scale(scale: number): this; + + /** + * Returns the current translation offset. + * The translation offset determines the pixel coordinates of the projection’s center. + */ + translate(): [number, number]; + /** + * Sets the projection’s translation offset to the specified two-element array [tx, ty] and returns the projection. + * The translation offset determines the pixel coordinates of the projection’s center. + * + * @param point A two-element array [tx, ty] specifying the translation offset. + */ + translate(point: [number, number]): this; +} + +/** + * Returns the identity transform which can be used to scale, translate and clip planar geometry. + */ +export function geoIdentity(): GeoIdentityTranform; diff --git a/d3-tip/index.d.ts b/d3-tip/index.d.ts index 2747851b90..e820e8120f 100644 --- a/d3-tip/index.d.ts +++ b/d3-tip/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for d3-tip +// Type definitions for d3-tip v3.5.5 // Project: https://github.com/Caged/d3-tip // Definitions by: Gert Braspenning // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/d3-tip/package.json b/d3-tip/package.json new file mode 100644 index 0000000000..6819221ead --- /dev/null +++ b/d3-tip/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/d3": "^3.5.36" + } +} diff --git a/d3-tip/tsconfig.json b/d3-tip/tsconfig.json index a8f36a3861..a490e65f55 100644 --- a/d3-tip/tsconfig.json +++ b/d3-tip/tsconfig.json @@ -4,11 +4,6 @@ "target": "es6", "noImplicitAny": true, "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/d3-voronoi/d3-voronoi-tests.ts b/d3-voronoi/d3-voronoi-tests.ts index 2255d75b74..966ab622ec 100644 --- a/d3-voronoi/d3-voronoi-tests.ts +++ b/d3-voronoi/d3-voronoi-tests.ts @@ -234,3 +234,18 @@ link = links[0]; testDatum = link.source; testDatum = link.target; + + +// find() =============================================================== + +let nearestSite: d3Voronoi.VoronoiSite | null; +let wrongSiteDataType: d3Voronoi.VoronoiSite<[number, number]> | null; + +// Without search radius +nearestSite = voronoiDiagram.find(10, 50); + +// With search radius +nearestSite = voronoiDiagram.find(10, 50, 20); + +// wrong data type +// wrongSiteDataType = voronoiDiagram.find(10, 50); // fails, due to data type mismatch diff --git a/d3-voronoi/index.d.ts b/d3-voronoi/index.d.ts index 0265019451..9bd270d11d 100644 --- a/d3-voronoi/index.d.ts +++ b/d3-voronoi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-voronoi module v1.0.2 +// Type definitions for D3JS d3-voronoi module v1.1.0 // Project: https://github.com/d3/d3-voronoi/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -28,60 +28,273 @@ export interface VoronoiPointPair extends Array<[number, number]> { 1: [number, number]; } +/** + * A Voronoi Polygon is represented as an array of points [x, y] where x and y are the point coordinates, and a data field that refers to the corresponding element in data. + * Polygons are open: they do not contain a closing point that duplicates the first point; a triangle, for example, is an array of three points. + * Polygons are also counterclockwise, assuming the origin ⟨0,0⟩ is in the top-left corner. + * + * The generic refers to the type of the data for the corresponding element. + */ export interface VoronoiPolygon extends Array<[number, number]> { + /** + * The input data corresponding to this Voronoi polygon. + */ data: T; } +/** + * Voronoi Triangle is a three-element array of elements from data. + * + * The generic refers to the type of the data for the corresponding element. + */ export type VoronoiTriangle = [T, T, T]; +/** + * A Voronoi Site in the diagram is an array [x, y] with two additional properties: + * index and data. + * + * The generic refers to the type of the data for the corresponding element. + */ export interface VoronoiSite extends VoronoiPoint { + /** + * The Voronoi Site’s index, corresponding to the associated input point. + */ index: number; + /** + * The input data corresponding to this site. + */ data: T; } +/** + * A Voronoi Cell in the diagram is an object with the following properties: + * site and halfEdges + * + * The generic refers to the type of the data for the corresponding element. + */ export interface VoronoiCell { + /** + * The Voronoi Site of the cell’s associated input point. + */ site: VoronoiSite; + /** + * An array of indexes into diagram.edges representing the cell’s polygon. + */ halfEdges: Array; } - +/** + * Voronoi Edge in the diagram is an array [[x0, y0], [x1, y1]] with two additional properties: + * left and right. + * + * The generic refers to the type of the data for the corresponding element. + */ export interface VoronoiEdge extends VoronoiPointPair { + /** + * The Voronoi site on the left side of the edge. + */ left: VoronoiSite; + /** + * The Voronoi site on the right side of the edge. null for a clipped border edge. + */ right: VoronoiSite | null; } +/** + * Voronoi Link for an edge in the mesh created by the Delaunay triangulation of the specified data array. + * Each link has the following attributes: source and target. + * + * The generic refers to the type of the data for the corresponding element. + */ export interface VoronoiLink { + /** + * The source node, an element in data. + */ source: T; + /** + * The target node, an element in data. + */ target: T; } +/** + * A Voronoi Layout. + * + * The generic refers to the type of the data for the corresponding element. + */ export interface VoronoiLayout { + /** + * Computes the Voronoi diagram for the specified data points. + * @param data Array of data elements + */ (data: Array): VoronoiDiagram; + + /** + * Return the current x-coordinate accessor, + * which defaults to accessing the first element of an array (i.e. at index 0). + */ x(): (d: T) => number; + /** + * Set the x-coordinate accessor and return the layout. + * @param x An accessor function which takes a data element as input and return a + * numeric value for the x-coordinate. + */ x(x: (d: T) => number): this; + + /** + * Return the current y-coordinate accessor, + * which defaults to accessing the second element of an array (i.e. at index 1). + */ y(): (d: T) => number; + /** + * Set the y-coordinate accessor and return the layout. + * @param y An accessor function which takes a data element as input and return a + * numeric value for the y-coordinate. + */ y(y: (d: T) => number): this; + + /** + * Returns the current clip extent which defaults to null. + * + * The extent bounds are specified as an array [[x0, y0], [x1, y1]], + * where x0 is the left side of the extent, y0 is the top, + * x1 is the right and y1 is the bottom. + * + * A clip extent is required when using voronoi.polygons. + * + */ extent(): [[number, number], [number, number]] | null; + /** + * Set the clip extent of the Voronoi layout to the specified bounds and return the layout. + * + * A clip extent is required when using voronoi.polygons. + * + * @param extent The extent bounds are specified as an array [[x0, y0], [x1, y1]], + * where x0 is the left side of the extent, y0 is the top, x1 is the right and y1 is the bottom. + */ extent(extent: [[number, number], [number, number]]): this; + + /** + * Get the clip size of the Voronoi layout. Size is an alias for voronoi.extent + * where the minimum x and y of the extent are ⟨0,0⟩. + */ size(): [number, number] | null; + /** + * Set the clip size and return the layout. + * + * Size is an alias for voronoi.extent where the minimum x and y of the extent are ⟨0,0⟩. + * + * @param size An array representing the x- and y-size of the clip extent, + * where the minimum x and y of the extent are ⟨0,0⟩. + */ size(size: [number, number]): this; + + /** + * Return an array of polygons clipped to the extent, one for each input point in the specified data points, + * corresponding to the cells in the computed Voronoi diagram. + * + * Each polygon is represented as an array of points [x, y] where x and y are the point coordinates, + * and a data field that refers to the corresponding element in data. + * Polygons are open: they do not contain a closing point that duplicates the first point; + * a triangle, for example, is an array of three points. Polygons are also counterclockwise, + * assuming the origin ⟨0,0⟩ is in the top-left corner. + * + * If the cell’s site is coincident with an earlier site, the associated polygon is null. + * + * Important: Using polygon requires the extent to be set for the layout. + * + * @param data Array of data points. + */ polygons(data: Array): Array>; + /** + * Return the Delaunay triangulation of the specified data array as an array of triangles. + * Each triangle is a three-element array of elements from data. + * + * @param data Array of data points. + */ triangles(data: Array): Array>; + /** + * Return the Delaunay triangulation of the specified data array as an array of links. + * Each link has source and target attributes referring to elements in data. + * + * @param data Array of data points. + */ links(data: Array): Array>; } + +/** + * Computed Voronoi diagram + * + * The generic refers to the type of the data for the corresponding element. + */ export interface VoronoiDiagram { + /** + * Array of Voronoi Edges + */ edges: Array>; + /** + * Array of Voronoi Cells, one per input point; a cell may be null for a coincident point. + */ cells: Array | null>; + /** + * Return an array of polygons clipped to the extent, one for each cell in the diagram. + * Each polygon is represented as an array of points [x, y] where x and y are the point coordinates, + * and a data field that refers to the corresponding element in data. + * Polygons are open: they do not contain a closing point that duplicates the first point; + * a triangle, for example, is an array of three points. Polygons are also counterclockwise, + * assuming the origin ⟨0,0⟩ is in the top-left corner. + * + * If the cell’s site is coincident with an earlier site, the associated polygon is null. + */ polygons(): Array>; + + /** + * Returns the Delaunay triangulation of the specified data array as an array of triangles. + * Each triangle is a three-element array of elements from data. + * Since the triangulation is computed as the dual of the Voronoi diagram, and the Voronoi diagram is clipped by the extent, + * a subset of the Delaunay triangulation is returned. + */ triangles(): Array>; + + /** + * Returns the Delaunay triangulation of the specified data array as an array of links, one for each edge in the mesh. + * Each link has the following attributes: + * - source (the source node, an element in data) + * - target (the target node, an element in data) + * + * Since the triangulation is computed as the dual of the Voronoi diagram, and the Voronoi diagram is clipped by the extent, a subset of the Delaunay links is returned. + */ links(): Array>; + + /** + * Return the nearest Voronoi Site to point [x, y]. If radius is specified, only sites within radius distance are considered. + * If no Voronoi Site can be found (within the specified radius), null is returned. + * + * @param x x-coordinate + * @param y y-coordinate + * @param radius Optional parameter for search radius around [x, y] + */ + find(x: number, y:number, radius?:number): VoronoiSite | null; } // -------------------------------------------------------------------------- // voronoi Export // -------------------------------------------------------------------------- +/** + * Creates a new Voronoi layout with default x- and y- accessors and a null extent. + * + * Without specifying a generic the layout is assumed to be based on data represented + * by a two-dimensional coordinate [number, number] for x- and y-coordinate, respectively. + */ export function voronoi(): VoronoiLayout<[number, number]>; +/** + * Creates a new Voronoi layout with default x- and y- accessors and a null extent. + * x- and y-accessors may have to be set to correspond to the data type provided by the + * generic. + * + * The generic refers to the type of the data for the corresponding element. + */ export function voronoi(): VoronoiLayout; diff --git a/d3.cloud.layout/index.d.ts b/d3.cloud.layout/index.d.ts index c189c7b240..474af57828 100644 --- a/d3.cloud.layout/index.d.ts +++ b/d3.cloud.layout/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for d3JS cloud layout plugin by Jason Davies +// Type definitions for d3JS cloud layout plugin by Jason Davies v1.2.2 // Project: https://github.com/jasondavies/d3-cloud // Definitions by: hans windhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/d3.cloud.layout/package.json b/d3.cloud.layout/package.json new file mode 100644 index 0000000000..5e771f4dcd --- /dev/null +++ b/d3.cloud.layout/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/d3": "^3.5.36" + } +} diff --git a/d3.cloud.layout/tsconfig.json b/d3.cloud.layout/tsconfig.json index d09257bfa2..45d7cc6006 100644 --- a/d3.cloud.layout/tsconfig.json +++ b/d3.cloud.layout/tsconfig.json @@ -4,11 +4,6 @@ "target": "es6", "noImplicitAny": true, "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, @@ -16,4 +11,4 @@ "index.d.ts", "d3.cloud.layout-tests.ts" ] -} \ No newline at end of file +} diff --git a/d3.slider/d3.slider-tests.ts b/d3.slider/d3.slider-tests.ts new file mode 100644 index 0000000000..e0e0473059 --- /dev/null +++ b/d3.slider/d3.slider-tests.ts @@ -0,0 +1,24 @@ +/// +/// + +d3.select('#slider1').call(d3.slider()); +d3.select('#slider2').call(d3.slider().value( [ 10, 25 ] )); +d3.select('#slider3').call(d3.slider().axis(true).value( [ 10, 25 ] ) + .on("slide", function(evt, value) { + d3.select('#slider3textmin').text(value[ 0 ]); + d3.select('#slider3textmax').text(value[ 1 ]); + })); +d3.select('#slider4').call(d3.slider().on("slide", function(evt, value) { + d3.select('#slider4text').text(value); + })); +d3.select('#slider5').call(d3.slider().axis(true)); +var axis = d3.svg.axis().orient("top").ticks(4); +d3.select('#slider6').call(d3.slider().axis(axis)); +d3.select('#slider7').call(d3.slider().axis(true).min(2000).max(2100).step(5)); +d3.select('#slider8').call(d3.slider().value(50).orientation("vertical")); +d3.select('#slider9').call(d3.slider().value( [10, 30] ).orientation("vertical")); +d3.select('#slider10').call(d3.slider().scale(d3.time.scale().domain([new Date(1984,1,1), new Date(2014,1,1)])).axis(d3.svg.axis())); +d3.select('#slider11').call(d3.slider().scale(d3.time.scale().domain([new Date(1984,1,1), new Date(2014,1,1)])).axis(d3.svg.axis()).snap(true).value(new Date(2000,1,1))); +let essai = d3.slider().scale(d3.scale.ordinal().domain(["Gecko", "Webkit", "Blink", "Trident"]).rangePoints([0, 1], 0.5)).axis(d3.svg.axis()).snap(true).value("Gecko"); +d3.select('#slider12').call(essai); + diff --git a/d3.slider/d3.slider.d.ts b/d3.slider/d3.slider.d.ts new file mode 100644 index 0000000000..d459f4f04c --- /dev/null +++ b/d3.slider/d3.slider.d.ts @@ -0,0 +1,35 @@ +// Type definitions for d3-slider +// Project: https://github.com/MasterMaps/d3-slider +// Definitions by: Linkun Chen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace d3 { + export function slider(): Slider; + + interface Slider { + (sel: d3.Selection): void; + min(): number; + min(val: number): Slider; + max(): number; + max(val: number): Slider; + step(): number; + step(val: number): Slider; + animate(): boolean | number; + animate(val: boolean | number): Slider; + orientation(): string; + orientation(val: string): Slider; + axis(): boolean | d3.svg.Axis; + axis(val: boolean | d3.svg.Axis): Slider; + margin(): number; + margin(val: number): Slider; + value(): any; + value(val: any): Slider; + snap(): boolean; + snap(val: boolean): Slider; + scale(): any; + scale(val: any): Slider; + on(evt: ("slide" | "slideend"), callback: (evt: any, val: any) => void): Slider; + } +} \ No newline at end of file diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index 380b15db96..ed90cbec40 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -1,2722 +1,12 @@ +import * as d3 from 'd3'; -//Example from http://bl.ocks.org/3887235 -interface TestPieChartData { - population: number; - age: string; -} -function testPieChart() { - var width = 960, - height = 500, - radius = Math.min(width, height) / 2; +// TODO: complete tests. Note the tests here should be limited to +// testing existence of re-exported members of the +// constituent modules comprising the D3 version 4 standard bundle - var color = d3.scale.ordinal() - .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); +// Ability to access d3-select related properties - var arc = d3.svg.arc>() - .outerRadius(radius - 10) - .innerRadius(0); +let d: d3.Selection = d3.selection(); - var pie = d3.layout.pie() - .sort(null) - .value(function (d) { return d.population; }); - var svg = d3.select("body").append("svg") - .attr("width", width) - .attr("height", height) - .append("g") - .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); - - d3.csv("data.csv", d => ({ population: +d['population'], age: d['age'] }), function (error, data) { - var g = svg.selectAll(".arc") - .data(pie(data)) - .enter().append("g") - .attr("class", "arc"); - - g.append("path") - .attr("d", arc) - .style("fill", function (d) { return color(d.data.age); }); - - g.append("text") - .attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; }) - .attr("dy", ".35em") - .style("text-anchor", "middle") - .text(function (d) { return d.data.age; }); - - }); -} - -function testMapConstructor() { - //No arg constructor - var emptyMap: d3.Map = d3.map(); - - //Object constructor - var object:{[key: string]: number } = {a: 1, b: 2, c: 3}; - var objectMap: d3.Map = d3.map(object); - - //Array constructor - var numberArray: number[] = [1, 2, 3] - var numberArrayMap: d3.Map = d3.map(numberArray); - - //Array with keyFn constructor - var objectArray: {key: string}[] = [{key: "v1"}, {key: "v2"}, {key: "v3"}]; - var indexes: number[] = []; - //keyFn with index - var objectArrayMap1: d3.Map<{key: string}> - = d3.map<{key: string}>(objectArray, (o: {key: string}, index: number) => { - indexes.push(index); - return o.key; - }); - //keyFn without index - var objectArrayMap2: d3.Map<{key: string}> - = d3.map<{key: string}>(objectArray, (o: {key: string}) => { - return o.key; - }); - - //Map constructor - var duplicateMap: d3.Map = d3.map(numberArrayMap); -} - -//Example from http://bl.ocks.org/3887051 -interface GroupedData { - State: string; - ages: Array<{ name: string; value: number;}>; -} -function groupedBarChart() { - var margin = { top: 20, right: 20, bottom: 30, left: 40 }, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom; - - var x0 = d3.scale.ordinal() - .rangeRoundBands([0, width], .1); - - var x1 = d3.scale.ordinal(); - - var y = d3.scale.linear() - .range([height, 0]); - - var color = d3.scale.ordinal() - .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); - - var xAxis = d3.svg.axis() - .scale(x0) - .orient("bottom"); - - var yAxis = d3.svg.axis() - .scale(y) - .orient("left") - .tickFormat(d3.format(".2s")); - - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - d3.csv("data.csv", function (error: any, data: Array) { - var ageNames = d3.keys(data[0]).filter(function (key) { return key !== "State"; }); - - data.forEach(function (d) { - d.ages = ageNames.map(function (name) { return { name: name, value: +( d)[name] }; }); - }); - - x0.domain(data.map(function (d) { return d.State; })); - x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]); - y.domain([0, d3.max(data, function (d) { return d3.max(d.ages, function (d) { return d.value; }); })]); - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); - - svg.append("g") - .attr("class", "y axis") - .call(yAxis) - .append("text") - .attr("transform", "rotate(-90)") - .attr("y", 6) - .attr("dy", ".71em") - .style("text-anchor", "end") - .text("Population"); - - var state = svg.selectAll(".state") - .data(data) - .enter().append("g") - .attr("class", "g") - .attr("transform", function (d) { return "translate(" + x0(d.State) + ",0)"; }); - - state.selectAll("rect") - .data(function (d) { return d.ages; }) - .enter().append("rect") - .attr("width", x1.rangeBand()) - .attr("x", function (d) { return x1(d.name); }) - .attr("y", function (d) { return y(d.value); }) - .attr("height", function (d) { return height - y(d.value); }) - .style("fill", function (d) { return color(d.name); }); - - var legend = svg.selectAll(".legend") - .data(ageNames.reverse()) - .enter().append("g") - .attr("class", "legend") - .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; }); - - legend.append("rect") - .attr("x", width - 18) - .attr("width", 18) - .attr("height", 18) - .style("fill", color); - - legend.append("text") - .attr("x", width - 24) - .attr("y", 9) - .attr("dy", ".35em") - .style("text-anchor", "end") - .text(function (d) { return d; }); - - }); -} - -//Example from http://bl.ocks.org/3886208 -function stackedBarChart() { - var margin = { top: 20, right: 20, bottom: 30, left: 40 }, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom; - - var x = d3.scale.ordinal() - .rangeRoundBands([0, width], .1); - - var y = d3.scale.linear() - .rangeRound([height, 0]); - - var color = d3.scale.ordinal() - .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); - - var xAxis = d3.svg.axis() - .scale(x) - .orient("bottom"); - - var yAxis = d3.svg.axis() - .scale(y) - .orient("left") - .tickFormat(d3.format(".2s")); - - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - d3.csv("data.csv", function (error: any, data: any) { - color.domain(d3.keys(data[0]).filter(function (key) { return key !== "State"; })); - - data.forEach(function (d: any) { - var y0 = 0; - d.ages = color.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; }); - d.total = d.ages[d.ages.length - 1].y1; - }); - - data.sort(function (a: any, b: any) { return b.total - a.total; }); - - x.domain(data.map(function (d: any) { return d.State; })); - y.domain([0, d3.max(data, function (d: { total: number }) { return d.total; })]); - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); - - svg.append("g") - .attr("class", "y axis") - .call(yAxis) - .append("text") - .attr("transform", "rotate(-90)") - .attr("y", 6) - .attr("dy", ".71em") - .style("text-anchor", "end") - .text("Population"); - - var state = svg.selectAll(".state") - .data(data) - .enter().append("g") - .attr("class", "g") - .attr("transform", function (d: any) { return "translate(" + x(d.State) + ",0)"; }); - - state.selectAll("rect") - .data(function (d: any) { return d.ages; }) - .enter().append("rect") - .attr("width", x.rangeBand()) - .attr("y", function (d: any) { return y(d.y1); }) - .attr("height", function (d: any) { return y(d.y0) - y(d.y1); }) - .style("fill", function (d: any) { return color(d.name); }); - - var legend = svg.selectAll(".legend") - .data(color.domain().reverse()) - .enter().append("g") - .attr("class", "legend") - .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; }); - - legend.append("rect") - .attr("x", width - 18) - .attr("width", 18) - .attr("height", 18) - .style("fill", color); - - legend.append("text") - .attr("x", width - 24) - .attr("y", 9) - .attr("dy", ".35em") - .style("text-anchor", "end") - .text(function (d) { return d; }); - - }); -} - -// example from http://bl.ocks.org/3886394 -function normalizedBarChart() { - var margin = { top: 20, right: 100, bottom: 30, left: 40 }, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom; - - var x = d3.scale.ordinal() - .rangeRoundBands([0, width], .1); - - var y = d3.scale.linear() - .rangeRound([height, 0]); - - var color = d3.scale.ordinal() - .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); - - var xAxis = d3.svg.axis() - .scale(x) - .orient("bottom"); - - var yAxis = d3.svg.axis() - .scale(y) - .orient("left") - .tickFormat(d3.format(".0%")); - - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - d3.csv("data.csv", function (error, data) { - color.domain(d3.keys(data[0]).filter(function (key) { return key !== "State"; })); - - data.forEach(function (d: any) { - var y0 = 0; - d.ages = color.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; }); - d.ages.forEach(function (d: any) { d.y0 /= y0; d.y1 /= y0; }); - }); - - data.sort(function (a: any, b: any) { return b.ages[0].y1 - a.ages[0].y1; }); - - x.domain(data.map(function (d: any) { return d.State; })); - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); - - svg.append("g") - .attr("class", "y axis") - .call(yAxis); - - var state = svg.selectAll(".state") - .data(data) - .enter().append("g") - .attr("class", "state") - .attr("transform", function (d: any) { return "translate(" + x(d.State) + ",0)"; }); - - state.selectAll("rect") - .data(function (d) { return d.ages; }) - .enter().append("rect") - .attr("width", x.rangeBand()) - .attr("y", function (d: any) { return y(d.y1); }) - .attr("height", function (d: any) { return y(d.y0) - y(d.y1); }) - .style("fill", function (d: any) { return color(d.name); }); - - var legend = svg.select(".state:last-child").selectAll(".legend") - .data(function (d: any) { return d.ages; }) - .enter().append("g") - .attr("class", "legend") - .attr("transform", function (d: any) { return "translate(" + x.rangeBand() / 2 + "," + y((d.y0 + d.y1) / 2) + ")"; }); - - legend.append("line") - .attr("x2", 10); - - legend.append("text") - .attr("x", 13) - .attr("dy", ".35em") - .text(function (d: any) { return d.name; }); - - }); -} - -// example from http://bl.ocks.org/3885705 -function sortablebarChart() { - var margin = { top: 20, right: 20, bottom: 30, left: 40 }, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom; - - var formatPercent = d3.format(".0%"); - - var x = d3.scale.ordinal() - .rangeRoundBands([0, width], .1, 1); - - var y = d3.scale.linear() - .range([height, 0]); - - var xAxis = d3.svg.axis() - .scale(x) - .orient("bottom"); - - var yAxis = d3.svg.axis() - .scale(y) - .orient("left") - .tickFormat(formatPercent); - - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - d3.tsv("data.tsv", function (error: any, data: any) { - - data.forEach(function (d: any) { - d.frequency = +d.frequency; - }); - - x.domain(data.map(function (d: any) { return d.letter; })); - y.domain([0, d3.max(data, function (d: any) { return d.frequency; })]); - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); - - svg.append("g") - .attr("class", "y axis") - .call(yAxis) - .append("text") - .attr("transform", "rotate(-90)") - .attr("y", 6) - .attr("dy", ".71em") - .style("text-anchor", "end") - .text("Frequency"); - - svg.selectAll(".bar") - .data(data) - .enter().append("rect") - .attr("class", "bar") - .attr("x", function (d: any) { return x(d.letter); }) - .attr("width", x.rangeBand()) - .attr("y", function (d: any) { return y(d.frequency); }) - .attr("height", function (d: any) { return height - y(d.frequency); }); - - d3.select("input").on("change", change); - - var sortTimeout = setTimeout(function () { - d3.select("input").property("checked", true).each(change); - }, 2000); - - function change() { - clearTimeout(sortTimeout); - - var x0 = x.domain(data.sort(this.checked - ? function (a: any, b: any) { return b.frequency - a.frequency; } - : function (a: any, b: any) { return d3.ascending(a.letter, b.letter); }) - .map(function (d: any) { return d.letter; })) - .copy(); - - var transition = svg.transition().duration(750), - delay = function (d: any, i: number) { return i * 50; }; - - transition.selectAll(".bar") - .delay(delay) - .attr("x", function (d: any) { return x0(d.letter); }); - - transition.select(".x.axis") - .call(xAxis) - .selectAll("g") - .delay(delay); - } - }); -} - -//example from http://bl.ocks.org/4063318 -function callenderView() { - var width = 960, - height = 136, - cellSize = 17; // cell size - - var day = d3.time.format("%w"), - week = d3.time.format("%U"), - percent = d3.format(".1%"), - format = d3.time.format("%Y-%m-%d"); - - var color = d3.scale.quantize() - .domain([-.05, .05]) - .range(d3.range(11).map(function (d) { return "q" + d + "-11"; })); - - var svg = d3.select("body").selectAll("svg") - .data(d3.range(1990, 2011)) - .enter().append("svg") - .attr("width", width) - .attr("height", height) - .attr("class", "RdYlGn") - .append("g") - .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")"); - - svg.append("text") - .attr("transform", "translate(-6," + cellSize * 3.5 + ")rotate(-90)") - .style("text-anchor", "middle") - .text(function (d) { return d; }); - - var rect = svg.selectAll(".day") - .data(function (d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) - .enter().append("rect") - .attr("class", "day") - .attr("width", cellSize) - .attr("height", cellSize) - .attr("x", function (d) { return parseInt(week(d)) * cellSize; }) - .attr("y", function (d) { return parseInt(day(d)) * cellSize; }) - .datum(format); - - rect.append("title") - .text(function (d) { return d; }); - - svg.selectAll(".month") - .data(function (d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) - .enter().append("path") - .attr("class", "month") - .attr("d", monthPath); - - d3.csv("dji.csv", function (error, csv) { - var data = d3.nest() - .key(function (d: any) { return d.Date; }) - .rollup(function (d: any) { return (d[0].Close - d[0].Open) / d[0].Open; }) - .map(csv); - - rect.filter(function (d) { return d in data; }) - .attr("class", function (d) { return "day " + color(data[d]); }) - .select("title") - .text(function (d) { return d + ": " + percent(data[d]); }); - }); - - function monthPath(t0: Date) { - var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0), - d0 = +day(t0), w0 = +week(t0), - d1 = +day(t1), w1 = +week(t1); - return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize - + "H" + w0 * cellSize + "V" + 7 * cellSize - + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize - + "H" + (w1 + 1) * cellSize + "V" + 0 - + "H" + (w0 + 1) * cellSize + "Z"; - } - - d3.select(self.frameElement).style("height", "2910px"); -} - -// example from http://bl.ocks.org/3883245 -function lineChart() { - var margin = { top: 20, right: 20, bottom: 30, left: 50 }, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom; - - var parseDate = d3.time.format("%d-%b-%y").parse; - - var x = d3.time.scale() - .range([0, width]); - - var y = d3.scale.linear() - .range([height, 0]); - - var xAxis = d3.svg.axis() - .scale(x) - .orient("bottom"); - - var yAxis = d3.svg.axis() - .scale(y) - .orient("left"); - - var line = d3.svg.line<{ date: Date; close: number }>() - .x(function (d) { return x(d.date); }) - .y(function (d) { return y(d.close); }); - - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - d3.tsv("data.tsv", function (error: any, data: any) { - data.forEach(function (d: any) { - d.date = parseDate(d.date); - d.close = +d.close; - }); - - x.domain(d3.extent(data, function (d: any) { return d.date; })); - y.domain(d3.extent(data, function (d: any) { return d.close; })); - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); - - svg.append("g") - .attr("class", "y axis") - .call(yAxis) - .append("text") - .attr("transform", "rotate(-90)") - .attr("y", 6) - .attr("dy", ".71em") - .style("text-anchor", "end") - .text("Price ($)"); - - svg.append("path") - .datum(data) - .attr("class", "line") - .attr("d", line); - }); -} - -//example from http://bl.ocks.org/3884914 -function bivariateAreaChart() { - var margin = { top: 20, right: 20, bottom: 30, left: 50 }, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom; - - var parseDate = d3.time.format("%Y%m%d").parse; - - var x = d3.time.scale() - .range([0, width]); - - var y = d3.scale.linear() - .range([height, 0]); - - var xAxis = d3.svg.axis() - .scale(x) - .orient("bottom"); - - var yAxis = d3.svg.axis() - .scale(y) - .orient("left"); - - var area = d3.svg.area<{ date: Date; low: number; high: number }>() - .x(function (d) { return x(d.date); }) - .y0(function (d) { return y(d.low); }) - .y1(function (d) { return y(d.high); }); - - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - d3.tsv("data.tsv", function (error: any, data: any) { - data.forEach(function (d: any) { - d.date = parseDate(d.date); - d.low = +d.low; - d.high = +d.high; - }); - - x.domain(d3.extent(data, function (d: any) { return d.date; })); - y.domain([d3.min(data, function (d: any) { return d.low; }), d3.max(data, function (d: any) { return d.high; })]); - - svg.append("path") - .datum(data) - .attr("class", "area") - .attr("d", area); - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); - - svg.append("g") - .attr("class", "y axis") - .call(yAxis) - .append("text") - .attr("transform", "rotate(-90)") - .attr("y", 6) - .attr("dy", ".71em") - .style("text-anchor", "end") - .text("Temperature (ºF)"); - }); -} - -//Example from http://bl.ocks.org/mbostock/1557377 -function dragMultiples() { - var width = 238, - height = 123, - radius = 20; - - var drag = d3.behavior.drag() - .origin(Object) - .on("drag", dragmove); - - var svg = d3.select("body").selectAll("svg") - .data(d3.range(16).map(function () { return { x: width / 2, y: height / 2 }; })) - .enter().append("svg") - .attr("width", width) - .attr("height", height); - - svg.append("circle") - .attr("r", radius) - .attr("cx", function (d) { return d.x; }) - .attr("cy", function (d) { return d.y; }) - .call(drag); - - function dragmove(d: { x: number; y: number }) { - d3.select(this) - .attr("cx", d.x = Math.max(radius, Math.min(width - radius, ( d3.event).x))) - .attr("cy", d.y = Math.max(radius, Math.min(height - radius, ( d3.event).y))); - } -} - -//Example from http://bl.ocks.org/mbostock/3892919 -function panAndZoom() { - var margin = { top: 20, right: 20, bottom: 30, left: 40 }, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom; - - var x = d3.scale.linear() - .domain([-width / 2, width / 2]) - .range([0, width]); - - var y = d3.scale.linear() - .domain([-height / 2, height / 2]) - .range([height, 0]); - - var xAxis = d3.svg.axis() - .scale(x) - .orient("bottom") - .tickSize(-height); - - var yAxis = d3.svg.axis() - .scale(y) - .orient("left") - .ticks(5) - .tickSize(-width); - - var zoom = d3.behavior.zoom() - .x(x) - .y(y) - .scaleExtent([1, 10]) - .on("zoom", zoomed); - - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")") - .call(zoom); - - svg.append("rect") - .attr("width", width) - .attr("height", height); - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); - - svg.append("g") - .attr("class", "y axis") - .call(yAxis); - - function zoomed() { - svg.select(".x.axis").call(xAxis); - svg.select(".y.axis").call(yAxis); - } -} - -//Example from http://bl.ocks.org/mbostock/1125997 -function chainedTransitions() { - var w = 960, - h = 500, - y = d3.scale.ordinal().domain(d3.range(50)).rangePoints([20, h - 20]), - t = Date.now(); - - var svg = d3.select("body").append("svg:svg") - .attr("width", w) - .attr("height", h); - - var circle = svg.selectAll("circle") - .data(y.domain()) - .enter().append("svg:circle") - .attr("r", 16) - .attr("cx", 20) - .attr("cy", y) - .each(slide(20, w - 20)); - - function slide(x0: number, x1: number) { - t += 50; - return function() { - d3.select(this).transition() - .duration(t - Date.now()) - .attr("cx", x1) - .each("end", slide(x1, x0)); - }; - } -} - -//Example from http://bl.ocks.org/mbostock/4062085 -interface PyramidData { - people: number; - year: number; - age: number; -} -function populationPyramid() { - var margin = { top: 20, right: 40, bottom: 30, left: 20 }, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom, - barWidth = Math.floor(width / 19) - 1; - - var x = d3.scale.linear() - .range([barWidth / 2, width - barWidth / 2]); - - var y = d3.scale.linear() - .range([height, 0]); - - var yAxis = d3.svg.axis() - .scale(y) - .orient("right") - .tickSize(-width) - .tickFormat(function (d) { return Math.round(d / 1e6) + "M"; } ); - - // An SVG element with a bottom-right origin. - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - // A sliding container to hold the bars by birthyear. - var birthyears = svg.append("g") - .attr("class", "birthyears"); - - // A label for the current year. - var title = svg.append("text") - .attr("class", "title") - .attr("dy", ".71em") - .text(2000); - - d3.csv("population.csv", function (error: any, rows: Array) { - - // Convert strings to numbers. - rows.forEach(function (d) { - d.people = +d.people; - d.year = +d.year; - d.age = +d.age; - } ); - - // Compute the extent of the data set in age and years. - var age1 = d3.max(rows, function (d) { return d.age; } ), - year0 = d3.min(rows, function (d) { return d.year; } ), - year1 = d3.max(rows, function (d) { return d.year; } ), - year = year1; - - // Update the scale domains. - x.domain([year1 - age1, year1]); - y.domain([0, d3.max(rows, function (d) { return d.people; } )]); - - // Produce a map from year and birthyear to [male, female]. - var data = d3.nest() - .key(function (d) { return '' + d.year; } ) - .key(function (d) { return '' + (d.year - d.age); } ) - .rollup(function (v) { return v.map(function (d) { return d.people; } ); } ) - .map(rows); - - // Add an axis to show the population values. - svg.append("g") - .attr("class", "y axis") - .attr("transform", "translate(" + width + ",0)") - .call(yAxis) - .selectAll("g") - .filter(function (value) { return !value; } ) - .classed("zero", true); - - // Add labeled rects for each birthyear (so that no enter or exit is required). - var birthyear = birthyears.selectAll(".birthyear") - .data(d3.range(year0 - age1, year1 + 1, 5)) - .enter().append("g") - .attr("class", "birthyear") - .attr("transform", function (birthyear) { return "translate(" + x(birthyear) + ",0)"; } ); - - birthyear.selectAll("rect") - .data(function (birthyear): number[] { return data[year][birthyear] || [0, 0]; } ) - .enter().append("rect") - .attr("x", -barWidth / 2) - .attr("width", barWidth) - .attr("y", y) - .attr("height", function (value) { return height - y(value); } ); - - // Add labels to show birthyear. - birthyear.append("text") - .attr("y", height - 4) - .text(function (birthyear) { return birthyear; } ); - - // Add labels to show age (separate; not animated). - svg.selectAll(".age") - .data(d3.range(0, age1 + 1, 5)) - .enter().append("text") - .attr("class", "age") - .attr("x", function (age) { return x(year - age); } ) - .attr("y", height + 4) - .attr("dy", ".71em") - .text(function (age) { return age; } ); - - // Allow the arrow keys to change the displayed year. - window.focus(); - d3.select(window).on("keydown", function () { - switch (( d3.event).keyCode) { - case 37: year = Math.max(year0, year - 10); break; - case 39: year = Math.min(year1, year + 10); break; - } - update(); - } ); - - function update() { - if (!(year in data)) return; - title.text(year); - - birthyears.transition() - .duration(750) - .attr("transform", "translate(" + (x(year1) - x(year)) + ",0)"); - - birthyear.selectAll("rect") - .data(function (birthyear): number[] { return data[year][birthyear] || [0, 0]; } ) - .transition() - .duration(750) - .attr("y", y) - .attr("height", function (value) { return height - y(value); } ); - } - } ); -} - -//Example from http://bl.ocks.org/MoritzStefaner/1377729 -namespace forcedBasedLabelPlacemant { - interface Node extends d3.layout.force.Node { - label: string; - } - - interface LabelAnchor extends d3.layout.force.Node { - node: Node; - } - - interface LabelAnchorLink extends d3.layout.force.Link { - source: Node; - target: Node; - weight: number; - } - - var w = 960, h = 500; - - var labelDistance = 0; - - var vis = d3.select("body").append("svg:svg").attr("width", w).attr("height", h); - - var nodes: Node[] = []; - var labelAnchors: LabelAnchor[] = []; - var labelAnchorLinks: { source: number; target: number; weight: number }[] = []; - var links: typeof labelAnchorLinks = []; - - for (var i = 0; i < 30; i++) { - var nodeLabel = { - label: "node " + i - }; - nodes.push(nodeLabel); - labelAnchors.push({ - node: nodeLabel - }); - labelAnchors.push({ - node: nodeLabel - }); - }; - - for (var i = 0; i < nodes.length; i++) { - for (var j = 0; j < i; j++) { - if (Math.random() > .95) - links.push({ - source: i, - target: j, - weight: Math.random() - }); - } - labelAnchorLinks.push({ - source: i * 2, - target: i * 2 + 1, - weight: 1 - }); - }; - - var force = d3.layout.force().size([w, h]).nodes(nodes).links(links).gravity(1).linkDistance(50).charge(-3000).linkStrength(function (x) { - return x.weight * 10 - } ); - - - force.start(); - - var force2 = d3.layout.force().nodes(labelAnchors).links(labelAnchorLinks).gravity(0).linkDistance(0).linkStrength(8).charge(-100).size([w, h]); - force2.start(); - - var link = vis.selectAll("line.link").data(links).enter().append("svg:line").attr("class", "link").style("stroke", "#CCC"); - - var node = vis.selectAll("g.node").data(force.nodes()).enter().append("svg:g").attr("class", "node"); - node.append("svg:circle").attr("r", 5).style("fill", "#555").style("stroke", "#FFF").style("stroke-width", 3); - node.call(force.drag); - - - var anchorLink = vis.selectAll("line.anchorLink").data(labelAnchorLinks)//.enter().append("svg:line").attr("class", "anchorLink").style("stroke", "#999"); - - var anchorNode = vis.selectAll("g.anchorNode").data(force2.nodes()).enter().append("svg:g").attr("class", "anchorNode"); - anchorNode.append("svg:circle").attr("r", 0).style("fill", "#FFF"); - anchorNode.append("svg:text").text(function (d, i) { - return i % 2 == 0 ? "" : d.node.label - } ).style("fill", "#555").style("font-family", "Arial").style("font-size", 12); - - var updateLink = function () { - (> this).attr("x1", function (d) { - return d.source.x; - } ).attr("y1", function (d) { - return d.source.y; - } ).attr("x2", function (d) { - return d.target.x; - } ).attr("y2", function (d) { - return d.target.y; - } ); - - } - - var updateNode = function () { - (> this).attr("transform", function (d) { - return "translate(" + d.x + "," + d.y + ")"; - } ); - - } - - force.on("tick", function () { - - force2.start(); - - node.call(updateNode); - - anchorNode.each(function (d, i) { - if (i % 2 == 0) { - d.x = d.node.x; - d.y = d.node.y; - } else { - var b = this.childNodes[1].getBBox(); - - var diffX = d.x - d.node.x; - var diffY = d.y - d.node.y; - - var dist = Math.sqrt(diffX * diffX + diffY * diffY); - - var shiftX = b.width * (diffX - dist) / (dist * 2); - shiftX = Math.max(-b.width, Math.min(0, shiftX)); - var shiftY = 5; - this.childNodes[1].setAttribute("transform", "translate(" + shiftX + "," + shiftY + ")"); - } - } ); - - - anchorNode.call(updateNode); - - link.call(updateLink); - anchorLink.call(updateLink); - - } ); -} - -//Example from http://bl.ocks.org/mbostock/1125997 -namespace forceCollapsable { - interface Node extends d3.layout.force.Node { - id: string; - _children: Node[]; - children?: Node[]; - size: number; - } - - var w = 1280, - h = 800, - node: d3.selection.Update, - link: d3.selection.Update>, - root: any; - - var force = d3.layout.force() - .on("tick", tick) - .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) - .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) - .size([w, h - 160]); - - var vis = d3.select("body").append("svg:svg") - .attr("width", w) - .attr("height", h); - - d3.json("flare.json", function (json) { - root = json; - root.fixed = true; - root.x = w / 2; - root.y = h / 2 - 80; - update(); - } ); - - function update() { - var nodes = flatten(root), - links = d3.layout.tree().links(nodes); - - // Restart the force layout. - force - .nodes(nodes) - .links(links) - .start(); - - // Update the links… - link = vis.selectAll("line.link") - .data(links, function (d) { return d.target.id; } ); - - // Enter any new links. - link.enter().insert("svg:line", ".node") - .attr("class", "link") - .attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); - - // Exit any old links. - link.exit().remove(); - - // Update the nodes… - node = vis.selectAll("circle.node") - .data(nodes, function (d) { return d.id; } ) - .style("fill", color); - - node.transition() - .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ); - - // Enter any new nodes. - node.enter().append("svg:circle") - .attr("class", "node") - .attr("cx", function (d) { return d.x; } ) - .attr("cy", function (d) { return d.y; } ) - .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ) - .style("fill", color) - .on("click", click) - .call(force.drag); - - // Exit any old nodes. - node.exit().remove(); - } - - function tick() { - link.attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); - - node.attr("cx", function (d) { return d.x; } ) - .attr("cy", function (d) { return d.y; } ); - } - - // Color leaf nodes orange, and packages white or blue. - function color(d: Node) { - return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c"; - } - - // Toggle children on click. - function click(d: Node) { - if (d.children) { - d._children = d.children; - d.children = null; - } else { - d.children = d._children; - d._children = null; - } - update(); - } - - // Returns a list of all nodes under the root. - function flatten(root: Node) { - var nodes: Node[] = [], i = 0; - - function recurse(node: Node) { - if (node.children) node.size = node.children.reduce(function (p, v) { return p + recurse(v); } , 0); - if (!node.id) node.id = String(++i); - nodes.push(node); - return node.size; - } - - root.size = recurse(root); - return nodes; - } -} - -//Example from http://bl.ocks.org/mbostock/3757110 -function azimuthalEquidistant() { - var width = 960, - height = 960; - var topojson: any; - - var projection = d3.geo.azimuthalEquidistant() - .scale(150) - .translate([width / 2, height / 2]) - .clipAngle(180 - 1e-3) - .precision(.1); - - var path = d3.geo.path() - .projection(projection); - - var graticule = d3.geo.graticule(); - - var svg = d3.select("body").append("svg") - .attr("width", width) - .attr("height", height); - - svg.append("defs").append("path") - .datum({ type: "Sphere" }) - .attr("id", "sphere") - .attr("d", path); - - svg.append("use") - .attr("class", "stroke") - .attr("xlink:href", "#sphere"); - - svg.append("use") - .attr("class", "fill") - .attr("xlink:href", "#sphere"); - - svg.append("path") - .datum(graticule) - .attr("class", "graticule") - .attr("d", path); - - d3.json("/mbostock/raw/4090846/world-50m.json", function (error, world) { - svg.insert("path", ".graticule") - .datum(topojson.feature(world, world.objects.land)) - .attr("class", "land") - .attr("d", path); - - svg.insert("path", ".graticule") - .datum(topojson.mesh(world, world.objects.countries, function (a: any, b: any) { return a !== b; } )) - .attr("class", "boundary") - .attr("d", path); - } ); - - d3.select(self.frameElement).style("height", height + "px"); -} - -//Example from http://bl.ocks.org/mbostock/4060366 -function voronoiTesselation() { - var width = 960, - height = 500; - - var vertices = d3.range(100).map(function (d): [number, number] { - return [Math.random() * width, Math.random() * height]; - } ); - - var voronoi = d3.geom.voronoi() - .clipExtent([[0, 0], [width, height]]); - - var svg = d3.select("body").append("svg") - .attr("width", width) - .attr("height", height) - .attr("class", "PiYG") - .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ); - - var path = >svg.append("g").selectAll("path"); - - svg.selectAll("circle") - .data(vertices.slice(1)) - .enter().append("circle") - .attr("transform", function (d) { return "translate(" + d + ")"; } ) - .attr("r", 2); - - redraw(); - - function redraw() { - path = path.data(voronoi(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String); - path.exit().remove(); - path.enter().append("path").attr("class", function (d, i) { return "q" + (i % 9) + "-9"; } ).attr("d", String); - path.order(); - } -} - -// Example from https://gist.github.com/christophermanning/1734663 -function forceDirectedVoronoi() { - var w = window.innerWidth > 960 ? 960 : (window.innerWidth || 960), - h = window.innerHeight > 500 ? 500 : (window.innerHeight || 500), - radius = 5.25, - simulate = true, - zoomToAdd = true, - color = d3.scale.quantize().domain([10000, 7250]).range(["#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]) - - var numVertices = (w*h) / 3000; - var vertices = d3.range(numVertices).map(function(i) { - var angle = radius * (i+10); - return {x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}; - }); - var d3_geom_voronoi = d3.geom.voronoi<{ x: number; y: number }>() - .x(function(d) { return d.x; }) - .y(function(d) { return d.y; }) - var prevEventScale = 1; - var zoom = d3.behavior.zoom().on("zoom", function(d,i) { - if (zoomToAdd){ - if (( d3.event).scale > prevEventScale) { - var angle = radius * vertices.length; - vertices.push({x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}) - } else if (vertices.length > 2 && ( d3.event).scale != prevEventScale) { - vertices.pop(); - } - force.nodes(vertices).start() - } else { - if (( d3.event).scale > prevEventScale) { - radius+= .01 - } else { - radius -= .01 - } - vertices.forEach(function(d, i) { - var angle = radius * (i+10); - vertices[i] = {x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}; - }); - force.nodes(vertices).start() - } - prevEventScale = ( d3.event).scale; - }); - - d3.select(window) - .on("keydown", function() { - // shift - if(( d3.event).keyCode == 16) { - zoomToAdd = false - } - - // s - if(( d3.event).keyCode == 83) { - simulate = !simulate - if(simulate) { - force.start() - } else { - force.stop() - } - } - }) - .on("keyup", function() { - zoomToAdd = true - }) - - var svg = d3.select("#chart") - .append("svg") - .attr("width", w) - .attr("height", h) - .call(zoom) - - var force = d3.layout.force() - .charge(-300) - .size([w, h]) - .on("tick", update); - - force.nodes(vertices).start(); - - var circle = > svg.selectAll("circle"); - var path = > svg.selectAll("path"); - var link = > svg.selectAll("line"); - - function update() { - path = path.data(d3_geom_voronoi(vertices)); - path.enter().append("path") - // drag node by dragging cell - .call(d3.behavior.drag() - .on("drag", function(d, i) { - vertices[i] = {x: vertices[i].x + ( d3.event).dx, y: vertices[i].y + ( d3.event).dy} - }) - ) - .style("fill", function(d, i) { return color(0) }) - path.attr("d", function(d) { return "M" + d.join("L") + "Z"; }) - .transition().duration(150).style("fill", function(d, i) { return color(d3.geom.polygon(d).area()) }) - path.exit().remove(); - - circle = circle.data(vertices) - circle.enter().append("circle") - .attr("r", 0) - .transition().duration(1000).attr("r", 5); - circle.attr("cx", function(d) { return d.x; }) - .attr("cy", function(d) { return d.y; }); - circle.exit().transition().attr("r", 0).remove(); - - link = link.data(d3_geom_voronoi.links(vertices)) - link.enter().append("line") - link.attr("x1", function(d) { return d.source.x; }) - .attr("y1", function(d) { return d.source.y; }) - .attr("x2", function(d) { return d.target.x; }) - .attr("y2", function(d) { return d.target.y; }) - - link.exit().remove() - - if(!simulate) force.stop() - } -} - -//Example from http://bl.ocks.org/mbostock/4341156 -function delaunayTesselation() { - var width = 960, - height = 500; - - var vertices = d3.range(100).map(function (d): [number, number] { - return [Math.random() * width, Math.random() * height]; - } ); - - var svg = d3.select("body").append("svg") - .attr("width", width) - .attr("height", height) - .attr("class", "PiYG") - .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ); - - var path = >svg.append("g").selectAll("path"); - - svg.selectAll("circle") - .data(vertices.slice(1)) - .enter().append("circle") - .attr("transform", function (d) { return "translate(" + d + ")"; } ) - .attr("r", 2); - - redraw(); - - function redraw() { - path = path.data(d3.geom.delaunay(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String); - path.exit().remove(); - path.enter().append("path").attr("class", function (d, i) { return "q" + (i % 9) + "-9"; } ).attr("d", String); - } -} - -//Example from http://bl.ocks.org/mbostock/4343214 -function quadtree() { - var width = 960, - height = 500; - - var data = d3.range(5000).map(function(): [number, number] { - return [Math.random() * width, Math.random() * width]; - }); - - var quadtree = d3.geom.quadtree() - .extent([[-1, -1], [width + 1, height + 1]]) - (data); - - var brush = d3.svg.brush() - .x(d3.scale.identity().domain([0, width])) - .y(d3.scale.identity().domain([0, height])) - .on("brush", brushed) - .extent([[100, 100], [200, 200]]); - - var svg = d3.select("body").append("svg") - .attr("width", width) - .attr("height", height); - - svg.selectAll(".node") - .data(nodes(quadtree)) - .enter().append("rect") - .attr("class", "node") - .attr("x", function (d) { return d.x; } ) - .attr("y", function (d) { return d.y; } ) - .attr("width", function (d) { return d.width; } ) - .attr("height", function (d) { return d.height; } ); - - var point = svg.selectAll(".point") - .data(<{ scanned?: boolean; selected?: boolean; 0: number; 1: number }[]> data) - .enter().append("circle") - .attr("class", "point") - .attr("cx", function (d) { return d[0]; } ) - .attr("cy", function (d) { return d[1]; } ) - .attr("r", 4); - - svg.append("g") - .attr("class", "brush") - .call(brush); - - brushed(); - - function brushed() { - var extent = <[[number, number], [number, number]]> brush.extent(); - point.each(function (d) { d.scanned = d.selected = false; } ); - search(quadtree, extent[0][0], extent[0][1], extent[1][0], extent[1][1]); - point.classed("scanned", function (d) { return d.scanned; } ); - point.classed("selected", function (d) { return d.selected; } ); - } - - // Collapse the quadtree into an array of rectangles. - function nodes(quadtree: d3.geom.quadtree.Quadtree<[number, number]>) { - var nodes: Array<{x: number; y: number; width: number; height: number}> = []; - quadtree.visit(function (node: d3.geom.quadtree.Node<[number, number]>, x1: number, y1: number, x2:number, y2: number) { - nodes.push({ x: x1, y: y1, width: x2 - x1, height: y2 - y1 }); - } ); - return nodes; - } - - // Find the nodes within the specified rectangle. - function search(quadtree: d3.geom.quadtree.Quadtree<{ scanned?: boolean; selected?: boolean; 0: number; 1: number }>, x0: number, y0: number, x3: number, y3: number) { - quadtree.visit(function (node: d3.geom.quadtree.Node<{ scanned?: boolean; selected?: boolean; 0: number; 1: number }>, x1: number, y1: number, x2:number, y2: number) { - var p = node.point; - if (p) { - p.scanned = true; - p.selected = (p[0] >= x0) && (p[0] < x3) && (p[1] >= y0) && (p[1] < y3); - } - return x1 >= x3 || y1 >= y3 || x2 < x0 || y2 < y0; - } ); - } -} - -//Example from http://bl.ocks.org/mbostock/4341699 -function convexHull() { - var width = 960, - height = 500; - - var randomX = d3.random.normal(width / 2, 60), - randomY = d3.random.normal(height / 2, 60), - vertices = d3.range(100).map(function (): [number, number] { return [randomX(), randomY()]; } ); - - var svg = d3.select("body").append("svg") - .attr("width", width) - .attr("height", height) - .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ) - .on("click", function () { vertices.push(d3.mouse(this)); redraw(); } ); - - svg.append("rect") - .attr("width", width) - .attr("height", height); - - var hull = svg.append("path") - .attr("class", "hull"); - - var circle = > svg.selectAll("circle"); - - redraw(); - - function redraw() { - hull.datum(d3.geom.hull(vertices)).attr("d", function (d) { return "M" + d.join("L") + "Z"; } ); - circle = circle.data(vertices); - circle.enter().append("circle").attr("r", 3); - circle.attr("transform", function (d) { return "translate(" + d + ")"; } ); - } -} - -// example from http://bl.ocks.org/mbostock/1044242 -namespace hierarchicalEdgeBundling { - interface Result extends d3.layout.cluster.Result { - parent: Result; - size: number; - key: string; - } - - var diameter = 960, - radius = diameter / 2, - innerRadius = radius - 120; - - var cluster = d3.layout.cluster() - .size([360, innerRadius]) - .sort(null) - .value(function (d) { return d.size; } ); - - var bundle = d3.layout.bundle(); - - var line = d3.svg.line.radial() - .interpolate("bundle") - .tension(.85) - .radius(function (d) { return d.y; } ) - .angle(function (d) { return d.x / 180 * Math.PI; } ); - - var svg = d3.select("body").append("svg") - .attr("width", diameter) - .attr("height", diameter) - .append("g") - .attr("transform", "translate(" + radius + "," + radius + ")"); - - d3.json("readme-flare-imports.json", function (error, classes) { - var nodes = cluster.nodes(packages.root(classes)), - links = packages.imports(nodes); - - svg.selectAll(".link") - .data(bundle(links)) - .enter().append("path") - .attr("class", "link") - .attr("d", line); - - svg.selectAll(".node") - .data(nodes.filter(function (n) { return !n.children; } )) - .enter().append("g") - .attr("class", "node") - .attr("transform", function (d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; } ) - .append("text") - .attr("dx", function (d) { return d.x < 180 ? 8 : -8; } ) - .attr("dy", ".31em") - .attr("text-anchor", function (d) { return d.x < 180 ? "start" : "end"; } ) - .attr("transform", function (d) { return d.x < 180 ? null : "rotate(180)"; } ) - .text(function (d) { return d.key; } ); - } ); - - d3.select(self.frameElement).style("height", diameter + "px"); - - var packages = { - - // Lazily construct the package hierarchy from class names. - root: function (classes: any[]) { - var map: {[key: string]: Result} = {}; - - function find(name: string, data?: any) { - var node: Result = map[name], i: number; - if (!node) { - node = map[name] = data || { name: name, children: [] }; - if (name.length) { - node.parent = find(name.substring(0, i = name.lastIndexOf("."))); - node.parent.children.push(node); - node.key = name.substring(i + 1); - } - } - return node; - } - - classes.forEach(function (d) { - find(d.name, d); - } ); - - return map[""]; - } , - - // Return a list of imports for the given array of nodes. - imports: function (nodes: any[]) { - var map: {[key: string]: Result} = {}, - imports: d3.layout.cluster.Link[] = []; - - // Compute a map from name to node. - nodes.forEach(function (d) { - map[d.name] = d; - } ); - - // For each import, construct a link from the source to target node. - nodes.forEach(function (d) { - if (d.imports) d.imports.forEach(function (i: string) { - imports.push({ source: map[d.name], target: map[i] }); - } ); - } ); - - return imports; - } - }; -} - -// example from http://bl.ocks.org/mbostock/1123639 -function roundedRectangles() { - var mouse = [480, 250], - count = 0; - - var svg = d3.select("body").append("svg:svg") - .attr("width", 960) - .attr("height", 500); - - var g = svg.selectAll("g") - .data(d3.range(25)) - .enter().append("svg:g") - .attr("transform", "translate(" + mouse + ")"); - - g.append("svg:rect") - .attr("rx", 6) - .attr("ry", 6) - .attr("x", -12.5) - .attr("y", -12.5) - .attr("width", 25) - .attr("height", 25) - .attr("transform", function (d, i) { return "scale(" + (1 - d / 25) * 20 + ")"; } ) - .style("fill", d3.scale.category20c()); - - var g0 = g.datum(function (d) { - return { center: [0, 0], angle: 0 }; - } ); - - svg.on("mousemove", function () { - mouse = d3.mouse(this); - } ); - - d3.timer(function () { - count++; - g0.attr("transform", function (d, i) { - d.center[0] += (mouse[0] - d.center[0]) / (i + 5); - d.center[1] += (mouse[1] - d.center[1]) / (i + 5); - d.angle += Math.sin((count + i) / 10) * 7; - return "translate(" + d.center + ")rotate(" + d.angle + ")"; - } ); - return true; - } ); -} - -// example from http://bl.ocks.org/mbostock/4060954 -function streamGraph() { - var n = 20, // number of layers - m = 200, // number of samples per layer - stack = d3.layout.stack().offset("wiggle"), - layers0 = stack(d3.range(n).map(function () { return bumpLayer(m); })), - layers1 = stack(d3.range(n).map(function () { return bumpLayer(m); })); - - var width = 960, - height = 500; - - var x = d3.scale.linear() - .domain([0, m - 1]) - .range([0, width]); - - var y = d3.scale.linear() - .domain([0, d3.max(layers0.concat(layers1), function (layer) { return d3.max(layer, function (d) { return d.y0 + d.y; }); })]) - .range([height, 0]); - - var color = d3.scale.linear() - .range(["#aad", "#556"]); - - var area = d3.svg.area<{ x: number; y: number; y0: number }>() - .x(function (d) { return x(d.x); }) - .y0(function (d) { return y(d.y0); }) - .y1(function (d) { return y(d.y0 + d.y); }); - - var svg = d3.select("body").append("svg") - .attr("width", width) - .attr("height", height); - - svg.selectAll("path") - .data(layers0) - .enter().append("path") - .attr("d", area) - .style("fill", function () { return color(Math.random()); }); - - function transition() { - d3.selectAll("path") - .data(function () { - var d = layers1; - layers1 = layers0; - return layers0 = d; - }) - .transition() - .duration(2500) - .attr("d", area); - } - - // Inspired by Lee Byron's test data generator. - function bumpLayer(n: number): Array<{x: number; y: number;y0?:number;}> { - - function bump(a: number[]) { - var x = 1 / (.1 + Math.random()), - y = 2 * Math.random() - .5, - z = 10 / (.1 + Math.random()); - for (var i = 0; i < n; i++) { - var w = (i / n - y) * z; - a[i] += x * Math.exp(-w * w); - } - } - - var a: number[] = [], i: number; - for (i = 0; i < n; ++i) a[i] = 0; - for (i = 0; i < 5; ++i) bump(a); - return a.map(function (d, i) { return { x: i, y: Math.max(0, d) }; } ); - } -} - -// example from http://mbostock.github.io/d3/talk/20111116/force-collapsible.html -namespace forceCollapsable2 { - interface Node extends d3.layout.force.Node { - children: Node[]; - _children: Node[]; - size: number; - id: string; - } - - var w = 1280, - h = 800, - node: d3.selection.Update, - link: d3.selection.Update>, - root: Node; - - var force = d3.layout.force() - .on("tick", tick) - .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) - .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) - .size([w, h - 160]); - - var vis = d3.select("body").append("svg:svg") - .attr("width", w) - .attr("height", h); - - d3.json("flare.json", function (json) { - root = json; - root.fixed = true; - root.x = w / 2; - root.y = h / 2 - 80; - update(); - } ); - - function update() { - var nodes = flatten(root), - links = d3.layout.tree().links(nodes); - - // Restart the force layout. - force - .nodes(nodes) - .links(links) - .start(); - - // Update the links… - link = vis.selectAll("line.link") - .data(links, function (d) { return d.target.id; } ); - - // Enter any new links. - link.enter().insert("svg:line", ".node") - .attr("class", "link") - .attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); - - // Exit any old links. - link.exit().remove(); - - // Update the nodes… - node = vis.selectAll("circle.node") - .data(nodes, function (d) { return d.id; } ) - .style("fill", color); - - node.transition() - .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ); - - // Enter any new nodes. - node.enter().append("svg:circle") - .attr("class", "node") - .attr("cx", function (d) { return d.x; } ) - .attr("cy", function (d) { return d.y; } ) - .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ) - .style("fill", color) - .on("click", click) - .call(force.drag); - - // Exit any old nodes. - node.exit().remove(); - } - - function tick() { - link.attr("x1", function (d) { return d.source.x; } ) - .attr("y1", function (d) { return d.source.y; } ) - .attr("x2", function (d) { return d.target.x; } ) - .attr("y2", function (d) { return d.target.y; } ); - - node.attr("cx", function (d) { return d.x; } ) - .attr("cy", function (d) { return d.y; } ); - } - - // Color leaf nodes orange, and packages white or blue. - function color(d: Node) { - return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c"; - } - - // Toggle children on click. - function click(d: Node) { - if (d.children) { - d._children = d.children; - d.children = null; - } else { - d.children = d._children; - d._children = null; - } - update(); - } - - // Returns a list of all nodes under the root. - function flatten(root: Node) { - var nodes: Node[] = [], i = 0; - - function recurse(node: Node) { - if (node.children) node.size = node.children.reduce(function (p, v) { return p + recurse(v); } , 0); - if (!node.id) node.id = String(++i); - nodes.push(node); - return node.size; - } - - root.size = recurse(root); - return nodes; - } -} - -//exapmle from http://bl.ocks.org/mbostock/4062006 -function chordDiagram() { - var matrix = [ - [11975, 5871, 8916, 2868], - [1951, 10048, 2060, 6171], - [8010, 16145, 8090, 8045], - [1013, 990, 940, 6907] - ]; - - var chord = d3.layout.chord() - .padding(.05) - .sortSubgroups(d3.descending) - .matrix(matrix); - - var width = 960, - height = 500, - innerRadius = Math.min(width, height) * .41, - outerRadius = innerRadius * 1.1; - - var fill = d3.scale.ordinal() - .domain(d3.range(4)) - .range(["#000000", "#FFDD89", "#957244", "#F26223"]); - - var svg = d3.select("body").append("svg") - .attr("width", width) - .attr("height", height) - .append("g") - .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); - - svg.append("g").selectAll("path") - .data(chord.groups) - .enter().append("path") - .style("fill", function (d) { return fill(d.index); } ) - .style("stroke", function (d) { return fill(d.index); } ) - .attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius)) - .on("mouseover", fade(.1)) - .on("mouseout", fade(1)); - - var ticks = svg.append("g").selectAll("g") - .data(chord.groups) - .enter().append("g").selectAll("g") - .data(groupTicks) - .enter().append("g") - .attr("transform", function (d) { - return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" - + "translate(" + outerRadius + ",0)"; - } ); - - ticks.append("line") - .attr("x1", 1) - .attr("y1", 0) - .attr("x2", 5) - .attr("y2", 0) - .style("stroke", "#000"); - - ticks.append("text") - .attr("x", 8) - .attr("dy", ".35em") - .attr("transform", function (d) { return d.angle > Math.PI ? "rotate(180)translate(-16)" : null; } ) - .style("text-anchor", function (d) { return d.angle > Math.PI ? "end" : null; } ) - .text(function (d) { return d.label; } ); - - svg.append("g") - .attr("class", "chord") - .selectAll("path") - .data(chord.chords) - .enter().append("path") - .attr("d", d3.svg.chord().radius(innerRadius)) - .style("fill", function (d) { return fill(d.target.index); } ) - .style("opacity", 1); - - // Returns an array of tick angles and labels, given a group. - function groupTicks(d: d3.layout.chord.Node) { - var k = (d.endAngle - d.startAngle) / d.value; - return d3.range(0, d.value, 1000).map(function (v, i) { - return { - angle: v * k + d.startAngle, - label: i % 5 ? null : v / 1000 + "k" - }; - } ); - } - - // Returns an event handler for fading a given chord group. - function fade(opacity: number) { - return function (g: {}, i: number) { - svg.selectAll(".chord path") - .filter(function (d) { return d.source.index != i && d.target.index != i; } ) - .transition() - .style("opacity", opacity); - }; - } -} - -//example from http://mbostock.github.io/d3/talk/20111116/iris-parallel.html -function irisParallel() { - var species = ["setosa", "versicolor", "virginica"], - traits = ["sepal length", "petal length", "sepal width", "petal width"]; - - var m = [80, 160, 200, 160], - w = 1280 - m[1] - m[3], - h = 800 - m[0] - m[2]; - - var x = d3.scale.ordinal().domain(traits).rangePoints([0, w]), - y: {[key: string]: any} = {}; - - var line = d3.svg.line(), - axis = d3.svg.axis().orient("left"), - foreground: d3.Selection<{ [key: string]: string}>; - - var svg = d3.select("body").append("svg:svg") - .attr("width", w + m[1] + m[3]) - .attr("height", h + m[0] + m[2]) - .append("svg:g") - .attr("transform", "translate(" + m[3] + "," + m[0] + ")"); - - d3.csv("iris.csv", function (flowers) { - var i: number; - - // Create a scale and brush for each trait. - traits.forEach(function (d) { - y[d] = d3.scale.linear() - .domain(d3.extent(flowers, function (p) { return +p[d]; } )) - .range([h, 0]); - - y[d].brush = d3.svg.brush() - .y(y[d]) - .on("brush", brush); - } ); - - // Add a legend. - var legend = svg.selectAll("g.legend") - .data(species) - .enter().append("svg:g") - .attr("class", "legend") - .attr("transform", function (d, i) { return "translate(0," + (i * 20 + 584) + ")"; } ); - - legend.append("svg:line") - .attr("class", String) - .attr("x2", 8); - - legend.append("svg:text") - .attr("x", 12) - .attr("dy", ".31em") - .text(function (d) { return "Iris " + d; } ); - - // Add foreground lines. - foreground = svg.append("svg:g") - .attr("class", "foreground") - .selectAll("path") - .data(flowers) - .enter().append("svg:path") - .attr("d", path) - .attr("class", function (d) { return d['species']; } ); - - // Add a group element for each trait. - var g = svg.selectAll(".trait") - .data(traits) - .enter().append("svg:g") - .attr("class", "trait") - .attr("transform", function (d) { return "translate(" + x(d) + ")"; } ) - .call(d3.behavior.drag() - .origin(function (d) { return { x: x(d), y: NaN }; } ) - .on("dragstart", dragstart) - .on("drag", drag) - .on("dragend", dragend)); - - // Add an axis and title. - g.append("svg:g") - .attr("class", "axis") - .each(function (d) { d3.select(this).call(axis.scale(y[d])); } ) - .append("svg:text") - .attr("text-anchor", "middle") - .attr("y", -9) - .text(String); - - // Add a brush for each axis. - g.append("svg:g") - .attr("class", "brush") - .each(function (d) { d3.select(this).call(y[d].brush); } ) - .selectAll("rect") - .attr("x", -8) - .attr("width", 16); - - function dragstart(d: string) { - i = traits.indexOf(d); - } - - function drag(d: string) { - x.range()[i] = ( d3.event).x; - traits.sort(function (a, b) { return x(a) - x(b); } ); - g.attr("transform", function (d) { return "translate(" + x(d) + ")"; } ); - foreground.attr("d", path); - } - - function dragend(d: string) { - x.domain(traits).rangePoints([0, w]); - var t = d3.transition().duration(500); - t.selectAll(".trait").attr("transform", function (d) { return "translate(" + x(d) + ")"; } ); - t.selectAll(".foreground path").attr("d", path); - } - } ); - - // Returns the path for a given data point. - function path(d: any): string { - return line(traits.map(function (p): [number, number] { return [x(p), y[p](d[p])]; } )); - } - - // Handles a brush event, toggling the display of foreground lines. - function brush() { - var actives = traits.filter(function (p) { return !y[p].brush.empty(); } ), - extents = actives.map(function (p) { return y[p].brush.extent(); } ); - foreground.classed("fade", function (d) { - return !actives.every(function (p, i) { - return extents[i][0] <= d[p] && d[p] <= extents[i][1]; - } ); - } ); - } -} - -//example from -function healthAndWealth() { - // Various accessors that specify the four dimensions of data to visualize. - function x(d: any) { return d.income; } - function y(d: any) { return d.lifeExpectancy; } - function radius(d: any) { return d.population; } - function color(d: any) { return d.region; } - function key(d: any) { return d.name; } - - // Chart dimensions. - var margin = { top: 19.5, right: 19.5, bottom: 19.5, left: 39.5 }, - width = 960 - margin.right, - height = 500 - margin.top - margin.bottom; - - // Various scales. These domains make assumptions of data, naturally. - var xScale = d3.scale.log().domain([300, 1e5]).range([0, width]), - yScale = d3.scale.linear().domain([10, 85]).range([height, 0]), - radiusScale = d3.scale.sqrt().domain([0, 5e8]).range([0, 40]), - colorScale = d3.scale.category10(); - - // The x & y axes. - var xAxis = d3.svg.axis().orient("bottom").scale(xScale).ticks(12, d3.format(",d")), - yAxis = d3.svg.axis().scale(yScale).orient("left"); - - // Create the SVG container and set the origin. - var svg = d3.select("#chart").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - // Add the x-axis. - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); - - // Add the y-axis. - svg.append("g") - .attr("class", "y axis") - .call(yAxis); - - // Add an x-axis label. - svg.append("text") - .attr("class", "x label") - .attr("text-anchor", "end") - .attr("x", width) - .attr("y", height - 6) - .text("income per capita, inflation-adjusted (dollars)"); - - // Add a y-axis label. - svg.append("text") - .attr("class", "y label") - .attr("text-anchor", "end") - .attr("y", 6) - .attr("dy", ".75em") - .attr("transform", "rotate(-90)") - .text("life expectancy (years)"); - - // Add the year label; the value is set on transition. - var label = svg.append("text") - .attr("class", "year label") - .attr("text-anchor", "end") - .attr("y", height - 24) - .attr("x", width) - .text(1800); - - // Load the data. - d3.json("nations.json", function (nations: any[]) { - - // A bisector since many nation's data is sparsely-defined. - var bisect = d3.bisector(function (d: any) { return d[0]; } ); - - // Add a dot per nation. Initialize the data at 1800, and set the colors. - var dot = svg.append("g") - .attr("class", "dots") - .selectAll(".dot") - .data(interpolateData(1800)) - .enter().append("circle") - .attr("class", "dot") - .style("fill", function (d) { return colorScale(color(d)); } ) - .call(position) - .sort(order); - - // Add a title. - dot.append("title") - .text(function (d) { return d.name; } ); - - // Add an overlay for the year label. - var box = (label.node()).getBBox(); - - var overlay = svg.append("rect") - .attr("class", "overlay") - .attr("x", box.x) - .attr("y", box.y) - .attr("width", box.width) - .attr("height", box.height) - .on("mouseover", enableInteraction); - - // Start a transition that interpolates the data based on year. - svg.transition() - .duration(30000) - .ease("linear") - .tween("year", tweenYear) - .each("end", enableInteraction); - - // Positions the dots based on data. - function position(dot: d3.Selection) { - dot.attr("cx", function (d) { return xScale(x(d)); } ) - .attr("cy", function (d) { return yScale(y(d)); } ) - .attr("r", function (d) { return radiusScale(radius(d)); } ); - } - - // Defines a sort order so that the smallest dots are drawn on top. - function order(a: any, b: any) { - return radius(b) - radius(a); - } - - // After the transition finishes, you can mouseover to change the year. - function enableInteraction() { - var yearScale = d3.scale.linear() - .domain([1800, 2009]) - .range([box.x + 10, box.x + box.width - 10]) - .clamp(true); - - // Cancel the current transition, if any. - svg.transition().duration(0); - - overlay - .on("mouseover", mouseover) - .on("mouseout", mouseout) - .on("mousemove", mousemove) - .on("touchmove", mousemove); - - function mouseover() { - label.classed("active", true); - } - - function mouseout() { - label.classed("active", false); - } - - function mousemove() { - displayYear(yearScale.invert(d3.mouse(this)[0])); - } - } - - // Tweens the entire chart by first tweening the year, and then the data. - // For the interpolated data, the dots and label are redrawn. - function tweenYear() { - var year = d3.interpolateNumber(1800, 2009); - return function (t: number) { displayYear(year(t)); }; - } - - // Updates the display to show the specified year. - function displayYear(year: number) { - dot.data(interpolateData(year), key).call(position).sort(order); - label.text(Math.round(year)); - } - - // Interpolates the dataset for the given (fractional) year. - function interpolateData(year: number) { - return nations.map(function (d) { - return { - name: d.name, - region: d.region, - income: interpolateValues(d.income, year), - population: interpolateValues(d.population, year), - lifeExpectancy: interpolateValues(d.lifeExpectancy, year) - }; - } ); - } - - // Finds (and possibly interpolates) the value for the specified year. - function interpolateValues(values: any[], year: number) { - var i = bisect.left(values, year, 0, values.length - 1), - a = values[i]; - if (i > 0) { - var b = values[i - 1], - t = (year - a[0]) / (b[0] - a[0]); - return a[1] * (1 - t) + b[1] * t; - } - return a[1]; - } - } ); -} - -// Test for d3.functor -function functorTest () { - var f: (n: number) => number = d3.functor(10); - var g = d3.functor(function (v: number) { return v; }); - - return f(10) === g(10); -} - -// Test for d3.Nest -// Most test adopted from: https://github.com/mbostock/d3/blob/master/test/arrays/nest-test.js -function nestTest () { - var data = [ - { - a: 10, - b: [ 1, 2 ] - }, - { - a: 20, - b: [ 2, 3 ] - }, - { - a: 30, - b: [ 1, 2 ] - } - ]; - - var n1 = d3.nest<{a: number; b: number[] }>() - .key(function (d) { return String(d.a); }) - .sortKeys(d3.descending) - .rollup(function (vals) { - return d3.sum(vals[0].b); - }); - n1.map(data); - n1.entries(data); - - var n2 = d3.nest<{ a: number; b: number[] }>() - .key(function (d) { return String(d.a); }) - .sortValues(function (x1, x2) { - return x1.b[0] < x1.b[1] ? -1 : (x1.b[0] > x1.b[0] ? 1 : 0); }); - n2.map(data); - n2.entries(data); - - // Tests adopted from d3's tests. - var keys = d3.nest<{ foo: number; }>() - .key(function(d) { return String(d.foo); }) - .entries([{foo: 1}, {foo: 1}, {foo: 2}]) - .map(function(d) { return d.key; }) - .sort(d3.ascending); - - var entries = d3.nest<{foo: number; bar?: number}>() - .key(function(d) { return String(d.foo); }) - .entries([{foo: 1, bar: 0}, {foo: 2}, {foo: 1, bar: 1}]); - - keys = d3.nest<{foo: number}>() - .key(function(d) { return String(d.foo); }).sortKeys(d3.descending) - .entries([{foo: 1}, {foo: 1}, {foo: 2}]) - .map(function(d) { return d.key; }); - - entries = d3.nest<{ foo: number; bar?: number }>() - .key(function(d) { return String(d.foo); }) - .sortValues(function(a, b) { return a.bar - b.bar; }) - .entries([{foo: 1, bar: 2}, {foo: 1, bar: 0}, {foo: 1, bar: 1}, {foo: 2}]); - - entries = d3.nest<{ foo: number; bar?: number }>() - .key(function(d) { return String(d.foo); }) - .rollup(function(values) { return d3.sum(values, function(d) { return d.bar; }); }) - .entries([{foo: 1, bar: 2}, {foo: 1, bar: 0}, {foo: 1, bar: 1}, {foo: 2}]); - - entries = d3.nest<[number, number]>() - .key(function(d) { return String(d[0]); }).sortKeys(d3.ascending) - .key(function(d) { return String(d[1]); }).sortKeys(d3.ascending) - .entries([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]); - - entries = d3.nest<[number, number]>() - .key(function(d) { return String(d[0]); }).sortKeys(d3.ascending) - .key(function(d) { return String(d[1]); }).sortKeys(d3.ascending) - .rollup(function(values) { return values.length; }) - .entries([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]); - - entries = d3.nest<{ 0: number; 1: number; 2?: number }>() - .key(function(d) { return String(d[0]); }).sortKeys(d3.ascending) - .key(function(d) { return String(d[1]); }).sortKeys(d3.ascending) - .sortValues(function(a, b) { return a[2] - b[2]; }) - .entries([[0, 1], [0, 2, 1], [1, 1], [1, 2], [0, 2, 0]]); - - var map = d3.nest<{ 0: number; 1: number; 2?: number }>() - .key(function(d) { return String(d[0]); }).sortKeys(d3.ascending) - .key(function(d) { return String(d[1]); }).sortKeys(d3.ascending) - .sortValues(function(a, b) { return a[2] - b[2]; }) - .map([[0, 1], [0, 2, 1], [1, 1], [1, 2], [0, 2, 0]]); -} - -// Test for setting attributes as an object -// From https://github.com/mbostock/d3/blob/master/test/selection/attr-test.js -function attrObjTest () { - d3.select('body') - .data(["orange"]) - .attr({"xlink:href": function(d, i) { return d + "-" + i + ".png"; }}); -} - -// Test for setting styles as an object -// From https://github.com/mbostock/d3/blob/master/test/selection/style-test.js -function styleObjTest () { - d3.select('body') - .style({"background-color": "white", opacity: .42}); -} - -// Test for setting styles as an object -// From https://github.com/mbostock/d3/blob/master/test/selection/property-test.js -function propertyObjTest () { - d3.select('body') - .property({bgcolor: "purple", opacity: .41}); -} - - -// Test for brushes -function brushTest() { - var xScale = d3.scale.linear(), - yScale = d3.scale.linear(); - - var xMin = 0, xMax = 1, - yMin = 0, yMax = 1; - - // Setting only x scale. - var brush1 = d3.svg.brush() - .x(xScale) - .on('brush', function () { - var extent = <[number, number]> brush1.extent(); - xMin = Math.max(extent[0], 0); - xMax = Math.min(extent[1], 1); - brush1.extent([xMin, xMax]); - }); - - // Setting both the x and y scale - var brush2 = d3.svg.brush() - .x(xScale) - .y(yScale) - .on('brush', function () { - var extent = <[[number, number], [number, number]]> brush2.extent(); - var xExtent = extent[0], - yExtent = extent[1]; - - xMin = Math.max(xExtent[0], 0); - xMax = Math.min(xExtent[1], 1); - - yMin = Math.max(yExtent[0], 0); - yMax = Math.min(yExtent[1], 1); - - brush1.extent([[xMin, xMax], [yMin, yMax]]); - }); -} - - -// Tests for area -// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/area-test.js -function svgAreaTest () { - var a = d3.svg.area(), - f: () => number, - n: number; - - a.x(f).x() === f; - a.x(n).x() === n; - a.x(0); - a.x(function (d) { return d[0] * 10; }); - a.x(function (d, i) { return i * 10; }); - - a.x(f).x0() === f; - a.x(n).x0() === n; - a.x0(0); - a.x0(function (d) { return d[0] * 10; }); - a.x0(function (d, i) { return i * 10; }); - - a.x(f).x1() === f; - a.x(n).x1() === n; - a.x1(0); - a.x1(function (d) { return d[0] * 10; }); - a.x1(function (d, i) { return i * 10; }); - - a.y(f).y() === f; - a.y(n).y() === n; - a.y(0); - a.y(function (d) { return d[0] * 10; }); - a.y(function (d, i) { return i * 10; }); - - a.y(f).y0() === f; - a.y(n).y0() === n; - a.y0(0); - a.y0(function (d) { return d[0] * 10; }); - a.y0(function (d, i) { return i * 10; }); - - a.y(f).y1() === f; - a.y(n).y1() === n; - a.y1(0); - a.y1(function (d) { return d[0] * 10; }); - a.y1(function (d, i) { return i * 10; }); -} - -// Tests for areaRadial -// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/area-radial-test.js -function svgAreaRadialTest () { - var a = d3.svg.area.radial(), - f: () => number, - n: number; - - a.radius(f).radius() === f; - a.radius(n).radius() === n; - a.radius(0); - a.radius(function (d) { return d[0] * 10; }); - a.radius(function (d, i) { return i * 10; }); - - a.radius(f).innerRadius() === f; - a.radius(n).innerRadius() === n; - a.innerRadius(0); - a.innerRadius(function (d) { return d[0] * 10; }); - a.innerRadius(function (d, i) { return i * 10; }); - - a.radius(f).outerRadius() === f; - a.radius(n).outerRadius() === n; - a.outerRadius(0); - a.outerRadius(function (d) { return d[1] * 10; }); - a.outerRadius(function (d, i) { return i * 10; }); - - a.angle(f).angle() === f; - a.angle(n).angle() === n; - a.angle(0); - a.angle(function (d) { return d[0] * 10; }); - a.angle(function (d, i) { return i * 10; }); - - a.angle(f).startAngle() === f; - a.angle(n).startAngle() === n; - a.startAngle(0); - a.startAngle(function (d) { return d[0] * 10; }); - a.startAngle(function (d, i) { return i * 10; }); - - a.angle(f).endAngle() === f; - a.angle(n).endAngle() === n; - a.endAngle(0); - a.endAngle(function (d) { return d[1] * 10; }); - a.endAngle(function (d, i) { return i * 10; }); -} - -// Tests for d3.svg.line -// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/line-test.js -function svgLineTest () { - var l = d3.svg.line(), - f: () => number, - n: number; - - l.x(f).x() === f; - l.x(n).x() === n; - l.x(0); - l.x(function (d) { return d[0]; }); - l.x(function (d, i) { return i; }); - - l.y(f).y() === f; - l.y(n).y() === n; - l.y(0); - l.y(function (d) { return d[1]; }); - l.y(function (d, i) { return i; }); -} - -// Tests for d3.svg.line.radial -// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/line-radial-test.js -function svgLineRadialTest () { - var l = d3.svg.line.radial(), - f: () => number, - n: number; - - l.radius(f).radius() === f; - l.radius(n).radius() === n; - l.radius(0); - l.radius(function (d) { return d[0]; }); - l.radius(function (d, i) { return i; }); - - l.angle(f).angle() === f; - l.angle(n).angle() === n; - l.angle(0); - l.angle(function (d) { return d[1]; }); - l.angle(function (d, i) { return i; }); -} - -// Tests for d3.svg.arc -// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/arc-test.js -function svgArcTest () { - var l = d3.svg.arc(), - f: () => number; - - l.innerRadius(f).innerRadius() === f; - l.innerRadius(0); - l.innerRadius(function (d) { return d.innerRadius; }); - l.innerRadius(function (d, i) { return i; }); - - l.outerRadius(f).outerRadius() === f; - l.outerRadius(0); - l.outerRadius(function (d) { return d.outerRadius; }); - l.outerRadius(function (d, i) { return i; }); - - l.startAngle(f).startAngle() === f; - l.startAngle(0); - l.startAngle(function (d) { return d.innerRadius; }); - l.startAngle(function (d, i) { return i; }); - - l.endAngle(f).endAngle() === f; - l.endAngle(0); - l.endAngle(function (d) { return d.outerRadius; }); - l.endAngle(function (d, i) { return i; }); -} - -function svgArcTest2 () { - var l = d3.svg.arc<[number, number]>(); - - l.innerRadius(d => d[0]); - l.outerRadius(d => d[1]); -} - -// Tests for d3.svg.diagonal -// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/diagonal-test.js -function svgDiagonalTest () { - var d = d3.svg.diagonal(); - - d.projection()({ x: 0, y: 1}, 0); - d.projection(function (d) { return [d.x, d.y]; }); - d.projection(function (d, i) { return [i, i + 1]; }); - - d.source()({ source: {x: 0, y: 1}, target: null }, 0); - d.source({x: 0, y: 1}); - d.source(function (d) { return {x: d.source.x, y: d.source.y}; }); - d.source(function (d, i) { return {x: d.source.x * i, y: d.source.y * i}; }); - - d.target()({ target: {x: 0, y: 1}, source: null }, 0); - d.target({x: 0, y: 1}); - d.target(function (d) { return {x: d.target.x, y: d.target.y}; }); - d.target(function (d, i) { return {x: d.target.x * i, y: d.target.y * i}; }); -} - -// Tests for d3.extent -// Adopted from: https://github.com/mbostock/d3/blob/master/test/arrays/extent-test.js -function extentTest() { - // usages of `o' suppressed as well as mixed-type comparisons - // see https://github.com/Microsoft/TypeScript/commit/c0db7ffe8f55b6ec335880482ca43b93b066689d - var o = { valueOf: function () { return NaN; } }; - - d3.extent([1]); - d3.extent([5, 1, 2, 3, 4]); - d3.extent([20, 3]); - d3.extent([3, 20]); - d3.extent(["c", "a", "b"]); - d3.extent(["20", "3"]); - d3.extent(["3", "20"]); - d3.extent([NaN, 1, 2, 3, 4, 5]); - // d3.extent([o, 1, 2, 3, 4, 5]); - d3.extent([1, 2, 3, 4, 5, NaN]); - // d3.extent([1, 2, 3, 4, 5, o]); - d3.extent([10, null, 3, undefined, 5, NaN]); - d3.extent([-1, null, -3, undefined, -5, NaN]); - // d3.extent([20, "3"]); - // d3.extent(["20", 3]); - // d3.extent([3, "20"]); - // d3.extent(["3", 20]); - - d3.extent([1], (d) => { return d; }); - d3.extent([5, 1, 2, 3, 4], (d) => { return d; }); - d3.extent([20, 3], (d) => { return d; }); - d3.extent([3, 20], (d) => { return d; }); - d3.extent(["c", "a", "b"], (d) => { return d; }); - d3.extent(["20", "3"], (d) => { return d; }); - d3.extent(["3", "20"], (d) => { return d; }); - d3.extent([NaN, 1, 2, 3, 4, 5], (d) => { return d; }); - // d3.extent([o, 1, 2, 3, 4, 5], (d) => { return d; }); - d3.extent([1, 2, 3, 4, 5, NaN], (d) => { return d; }); - // d3.extent([1, 2, 3, 4, 5, o], (d) => { return d; }); - d3.extent([10, null, 3, undefined, 5, NaN], (d) => { return d; }); - d3.extent([-1, null, -3, undefined, -5, NaN], (d) => { return d; }); - // d3.extent([20, "3"], (d) => { return d; }); - // d3.extent(["20", 3], (d) => { return d; }); - // d3.extent([3, "20"], (d) => { return d; }); - // d3.extent(["3", 20], (d) => { return d; }); -} - -// Tests for d3.time.format.multi -// Adopted from http://bl.ocks.org/mbostock/4149176 -function multiTest() { - var customTimeFormat = d3.time.format.multi([ - [".%L", function(d) { return !!d.getMilliseconds(); }], - [":%S", function(d) { return !!d.getSeconds(); }], - ["%I:%M", function(d) { return !!d.getMinutes(); }], - ["%I %p", function(d) { return !!d.getHours(); }], - ["%a %d", function(d) { return !!d.getDay() && d.getDate() != 1; }], - ["%b %d", function(d) { return d.getDate() != 1; }], - ["%B", function(d) { return !!d.getMonth(); }], - ["%Y", function() { return true; }] - ]); - - var margin = {top: 250, right: 40, bottom: 250, left: 40}, - width = 960 - margin.left - margin.right, - height = 500 - margin.top - margin.bottom; - - var x = d3.time.scale() - .domain([new Date(2012, 0, 1), new Date(2013, 0, 1)]) - .range([0, width]); - - var xAxis = d3.svg.axis() - .scale(x) - .tickFormat(customTimeFormat); - - var svg = d3.select("body").append("svg") - .attr("width", width + margin.left + margin.right) - .attr("height", height + margin.top + margin.bottom) - .append("g") - .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); - - svg.append("g") - .attr("class", "x axis") - .attr("transform", "translate(0," + height + ")") - .call(xAxis); -} - -function testD3Events () { - d3.select('svg') - .on('click', () => { - let e = d3.event; - var coords = [e.pageX, e.pageY]; - console.log("clicked", e.target, "at " + coords); - }) - .on('keypress', () => { - let e = d3.event; - if (e.shiftKey) { - console.log('shift + ' + e.which); - } - }); -} - -function testD3MutlieTimeFormat() { - var format = d3.time.format.multi([ - [".%L", function(d) { return d.getMilliseconds(); }], - [":%S", function(d) { return d.getSeconds(); }], - ["%I:%M", function(d) { return d.getMinutes(); }], - ["%I %p", function(d) { return d.getHours(); }], - ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }], - ["%b %d", function(d) { return d.getDate() != 1; }], - ["%B", function(d) { return d.getMonth(); }], - ["%Y", function() { return true; }] - ]); -} - -function testMultiUtcFormat() { - var format = d3.time.format.utc.multi([ - [".%L", function(d) { return d.getMilliseconds(); }], - [":%S", function(d) { return d.getSeconds(); }], - ["%I:%M", function(d) { return d.getMinutes(); }], - ["%I %p", function(d) { return d.getHours(); }], - ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }], - ["%b %d", function(d) { return d.getDate() != 1; }], - ["%B", function(d) { return d.getMonth(); }], - ["%Y", function() { return true; }] - ]); -} - -function testEnterSizeEmpty() { - - var selectionSize: number, - emptyStatus: boolean; - - var newNodes = d3.selectAll('.test') - .data(['1', '2', '3']) - .enter(); - - emptyStatus = newNodes.empty(); - selectionSize = newNodes.size(); - -} \ No newline at end of file diff --git a/d3/d3-v3.5-tests.ts b/d3/d3-v3.5-tests.ts new file mode 100644 index 0000000000..380b15db96 --- /dev/null +++ b/d3/d3-v3.5-tests.ts @@ -0,0 +1,2722 @@ + + +//Example from http://bl.ocks.org/3887235 +interface TestPieChartData { + population: number; + age: string; +} +function testPieChart() { + var width = 960, + height = 500, + radius = Math.min(width, height) / 2; + + var color = d3.scale.ordinal() + .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); + + var arc = d3.svg.arc>() + .outerRadius(radius - 10) + .innerRadius(0); + + var pie = d3.layout.pie() + .sort(null) + .value(function (d) { return d.population; }); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .append("g") + .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); + + d3.csv("data.csv", d => ({ population: +d['population'], age: d['age'] }), function (error, data) { + var g = svg.selectAll(".arc") + .data(pie(data)) + .enter().append("g") + .attr("class", "arc"); + + g.append("path") + .attr("d", arc) + .style("fill", function (d) { return color(d.data.age); }); + + g.append("text") + .attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; }) + .attr("dy", ".35em") + .style("text-anchor", "middle") + .text(function (d) { return d.data.age; }); + + }); +} + +function testMapConstructor() { + //No arg constructor + var emptyMap: d3.Map = d3.map(); + + //Object constructor + var object:{[key: string]: number } = {a: 1, b: 2, c: 3}; + var objectMap: d3.Map = d3.map(object); + + //Array constructor + var numberArray: number[] = [1, 2, 3] + var numberArrayMap: d3.Map = d3.map(numberArray); + + //Array with keyFn constructor + var objectArray: {key: string}[] = [{key: "v1"}, {key: "v2"}, {key: "v3"}]; + var indexes: number[] = []; + //keyFn with index + var objectArrayMap1: d3.Map<{key: string}> + = d3.map<{key: string}>(objectArray, (o: {key: string}, index: number) => { + indexes.push(index); + return o.key; + }); + //keyFn without index + var objectArrayMap2: d3.Map<{key: string}> + = d3.map<{key: string}>(objectArray, (o: {key: string}) => { + return o.key; + }); + + //Map constructor + var duplicateMap: d3.Map = d3.map(numberArrayMap); +} + +//Example from http://bl.ocks.org/3887051 +interface GroupedData { + State: string; + ages: Array<{ name: string; value: number;}>; +} +function groupedBarChart() { + var margin = { top: 20, right: 20, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x0 = d3.scale.ordinal() + .rangeRoundBands([0, width], .1); + + var x1 = d3.scale.ordinal(); + + var y = d3.scale.linear() + .range([height, 0]); + + var color = d3.scale.ordinal() + .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); + + var xAxis = d3.svg.axis() + .scale(x0) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .tickFormat(d3.format(".2s")); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.csv("data.csv", function (error: any, data: Array) { + var ageNames = d3.keys(data[0]).filter(function (key) { return key !== "State"; }); + + data.forEach(function (d) { + d.ages = ageNames.map(function (name) { return { name: name, value: +( d)[name] }; }); + }); + + x0.domain(data.map(function (d) { return d.State; })); + x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]); + y.domain([0, d3.max(data, function (d) { return d3.max(d.ages, function (d) { return d.value; }); })]); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Population"); + + var state = svg.selectAll(".state") + .data(data) + .enter().append("g") + .attr("class", "g") + .attr("transform", function (d) { return "translate(" + x0(d.State) + ",0)"; }); + + state.selectAll("rect") + .data(function (d) { return d.ages; }) + .enter().append("rect") + .attr("width", x1.rangeBand()) + .attr("x", function (d) { return x1(d.name); }) + .attr("y", function (d) { return y(d.value); }) + .attr("height", function (d) { return height - y(d.value); }) + .style("fill", function (d) { return color(d.name); }); + + var legend = svg.selectAll(".legend") + .data(ageNames.reverse()) + .enter().append("g") + .attr("class", "legend") + .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; }); + + legend.append("rect") + .attr("x", width - 18) + .attr("width", 18) + .attr("height", 18) + .style("fill", color); + + legend.append("text") + .attr("x", width - 24) + .attr("y", 9) + .attr("dy", ".35em") + .style("text-anchor", "end") + .text(function (d) { return d; }); + + }); +} + +//Example from http://bl.ocks.org/3886208 +function stackedBarChart() { + var margin = { top: 20, right: 20, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.scale.ordinal() + .rangeRoundBands([0, width], .1); + + var y = d3.scale.linear() + .rangeRound([height, 0]); + + var color = d3.scale.ordinal() + .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .tickFormat(d3.format(".2s")); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.csv("data.csv", function (error: any, data: any) { + color.domain(d3.keys(data[0]).filter(function (key) { return key !== "State"; })); + + data.forEach(function (d: any) { + var y0 = 0; + d.ages = color.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; }); + d.total = d.ages[d.ages.length - 1].y1; + }); + + data.sort(function (a: any, b: any) { return b.total - a.total; }); + + x.domain(data.map(function (d: any) { return d.State; })); + y.domain([0, d3.max(data, function (d: { total: number }) { return d.total; })]); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Population"); + + var state = svg.selectAll(".state") + .data(data) + .enter().append("g") + .attr("class", "g") + .attr("transform", function (d: any) { return "translate(" + x(d.State) + ",0)"; }); + + state.selectAll("rect") + .data(function (d: any) { return d.ages; }) + .enter().append("rect") + .attr("width", x.rangeBand()) + .attr("y", function (d: any) { return y(d.y1); }) + .attr("height", function (d: any) { return y(d.y0) - y(d.y1); }) + .style("fill", function (d: any) { return color(d.name); }); + + var legend = svg.selectAll(".legend") + .data(color.domain().reverse()) + .enter().append("g") + .attr("class", "legend") + .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; }); + + legend.append("rect") + .attr("x", width - 18) + .attr("width", 18) + .attr("height", 18) + .style("fill", color); + + legend.append("text") + .attr("x", width - 24) + .attr("y", 9) + .attr("dy", ".35em") + .style("text-anchor", "end") + .text(function (d) { return d; }); + + }); +} + +// example from http://bl.ocks.org/3886394 +function normalizedBarChart() { + var margin = { top: 20, right: 100, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.scale.ordinal() + .rangeRoundBands([0, width], .1); + + var y = d3.scale.linear() + .rangeRound([height, 0]); + + var color = d3.scale.ordinal() + .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .tickFormat(d3.format(".0%")); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.csv("data.csv", function (error, data) { + color.domain(d3.keys(data[0]).filter(function (key) { return key !== "State"; })); + + data.forEach(function (d: any) { + var y0 = 0; + d.ages = color.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; }); + d.ages.forEach(function (d: any) { d.y0 /= y0; d.y1 /= y0; }); + }); + + data.sort(function (a: any, b: any) { return b.ages[0].y1 - a.ages[0].y1; }); + + x.domain(data.map(function (d: any) { return d.State; })); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis); + + var state = svg.selectAll(".state") + .data(data) + .enter().append("g") + .attr("class", "state") + .attr("transform", function (d: any) { return "translate(" + x(d.State) + ",0)"; }); + + state.selectAll("rect") + .data(function (d) { return d.ages; }) + .enter().append("rect") + .attr("width", x.rangeBand()) + .attr("y", function (d: any) { return y(d.y1); }) + .attr("height", function (d: any) { return y(d.y0) - y(d.y1); }) + .style("fill", function (d: any) { return color(d.name); }); + + var legend = svg.select(".state:last-child").selectAll(".legend") + .data(function (d: any) { return d.ages; }) + .enter().append("g") + .attr("class", "legend") + .attr("transform", function (d: any) { return "translate(" + x.rangeBand() / 2 + "," + y((d.y0 + d.y1) / 2) + ")"; }); + + legend.append("line") + .attr("x2", 10); + + legend.append("text") + .attr("x", 13) + .attr("dy", ".35em") + .text(function (d: any) { return d.name; }); + + }); +} + +// example from http://bl.ocks.org/3885705 +function sortablebarChart() { + var margin = { top: 20, right: 20, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var formatPercent = d3.format(".0%"); + + var x = d3.scale.ordinal() + .rangeRoundBands([0, width], .1, 1); + + var y = d3.scale.linear() + .range([height, 0]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .tickFormat(formatPercent); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.tsv("data.tsv", function (error: any, data: any) { + + data.forEach(function (d: any) { + d.frequency = +d.frequency; + }); + + x.domain(data.map(function (d: any) { return d.letter; })); + y.domain([0, d3.max(data, function (d: any) { return d.frequency; })]); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Frequency"); + + svg.selectAll(".bar") + .data(data) + .enter().append("rect") + .attr("class", "bar") + .attr("x", function (d: any) { return x(d.letter); }) + .attr("width", x.rangeBand()) + .attr("y", function (d: any) { return y(d.frequency); }) + .attr("height", function (d: any) { return height - y(d.frequency); }); + + d3.select("input").on("change", change); + + var sortTimeout = setTimeout(function () { + d3.select("input").property("checked", true).each(change); + }, 2000); + + function change() { + clearTimeout(sortTimeout); + + var x0 = x.domain(data.sort(this.checked + ? function (a: any, b: any) { return b.frequency - a.frequency; } + : function (a: any, b: any) { return d3.ascending(a.letter, b.letter); }) + .map(function (d: any) { return d.letter; })) + .copy(); + + var transition = svg.transition().duration(750), + delay = function (d: any, i: number) { return i * 50; }; + + transition.selectAll(".bar") + .delay(delay) + .attr("x", function (d: any) { return x0(d.letter); }); + + transition.select(".x.axis") + .call(xAxis) + .selectAll("g") + .delay(delay); + } + }); +} + +//example from http://bl.ocks.org/4063318 +function callenderView() { + var width = 960, + height = 136, + cellSize = 17; // cell size + + var day = d3.time.format("%w"), + week = d3.time.format("%U"), + percent = d3.format(".1%"), + format = d3.time.format("%Y-%m-%d"); + + var color = d3.scale.quantize() + .domain([-.05, .05]) + .range(d3.range(11).map(function (d) { return "q" + d + "-11"; })); + + var svg = d3.select("body").selectAll("svg") + .data(d3.range(1990, 2011)) + .enter().append("svg") + .attr("width", width) + .attr("height", height) + .attr("class", "RdYlGn") + .append("g") + .attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")"); + + svg.append("text") + .attr("transform", "translate(-6," + cellSize * 3.5 + ")rotate(-90)") + .style("text-anchor", "middle") + .text(function (d) { return d; }); + + var rect = svg.selectAll(".day") + .data(function (d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) + .enter().append("rect") + .attr("class", "day") + .attr("width", cellSize) + .attr("height", cellSize) + .attr("x", function (d) { return parseInt(week(d)) * cellSize; }) + .attr("y", function (d) { return parseInt(day(d)) * cellSize; }) + .datum(format); + + rect.append("title") + .text(function (d) { return d; }); + + svg.selectAll(".month") + .data(function (d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) + .enter().append("path") + .attr("class", "month") + .attr("d", monthPath); + + d3.csv("dji.csv", function (error, csv) { + var data = d3.nest() + .key(function (d: any) { return d.Date; }) + .rollup(function (d: any) { return (d[0].Close - d[0].Open) / d[0].Open; }) + .map(csv); + + rect.filter(function (d) { return d in data; }) + .attr("class", function (d) { return "day " + color(data[d]); }) + .select("title") + .text(function (d) { return d + ": " + percent(data[d]); }); + }); + + function monthPath(t0: Date) { + var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0), + d0 = +day(t0), w0 = +week(t0), + d1 = +day(t1), w1 = +week(t1); + return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize + + "H" + w0 * cellSize + "V" + 7 * cellSize + + "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize + + "H" + (w1 + 1) * cellSize + "V" + 0 + + "H" + (w0 + 1) * cellSize + "Z"; + } + + d3.select(self.frameElement).style("height", "2910px"); +} + +// example from http://bl.ocks.org/3883245 +function lineChart() { + var margin = { top: 20, right: 20, bottom: 30, left: 50 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var parseDate = d3.time.format("%d-%b-%y").parse; + + var x = d3.time.scale() + .range([0, width]); + + var y = d3.scale.linear() + .range([height, 0]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left"); + + var line = d3.svg.line<{ date: Date; close: number }>() + .x(function (d) { return x(d.date); }) + .y(function (d) { return y(d.close); }); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.tsv("data.tsv", function (error: any, data: any) { + data.forEach(function (d: any) { + d.date = parseDate(d.date); + d.close = +d.close; + }); + + x.domain(d3.extent(data, function (d: any) { return d.date; })); + y.domain(d3.extent(data, function (d: any) { return d.close; })); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Price ($)"); + + svg.append("path") + .datum(data) + .attr("class", "line") + .attr("d", line); + }); +} + +//example from http://bl.ocks.org/3884914 +function bivariateAreaChart() { + var margin = { top: 20, right: 20, bottom: 30, left: 50 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var parseDate = d3.time.format("%Y%m%d").parse; + + var x = d3.time.scale() + .range([0, width]); + + var y = d3.scale.linear() + .range([height, 0]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom"); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left"); + + var area = d3.svg.area<{ date: Date; low: number; high: number }>() + .x(function (d) { return x(d.date); }) + .y0(function (d) { return y(d.low); }) + .y1(function (d) { return y(d.high); }); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + d3.tsv("data.tsv", function (error: any, data: any) { + data.forEach(function (d: any) { + d.date = parseDate(d.date); + d.low = +d.low; + d.high = +d.high; + }); + + x.domain(d3.extent(data, function (d: any) { return d.date; })); + y.domain([d3.min(data, function (d: any) { return d.low; }), d3.max(data, function (d: any) { return d.high; })]); + + svg.append("path") + .datum(data) + .attr("class", "area") + .attr("d", area); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("Temperature (ºF)"); + }); +} + +//Example from http://bl.ocks.org/mbostock/1557377 +function dragMultiples() { + var width = 238, + height = 123, + radius = 20; + + var drag = d3.behavior.drag() + .origin(Object) + .on("drag", dragmove); + + var svg = d3.select("body").selectAll("svg") + .data(d3.range(16).map(function () { return { x: width / 2, y: height / 2 }; })) + .enter().append("svg") + .attr("width", width) + .attr("height", height); + + svg.append("circle") + .attr("r", radius) + .attr("cx", function (d) { return d.x; }) + .attr("cy", function (d) { return d.y; }) + .call(drag); + + function dragmove(d: { x: number; y: number }) { + d3.select(this) + .attr("cx", d.x = Math.max(radius, Math.min(width - radius, ( d3.event).x))) + .attr("cy", d.y = Math.max(radius, Math.min(height - radius, ( d3.event).y))); + } +} + +//Example from http://bl.ocks.org/mbostock/3892919 +function panAndZoom() { + var margin = { top: 20, right: 20, bottom: 30, left: 40 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.scale.linear() + .domain([-width / 2, width / 2]) + .range([0, width]); + + var y = d3.scale.linear() + .domain([-height / 2, height / 2]) + .range([height, 0]); + + var xAxis = d3.svg.axis() + .scale(x) + .orient("bottom") + .tickSize(-height); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("left") + .ticks(5) + .tickSize(-width); + + var zoom = d3.behavior.zoom() + .x(x) + .y(y) + .scaleExtent([1, 10]) + .on("zoom", zoomed); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")") + .call(zoom); + + svg.append("rect") + .attr("width", width) + .attr("height", height); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + svg.append("g") + .attr("class", "y axis") + .call(yAxis); + + function zoomed() { + svg.select(".x.axis").call(xAxis); + svg.select(".y.axis").call(yAxis); + } +} + +//Example from http://bl.ocks.org/mbostock/1125997 +function chainedTransitions() { + var w = 960, + h = 500, + y = d3.scale.ordinal().domain(d3.range(50)).rangePoints([20, h - 20]), + t = Date.now(); + + var svg = d3.select("body").append("svg:svg") + .attr("width", w) + .attr("height", h); + + var circle = svg.selectAll("circle") + .data(y.domain()) + .enter().append("svg:circle") + .attr("r", 16) + .attr("cx", 20) + .attr("cy", y) + .each(slide(20, w - 20)); + + function slide(x0: number, x1: number) { + t += 50; + return function() { + d3.select(this).transition() + .duration(t - Date.now()) + .attr("cx", x1) + .each("end", slide(x1, x0)); + }; + } +} + +//Example from http://bl.ocks.org/mbostock/4062085 +interface PyramidData { + people: number; + year: number; + age: number; +} +function populationPyramid() { + var margin = { top: 20, right: 40, bottom: 30, left: 20 }, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom, + barWidth = Math.floor(width / 19) - 1; + + var x = d3.scale.linear() + .range([barWidth / 2, width - barWidth / 2]); + + var y = d3.scale.linear() + .range([height, 0]); + + var yAxis = d3.svg.axis() + .scale(y) + .orient("right") + .tickSize(-width) + .tickFormat(function (d) { return Math.round(d / 1e6) + "M"; } ); + + // An SVG element with a bottom-right origin. + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + // A sliding container to hold the bars by birthyear. + var birthyears = svg.append("g") + .attr("class", "birthyears"); + + // A label for the current year. + var title = svg.append("text") + .attr("class", "title") + .attr("dy", ".71em") + .text(2000); + + d3.csv("population.csv", function (error: any, rows: Array) { + + // Convert strings to numbers. + rows.forEach(function (d) { + d.people = +d.people; + d.year = +d.year; + d.age = +d.age; + } ); + + // Compute the extent of the data set in age and years. + var age1 = d3.max(rows, function (d) { return d.age; } ), + year0 = d3.min(rows, function (d) { return d.year; } ), + year1 = d3.max(rows, function (d) { return d.year; } ), + year = year1; + + // Update the scale domains. + x.domain([year1 - age1, year1]); + y.domain([0, d3.max(rows, function (d) { return d.people; } )]); + + // Produce a map from year and birthyear to [male, female]. + var data = d3.nest() + .key(function (d) { return '' + d.year; } ) + .key(function (d) { return '' + (d.year - d.age); } ) + .rollup(function (v) { return v.map(function (d) { return d.people; } ); } ) + .map(rows); + + // Add an axis to show the population values. + svg.append("g") + .attr("class", "y axis") + .attr("transform", "translate(" + width + ",0)") + .call(yAxis) + .selectAll("g") + .filter(function (value) { return !value; } ) + .classed("zero", true); + + // Add labeled rects for each birthyear (so that no enter or exit is required). + var birthyear = birthyears.selectAll(".birthyear") + .data(d3.range(year0 - age1, year1 + 1, 5)) + .enter().append("g") + .attr("class", "birthyear") + .attr("transform", function (birthyear) { return "translate(" + x(birthyear) + ",0)"; } ); + + birthyear.selectAll("rect") + .data(function (birthyear): number[] { return data[year][birthyear] || [0, 0]; } ) + .enter().append("rect") + .attr("x", -barWidth / 2) + .attr("width", barWidth) + .attr("y", y) + .attr("height", function (value) { return height - y(value); } ); + + // Add labels to show birthyear. + birthyear.append("text") + .attr("y", height - 4) + .text(function (birthyear) { return birthyear; } ); + + // Add labels to show age (separate; not animated). + svg.selectAll(".age") + .data(d3.range(0, age1 + 1, 5)) + .enter().append("text") + .attr("class", "age") + .attr("x", function (age) { return x(year - age); } ) + .attr("y", height + 4) + .attr("dy", ".71em") + .text(function (age) { return age; } ); + + // Allow the arrow keys to change the displayed year. + window.focus(); + d3.select(window).on("keydown", function () { + switch (( d3.event).keyCode) { + case 37: year = Math.max(year0, year - 10); break; + case 39: year = Math.min(year1, year + 10); break; + } + update(); + } ); + + function update() { + if (!(year in data)) return; + title.text(year); + + birthyears.transition() + .duration(750) + .attr("transform", "translate(" + (x(year1) - x(year)) + ",0)"); + + birthyear.selectAll("rect") + .data(function (birthyear): number[] { return data[year][birthyear] || [0, 0]; } ) + .transition() + .duration(750) + .attr("y", y) + .attr("height", function (value) { return height - y(value); } ); + } + } ); +} + +//Example from http://bl.ocks.org/MoritzStefaner/1377729 +namespace forcedBasedLabelPlacemant { + interface Node extends d3.layout.force.Node { + label: string; + } + + interface LabelAnchor extends d3.layout.force.Node { + node: Node; + } + + interface LabelAnchorLink extends d3.layout.force.Link { + source: Node; + target: Node; + weight: number; + } + + var w = 960, h = 500; + + var labelDistance = 0; + + var vis = d3.select("body").append("svg:svg").attr("width", w).attr("height", h); + + var nodes: Node[] = []; + var labelAnchors: LabelAnchor[] = []; + var labelAnchorLinks: { source: number; target: number; weight: number }[] = []; + var links: typeof labelAnchorLinks = []; + + for (var i = 0; i < 30; i++) { + var nodeLabel = { + label: "node " + i + }; + nodes.push(nodeLabel); + labelAnchors.push({ + node: nodeLabel + }); + labelAnchors.push({ + node: nodeLabel + }); + }; + + for (var i = 0; i < nodes.length; i++) { + for (var j = 0; j < i; j++) { + if (Math.random() > .95) + links.push({ + source: i, + target: j, + weight: Math.random() + }); + } + labelAnchorLinks.push({ + source: i * 2, + target: i * 2 + 1, + weight: 1 + }); + }; + + var force = d3.layout.force().size([w, h]).nodes(nodes).links(links).gravity(1).linkDistance(50).charge(-3000).linkStrength(function (x) { + return x.weight * 10 + } ); + + + force.start(); + + var force2 = d3.layout.force().nodes(labelAnchors).links(labelAnchorLinks).gravity(0).linkDistance(0).linkStrength(8).charge(-100).size([w, h]); + force2.start(); + + var link = vis.selectAll("line.link").data(links).enter().append("svg:line").attr("class", "link").style("stroke", "#CCC"); + + var node = vis.selectAll("g.node").data(force.nodes()).enter().append("svg:g").attr("class", "node"); + node.append("svg:circle").attr("r", 5).style("fill", "#555").style("stroke", "#FFF").style("stroke-width", 3); + node.call(force.drag); + + + var anchorLink = vis.selectAll("line.anchorLink").data(labelAnchorLinks)//.enter().append("svg:line").attr("class", "anchorLink").style("stroke", "#999"); + + var anchorNode = vis.selectAll("g.anchorNode").data(force2.nodes()).enter().append("svg:g").attr("class", "anchorNode"); + anchorNode.append("svg:circle").attr("r", 0).style("fill", "#FFF"); + anchorNode.append("svg:text").text(function (d, i) { + return i % 2 == 0 ? "" : d.node.label + } ).style("fill", "#555").style("font-family", "Arial").style("font-size", 12); + + var updateLink = function () { + (> this).attr("x1", function (d) { + return d.source.x; + } ).attr("y1", function (d) { + return d.source.y; + } ).attr("x2", function (d) { + return d.target.x; + } ).attr("y2", function (d) { + return d.target.y; + } ); + + } + + var updateNode = function () { + (> this).attr("transform", function (d) { + return "translate(" + d.x + "," + d.y + ")"; + } ); + + } + + force.on("tick", function () { + + force2.start(); + + node.call(updateNode); + + anchorNode.each(function (d, i) { + if (i % 2 == 0) { + d.x = d.node.x; + d.y = d.node.y; + } else { + var b = this.childNodes[1].getBBox(); + + var diffX = d.x - d.node.x; + var diffY = d.y - d.node.y; + + var dist = Math.sqrt(diffX * diffX + diffY * diffY); + + var shiftX = b.width * (diffX - dist) / (dist * 2); + shiftX = Math.max(-b.width, Math.min(0, shiftX)); + var shiftY = 5; + this.childNodes[1].setAttribute("transform", "translate(" + shiftX + "," + shiftY + ")"); + } + } ); + + + anchorNode.call(updateNode); + + link.call(updateLink); + anchorLink.call(updateLink); + + } ); +} + +//Example from http://bl.ocks.org/mbostock/1125997 +namespace forceCollapsable { + interface Node extends d3.layout.force.Node { + id: string; + _children: Node[]; + children?: Node[]; + size: number; + } + + var w = 1280, + h = 800, + node: d3.selection.Update, + link: d3.selection.Update>, + root: any; + + var force = d3.layout.force() + .on("tick", tick) + .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) + .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) + .size([w, h - 160]); + + var vis = d3.select("body").append("svg:svg") + .attr("width", w) + .attr("height", h); + + d3.json("flare.json", function (json) { + root = json; + root.fixed = true; + root.x = w / 2; + root.y = h / 2 - 80; + update(); + } ); + + function update() { + var nodes = flatten(root), + links = d3.layout.tree().links(nodes); + + // Restart the force layout. + force + .nodes(nodes) + .links(links) + .start(); + + // Update the links… + link = vis.selectAll("line.link") + .data(links, function (d) { return d.target.id; } ); + + // Enter any new links. + link.enter().insert("svg:line", ".node") + .attr("class", "link") + .attr("x1", function (d) { return d.source.x; } ) + .attr("y1", function (d) { return d.source.y; } ) + .attr("x2", function (d) { return d.target.x; } ) + .attr("y2", function (d) { return d.target.y; } ); + + // Exit any old links. + link.exit().remove(); + + // Update the nodes… + node = vis.selectAll("circle.node") + .data(nodes, function (d) { return d.id; } ) + .style("fill", color); + + node.transition() + .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ); + + // Enter any new nodes. + node.enter().append("svg:circle") + .attr("class", "node") + .attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ) + .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ) + .style("fill", color) + .on("click", click) + .call(force.drag); + + // Exit any old nodes. + node.exit().remove(); + } + + function tick() { + link.attr("x1", function (d) { return d.source.x; } ) + .attr("y1", function (d) { return d.source.y; } ) + .attr("x2", function (d) { return d.target.x; } ) + .attr("y2", function (d) { return d.target.y; } ); + + node.attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ); + } + + // Color leaf nodes orange, and packages white or blue. + function color(d: Node) { + return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c"; + } + + // Toggle children on click. + function click(d: Node) { + if (d.children) { + d._children = d.children; + d.children = null; + } else { + d.children = d._children; + d._children = null; + } + update(); + } + + // Returns a list of all nodes under the root. + function flatten(root: Node) { + var nodes: Node[] = [], i = 0; + + function recurse(node: Node) { + if (node.children) node.size = node.children.reduce(function (p, v) { return p + recurse(v); } , 0); + if (!node.id) node.id = String(++i); + nodes.push(node); + return node.size; + } + + root.size = recurse(root); + return nodes; + } +} + +//Example from http://bl.ocks.org/mbostock/3757110 +function azimuthalEquidistant() { + var width = 960, + height = 960; + var topojson: any; + + var projection = d3.geo.azimuthalEquidistant() + .scale(150) + .translate([width / 2, height / 2]) + .clipAngle(180 - 1e-3) + .precision(.1); + + var path = d3.geo.path() + .projection(projection); + + var graticule = d3.geo.graticule(); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height); + + svg.append("defs").append("path") + .datum({ type: "Sphere" }) + .attr("id", "sphere") + .attr("d", path); + + svg.append("use") + .attr("class", "stroke") + .attr("xlink:href", "#sphere"); + + svg.append("use") + .attr("class", "fill") + .attr("xlink:href", "#sphere"); + + svg.append("path") + .datum(graticule) + .attr("class", "graticule") + .attr("d", path); + + d3.json("/mbostock/raw/4090846/world-50m.json", function (error, world) { + svg.insert("path", ".graticule") + .datum(topojson.feature(world, world.objects.land)) + .attr("class", "land") + .attr("d", path); + + svg.insert("path", ".graticule") + .datum(topojson.mesh(world, world.objects.countries, function (a: any, b: any) { return a !== b; } )) + .attr("class", "boundary") + .attr("d", path); + } ); + + d3.select(self.frameElement).style("height", height + "px"); +} + +//Example from http://bl.ocks.org/mbostock/4060366 +function voronoiTesselation() { + var width = 960, + height = 500; + + var vertices = d3.range(100).map(function (d): [number, number] { + return [Math.random() * width, Math.random() * height]; + } ); + + var voronoi = d3.geom.voronoi() + .clipExtent([[0, 0], [width, height]]); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .attr("class", "PiYG") + .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ); + + var path = >svg.append("g").selectAll("path"); + + svg.selectAll("circle") + .data(vertices.slice(1)) + .enter().append("circle") + .attr("transform", function (d) { return "translate(" + d + ")"; } ) + .attr("r", 2); + + redraw(); + + function redraw() { + path = path.data(voronoi(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String); + path.exit().remove(); + path.enter().append("path").attr("class", function (d, i) { return "q" + (i % 9) + "-9"; } ).attr("d", String); + path.order(); + } +} + +// Example from https://gist.github.com/christophermanning/1734663 +function forceDirectedVoronoi() { + var w = window.innerWidth > 960 ? 960 : (window.innerWidth || 960), + h = window.innerHeight > 500 ? 500 : (window.innerHeight || 500), + radius = 5.25, + simulate = true, + zoomToAdd = true, + color = d3.scale.quantize().domain([10000, 7250]).range(["#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"]) + + var numVertices = (w*h) / 3000; + var vertices = d3.range(numVertices).map(function(i) { + var angle = radius * (i+10); + return {x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}; + }); + var d3_geom_voronoi = d3.geom.voronoi<{ x: number; y: number }>() + .x(function(d) { return d.x; }) + .y(function(d) { return d.y; }) + var prevEventScale = 1; + var zoom = d3.behavior.zoom().on("zoom", function(d,i) { + if (zoomToAdd){ + if (( d3.event).scale > prevEventScale) { + var angle = radius * vertices.length; + vertices.push({x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}) + } else if (vertices.length > 2 && ( d3.event).scale != prevEventScale) { + vertices.pop(); + } + force.nodes(vertices).start() + } else { + if (( d3.event).scale > prevEventScale) { + radius+= .01 + } else { + radius -= .01 + } + vertices.forEach(function(d, i) { + var angle = radius * (i+10); + vertices[i] = {x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)}; + }); + force.nodes(vertices).start() + } + prevEventScale = ( d3.event).scale; + }); + + d3.select(window) + .on("keydown", function() { + // shift + if(( d3.event).keyCode == 16) { + zoomToAdd = false + } + + // s + if(( d3.event).keyCode == 83) { + simulate = !simulate + if(simulate) { + force.start() + } else { + force.stop() + } + } + }) + .on("keyup", function() { + zoomToAdd = true + }) + + var svg = d3.select("#chart") + .append("svg") + .attr("width", w) + .attr("height", h) + .call(zoom) + + var force = d3.layout.force() + .charge(-300) + .size([w, h]) + .on("tick", update); + + force.nodes(vertices).start(); + + var circle = > svg.selectAll("circle"); + var path = > svg.selectAll("path"); + var link = > svg.selectAll("line"); + + function update() { + path = path.data(d3_geom_voronoi(vertices)); + path.enter().append("path") + // drag node by dragging cell + .call(d3.behavior.drag() + .on("drag", function(d, i) { + vertices[i] = {x: vertices[i].x + ( d3.event).dx, y: vertices[i].y + ( d3.event).dy} + }) + ) + .style("fill", function(d, i) { return color(0) }) + path.attr("d", function(d) { return "M" + d.join("L") + "Z"; }) + .transition().duration(150).style("fill", function(d, i) { return color(d3.geom.polygon(d).area()) }) + path.exit().remove(); + + circle = circle.data(vertices) + circle.enter().append("circle") + .attr("r", 0) + .transition().duration(1000).attr("r", 5); + circle.attr("cx", function(d) { return d.x; }) + .attr("cy", function(d) { return d.y; }); + circle.exit().transition().attr("r", 0).remove(); + + link = link.data(d3_geom_voronoi.links(vertices)) + link.enter().append("line") + link.attr("x1", function(d) { return d.source.x; }) + .attr("y1", function(d) { return d.source.y; }) + .attr("x2", function(d) { return d.target.x; }) + .attr("y2", function(d) { return d.target.y; }) + + link.exit().remove() + + if(!simulate) force.stop() + } +} + +//Example from http://bl.ocks.org/mbostock/4341156 +function delaunayTesselation() { + var width = 960, + height = 500; + + var vertices = d3.range(100).map(function (d): [number, number] { + return [Math.random() * width, Math.random() * height]; + } ); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .attr("class", "PiYG") + .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ); + + var path = >svg.append("g").selectAll("path"); + + svg.selectAll("circle") + .data(vertices.slice(1)) + .enter().append("circle") + .attr("transform", function (d) { return "translate(" + d + ")"; } ) + .attr("r", 2); + + redraw(); + + function redraw() { + path = path.data(d3.geom.delaunay(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String); + path.exit().remove(); + path.enter().append("path").attr("class", function (d, i) { return "q" + (i % 9) + "-9"; } ).attr("d", String); + } +} + +//Example from http://bl.ocks.org/mbostock/4343214 +function quadtree() { + var width = 960, + height = 500; + + var data = d3.range(5000).map(function(): [number, number] { + return [Math.random() * width, Math.random() * width]; + }); + + var quadtree = d3.geom.quadtree() + .extent([[-1, -1], [width + 1, height + 1]]) + (data); + + var brush = d3.svg.brush() + .x(d3.scale.identity().domain([0, width])) + .y(d3.scale.identity().domain([0, height])) + .on("brush", brushed) + .extent([[100, 100], [200, 200]]); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height); + + svg.selectAll(".node") + .data(nodes(quadtree)) + .enter().append("rect") + .attr("class", "node") + .attr("x", function (d) { return d.x; } ) + .attr("y", function (d) { return d.y; } ) + .attr("width", function (d) { return d.width; } ) + .attr("height", function (d) { return d.height; } ); + + var point = svg.selectAll(".point") + .data(<{ scanned?: boolean; selected?: boolean; 0: number; 1: number }[]> data) + .enter().append("circle") + .attr("class", "point") + .attr("cx", function (d) { return d[0]; } ) + .attr("cy", function (d) { return d[1]; } ) + .attr("r", 4); + + svg.append("g") + .attr("class", "brush") + .call(brush); + + brushed(); + + function brushed() { + var extent = <[[number, number], [number, number]]> brush.extent(); + point.each(function (d) { d.scanned = d.selected = false; } ); + search(quadtree, extent[0][0], extent[0][1], extent[1][0], extent[1][1]); + point.classed("scanned", function (d) { return d.scanned; } ); + point.classed("selected", function (d) { return d.selected; } ); + } + + // Collapse the quadtree into an array of rectangles. + function nodes(quadtree: d3.geom.quadtree.Quadtree<[number, number]>) { + var nodes: Array<{x: number; y: number; width: number; height: number}> = []; + quadtree.visit(function (node: d3.geom.quadtree.Node<[number, number]>, x1: number, y1: number, x2:number, y2: number) { + nodes.push({ x: x1, y: y1, width: x2 - x1, height: y2 - y1 }); + } ); + return nodes; + } + + // Find the nodes within the specified rectangle. + function search(quadtree: d3.geom.quadtree.Quadtree<{ scanned?: boolean; selected?: boolean; 0: number; 1: number }>, x0: number, y0: number, x3: number, y3: number) { + quadtree.visit(function (node: d3.geom.quadtree.Node<{ scanned?: boolean; selected?: boolean; 0: number; 1: number }>, x1: number, y1: number, x2:number, y2: number) { + var p = node.point; + if (p) { + p.scanned = true; + p.selected = (p[0] >= x0) && (p[0] < x3) && (p[1] >= y0) && (p[1] < y3); + } + return x1 >= x3 || y1 >= y3 || x2 < x0 || y2 < y0; + } ); + } +} + +//Example from http://bl.ocks.org/mbostock/4341699 +function convexHull() { + var width = 960, + height = 500; + + var randomX = d3.random.normal(width / 2, 60), + randomY = d3.random.normal(height / 2, 60), + vertices = d3.range(100).map(function (): [number, number] { return [randomX(), randomY()]; } ); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .on("mousemove", function () { vertices[0] = d3.mouse(this); redraw(); } ) + .on("click", function () { vertices.push(d3.mouse(this)); redraw(); } ); + + svg.append("rect") + .attr("width", width) + .attr("height", height); + + var hull = svg.append("path") + .attr("class", "hull"); + + var circle = > svg.selectAll("circle"); + + redraw(); + + function redraw() { + hull.datum(d3.geom.hull(vertices)).attr("d", function (d) { return "M" + d.join("L") + "Z"; } ); + circle = circle.data(vertices); + circle.enter().append("circle").attr("r", 3); + circle.attr("transform", function (d) { return "translate(" + d + ")"; } ); + } +} + +// example from http://bl.ocks.org/mbostock/1044242 +namespace hierarchicalEdgeBundling { + interface Result extends d3.layout.cluster.Result { + parent: Result; + size: number; + key: string; + } + + var diameter = 960, + radius = diameter / 2, + innerRadius = radius - 120; + + var cluster = d3.layout.cluster() + .size([360, innerRadius]) + .sort(null) + .value(function (d) { return d.size; } ); + + var bundle = d3.layout.bundle(); + + var line = d3.svg.line.radial() + .interpolate("bundle") + .tension(.85) + .radius(function (d) { return d.y; } ) + .angle(function (d) { return d.x / 180 * Math.PI; } ); + + var svg = d3.select("body").append("svg") + .attr("width", diameter) + .attr("height", diameter) + .append("g") + .attr("transform", "translate(" + radius + "," + radius + ")"); + + d3.json("readme-flare-imports.json", function (error, classes) { + var nodes = cluster.nodes(packages.root(classes)), + links = packages.imports(nodes); + + svg.selectAll(".link") + .data(bundle(links)) + .enter().append("path") + .attr("class", "link") + .attr("d", line); + + svg.selectAll(".node") + .data(nodes.filter(function (n) { return !n.children; } )) + .enter().append("g") + .attr("class", "node") + .attr("transform", function (d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; } ) + .append("text") + .attr("dx", function (d) { return d.x < 180 ? 8 : -8; } ) + .attr("dy", ".31em") + .attr("text-anchor", function (d) { return d.x < 180 ? "start" : "end"; } ) + .attr("transform", function (d) { return d.x < 180 ? null : "rotate(180)"; } ) + .text(function (d) { return d.key; } ); + } ); + + d3.select(self.frameElement).style("height", diameter + "px"); + + var packages = { + + // Lazily construct the package hierarchy from class names. + root: function (classes: any[]) { + var map: {[key: string]: Result} = {}; + + function find(name: string, data?: any) { + var node: Result = map[name], i: number; + if (!node) { + node = map[name] = data || { name: name, children: [] }; + if (name.length) { + node.parent = find(name.substring(0, i = name.lastIndexOf("."))); + node.parent.children.push(node); + node.key = name.substring(i + 1); + } + } + return node; + } + + classes.forEach(function (d) { + find(d.name, d); + } ); + + return map[""]; + } , + + // Return a list of imports for the given array of nodes. + imports: function (nodes: any[]) { + var map: {[key: string]: Result} = {}, + imports: d3.layout.cluster.Link[] = []; + + // Compute a map from name to node. + nodes.forEach(function (d) { + map[d.name] = d; + } ); + + // For each import, construct a link from the source to target node. + nodes.forEach(function (d) { + if (d.imports) d.imports.forEach(function (i: string) { + imports.push({ source: map[d.name], target: map[i] }); + } ); + } ); + + return imports; + } + }; +} + +// example from http://bl.ocks.org/mbostock/1123639 +function roundedRectangles() { + var mouse = [480, 250], + count = 0; + + var svg = d3.select("body").append("svg:svg") + .attr("width", 960) + .attr("height", 500); + + var g = svg.selectAll("g") + .data(d3.range(25)) + .enter().append("svg:g") + .attr("transform", "translate(" + mouse + ")"); + + g.append("svg:rect") + .attr("rx", 6) + .attr("ry", 6) + .attr("x", -12.5) + .attr("y", -12.5) + .attr("width", 25) + .attr("height", 25) + .attr("transform", function (d, i) { return "scale(" + (1 - d / 25) * 20 + ")"; } ) + .style("fill", d3.scale.category20c()); + + var g0 = g.datum(function (d) { + return { center: [0, 0], angle: 0 }; + } ); + + svg.on("mousemove", function () { + mouse = d3.mouse(this); + } ); + + d3.timer(function () { + count++; + g0.attr("transform", function (d, i) { + d.center[0] += (mouse[0] - d.center[0]) / (i + 5); + d.center[1] += (mouse[1] - d.center[1]) / (i + 5); + d.angle += Math.sin((count + i) / 10) * 7; + return "translate(" + d.center + ")rotate(" + d.angle + ")"; + } ); + return true; + } ); +} + +// example from http://bl.ocks.org/mbostock/4060954 +function streamGraph() { + var n = 20, // number of layers + m = 200, // number of samples per layer + stack = d3.layout.stack().offset("wiggle"), + layers0 = stack(d3.range(n).map(function () { return bumpLayer(m); })), + layers1 = stack(d3.range(n).map(function () { return bumpLayer(m); })); + + var width = 960, + height = 500; + + var x = d3.scale.linear() + .domain([0, m - 1]) + .range([0, width]); + + var y = d3.scale.linear() + .domain([0, d3.max(layers0.concat(layers1), function (layer) { return d3.max(layer, function (d) { return d.y0 + d.y; }); })]) + .range([height, 0]); + + var color = d3.scale.linear() + .range(["#aad", "#556"]); + + var area = d3.svg.area<{ x: number; y: number; y0: number }>() + .x(function (d) { return x(d.x); }) + .y0(function (d) { return y(d.y0); }) + .y1(function (d) { return y(d.y0 + d.y); }); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height); + + svg.selectAll("path") + .data(layers0) + .enter().append("path") + .attr("d", area) + .style("fill", function () { return color(Math.random()); }); + + function transition() { + d3.selectAll("path") + .data(function () { + var d = layers1; + layers1 = layers0; + return layers0 = d; + }) + .transition() + .duration(2500) + .attr("d", area); + } + + // Inspired by Lee Byron's test data generator. + function bumpLayer(n: number): Array<{x: number; y: number;y0?:number;}> { + + function bump(a: number[]) { + var x = 1 / (.1 + Math.random()), + y = 2 * Math.random() - .5, + z = 10 / (.1 + Math.random()); + for (var i = 0; i < n; i++) { + var w = (i / n - y) * z; + a[i] += x * Math.exp(-w * w); + } + } + + var a: number[] = [], i: number; + for (i = 0; i < n; ++i) a[i] = 0; + for (i = 0; i < 5; ++i) bump(a); + return a.map(function (d, i) { return { x: i, y: Math.max(0, d) }; } ); + } +} + +// example from http://mbostock.github.io/d3/talk/20111116/force-collapsible.html +namespace forceCollapsable2 { + interface Node extends d3.layout.force.Node { + children: Node[]; + _children: Node[]; + size: number; + id: string; + } + + var w = 1280, + h = 800, + node: d3.selection.Update, + link: d3.selection.Update>, + root: Node; + + var force = d3.layout.force() + .on("tick", tick) + .charge(function (d) { return d._children ? -d.size / 100 : -30; } ) + .linkDistance(function (d) { return d.target._children ? 80 : 30; } ) + .size([w, h - 160]); + + var vis = d3.select("body").append("svg:svg") + .attr("width", w) + .attr("height", h); + + d3.json("flare.json", function (json) { + root = json; + root.fixed = true; + root.x = w / 2; + root.y = h / 2 - 80; + update(); + } ); + + function update() { + var nodes = flatten(root), + links = d3.layout.tree().links(nodes); + + // Restart the force layout. + force + .nodes(nodes) + .links(links) + .start(); + + // Update the links… + link = vis.selectAll("line.link") + .data(links, function (d) { return d.target.id; } ); + + // Enter any new links. + link.enter().insert("svg:line", ".node") + .attr("class", "link") + .attr("x1", function (d) { return d.source.x; } ) + .attr("y1", function (d) { return d.source.y; } ) + .attr("x2", function (d) { return d.target.x; } ) + .attr("y2", function (d) { return d.target.y; } ); + + // Exit any old links. + link.exit().remove(); + + // Update the nodes… + node = vis.selectAll("circle.node") + .data(nodes, function (d) { return d.id; } ) + .style("fill", color); + + node.transition() + .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ); + + // Enter any new nodes. + node.enter().append("svg:circle") + .attr("class", "node") + .attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ) + .attr("r", function (d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; } ) + .style("fill", color) + .on("click", click) + .call(force.drag); + + // Exit any old nodes. + node.exit().remove(); + } + + function tick() { + link.attr("x1", function (d) { return d.source.x; } ) + .attr("y1", function (d) { return d.source.y; } ) + .attr("x2", function (d) { return d.target.x; } ) + .attr("y2", function (d) { return d.target.y; } ); + + node.attr("cx", function (d) { return d.x; } ) + .attr("cy", function (d) { return d.y; } ); + } + + // Color leaf nodes orange, and packages white or blue. + function color(d: Node) { + return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c"; + } + + // Toggle children on click. + function click(d: Node) { + if (d.children) { + d._children = d.children; + d.children = null; + } else { + d.children = d._children; + d._children = null; + } + update(); + } + + // Returns a list of all nodes under the root. + function flatten(root: Node) { + var nodes: Node[] = [], i = 0; + + function recurse(node: Node) { + if (node.children) node.size = node.children.reduce(function (p, v) { return p + recurse(v); } , 0); + if (!node.id) node.id = String(++i); + nodes.push(node); + return node.size; + } + + root.size = recurse(root); + return nodes; + } +} + +//exapmle from http://bl.ocks.org/mbostock/4062006 +function chordDiagram() { + var matrix = [ + [11975, 5871, 8916, 2868], + [1951, 10048, 2060, 6171], + [8010, 16145, 8090, 8045], + [1013, 990, 940, 6907] + ]; + + var chord = d3.layout.chord() + .padding(.05) + .sortSubgroups(d3.descending) + .matrix(matrix); + + var width = 960, + height = 500, + innerRadius = Math.min(width, height) * .41, + outerRadius = innerRadius * 1.1; + + var fill = d3.scale.ordinal() + .domain(d3.range(4)) + .range(["#000000", "#FFDD89", "#957244", "#F26223"]); + + var svg = d3.select("body").append("svg") + .attr("width", width) + .attr("height", height) + .append("g") + .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); + + svg.append("g").selectAll("path") + .data(chord.groups) + .enter().append("path") + .style("fill", function (d) { return fill(d.index); } ) + .style("stroke", function (d) { return fill(d.index); } ) + .attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius)) + .on("mouseover", fade(.1)) + .on("mouseout", fade(1)); + + var ticks = svg.append("g").selectAll("g") + .data(chord.groups) + .enter().append("g").selectAll("g") + .data(groupTicks) + .enter().append("g") + .attr("transform", function (d) { + return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")" + + "translate(" + outerRadius + ",0)"; + } ); + + ticks.append("line") + .attr("x1", 1) + .attr("y1", 0) + .attr("x2", 5) + .attr("y2", 0) + .style("stroke", "#000"); + + ticks.append("text") + .attr("x", 8) + .attr("dy", ".35em") + .attr("transform", function (d) { return d.angle > Math.PI ? "rotate(180)translate(-16)" : null; } ) + .style("text-anchor", function (d) { return d.angle > Math.PI ? "end" : null; } ) + .text(function (d) { return d.label; } ); + + svg.append("g") + .attr("class", "chord") + .selectAll("path") + .data(chord.chords) + .enter().append("path") + .attr("d", d3.svg.chord().radius(innerRadius)) + .style("fill", function (d) { return fill(d.target.index); } ) + .style("opacity", 1); + + // Returns an array of tick angles and labels, given a group. + function groupTicks(d: d3.layout.chord.Node) { + var k = (d.endAngle - d.startAngle) / d.value; + return d3.range(0, d.value, 1000).map(function (v, i) { + return { + angle: v * k + d.startAngle, + label: i % 5 ? null : v / 1000 + "k" + }; + } ); + } + + // Returns an event handler for fading a given chord group. + function fade(opacity: number) { + return function (g: {}, i: number) { + svg.selectAll(".chord path") + .filter(function (d) { return d.source.index != i && d.target.index != i; } ) + .transition() + .style("opacity", opacity); + }; + } +} + +//example from http://mbostock.github.io/d3/talk/20111116/iris-parallel.html +function irisParallel() { + var species = ["setosa", "versicolor", "virginica"], + traits = ["sepal length", "petal length", "sepal width", "petal width"]; + + var m = [80, 160, 200, 160], + w = 1280 - m[1] - m[3], + h = 800 - m[0] - m[2]; + + var x = d3.scale.ordinal().domain(traits).rangePoints([0, w]), + y: {[key: string]: any} = {}; + + var line = d3.svg.line(), + axis = d3.svg.axis().orient("left"), + foreground: d3.Selection<{ [key: string]: string}>; + + var svg = d3.select("body").append("svg:svg") + .attr("width", w + m[1] + m[3]) + .attr("height", h + m[0] + m[2]) + .append("svg:g") + .attr("transform", "translate(" + m[3] + "," + m[0] + ")"); + + d3.csv("iris.csv", function (flowers) { + var i: number; + + // Create a scale and brush for each trait. + traits.forEach(function (d) { + y[d] = d3.scale.linear() + .domain(d3.extent(flowers, function (p) { return +p[d]; } )) + .range([h, 0]); + + y[d].brush = d3.svg.brush() + .y(y[d]) + .on("brush", brush); + } ); + + // Add a legend. + var legend = svg.selectAll("g.legend") + .data(species) + .enter().append("svg:g") + .attr("class", "legend") + .attr("transform", function (d, i) { return "translate(0," + (i * 20 + 584) + ")"; } ); + + legend.append("svg:line") + .attr("class", String) + .attr("x2", 8); + + legend.append("svg:text") + .attr("x", 12) + .attr("dy", ".31em") + .text(function (d) { return "Iris " + d; } ); + + // Add foreground lines. + foreground = svg.append("svg:g") + .attr("class", "foreground") + .selectAll("path") + .data(flowers) + .enter().append("svg:path") + .attr("d", path) + .attr("class", function (d) { return d['species']; } ); + + // Add a group element for each trait. + var g = svg.selectAll(".trait") + .data(traits) + .enter().append("svg:g") + .attr("class", "trait") + .attr("transform", function (d) { return "translate(" + x(d) + ")"; } ) + .call(d3.behavior.drag() + .origin(function (d) { return { x: x(d), y: NaN }; } ) + .on("dragstart", dragstart) + .on("drag", drag) + .on("dragend", dragend)); + + // Add an axis and title. + g.append("svg:g") + .attr("class", "axis") + .each(function (d) { d3.select(this).call(axis.scale(y[d])); } ) + .append("svg:text") + .attr("text-anchor", "middle") + .attr("y", -9) + .text(String); + + // Add a brush for each axis. + g.append("svg:g") + .attr("class", "brush") + .each(function (d) { d3.select(this).call(y[d].brush); } ) + .selectAll("rect") + .attr("x", -8) + .attr("width", 16); + + function dragstart(d: string) { + i = traits.indexOf(d); + } + + function drag(d: string) { + x.range()[i] = ( d3.event).x; + traits.sort(function (a, b) { return x(a) - x(b); } ); + g.attr("transform", function (d) { return "translate(" + x(d) + ")"; } ); + foreground.attr("d", path); + } + + function dragend(d: string) { + x.domain(traits).rangePoints([0, w]); + var t = d3.transition().duration(500); + t.selectAll(".trait").attr("transform", function (d) { return "translate(" + x(d) + ")"; } ); + t.selectAll(".foreground path").attr("d", path); + } + } ); + + // Returns the path for a given data point. + function path(d: any): string { + return line(traits.map(function (p): [number, number] { return [x(p), y[p](d[p])]; } )); + } + + // Handles a brush event, toggling the display of foreground lines. + function brush() { + var actives = traits.filter(function (p) { return !y[p].brush.empty(); } ), + extents = actives.map(function (p) { return y[p].brush.extent(); } ); + foreground.classed("fade", function (d) { + return !actives.every(function (p, i) { + return extents[i][0] <= d[p] && d[p] <= extents[i][1]; + } ); + } ); + } +} + +//example from +function healthAndWealth() { + // Various accessors that specify the four dimensions of data to visualize. + function x(d: any) { return d.income; } + function y(d: any) { return d.lifeExpectancy; } + function radius(d: any) { return d.population; } + function color(d: any) { return d.region; } + function key(d: any) { return d.name; } + + // Chart dimensions. + var margin = { top: 19.5, right: 19.5, bottom: 19.5, left: 39.5 }, + width = 960 - margin.right, + height = 500 - margin.top - margin.bottom; + + // Various scales. These domains make assumptions of data, naturally. + var xScale = d3.scale.log().domain([300, 1e5]).range([0, width]), + yScale = d3.scale.linear().domain([10, 85]).range([height, 0]), + radiusScale = d3.scale.sqrt().domain([0, 5e8]).range([0, 40]), + colorScale = d3.scale.category10(); + + // The x & y axes. + var xAxis = d3.svg.axis().orient("bottom").scale(xScale).ticks(12, d3.format(",d")), + yAxis = d3.svg.axis().scale(yScale).orient("left"); + + // Create the SVG container and set the origin. + var svg = d3.select("#chart").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + // Add the x-axis. + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); + + // Add the y-axis. + svg.append("g") + .attr("class", "y axis") + .call(yAxis); + + // Add an x-axis label. + svg.append("text") + .attr("class", "x label") + .attr("text-anchor", "end") + .attr("x", width) + .attr("y", height - 6) + .text("income per capita, inflation-adjusted (dollars)"); + + // Add a y-axis label. + svg.append("text") + .attr("class", "y label") + .attr("text-anchor", "end") + .attr("y", 6) + .attr("dy", ".75em") + .attr("transform", "rotate(-90)") + .text("life expectancy (years)"); + + // Add the year label; the value is set on transition. + var label = svg.append("text") + .attr("class", "year label") + .attr("text-anchor", "end") + .attr("y", height - 24) + .attr("x", width) + .text(1800); + + // Load the data. + d3.json("nations.json", function (nations: any[]) { + + // A bisector since many nation's data is sparsely-defined. + var bisect = d3.bisector(function (d: any) { return d[0]; } ); + + // Add a dot per nation. Initialize the data at 1800, and set the colors. + var dot = svg.append("g") + .attr("class", "dots") + .selectAll(".dot") + .data(interpolateData(1800)) + .enter().append("circle") + .attr("class", "dot") + .style("fill", function (d) { return colorScale(color(d)); } ) + .call(position) + .sort(order); + + // Add a title. + dot.append("title") + .text(function (d) { return d.name; } ); + + // Add an overlay for the year label. + var box = (label.node()).getBBox(); + + var overlay = svg.append("rect") + .attr("class", "overlay") + .attr("x", box.x) + .attr("y", box.y) + .attr("width", box.width) + .attr("height", box.height) + .on("mouseover", enableInteraction); + + // Start a transition that interpolates the data based on year. + svg.transition() + .duration(30000) + .ease("linear") + .tween("year", tweenYear) + .each("end", enableInteraction); + + // Positions the dots based on data. + function position(dot: d3.Selection) { + dot.attr("cx", function (d) { return xScale(x(d)); } ) + .attr("cy", function (d) { return yScale(y(d)); } ) + .attr("r", function (d) { return radiusScale(radius(d)); } ); + } + + // Defines a sort order so that the smallest dots are drawn on top. + function order(a: any, b: any) { + return radius(b) - radius(a); + } + + // After the transition finishes, you can mouseover to change the year. + function enableInteraction() { + var yearScale = d3.scale.linear() + .domain([1800, 2009]) + .range([box.x + 10, box.x + box.width - 10]) + .clamp(true); + + // Cancel the current transition, if any. + svg.transition().duration(0); + + overlay + .on("mouseover", mouseover) + .on("mouseout", mouseout) + .on("mousemove", mousemove) + .on("touchmove", mousemove); + + function mouseover() { + label.classed("active", true); + } + + function mouseout() { + label.classed("active", false); + } + + function mousemove() { + displayYear(yearScale.invert(d3.mouse(this)[0])); + } + } + + // Tweens the entire chart by first tweening the year, and then the data. + // For the interpolated data, the dots and label are redrawn. + function tweenYear() { + var year = d3.interpolateNumber(1800, 2009); + return function (t: number) { displayYear(year(t)); }; + } + + // Updates the display to show the specified year. + function displayYear(year: number) { + dot.data(interpolateData(year), key).call(position).sort(order); + label.text(Math.round(year)); + } + + // Interpolates the dataset for the given (fractional) year. + function interpolateData(year: number) { + return nations.map(function (d) { + return { + name: d.name, + region: d.region, + income: interpolateValues(d.income, year), + population: interpolateValues(d.population, year), + lifeExpectancy: interpolateValues(d.lifeExpectancy, year) + }; + } ); + } + + // Finds (and possibly interpolates) the value for the specified year. + function interpolateValues(values: any[], year: number) { + var i = bisect.left(values, year, 0, values.length - 1), + a = values[i]; + if (i > 0) { + var b = values[i - 1], + t = (year - a[0]) / (b[0] - a[0]); + return a[1] * (1 - t) + b[1] * t; + } + return a[1]; + } + } ); +} + +// Test for d3.functor +function functorTest () { + var f: (n: number) => number = d3.functor(10); + var g = d3.functor(function (v: number) { return v; }); + + return f(10) === g(10); +} + +// Test for d3.Nest +// Most test adopted from: https://github.com/mbostock/d3/blob/master/test/arrays/nest-test.js +function nestTest () { + var data = [ + { + a: 10, + b: [ 1, 2 ] + }, + { + a: 20, + b: [ 2, 3 ] + }, + { + a: 30, + b: [ 1, 2 ] + } + ]; + + var n1 = d3.nest<{a: number; b: number[] }>() + .key(function (d) { return String(d.a); }) + .sortKeys(d3.descending) + .rollup(function (vals) { + return d3.sum(vals[0].b); + }); + n1.map(data); + n1.entries(data); + + var n2 = d3.nest<{ a: number; b: number[] }>() + .key(function (d) { return String(d.a); }) + .sortValues(function (x1, x2) { + return x1.b[0] < x1.b[1] ? -1 : (x1.b[0] > x1.b[0] ? 1 : 0); }); + n2.map(data); + n2.entries(data); + + // Tests adopted from d3's tests. + var keys = d3.nest<{ foo: number; }>() + .key(function(d) { return String(d.foo); }) + .entries([{foo: 1}, {foo: 1}, {foo: 2}]) + .map(function(d) { return d.key; }) + .sort(d3.ascending); + + var entries = d3.nest<{foo: number; bar?: number}>() + .key(function(d) { return String(d.foo); }) + .entries([{foo: 1, bar: 0}, {foo: 2}, {foo: 1, bar: 1}]); + + keys = d3.nest<{foo: number}>() + .key(function(d) { return String(d.foo); }).sortKeys(d3.descending) + .entries([{foo: 1}, {foo: 1}, {foo: 2}]) + .map(function(d) { return d.key; }); + + entries = d3.nest<{ foo: number; bar?: number }>() + .key(function(d) { return String(d.foo); }) + .sortValues(function(a, b) { return a.bar - b.bar; }) + .entries([{foo: 1, bar: 2}, {foo: 1, bar: 0}, {foo: 1, bar: 1}, {foo: 2}]); + + entries = d3.nest<{ foo: number; bar?: number }>() + .key(function(d) { return String(d.foo); }) + .rollup(function(values) { return d3.sum(values, function(d) { return d.bar; }); }) + .entries([{foo: 1, bar: 2}, {foo: 1, bar: 0}, {foo: 1, bar: 1}, {foo: 2}]); + + entries = d3.nest<[number, number]>() + .key(function(d) { return String(d[0]); }).sortKeys(d3.ascending) + .key(function(d) { return String(d[1]); }).sortKeys(d3.ascending) + .entries([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]); + + entries = d3.nest<[number, number]>() + .key(function(d) { return String(d[0]); }).sortKeys(d3.ascending) + .key(function(d) { return String(d[1]); }).sortKeys(d3.ascending) + .rollup(function(values) { return values.length; }) + .entries([[0, 1], [0, 2], [1, 1], [1, 2], [0, 2]]); + + entries = d3.nest<{ 0: number; 1: number; 2?: number }>() + .key(function(d) { return String(d[0]); }).sortKeys(d3.ascending) + .key(function(d) { return String(d[1]); }).sortKeys(d3.ascending) + .sortValues(function(a, b) { return a[2] - b[2]; }) + .entries([[0, 1], [0, 2, 1], [1, 1], [1, 2], [0, 2, 0]]); + + var map = d3.nest<{ 0: number; 1: number; 2?: number }>() + .key(function(d) { return String(d[0]); }).sortKeys(d3.ascending) + .key(function(d) { return String(d[1]); }).sortKeys(d3.ascending) + .sortValues(function(a, b) { return a[2] - b[2]; }) + .map([[0, 1], [0, 2, 1], [1, 1], [1, 2], [0, 2, 0]]); +} + +// Test for setting attributes as an object +// From https://github.com/mbostock/d3/blob/master/test/selection/attr-test.js +function attrObjTest () { + d3.select('body') + .data(["orange"]) + .attr({"xlink:href": function(d, i) { return d + "-" + i + ".png"; }}); +} + +// Test for setting styles as an object +// From https://github.com/mbostock/d3/blob/master/test/selection/style-test.js +function styleObjTest () { + d3.select('body') + .style({"background-color": "white", opacity: .42}); +} + +// Test for setting styles as an object +// From https://github.com/mbostock/d3/blob/master/test/selection/property-test.js +function propertyObjTest () { + d3.select('body') + .property({bgcolor: "purple", opacity: .41}); +} + + +// Test for brushes +function brushTest() { + var xScale = d3.scale.linear(), + yScale = d3.scale.linear(); + + var xMin = 0, xMax = 1, + yMin = 0, yMax = 1; + + // Setting only x scale. + var brush1 = d3.svg.brush() + .x(xScale) + .on('brush', function () { + var extent = <[number, number]> brush1.extent(); + xMin = Math.max(extent[0], 0); + xMax = Math.min(extent[1], 1); + brush1.extent([xMin, xMax]); + }); + + // Setting both the x and y scale + var brush2 = d3.svg.brush() + .x(xScale) + .y(yScale) + .on('brush', function () { + var extent = <[[number, number], [number, number]]> brush2.extent(); + var xExtent = extent[0], + yExtent = extent[1]; + + xMin = Math.max(xExtent[0], 0); + xMax = Math.min(xExtent[1], 1); + + yMin = Math.max(yExtent[0], 0); + yMax = Math.min(yExtent[1], 1); + + brush1.extent([[xMin, xMax], [yMin, yMax]]); + }); +} + + +// Tests for area +// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/area-test.js +function svgAreaTest () { + var a = d3.svg.area(), + f: () => number, + n: number; + + a.x(f).x() === f; + a.x(n).x() === n; + a.x(0); + a.x(function (d) { return d[0] * 10; }); + a.x(function (d, i) { return i * 10; }); + + a.x(f).x0() === f; + a.x(n).x0() === n; + a.x0(0); + a.x0(function (d) { return d[0] * 10; }); + a.x0(function (d, i) { return i * 10; }); + + a.x(f).x1() === f; + a.x(n).x1() === n; + a.x1(0); + a.x1(function (d) { return d[0] * 10; }); + a.x1(function (d, i) { return i * 10; }); + + a.y(f).y() === f; + a.y(n).y() === n; + a.y(0); + a.y(function (d) { return d[0] * 10; }); + a.y(function (d, i) { return i * 10; }); + + a.y(f).y0() === f; + a.y(n).y0() === n; + a.y0(0); + a.y0(function (d) { return d[0] * 10; }); + a.y0(function (d, i) { return i * 10; }); + + a.y(f).y1() === f; + a.y(n).y1() === n; + a.y1(0); + a.y1(function (d) { return d[0] * 10; }); + a.y1(function (d, i) { return i * 10; }); +} + +// Tests for areaRadial +// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/area-radial-test.js +function svgAreaRadialTest () { + var a = d3.svg.area.radial(), + f: () => number, + n: number; + + a.radius(f).radius() === f; + a.radius(n).radius() === n; + a.radius(0); + a.radius(function (d) { return d[0] * 10; }); + a.radius(function (d, i) { return i * 10; }); + + a.radius(f).innerRadius() === f; + a.radius(n).innerRadius() === n; + a.innerRadius(0); + a.innerRadius(function (d) { return d[0] * 10; }); + a.innerRadius(function (d, i) { return i * 10; }); + + a.radius(f).outerRadius() === f; + a.radius(n).outerRadius() === n; + a.outerRadius(0); + a.outerRadius(function (d) { return d[1] * 10; }); + a.outerRadius(function (d, i) { return i * 10; }); + + a.angle(f).angle() === f; + a.angle(n).angle() === n; + a.angle(0); + a.angle(function (d) { return d[0] * 10; }); + a.angle(function (d, i) { return i * 10; }); + + a.angle(f).startAngle() === f; + a.angle(n).startAngle() === n; + a.startAngle(0); + a.startAngle(function (d) { return d[0] * 10; }); + a.startAngle(function (d, i) { return i * 10; }); + + a.angle(f).endAngle() === f; + a.angle(n).endAngle() === n; + a.endAngle(0); + a.endAngle(function (d) { return d[1] * 10; }); + a.endAngle(function (d, i) { return i * 10; }); +} + +// Tests for d3.svg.line +// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/line-test.js +function svgLineTest () { + var l = d3.svg.line(), + f: () => number, + n: number; + + l.x(f).x() === f; + l.x(n).x() === n; + l.x(0); + l.x(function (d) { return d[0]; }); + l.x(function (d, i) { return i; }); + + l.y(f).y() === f; + l.y(n).y() === n; + l.y(0); + l.y(function (d) { return d[1]; }); + l.y(function (d, i) { return i; }); +} + +// Tests for d3.svg.line.radial +// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/line-radial-test.js +function svgLineRadialTest () { + var l = d3.svg.line.radial(), + f: () => number, + n: number; + + l.radius(f).radius() === f; + l.radius(n).radius() === n; + l.radius(0); + l.radius(function (d) { return d[0]; }); + l.radius(function (d, i) { return i; }); + + l.angle(f).angle() === f; + l.angle(n).angle() === n; + l.angle(0); + l.angle(function (d) { return d[1]; }); + l.angle(function (d, i) { return i; }); +} + +// Tests for d3.svg.arc +// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/arc-test.js +function svgArcTest () { + var l = d3.svg.arc(), + f: () => number; + + l.innerRadius(f).innerRadius() === f; + l.innerRadius(0); + l.innerRadius(function (d) { return d.innerRadius; }); + l.innerRadius(function (d, i) { return i; }); + + l.outerRadius(f).outerRadius() === f; + l.outerRadius(0); + l.outerRadius(function (d) { return d.outerRadius; }); + l.outerRadius(function (d, i) { return i; }); + + l.startAngle(f).startAngle() === f; + l.startAngle(0); + l.startAngle(function (d) { return d.innerRadius; }); + l.startAngle(function (d, i) { return i; }); + + l.endAngle(f).endAngle() === f; + l.endAngle(0); + l.endAngle(function (d) { return d.outerRadius; }); + l.endAngle(function (d, i) { return i; }); +} + +function svgArcTest2 () { + var l = d3.svg.arc<[number, number]>(); + + l.innerRadius(d => d[0]); + l.outerRadius(d => d[1]); +} + +// Tests for d3.svg.diagonal +// Adopted from: https://github.com/mbostock/d3/blob/master/test/svg/diagonal-test.js +function svgDiagonalTest () { + var d = d3.svg.diagonal(); + + d.projection()({ x: 0, y: 1}, 0); + d.projection(function (d) { return [d.x, d.y]; }); + d.projection(function (d, i) { return [i, i + 1]; }); + + d.source()({ source: {x: 0, y: 1}, target: null }, 0); + d.source({x: 0, y: 1}); + d.source(function (d) { return {x: d.source.x, y: d.source.y}; }); + d.source(function (d, i) { return {x: d.source.x * i, y: d.source.y * i}; }); + + d.target()({ target: {x: 0, y: 1}, source: null }, 0); + d.target({x: 0, y: 1}); + d.target(function (d) { return {x: d.target.x, y: d.target.y}; }); + d.target(function (d, i) { return {x: d.target.x * i, y: d.target.y * i}; }); +} + +// Tests for d3.extent +// Adopted from: https://github.com/mbostock/d3/blob/master/test/arrays/extent-test.js +function extentTest() { + // usages of `o' suppressed as well as mixed-type comparisons + // see https://github.com/Microsoft/TypeScript/commit/c0db7ffe8f55b6ec335880482ca43b93b066689d + var o = { valueOf: function () { return NaN; } }; + + d3.extent([1]); + d3.extent([5, 1, 2, 3, 4]); + d3.extent([20, 3]); + d3.extent([3, 20]); + d3.extent(["c", "a", "b"]); + d3.extent(["20", "3"]); + d3.extent(["3", "20"]); + d3.extent([NaN, 1, 2, 3, 4, 5]); + // d3.extent([o, 1, 2, 3, 4, 5]); + d3.extent([1, 2, 3, 4, 5, NaN]); + // d3.extent([1, 2, 3, 4, 5, o]); + d3.extent([10, null, 3, undefined, 5, NaN]); + d3.extent([-1, null, -3, undefined, -5, NaN]); + // d3.extent([20, "3"]); + // d3.extent(["20", 3]); + // d3.extent([3, "20"]); + // d3.extent(["3", 20]); + + d3.extent([1], (d) => { return d; }); + d3.extent([5, 1, 2, 3, 4], (d) => { return d; }); + d3.extent([20, 3], (d) => { return d; }); + d3.extent([3, 20], (d) => { return d; }); + d3.extent(["c", "a", "b"], (d) => { return d; }); + d3.extent(["20", "3"], (d) => { return d; }); + d3.extent(["3", "20"], (d) => { return d; }); + d3.extent([NaN, 1, 2, 3, 4, 5], (d) => { return d; }); + // d3.extent([o, 1, 2, 3, 4, 5], (d) => { return d; }); + d3.extent([1, 2, 3, 4, 5, NaN], (d) => { return d; }); + // d3.extent([1, 2, 3, 4, 5, o], (d) => { return d; }); + d3.extent([10, null, 3, undefined, 5, NaN], (d) => { return d; }); + d3.extent([-1, null, -3, undefined, -5, NaN], (d) => { return d; }); + // d3.extent([20, "3"], (d) => { return d; }); + // d3.extent(["20", 3], (d) => { return d; }); + // d3.extent([3, "20"], (d) => { return d; }); + // d3.extent(["3", 20], (d) => { return d; }); +} + +// Tests for d3.time.format.multi +// Adopted from http://bl.ocks.org/mbostock/4149176 +function multiTest() { + var customTimeFormat = d3.time.format.multi([ + [".%L", function(d) { return !!d.getMilliseconds(); }], + [":%S", function(d) { return !!d.getSeconds(); }], + ["%I:%M", function(d) { return !!d.getMinutes(); }], + ["%I %p", function(d) { return !!d.getHours(); }], + ["%a %d", function(d) { return !!d.getDay() && d.getDate() != 1; }], + ["%b %d", function(d) { return d.getDate() != 1; }], + ["%B", function(d) { return !!d.getMonth(); }], + ["%Y", function() { return true; }] + ]); + + var margin = {top: 250, right: 40, bottom: 250, left: 40}, + width = 960 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + + var x = d3.time.scale() + .domain([new Date(2012, 0, 1), new Date(2013, 0, 1)]) + .range([0, width]); + + var xAxis = d3.svg.axis() + .scale(x) + .tickFormat(customTimeFormat); + + var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) + .append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + + svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis); +} + +function testD3Events () { + d3.select('svg') + .on('click', () => { + let e = d3.event; + var coords = [e.pageX, e.pageY]; + console.log("clicked", e.target, "at " + coords); + }) + .on('keypress', () => { + let e = d3.event; + if (e.shiftKey) { + console.log('shift + ' + e.which); + } + }); +} + +function testD3MutlieTimeFormat() { + var format = d3.time.format.multi([ + [".%L", function(d) { return d.getMilliseconds(); }], + [":%S", function(d) { return d.getSeconds(); }], + ["%I:%M", function(d) { return d.getMinutes(); }], + ["%I %p", function(d) { return d.getHours(); }], + ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }], + ["%b %d", function(d) { return d.getDate() != 1; }], + ["%B", function(d) { return d.getMonth(); }], + ["%Y", function() { return true; }] + ]); +} + +function testMultiUtcFormat() { + var format = d3.time.format.utc.multi([ + [".%L", function(d) { return d.getMilliseconds(); }], + [":%S", function(d) { return d.getSeconds(); }], + ["%I:%M", function(d) { return d.getMinutes(); }], + ["%I %p", function(d) { return d.getHours(); }], + ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }], + ["%b %d", function(d) { return d.getDate() != 1; }], + ["%B", function(d) { return d.getMonth(); }], + ["%Y", function() { return true; }] + ]); +} + +function testEnterSizeEmpty() { + + var selectionSize: number, + emptyStatus: boolean; + + var newNodes = d3.selectAll('.test') + .data(['1', '2', '3']) + .enter(); + + emptyStatus = newNodes.empty(); + selectionSize = newNodes.size(); + +} \ No newline at end of file diff --git a/d3/d3-v3.5.d.ts b/d3/d3-v3.5.d.ts new file mode 100644 index 0000000000..d8469d68a3 --- /dev/null +++ b/d3/d3-v3.5.d.ts @@ -0,0 +1,3375 @@ +// Type definitions for d3JS v3.5.17 +// Project: http://d3js.org/ +// Definitions by: Alex Ford , Boris Yankov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = d3; +export as namespace d3; + +declare namespace d3 { + /** + * The current version of D3.js. + */ + export var version: string; + + /** + * Find the first element that matches the given selector string. + */ + export function select(selector: string): Selection; + + /** + * Create a selection from the given node reference. + */ + export function select(node: EventTarget): Selection; + + /** + * Find all elements that match the given selector string. + */ + export function selectAll(selector: string): Selection; + + /** + * Create a selection from the given list of nodes. + */ + export function selectAll(nodes: EventTarget[]): Selection; + + /** + * Returns the root selection (as if by d3.select(document.documentElement)). This function may be used for 'instanceof' tests, and extending its prototype will add properties to all selections. + */ + export function selection(): Selection; + + namespace selection { + export var prototype: Selection; + + /** + * Selections are grouped into arrays of nodes, with the parent tracked in the 'parentNode' property. + */ + interface Group extends Array { + parentNode: EventTarget; + } + + interface Update { + /** + * Retrieve a grouped selection. + */ + [index: number]: Group; + + /** + * The number of groups in this selection. + */ + length: number; + + /** + * Retrieve the value of the given attribute for the first node in the selection. + * + * @param name The attribute name to query. May be prefixed (see d3.ns.prefix). + */ + attr(name: string): string; + + /** + * For all nodes, set the attribute to the specified constant value. Use null to remove. + * + * @param name The attribute name, optionally prefixed. + * @param value The attribute value to use. Note that this is coerced to a string automatically. + */ + attr(name: string, value: Primitive): Update; + + /** + * Derive an attribute value for each node in the selection based on bound data. + * + * @param name The attribute name, optionally prefixed. + * @param value The function of the datum (the bound data item), index (the position in the subgrouping), and outer index (overall position in nested selections) which computes the attribute value. If the function returns null, the attribute is removed. + */ + attr(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive): Update; + + /** + * Set multiple properties at once using an Object. D3 iterates over all enumerable properties and either sets or computes the attribute's value based on the corresponding entry in the Object. + * + * @param obj A key-value mapping corresponding to attributes and values. If the value is a simple string or number, it is taken as a constant. Otherwise, it is a function that derives the attribute value. + */ + attr(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }): Update; + + /** + * Returns true if the first node in this selection has the given class list. If multiple classes are specified (i.e., "foo bar"), then returns true only if all classes match. + * + * @param name The class list to query. + */ + classed(name: string): boolean; + + /** + * Adds (or removes) the given class list. + * + * @param name The class list to toggle. Spaces separate class names: "foo bar" is a list of two classes. + * @param value If true, add the classes. If false, remove them. + */ + classed(name: string, value: boolean): Update; + + /** + * Determine if the given class list should be toggled for each node in the selection. + * + * @param name The class list. Spaces separate multiple class names. + * @param value The function to run for each node. Should return true to add the class to the node, or false to remove it. + */ + classed(name: string, value: (datum: Datum, index: number, outerIndex: number) => boolean): Update; + + /** + * Set or derive classes for multiple class lists at once. + * + * @param obj An Object mapping class lists to values that are either plain booleans or functions that return booleans. + */ + classed(obj: { [key: string]: boolean | ((datum: Datum, index: number, outerIndex: number) => boolean) }): Update; + + /** + * Retrieve the computed style value for the first node in the selection. + * @param name The CSS property name to query + */ + style(name: string): string; + + /** + * Set a style property for all nodes in the selection. + * @param name the CSS property name + * @param value the property value + * @param priority if specified, either null or the string "important" (no exclamation mark) + */ + style(name: string, value: Primitive, priority?: string): Update; + + /** + * Derive a property value for each node in the selection. + * @param name the CSS property name + * @param value the function to derive the value + * @param priority if specified, either null or the string "important" (no exclamation mark) + */ + style(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive, priority?: string): Update; + + /** + * Set a large number of CSS properties from an object. + * + * @param obj an Object whose keys correspond to CSS property names and values are either constants or functions that derive property values + * @param priority if specified, either null or the string "important" (no exclamation mark) + */ + style(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }, priority?: string): Update; + + /** + * Retrieve an arbitrary node property such as the 'checked' property of checkboxes, or the 'value' of text boxes. + * + * @param name the node's property to retrieve + */ + property(name: string): any; + + /** + * For each node, set the property value. Internally, this sets the node property directly (e.g., node[name] = value), so take care not to mutate special properties like __proto__. + * + * @param name the property name + * @param value the property value + */ + property(name: string, value: any): Update; + + /** + * For each node, derive the property value. Internally, this sets the node property directly (e.g., node[name] = value), so take care not to mutate special properties like __proto__. + * + * @param name the property name + * @param value the function used to derive the property's value + */ + property(name: string, value: (datum: Datum, index: number, outerIndex: number) => any): Update; + + /** + * Set multiple node properties. Caveats apply: take care not to mutate special properties like __proto__. + * + * @param obj an Object whose keys correspond to node properties and values are either constants or functions that will compute a value. + */ + property(obj: { [key: string]: any | ((datum: Datum, index: number, outerIndex: number) => any) }): Update; + + /** + * Retrieve the textContent of the first node in the selection. + */ + text(): string; + + /** + * Set the textContent of each node in the selection. + * @param value the text to use for all nodes + */ + text(value: Primitive): Update; + + /** + * Compute the textContent of each node in the selection. + * @param value the function which will compute the text + */ + text(value: (datum: Datum, index: number, outerIndex: number) => Primitive): Update; + + /** + * Retrieve the HTML content of the first node in the selection. Uses 'innerHTML' internally and will not work with SVG or other elements without a polyfill. + */ + html(): string; + + /** + * Set the HTML content of every node in the selection. Uses 'innerHTML' internally and thus will not work with SVG or other elements without a polyfill. + * @param value the HTML content to use. + */ + html(value: string): Selection; + + /** + * Compute the HTML content for each node in the selection. Uses 'innerHTML' internally and thus will not work with SVG or other elements without a polyfill. + * @param value the function to compute HTML content + */ + html(value: (datum: Datum, index: number, outerIndex: number) => string): Selection; + + /** + * Appends a new child to each node in the selection. This child will inherit the parent's data (if available). Returns a fresh selection consisting of the newly-appended children. + * + * @param name the element name to append. May be prefixed (see d3.ns.prefix). + */ + append(name: string): Selection; + + /** + * Appends a new child to each node in the selection by computing a new node. This child will inherit the parent's data (if available). Returns a fresh selection consisting of the newly-appended children. + * + * @param name the function to compute a new element + */ + append(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; + + /** + * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. + * @param name the element name to append. May be prefixed (see d3.ns.prefix). + * @param before the selector to determine position (e.g., ":first-child") + */ + insert(name: string, before: string): Update; + + /** + * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. + * @param name the element name to append. May be prefixed (see d3.ns.prefix). + * @param before a function to determine the node to use as the next sibling + */ + insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; + + /** + * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. + * @param name the function to compute a new child + * @param before the selector to determine position (e.g., ":first-child") + */ + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: string): Update; + + /** + * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. + * @param name the function to compute a new child + * @param before a function to determine the node to use as the next sibling + */ + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; + + /** + * Removes the elements from the DOM. They are in a detached state and may be re-added (though there is currently no dedicated API for doing so). + */ + remove(): Update; + + /** + * Retrieves the data bound to the first group in this selection. + */ + data(): Datum[]; + + /** + * Binds data to this selection. + * @param data the array of data to bind to this selection + * @param key the optional function to determine the unique key for each piece of data. When unspecified, uses the index of the element. + */ + data(data: NewDatum[], key?: (datum: NewDatum, index: number, outerIndex: number) => string): Update; + + /** + * Derives data to bind to this selection. + * @param data the function to derive data. Must return an array. + * @param key the optional function to determine the unique key for each data item. When unspecified, uses the index of the element. + */ + data(data: (datum: Datum, index: number, outerIndex: number) => NewDatum[], key?: (datum: NewDatum, index: number, outerIndex: number) => string): Update; + + /** + * Filters the selection, returning only those nodes that match the given CSS selector. + * @param selector the CSS selector + */ + filter(selector: string): Update; + + /** + * Filters the selection, returning only those nodes for which the given function returned true. + * @param selector the filter function + */ + filter(selector: (datum: Datum, index: number, outerIndex: number) => boolean): Update; + + /** + * Return the data item bound to the first element in the selection. + */ + datum(): Datum; + + /** + * Derive the data item for each node in the selection. Useful for situations such as the HTML5 'dataset' attribute. + * @param value the function to compute data for each node + */ + datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update; + + /** + * Set the data item for each node in the selection. + * @param value the constant element to use for each node + */ + datum(value: NewDatum): Update; + + /** + * Reorders nodes in the selection based on the given comparator. Nodes are re-inserted into the document once sorted. + * @param comparator the comparison function, which defaults to d3.ascending + */ + sort(comparator?: (a: Datum, b: Datum) => number): Update; + + /** + * Reorders nodes in the document to match the selection order. More efficient than calling sort() if the selection is already ordered. + */ + order(): Update; + + /** + * Returns the listener (if any) for the given event. + * @param type the type of event to load the listener for. May have a namespace (e.g., ".foo") at the end. + */ + on(type: string): (datum: Datum, index: number, outerIndex: number) => any; + + /** + * Adds a listener for the specified event. If one was already registered, it is removed before the new listener is added. The return value of the listener function is ignored. + * @param type the of event to listen to. May have a namespace (e.g., ".foo") at the end. + * @param listener an event listener function, or null to unregister + * @param capture sets the DOM useCapture flag + */ + on(type: string, listener: (datum: Datum, index: number, outerIndex: number) => any, capture?: boolean): Update; + + /** + * Begins a new transition. Interrupts any active transitions of the same name. + * @param name the transition name (defaults to "") + */ + transition(name?: string): Transition; + + /** + * Interrupts the active transition of the provided name. Does not cancel scheduled transitions. + * @param name the transition name (defaults to "") + */ + interrupt(name?: string): Update; + + /** + * Creates a subselection by finding the first descendent matching the selector string. Bound data is inherited. + * @param selector the CSS selector to match against + */ + select(selector: string): Update; + + /** + * Creates a subselection by using a function to find descendent elements. Bound data is inherited. + * @param selector the function to find matching descendants + */ + select(selector: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; + + /** + * Creates a subselection by finding all descendents that match the given selector. Bound data is not inherited. + * @param selector the CSS selector to match against + */ + selectAll(selector: string): Update; + + /** + * Creates a subselection by using a function to find descendent elements. Bound data is not inherited. + * @param selector the function to find matching descendents + */ + selectAll(selector: (datum: Datum, index: number, outerIndex: number) => Array | NodeList): Update; + + /** + * Invoke the given function for each element in the selection. The return value of the function is ignored. + * @param func the function to invoke + */ + each(func: (datum: Datum, index: number, outerIndex: number) => any): Update; + + /** + * Call a function on the selection. sel.call(foo) is equivalent to foo(sel). + * @param func the function to call on the selection + * @param args any optional args + */ + call(func: (sel: Update, ...args: any[]) => any, ...args: any[]): Update; + + /** + * Returns true if the current selection is empty. + */ + empty(): boolean; + + /** + * Returns the first non-null element in the selection, or null otherwise. + */ + node(): Node; + + /** + * Returns the total number of elements in the selection. + */ + size(): number; + + /** + * Returns the placeholder nodes for each data element for which no corresponding DOM element was found. + */ + enter(): Enter; + + /** + * Returns a selection for those DOM nodes for which no new data element was found. + */ + exit(): Selection; + } + + interface Enter { + append(name: string): Selection; + append(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + + insert(name: string, before?: string): Selection; + insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: string): Selection; + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + + select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + call(func: (selection: Enter, ...args: any[]) => any, ...args: any[]): Enter; + + empty(): boolean; + size(): number; + } + } + + /** + * Administrivia: JavaScript primitive types, or "things that toString() predictably". + */ + export type Primitive = number | string | boolean; + + /** + * Administrivia: anything with a valueOf(): number method is comparable, so we allow it in numeric operations + */ + interface Numeric { + valueOf(): number; + } + + /** + * A grouped array of nodes. + * @param Datum the data bound to this selection. + */ + interface Selection { + /** + * Retrieve a grouped selection. + */ + [index: number]: selection.Group; + + /** + * The number of groups in this selection. + */ + length: number; + + /** + * Retrieve the value of the given attribute for the first node in the selection. + * + * @param name The attribute name to query. May be prefixed (see d3.ns.prefix). + */ + attr(name: string): string; + + /** + * For all nodes, set the attribute to the specified constant value. Use null to remove. + * + * @param name The attribute name, optionally prefixed. + * @param value The attribute value to use. Note that this is coerced to a string automatically. + */ + attr(name: string, value: Primitive): Selection; + + /** + * Derive an attribute value for each node in the selection based on bound data. + * + * @param name The attribute name, optionally prefixed. + * @param value The function of the datum (the bound data item), index (the position in the subgrouping), and outer index (overall position in nested selections) which computes the attribute value. If the function returns null, the attribute is removed. + */ + attr(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive): Selection; + + /** + * Set multiple properties at once using an Object. D3 iterates over all enumerable properties and either sets or computes the attribute's value based on the corresponding entry in the Object. + * + * @param obj A key-value mapping corresponding to attributes and values. If the value is a simple string or number, it is taken as a constant. Otherwise, it is a function that derives the attribute value. + */ + attr(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }): Selection; + + /** + * Returns true if the first node in this selection has the given class list. If multiple classes are specified (i.e., "foo bar"), then returns true only if all classes match. + * + * @param name The class list to query. + */ + classed(name: string): boolean; + + /** + * Adds (or removes) the given class list. + * + * @param name The class list to toggle. Spaces separate class names: "foo bar" is a list of two classes. + * @param value If true, add the classes. If false, remove them. + */ + classed(name: string, value: boolean): Selection; + + /** + * Determine if the given class list should be toggled for each node in the selection. + * + * @param name The class list. Spaces separate multiple class names. + * @param value The function to run for each node. Should return true to add the class to the node, or false to remove it. + */ + classed(name: string, value: (datum: Datum, index: number, outerIndex: number) => boolean): Selection; + + /** + * Set or derive classes for multiple class lists at once. + * + * @param obj An Object mapping class lists to values that are either plain booleans or functions that return booleans. + */ + classed(obj: { [key: string]: boolean | ((datum: Datum, index: number, outerIndex: number) => boolean) }): Selection; + + /** + * Retrieve the computed style value for the first node in the selection. + * @param name The CSS property name to query + */ + style(name: string): string; + + /** + * Set a style property for all nodes in the selection. + * @param name the CSS property name + * @param value the property value + * @param priority if specified, either null or the string "important" (no exclamation mark) + */ + style(name: string, value: Primitive, priority?: string): Selection; + + /** + * Derive a property value for each node in the selection. + * @param name the CSS property name + * @param value the function to derive the value + * @param priority if specified, either null or the string "important" (no exclamation mark) + */ + style(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive, priority?: string): Selection; + + /** + * Set a large number of CSS properties from an object. + * + * @param obj an Object whose keys correspond to CSS property names and values are either constants or functions that derive property values + * @param priority if specified, either null or the string "important" (no exclamation mark) + */ + style(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }, priority?: string): Selection; + + /** + * Retrieve an arbitrary node property such as the 'checked' property of checkboxes, or the 'value' of text boxes. + * + * @param name the node's property to retrieve + */ + property(name: string): any; + + /** + * For each node, set the property value. Internally, this sets the node property directly (e.g., node[name] = value), so take care not to mutate special properties like __proto__. + * + * @param name the property name + * @param value the property value + */ + property(name: string, value: any): Selection; + + /** + * For each node, derive the property value. Internally, this sets the node property directly (e.g., node[name] = value), so take care not to mutate special properties like __proto__. + * + * @param name the property name + * @param value the function used to derive the property's value + */ + property(name: string, value: (datum: Datum, index: number, outerIndex: number) => any): Selection; + + /** + * Set multiple node properties. Caveats apply: take care not to mutate special properties like __proto__. + * + * @param obj an Object whose keys correspond to node properties and values are either constants or functions that will compute a value. + */ + property(obj: { [key: string]: any | ((datum: Datum, index: number, innerInder: number) => any) }): Selection; + + /** + * Retrieve the textContent of the first node in the selection. + */ + text(): string; + + /** + * Set the textContent of each node in the selection. + * @param value the text to use for all nodes + */ + text(value: Primitive): Selection; + + /** + * Compute the textContent of each node in the selection. + * @param value the function which will compute the text + */ + text(value: (datum: Datum, index: number, outerIndex: number) => Primitive): Selection; + + /** + * Retrieve the HTML content of the first node in the selection. Uses 'innerHTML' internally and will not work with SVG or other elements without a polyfill. + */ + html(): string; + + /** + * Set the HTML content of every node in the selection. Uses 'innerHTML' internally and thus will not work with SVG or other elements without a polyfill. + * @param value the HTML content to use. + */ + html(value: string): Selection; + + /** + * Compute the HTML content for each node in the selection. Uses 'innerHTML' internally and thus will not work with SVG or other elements without a polyfill. + * @param value the function to compute HTML content + */ + html(value: (datum: Datum, index: number, outerIndex: number) => string): Selection; + + /** + * Appends a new child to each node in the selection. This child will inherit the parent's data (if available). Returns a fresh selection consisting of the newly-appended children. + * + * @param name the element name to append. May be prefixed (see d3.ns.prefix). + */ + append(name: string): Selection; + + /** + * Appends a new child to each node in the selection by computing a new node. This child will inherit the parent's data (if available). Returns a fresh selection consisting of the newly-appended children. + * + * @param name the function to compute a new element + */ + append(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + + /** + * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. + * @param name the element name to append. May be prefixed (see d3.ns.prefix). + * @param before the selector to determine position (e.g., ":first-child") + */ + insert(name: string, before: string): Selection; + + /** + * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. + * @param name the element name to append. May be prefixed (see d3.ns.prefix). + * @param before a function to determine the node to use as the next sibling + */ + insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + + /** + * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. + * @param name the function to compute a new child + * @param before the selector to determine position (e.g., ":first-child") + */ + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: string): Selection; + + /** + * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. + * @param name the function to compute a new child + * @param before a function to determine the node to use as the next sibling + */ + insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + + /** + * Removes the elements from the DOM. They are in a detached state and may be re-added (though there is currently no dedicated API for doing so). + */ + remove(): Selection; + + /** + * Retrieves the data bound to the first group in this selection. + */ + data(): Datum[]; + + /** + * Binds data to this selection. + * @param data the array of data to bind to this selection + * @param key the optional function to determine the unique key for each piece of data. When unspecified, uses the index of the element. + */ + data(data: NewDatum[], key?: (datum: NewDatum, index: number, outerIndex: number) => string): selection.Update; + + /** + * Derives data to bind to this selection. + * @param data the function to derive data. Must return an array. + * @param key the optional function to determine the unique key for each data item. When unspecified, uses the index of the element. + */ + data(data: (datum: Datum, index: number, outerIndex: number) => NewDatum[], key?: (datum: NewDatum, index: number, outerIndex: number) => string): selection.Update; + + /** + * Filters the selection, returning only those nodes that match the given CSS selector. + * @param selector the CSS selector + */ + filter(selector: string): Selection; + + /** + * Filters the selection, returning only those nodes for which the given function returned true. + * @param selector the filter function + */ + filter(selector: (datum: Datum, index: number, outerIndex: number) => boolean): Selection; + + /** + * Return the data item bound to the first element in the selection. + */ + datum(): Datum; + + /** + * Derive the data item for each node in the selection. Useful for situations such as the HTML5 'dataset' attribute. + * @param value the function to compute data for each node + */ + datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Selection; + + /** + * Set the data item for each node in the selection. + * @param value the constant element to use for each node + */ + datum(value: NewDatum): Selection; + + /** + * Reorders nodes in the selection based on the given comparator. Nodes are re-inserted into the document once sorted. + * @param comparator the comparison function, which defaults to d3.ascending + */ + sort(comparator?: (a: Datum, b: Datum) => number): Selection; + + /** + * Reorders nodes in the document to match the selection order. More efficient than calling sort() if the selection is already ordered. + */ + order(): Selection; + + /** + * Returns the listener (if any) for the given event. + * @param type the type of event to load the listener for. May have a namespace (e.g., ".foo") at the end. + */ + on(type: string): (datum: Datum, index: number, outerIndex: number) => any; + + /** + * Adds a listener for the specified event. If one was already registered, it is removed before the new listener is added. The return value of the listener function is ignored. + * @param type the of event to listen to. May have a namespace (e.g., ".foo") at the end. + * @param listener an event listener function, or null to unregister + * @param capture sets the DOM useCapture flag + */ + on(type: string, listener: (datum: Datum, index: number, outerIndex: number) => any, capture?: boolean): Selection; + + /** + * Begins a new transition. Interrupts any active transitions of the same name. + * @param name the transition name (defaults to "") + */ + transition(name?: string): Transition; + + /** + * Interrupts the active transition of the provided name. Does not cancel scheduled transitions. + * @param name the transition name (defaults to "") + */ + interrupt(name?: string): Selection; + + /** + * Creates a subselection by finding the first descendent matching the selector string. Bound data is inherited. + * @param selector the CSS selector to match against + */ + select(selector: string): Selection; + + /** + * Creates a subselection by using a function to find descendent elements. Bound data is inherited. + * @param selector the function to find matching descendants + */ + select(selector: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; + + /** + * Creates a subselection by finding all descendents that match the given selector. Bound data is not inherited. + * @param selector the CSS selector to match against + */ + selectAll(selector: string): Selection; + + /** + * Creates a subselection by finding all descendants that match the given selector. Bound data is not inherited. + * + * Use this overload when data-binding a subselection (that is, sel.selectAll('.foo').data(d => ...)). The type will carry over. + */ + selectAll(selector: string): Selection; + + /** + * Creates a subselection by using a function to find descendent elements. Bound data is not inherited. + * @param selector the function to find matching descendents + */ + selectAll(selector: (datum: Datum, index: number, outerIndex: number) => Array | NodeList): Selection; + + /** + * Creates a subselection by using a function to find descendent elements. Bound data is not inherited. + * + * Use this overload when data-binding a subselection (that is, sel.selectAll('.foo').data(d => ...)). The type will carry over. + * @param selector the function to find matching descendents + */ + selectAll(selector: (datum: Datum, index: number, outerIndex: number) => Array | NodeList): Selection; + + /** + * Invoke the given function for each element in the selection. The return value of the function is ignored. + * @param func the function to invoke + */ + each(func: (datum: Datum, index: number, outerIndex: number) => any): Selection; + + /** + * Call a function on the selection. sel.call(foo) is equivalent to foo(sel). + * @param func the function to call on the selection + * @param args any optional args + */ + call(func: (sel: Selection, ...args: any[]) => any, ...args: any[]): Selection; + + /** + * Returns true if the current selection is empty. + */ + empty(): boolean; + + /** + * Returns the first non-null element in the selection, or null otherwise. + */ + node(): Node; + + /** + * Returns the total number of elements in the selection. + */ + size(): number; + } + + export function transition(): Transition; + namespace transition { + export var prototype: Transition; + } + + interface Transition { + + transition(): Transition; + + delay(): number; + delay(delay: number): Transition; + delay(delay: (datum: Datum, index: number, outerIndex: number) => number): Transition; + + duration(): number; + duration(duration: number): Transition; + duration(duration: (datum: Datum, index: number, outerIndex: number) => number): Transition; + + ease(): (t: number) => number; + ease(value: string, ...args: any[]): Transition; + ease(value: (t: number) => number): Transition; + + attr(name: string, value: Primitive): Transition; + attr(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive): Transition; + attr(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }): Transition; + + attrTween(name: string, tween: (datum: Datum, index: number, attr: string) => (t: number) => Primitive): Transition; + + style(name: string, value: Primitive, priority?: string): Transition; + style(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive, priority?: string): Transition; + style(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }, priority?: string): Transition; + + styleTween(name: string, tween: (datum: Datum, index: number, attr: string) => (t: number) => Primitive, priority?: string): Transition; + + text(value: Primitive): Transition; + text(value: (datum: Datum, index: number, outerIndex: number) => Primitive): Transition; + + tween(name: string, factory: () => (t: number) => any): Transition; + + remove(): Transition; + + select(selector: string): Transition; + select(selector: (d: Datum, i: number) => EventTarget): Transition; + + selectAll(selector: string): Transition; + selectAll(selector: (d: Datum, i: number) => EventTarget[]): Transition; + + filter(selector: string): Transition; + filter(selector: (d: Datum, i: number) => boolean): Transition; + + each(type: string, listener: (d: Datum, i: number) => any): Transition; + each(listener: (d: Datum, i: number) => any): Transition; + + call(func: (transition: Transition, ...args: any[]) => any, ...args: any[]): Transition; + + empty(): boolean; + node(): Node; + size(): number; + } + + export function ease(type: 'linear'): (t: number) => number; + export function ease(type: 'linear-in'): (t: number) => number; + export function ease(type: 'linear-out'): (t: number) => number; + export function ease(type: 'linear-in-out'): (t: number) => number; + export function ease(type: 'linear-out-in'): (t: number) => number; + + export function ease(type: 'poly', k: number): (t: number) => number; + export function ease(type: 'poly-in', k: number): (t: number) => number; + export function ease(type: 'poly-out', k: number): (t: number) => number; + export function ease(type: 'poly-in-out', k: number): (t: number) => number; + export function ease(type: 'poly-out-in', k: number): (t: number) => number; + + export function ease(type: 'quad'): (t: number) => number; + export function ease(type: 'quad-in'): (t: number) => number; + export function ease(type: 'quad-out'): (t: number) => number; + export function ease(type: 'quad-in-out'): (t: number) => number; + export function ease(type: 'quad-out-in'): (t: number) => number; + + export function ease(type: 'cubic'): (t: number) => number; + export function ease(type: 'cubic-in'): (t: number) => number; + export function ease(type: 'cubic-out'): (t: number) => number; + export function ease(type: 'cubic-in-out'): (t: number) => number; + export function ease(type: 'cubic-out-in'): (t: number) => number; + + export function ease(type: 'sin'): (t: number) => number; + export function ease(type: 'sin-in'): (t: number) => number; + export function ease(type: 'sin-out'): (t: number) => number; + export function ease(type: 'sin-in-out'): (t: number) => number; + export function ease(type: 'sin-out-in'): (t: number) => number; + + export function ease(type: 'circle'): (t: number) => number; + export function ease(type: 'circle-in'): (t: number) => number; + export function ease(type: 'circle-out'): (t: number) => number; + export function ease(type: 'circle-in-out'): (t: number) => number; + export function ease(type: 'circle-out-in'): (t: number) => number; + + export function ease(type: 'elastic', a?: number, b?: number): (t: number) => number; + export function ease(type: 'elastic-in', a?: number, b?: number): (t: number) => number; + export function ease(type: 'elastic-out', a?: number, b?: number): (t: number) => number; + export function ease(type: 'elastic-in-out', a?: number, b?: number): (t: number) => number; + export function ease(type: 'elastic-out-in', a?: number, b?: number): (t: number) => number; + + export function ease(type: 'back', s: number): (t: number) => number; + export function ease(type: 'back-in', s: number): (t: number) => number; + export function ease(type: 'back-out', s: number): (t: number) => number; + export function ease(type: 'back-in-out', s: number): (t: number) => number; + export function ease(type: 'back-out-in', s: number): (t: number) => number; + + export function ease(type: 'bounce'): (t: number) => number; + export function ease(type: 'bounce-in'): (t: number) => number; + export function ease(type: 'bounce-out'): (t: number) => number; + export function ease(type: 'bounce-in-out'): (t: number) => number; + export function ease(type: 'bounce-out-in'): (t: number) => number; + + export function ease(type: string, ...args: any[]): (t: number) => number; + + export function timer(func: () => any, delay?: number, time?: number): void; + + namespace timer { + export function flush(): void; + } + + interface BaseEvent { + type: string; + sourceEvent?: Event; + } + + /** + * Define a D3-specific ZoomEvent per https://github.com/mbostock/d3/wiki/Zoom-Behavior#event + */ + interface ZoomEvent extends BaseEvent { + scale: number; + translate: [number, number]; + } + + /** + * Define a D3-specific DragEvent per https://github.com/mbostock/d3/wiki/Drag-Behavior#on + */ + interface DragEvent extends BaseEvent { + x: number; + y: number; + dx: number; + dy: number; + } + + /** + * The current event's value. Use this variable in a handler registered with `selection.on`. + */ + export var event: Event | BaseEvent; + + /** + * Returns the x and y coordinates of the mouse relative to the provided container element, using d3.event for the mouse's position on the page. + * @param container the container element (e.g. an SVG element) + */ + export function mouse(container: EventTarget): [number, number]; + + /** + * Given a container element and a touch identifier, determine the x and y coordinates of the touch. + * @param container the container element (e.g., an SVG element) + * @param identifier the given touch identifier + */ + export function touch(container: EventTarget, identifer: number): [number, number]; + + /** + * Given a container element, a list of touches, and a touch identifier, determine the x and y coordinates of the touch. + * @param container the container element (e.g., an SVG element) + * @param identifier the given touch identifier + */ + export function touch(container: EventTarget, touches: TouchList, identifer: number): [number, number]; + + /** + * Given a container element and an optional list of touches, return the position of every touch relative to the container. + * @param container the container element + * @param touches an optional list of touches (defaults to d3.event.touches) + */ + export function touches(container: EventTarget, touches?: TouchList): Array<[number, number]>; + + // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. + /** + * Compares two primitive values for sorting (in ascending order). + */ + export function ascending(a: Primitive, b: Primitive): number; + + /** + * Compares two primitive values for sorting (in ascending order). + */ + export function descending(a: Primitive, b: Primitive): number; + + /** + * Return the minimum value in the array using natural order. + */ + export function min(array: number[]): number; + + /** + * Return the minimum value in the array using natural order. + */ + export function min(array: string[]): string; + + /** + * Return the minimum value in the array using natural order. + */ + export function min(array: T[]): T; + + /** + * Return the minimum value in the array using natural order. + */ + export function min(array: T[], accessor: (datum: T, index: number) => number): number; + + /** + * Return the minimum value in the array using natural order. + */ + export function min(array: T[], accessor: (datum: T, index: number) => string): string; + + /** + * Return the minimum value in the array using natural order. + */ + export function min(array: T[], accessor: (datum: T, index: number) => U): U; + + /** + * Return the maximum value in the array of numbers using natural order. + */ + export function max(array: number[]): number; + + /** + * Return the maximum value in the array of strings using natural order. + */ + export function max(array: string[]): string; + + /** + * Return the maximum value in the array of numbers using natural order. + */ + export function max(array: T[]): T; + + /** + * Return the maximum value in the array using natural order and a projection function to map values to numbers. + */ + export function max(array: T[], accessor: (datum: T, index: number) => number): number; + + /** + * Return the maximum value in the array using natural order and a projection function to map values to strings. + */ + export function max(array: T[], accessor: (datum: T, index: number) => string): string; + + /** + * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. + */ + export function max(array: T[], accessor: (datum: T, index: number) => U): U; + + /** + * Return the min and max simultaneously. + */ + export function extent(array: number[]): [number, number]; + + /** + * Return the min and max simultaneously. + */ + export function extent(array: string[]): [string, string]; + + /** + * Return the min and max simultaneously. + */ + export function extent(array: T[]): [T, T]; + + /** + * Return the min and max simultaneously. + */ + export function extent(array: Array): [T | Primitive, T | Primitive]; + + /** + * Return the min and max simultaneously. + */ + export function extent(array: T[], accessor: (datum: T, index: number) => number): [number, number]; + + /** + * Return the min and max simultaneously. + */ + export function extent(array: T[], accessor: (datum: T, index: number) => string): [string, string]; + + /** + * Return the min and max simultaneously. + */ + export function extent(array: T[], accessor: (datum: T, index: number) => Date): [Date, Date]; + + /** + * Return the min and max simultaneously. + */ + export function extent(array: T[], accessor: (datum: T, index: number) => U): [U | Primitive, U | Primitive]; + + /** + * Compute the sum of an array of numbers. + */ + export function sum(array: number[]): number; + + /** + * Compute the sum of an array, using the given accessor to convert values to numbers. + */ + export function sum(array: T[], accessor: (datum: T, index: number) => number): number; + + export function mean(array: number[]): number; + export function mean(array: T[], accessor: (datum: T, index: number) => number): number; + + /** + * Compute the median of an array of numbers (the 0.5-quantile). + */ + export function median(array: number[]): number; + export function median(datum: T[], accessor: (datum: T, index: number) => number): number; + + export function quantile(array: number[], p: number): number; + + export function variance(array: number[]): number; + export function variance(array: T[], accessor: (datum: T, index: number) => number): number; + + export function deviation(array: number[]): number; + export function deviation(array: T[], accessor: (datum: T, index: number) => number): number; + + export function bisectLeft(array: T[], x: T, lo?: number, hi?: number): number; + + export var bisect: typeof bisectRight; + + export function bisectRight(array: T[], x: T, lo?: number, hi?: number): number; + + export function bisector(accessor: (x: T) => U): { + left: (array: T[], x: U, lo?: number, hi?: number) => number; + right: (array: T[], x: U, lo?: number, hi?: number) => number; + } + + export function bisector(comparator: (a: T, b: U) => number): { + left: (array: T[], x: U, lo?: number, hi?: number) => number; + right: (array: T[], x: U, lo?: number, hi?: number) => number; + } + + export function shuffle(array: T[], lo?: number, hi?: number): T[]; + + /** + * Returns the enumerable property names of the specified object. + * @param object a JavaScript object + */ + export function keys(object: Object): string[]; + + /** + * Returns an array containing the property values of the specified object. + */ + export function values(object: { [key: string]: T }): T[]; + /** + * Returns an array containing the property values of the specified object. + */ + export function values(object: { [key: number]: T }): T[]; + /** + * Returns an array containing the property values of the specified object. + */ + export function values(object: Object): any[]; + + /** + * Returns an array of key-value pairs containing the property values of the specified object. + */ + export function entries(object: { [key: string]: T }): { key: string; value: T }[]; + + /** + * Returns an array of key-value pairs containing the property values of the specified object. + */ + export function entries(object: { [key: number]: T }): { key: string; value: T }[]; + + /** + * Returns an array of key-value pairs containing the property values of the specified object. + */ + export function entries(object: Object): { key: string; value: any }[]; + + /** + * A shim for ES6 maps. The implementation uses a JavaScript object internally, and thus keys are limited to strings. + */ + interface Map { + /** + * Does the map contain the given key? + */ + has(key: string): boolean; + + /** + * Retrieve the value for the given key. Returns undefined if there is no value stored. + */ + get(key: string): T; + + /** + * Set the value for the given key. Returns the new value. + */ + set(key: string, value: T): T; + + /** + * Remove the value for the given key. Returns true if there was a value and false otherwise. + */ + remove(key: string): boolean; + + /** + * Returns an array of all keys in arbitrary order. + */ + keys(): string[]; + + /** + * Returns an array of all values in arbitrary order. + */ + values(): T[]; + + /** + * Returns an array of key-value objects in arbitrary order. + */ + entries(): { key: string; value: T }[]; + + /** + * Calls the function for each key and value pair in the map. The 'this' context is the map itself. + */ + forEach(func: (key: string, value: T) => any): void; + + /** + * Is this map empty? + */ + empty(): boolean; + + /** + * Returns the number of elements stored in the map. + */ + size(): number; + } + + /** + * Constructs an initially empty map. + */ + export function map(): Map; + + /** + * Construct a new map by copying keys and values from the given one. + */ + export function map(object: Map): Map; + + /** + * Construct a new map by copying enumerable properties and values from the given object. + */ + export function map(object: { [key: string]: T }): Map; + + /** + * Construct a new map by copying enumerable properties and values from the given object. + */ + export function map(object: { [key: number]: T }): Map; + + /** + * Construct a new map by copying elements from the array. The key function is used to identify each object. + */ + export function map(array: T[], key: (datum: T, index: number) => string): Map; + + /** + * Construct a new map by copying enumerable properties and values from the given object. + */ + export function map(object: Object): Map; + + /** + * A shim for ES6 sets. Is only able to store strings. + */ + interface Set { + /** + * Is the given string stored in this set? + */ + has(value: string): boolean; + + /** + * Add the string to this set. Returns the value. + */ + add(value: string): string; + + /** + * Remove the given value from the set. Returns true if it was stored, and false otherwise. + */ + remove(value: string): boolean; + + /** + * Returns an array of the strings stored in this set. + */ + values(): string[]; + + /** + * Calls a given function for each value in the set. The return value of the function is ignored. The this context of the function is the set itself. + */ + forEach(func: (value: string) => any): void; + + /** + * Is this set empty? + */ + empty(): boolean; + + /** + * Returns the number of values stored in this set. + */ + size(): number; + } + + /** + * Creates an initially-empty set. + */ + export function set(): Set; + + /** + * Initializes a set from the given array of strings. + */ + export function set(array: string[]): Set; + + /** + * Merges the specified arrays into a single array. + */ + export function merge(arrays: T[][]): T[]; + + /** + * Generates a 0-based numeric sequence. The output range does not include 'stop'. + */ + export function range(stop: number): number[]; + + /** + * Generates a numeric sequence starting from the given start and stop values. 'step' defaults to 1. The output range does not include 'stop'. + */ + export function range(start: number, stop: number, step?: number): number[]; + + /** + * Given the specified array, return an array corresponding to the list of indices in 'keys'. + */ + export function permute(array: { [key: number]: T }, keys: number[]): T[]; + + /** + * Given the specified object, return an array corresponding to the list of property names in 'keys'. + */ + export function permute(object: { [key: string]: T }, keys: string[]): T[]; + + // TODO construct n-tuples from n input arrays + export function zip(...arrays: T[][]): T[][]; + + export function transpose(matrix: T[][]): T[][]; + + /** + * For each adjacent pair of elements in the specified array, returns a new array of tuples of elements i and i - 1. + * Returns the empty array if the input array has fewer than two elements. + */ + export function pairs(array: T[]): Array<[T, T]>; + + interface Nest { + key(func: (datum: T) => string): Nest; + sortKeys(comparator: (a: string, b: string) => number): Nest; + sortValues(comparator: (a: T, b: T) => number): Nest; + rollup(func: (values: T[]) => U): Nest; + map(array: T[]): { [key: string]: any }; + map(array: T[], mapType: typeof d3.map): Map; + entries(array: T[]): { key: string; values: any }[]; + } + + export function nest(): Nest; + + export module random { + export function normal(mean?: number, deviation?: number): () => number; + export function logNormal(mean?: number, deviation?: number): () => number; + export function bates(count: number): () => number; + export function irwinHall(count: number): () => number; + } + + interface Transform { + rotate: number; + translate: [number, number]; + skew: number; + scale: [number, number]; + toString(): string; + } + + export function transform(transform: string): Transform; + + export function format(specifier: string): (n: number) => string; + + interface FormatPrefix { + symbol: string; + scale(n: number): number; + } + + export function formatPrefix(value: number, precision?: number): FormatPrefix; + + export function round(x: number, n?: number): number; + + export function requote(string: string): string; + + export var rgb: { + new (r: number, g: number, b: number): Rgb; + new (color: string): Rgb; + + (r: number, g: number, b: number): Rgb; + (color: string): Rgb; + }; + + interface Rgb extends Color { + r: number; + g: number; + b: number; + + brighter(k?: number): Rgb; + darker(k?: number): Rgb; + + hsl(): Hsl; + + toString(): string; + } + + export var hsl: { + new (h: number, s: number, l: number): Hsl; + new (color: string): Hsl; + + (h: number, s: number, l: number): Hsl; + (color: string): Hsl; + }; + + interface Hsl extends Color { + h: number; + s: number; + l: number; + + brighter(k?: number): Hsl; + darker(k?: number): Hsl; + + rgb(): Rgb; + + toString(): string; + } + + export var hcl: { + new (h: number, c: number, l: number): Hcl; + new (color: string): Hcl; + + (h: number, c: number, l: number): Hcl; + (color: string): Hcl; + }; + + interface Hcl extends Color { + h: number; + c: number; + l: number; + + brighter(k?: number): Hcl; + darker(k?: number): Hcl; + } + + export var lab: { + new (l: number, a: number, b: number): Lab; + new (color: string): Lab; + + (l: number, a: number, b: number): Lab; + (color: string): Lab; + } + + interface Lab extends Color { + l: number; + a: number; + b: number; + + brighter(k?: number): Lab; + darker(k?: number): Lab; + + rgb(): Rgb; + toString(): string; + } + + export var color: { + (): Color; + new (): Color; + }; + + interface Color { + rgb(): Rgb; + } + + export module ns { + interface Qualified { + space: string; + local: string; + } + + export var prefix: { [key: string]: string }; + export function qualify(name: string): Qualified | string; + } + + export function functor(value: T): T; + export function functor(value: T): () => T; + + export function rebind(target: {}, source: {}, ...names: string[]): any; + + export function dispatch(...names: string[]): Dispatch; + + interface Dispatch { + on(type: string): (...args: any[]) => void; + on(type: string, listener: (...args: any[]) => any): Dispatch; + [event: string]: (...args: any[]) => void; + } + + export module scale { + export function identity(): Identity; + + interface Identity { + (n: number): number; + invert(n: number): number; + + domain(): number[]; + domain(numbers: number[]): Identity; + + range(): number[]; + range(numbers: number[]): Identity; + + ticks(count?: number): number[]; + + tickFormat(count?: number, format?: string): (n: number) => string; + + copy(): Identity; + } + + export function linear(): Linear; + export function linear(): Linear; + export function linear(): Linear; + + interface Linear { + (x: number): Output; + invert(y: number): number; + + domain(): number[]; + domain(numbers: number[]): Linear; + + range(): Range[]; + range(values: Range[]): Linear; + + rangeRound(values: number[]): Linear; + + interpolate(): (a: Range, b: Range) => (t: number) => Output; + interpolate(factory: (a: Range, b: Range) => (t: number) => Output): Linear; + + clamp(): boolean; + clamp(clamp: boolean): Linear; + + nice(count?: number): Linear; + + ticks(count?: number): number[]; + + tickFormat(count?: number, format?: string): (n: number) => string; + + copy(): Linear; + } + + export function sqrt(): Pow; + export function sqrt(): Pow; + export function sqrt(): Pow; + + export function pow(): Pow; + export function pow(): Pow; + export function pow(): Pow; + + interface Pow { + (x: number): Output; + + invert(y: number): number; + + domain(): number[]; + domain(numbers: number[]): Pow; + + range(): Range[]; + range(values: Range[]): Pow; + + rangeRound(values: number[]): Pow; + + exponent(): number; + exponent(k: number): Pow; + + interpolate(): (a: Range, b: Range) => (t: number) => Output; + interpolate(factory: (a: Range, b: Range) => (t: number) => Output): Pow; + + clamp(): boolean; + clamp(clamp: boolean): Pow; + + nice(m?: number): Pow; + + ticks(count?: number): number[]; + + tickFormat(count?: number, format?: string): (n: number) => string; + + copy(): Pow; + } + + export function log(): Log; + export function log(): Log; + export function log(): Log; + + interface Log { + (x: number): Output; + + invert(y: number): number; + + domain(): number[]; + domain(numbers: number[]): Log; + + range(): Range[]; + range(values: Range[]): Log; + + rangeRound(values: number[]): Log; + + base(): number; + base(base: number): Log; + + interpolate(): (a: Range, b: Range) => (t: number) => Output; + interpolate(factory: (a: Range, b: Range) => (t: number) => Output): Log; + + clamp(): boolean; + clamp(clamp: boolean): Log; + + nice(): Log; + + ticks(): number[]; + + tickFormat(count?: number, format?: string): (t: number) => string; + + copy(): Log; + } + + export function quantize(): Quantize; + + interface Quantize { + (x: number): T; + + invertExtent(y: T): [number, number]; + + domain(): number[]; + domain(numbers: number[]): Quantize; + + range(): T[]; + range(values: T[]): Quantize; + + copy(): Quantize; + } + + export function quantile(): Quantile; + + interface Quantile { + (x: number): T; + + invertExtent(y: T): [number, number]; + + domain(): number[]; + domain(numbers: number[]): Quantile; + + range(): T[]; + range(values: T[]): Quantile; + + quantiles(): number[]; + + copy(): Quantile; + } + + export function threshold(): Threshold; + export function threshold(): Threshold; + + interface Threshold { + (x: number): Range; + + invertExtent(y: Range): [Domain, Domain]; + + domain(): Domain[]; + domain(domain: Domain[]): Threshold; + + range(): Range[]; + range(values: Range[]): Threshold; + + copy(): Threshold; + } + + export function ordinal(): Ordinal; + export function ordinal(): Ordinal; + export function category10(): Ordinal; + export function category10(): Ordinal; + export function category20(): Ordinal; + export function category20(): Ordinal; + export function category20b(): Ordinal; + export function category20b(): Ordinal; + export function category20c(): Ordinal; + export function category20c(): Ordinal; + + interface Ordinal { + (x: Domain): Range; + + domain(): Domain[]; + domain(values: Domain[]): Ordinal; + + range(): Range[]; + range(values: Range[]): Ordinal; + + rangePoints(interval: [number, number], padding?: number): Ordinal; + rangeRoundPoints(interval: [number, number], padding?: number): Ordinal; + + rangeBands(interval: [number, number], padding?: number, outerPadding?: number): Ordinal; + rangeRoundBands(interval: [number, number], padding?: number, outerPadding?: number): Ordinal; + + rangeBand(): number; + rangeExtent(): [number, number]; + + copy(): Ordinal; + } + } + + export function interpolate(a: number, b: number): (t: number) => number; + export function interpolate(a: string, b: string): (t: number) => string; + export function interpolate(a: string | Color, b: Color): (t: number) => string; + export function interpolate(a: Array, b: Color[]): (t: number) => string; + export function interpolate(a: Range[], b: Output[]): (t: number) => Output[]; + export function interpolate(a: Range[], b: Range[]): (t: number) => Output[]; + export function interpolate(a: { [key: string]: string | Color }, b: { [key: string]: Color }): (t: number) => { [key: string]: string }; + export function interpolate(a: { [key: string]: Range }, b: { [key: string]: Output }): (t: number) => { [key: string]: Output }; + export function interpolate(a: { [key: string]: Range }, b: { [key: string]: Range }): (t: number) => { [key: string]: Output }; + + export function interpolateNumber(a: number, b: number): (t: number) => number; + + export function interpolateRound(a: number, b: number): (t: number) => number; + + export function interpolateString(a: string, b: string): (t: number) => string; + + export function interpolateRgb(a: string | Color, b: string | Color): (t: number) => string; + + export function interpolateHsl(a: string | Color, b: string | Color): (t: number) => string; + + export function interpolateLab(a: string | Color, b: string | Color): (t: number) => string; + + export function interpolateHcl(a: string | Color, b: string | Color): (t: number) => string; + + export function interpolateArray(a: Array, b: Color[]): (t: number) => string[]; + export function interpolateArray(a: Range[], b: Range[]): (t: number) => Output[]; + export function interpolateArray(a: Range[], b: Output[]): (t: number) => Output[]; + + export function interpolateObject(a: { [key: string]: string | Color }, b: { [key: string]: Color }): (t: number) => { [key: string]: string }; + export function interpolateObject(a: { [key: string]: Range }, b: { [key: string]: Output }): (t: number) => { [key: string]: Output }; + export function interpolateObject(a: { [key: string]: Range }, b: { [key: string]: Range }): (t: number) => { [key: string]: Output }; + + export function interpolateTransform(a: string | Transform, b: string | Transform): (t: number) => string; + + export function interpolateZoom(a: [number, number, number], b: [number, number, number]): { + (t: number): [number, number, number]; + duration: number; + }; + + export var interpolators: Array<(a: any, b: any) => (t: number) => any>; + + export module time { + export var second: Interval; + export var minute: Interval; + export var hour: Interval; + export var day: Interval; + export var week: Interval; + export var sunday: Interval; + export var monday: Interval; + export var tuesday: Interval; + export var wednesday: Interval; + export var thursday: Interval; + export var friday: Interval; + export var saturday: Interval; + export var month: Interval; + export var year: Interval; + + interface Interval { + (d: Date): Date; + + floor(d: Date): Date; + + round(d: Date): Date; + + ceil(d: Date): Date; + + range(start: Date, stop: Date, step?: number): Date[]; + + offset(date: Date, step: number): Date; + + utc: { + (d: Date): Date; + + floor(d: Date): Date; + + round(d: Date): Date; + + ceil(d: Date): Date; + + range(start: Date, stop: Date, step?: number): Date[]; + + offset(date: Date, step: number): Date; + } + } + + export function seconds(start: Date, stop: Date, step?: number): Date[]; + export function minutes(start: Date, stop: Date, step?: number): Date[]; + export function hours(start: Date, stop: Date, step?: number): Date[]; + export function days(start: Date, stop: Date, step?: number): Date[]; + export function weeks(start: Date, stop: Date, step?: number): Date[]; + export function sundays(start: Date, stop: Date, step?: number): Date[]; + export function mondays(start: Date, stop: Date, step?: number): Date[]; + export function tuesdays(start: Date, stop: Date, step?: number): Date[]; + export function wednesdays(start: Date, stop: Date, step?: number): Date[]; + export function thursdays(start: Date, stop: Date, step?: number): Date[]; + export function fridays(start: Date, stop: Date, step?: number): Date[]; + export function saturdays(start: Date, stop: Date, step?: number): Date[]; + export function months(start: Date, stop: Date, step?: number): Date[]; + export function years(start: Date, stop: Date, step?: number): Date[]; + + export function dayOfYear(d: Date): number; + export function weekOfYear(d: Date): number; + export function sundayOfYear(d: Date): number; + export function mondayOfYear(d: Date): number; + export function tuesdayOfYear(d: Date): number; + export function wednesdayOfYear(d: Date): number; + export function fridayOfYear(d: Date): number; + export function saturdayOfYear(d: Date): number; + + export function format(specifier: string): Format; + + export module format { + export function multi(formats: Array<[string, (d: Date) => boolean|number]>): Format; + export function utc(specifier: string): Format; + namespace utc { + export function multi(formats: Array<[string, (d: Date) => boolean|number]>): Format; + } + + export var iso: Format; + } + + interface Format { + (d: Date): string; + parse(input: string): Date; + } + + export function scale(): Scale; + export function scale(): Scale; + export function scale(): Scale; + + export module scale { + export function utc(): Scale; + export function utc(): Scale; + export function utc(): Scale; + } + + + interface Scale { + (x: Date): Output; + + invert(y: number): Date; + + domain(): Date[]; + domain(dates: number[]): Scale; + domain(dates: Date[]): Scale; + + nice(): Scale; + nice(interval: Interval, step?: number): Scale; + + range(): Range[]; + range(values: Range[]): Scale; + + rangeRound(values: number[]): Scale; + + interpolate(): (a: Range, b: Range) => (t: number) => Output; + interpolate(factory: (a: Range, b: Range) => (t: number) => Output): Scale; + + clamp(): boolean; + clamp(clamp: boolean): Scale; + + ticks(): Date[]; + ticks(interval: Interval, step?: number): Date[]; + ticks(count: number): Date[]; + + tickFormat(count: number): (d: Date) => string; + + copy(): Scale; + } + } + + export module behavior { + export function drag(): Drag; + + interface Drag { + (selection: Selection): void; + + on(type: string): (d: Datum, i: number) => any; + on(type: string, listener: (d: Datum, i: number) => any): Drag; + + origin(): (d: Datum, i: number) => { x: number; y: number }; + origin(accessor: (d: Datum, i: number) => { x: number; y: number }): Drag; + } + + export function zoom(): Zoom; + + namespace zoom { + interface Scale { + domain(): number[]; + domain(values: number[]): Scale; + + invert(y: number): number; + + range(values: number[]): Scale; + range(): number[]; + } + } + + interface Zoom { + (selection: Selection): void; + + translate(): [number, number]; + translate(translate: [number, number]): Zoom; + + scale(): number; + scale(scale: number): Zoom; + + scaleExtent(): [number, number]; + scaleExtent(extent: [number, number]): Zoom; + + center(): [number, number]; + center(center: [number, number]): Zoom; + + size(): [number, number]; + size(size: [number, number]): Zoom; + + x(): zoom.Scale; + x(x: zoom.Scale): Zoom; + + y(): zoom.Scale; + y(y: zoom.Scale): Zoom; + + on(type: string): (d: Datum, i: number) => any; + on(type: string, listener: (d: Datum, i: number) => any): Zoom; + + event(selection: Selection): void; + event(transition: Transition): void; + } + } + + export module geo { + export function path(): Path; + + interface Path { + (feature: any, index?: number): string; + + area(feature: any): number; + + centroid(feature: any): [number, number]; + + bounds(feature: any): [[number, number], [number, number]]; + + projection(): Transform | ((coordinates: [number, number]) => [number, number]); + projection(stream: Transform): Path; + projection(projection: (coordinates: [number, number]) => [number, number]): Path; + + pointRadius(): number | ((datum: any, index: number) => number); + pointRadius(radius: number): Path; + pointRadius(radius: (datum: any, index: number) => number): Path; + + context(): CanvasRenderingContext2D; + context(context: CanvasRenderingContext2D): Path; + } + + export function graticule(): Graticule; + + interface Graticule { + (): any; + + lines(): any[]; + + outline(): any; + + extent(): [[number, number], [number, number]]; + extent(extent: [[number, number], [number, number]]): Graticule; + + majorExtent(): [[number, number], [number, number]]; + majorExtent(extent: [[number, number], [number, number]]): Graticule; + + minorExtent(): [[number, number], [number, number]]; + minorExtent(extent: [[number, number], [number, number]]): Graticule; + + step(): [number, number]; + step(step: [number, number]): Graticule; + + majorStep(): [number, number]; + majorStep(step: [number, number]): Graticule; + + minorStep(): [number, number]; + minorStep(step: [number, number]): Graticule; + + precision(): number; + precision(precision: number): Graticule; + } + + export function circle(): Circle; + + interface Circle { + (...args: any[]): any; + + origin(): [number, number] | ((...args: any[]) => [number, number]); + origin(origin: [number, number]): Circle; + origin(origin: (...args: any[]) => [number, number]): Circle; + + angle(): number; + angle(angle: number): Circle; + + precision(): number; + precision(precision: number): Circle; + } + + export function area(feature: any): number; + export function centroid(feature: any): [number, number]; + export function bounds(feature: any): [[number, number], [number, number]]; + export function distance(a: [number, number], b: [number, number]): number; + export function length(feature: any): number; + export function interpolate(a: [number, number], b: [number, number]): (t: number) => [number, number]; + + export function rotation(rotate: [number, number] | [number, number, number]): Rotation; + + interface Rotation { + (location: [number, number]): [number, number]; + invert(location: [number, number]): [number, number]; + } + + export function stream(object: any, listener: Listener): void; + + interface Listener { + point(x: number, y: number, z: number): void; + lineStart(): void; + lineEnd(): void; + polygonStart(): void; + polygonEnd(): void; + sphere(): void; + } + + export function transform(methods: TransformMethods): Transform; + + interface TransformMethods { + point?(x: number, y: number, z: number): void; + lineStart?(): void; + lineEnd?(): void; + polygonStart?(): void; + polygonEnd?(): void; + sphere?(): void; + } + + interface Transform { + stream(stream: Listener): Listener; + } + + export function clipExtent(): ClipExtent; + + interface ClipExtent extends Transform { + extent(): [[number, number], [number, number]]; + extent(extent: [[number, number], [number, number]]): ClipExtent; + } + + export function projection(raw: RawInvertibleProjection): InvertibleProjection; + export function projection(raw: RawProjection): Projection; + + export function projectionMutator(factory: (...args: any[]) => RawInvertibleProjection): (...args: any[]) => InvertibleProjection; + export function projectionMutator(factory: (...args: any[]) => RawProjection): (...args: any[]) => Projection; + + export function albers(): ConicProjection; + export function albersUsa(): ConicProjection; + export function azimuthalEqualArea(): InvertibleProjection; + namespace azimuthalEqualArea { + export function raw(lambda: number, phi: number): [number, number]; + namespace raw { + export function invert(x: number, y: number): [number, number]; + } + } + + export function azimuthalEquidistant(): InvertibleProjection; + namespace azimuthalEquidistant { + export function raw(lambda: number, phi: number): [number, number]; + namespace raw { + export function invert(x: number, y: number): [number, number]; + } + } + + export function conicConformal(): ConicProjection; + namespace conicConformal { + export function raw(phi0: number, phi1: number): RawInvertibleProjection; + } + + export function conicEqualArea(): ConicProjection; + namespace conicEqualArea { + export function raw(phi0: number, phi1: number): RawInvertibleProjection; + } + + export function conicEquidistant(): ConicProjection; + namespace conicEquidistant { + export function raw(phi0: number, phi1: number): RawInvertibleProjection; + } + + export function equirectangular(): InvertibleProjection; + namespace equirectangular { + export function raw(lambda: number, phi: number): [number, number]; + namespace raw { + export function invert(x: number, y: number): [number, number]; + } + } + + export function gnomonic(): InvertibleProjection; + namespace gnomonic { + export function raw(lambda: number, phi: number): [number, number]; + namespace raw { + export function invert(x: number, y: number): [number, number]; + } + } + + export function mercator(): InvertibleProjection; + namespace mercator { + export function raw(lambda: number, phi: number): [number, number]; + namespace raw { + export function invert(x: number, y: number): [number, number]; + } + } + + export function orthographic(): InvertibleProjection; + namespace orthographic { + export function raw(lambda: number, phi: number): [number, number]; + namespace raw { + export function invert(x: number, y: number): [number, number]; + } + } + + export function stereographic(): InvertibleProjection; + namespace stereographic { + export function raw(lambda: number, phi: number): [number, number]; + namespace raw { + export function invert(x: number, y: number): [number, number]; + } + } + + export function transverseMercator(): InvertibleProjection; + namespace transverseMercator { + export function raw(lambda: number, phi: number): [number, number]; + namespace raw { + export function invert(x: number, y: number): [number, number]; + } + } + + interface Projection { + (location: [number, number]): [number, number]; + + rotate(): [number, number, number]; + rotate(rotation: [number, number, number]): Projection; + + center(): [number, number]; + center(location: [number, number]): Projection; + + translate(): [number, number]; + translate(point: [number, number]): Projection; + + scale(): number; + scale(scale: number): Projection; + + clipAngle(): number; + clipAngle(angle: number): Projection; + + clipExtent(): [[number, number], [number, number]]; + clipExtent(extent: [[number, number], [number, number]]): Projection; + + precision(): number; + precision(precision: number): Projection; + + stream(listener: Listener): Listener; + } + + interface InvertibleProjection extends Projection { + invert(point: [number, number]): [number, number]; + } + + interface ConicProjection extends InvertibleProjection { + parallels(): [number, number]; + parallels(parallels: [number, number]): ConicProjection; + + rotate(): [number, number, number]; + rotate(rotation: [number, number, number]): ConicProjection; + + center(): [number, number]; + center(location: [number, number]): ConicProjection; + + translate(): [number, number]; + translate(point: [number, number]): ConicProjection; + + scale(): number; + scale(scale: number): ConicProjection; + + clipAngle(): number; + clipAngle(angle: number): ConicProjection; + + clipExtent(): [[number, number], [number, number]]; + clipExtent(extent: [[number, number], [number, number]]): ConicProjection; + + precision(): number; + precision(precision: number): ConicProjection; + } + + interface RawProjection { + (lambda: number, phi: number): [number, number]; + } + + interface RawInvertibleProjection extends RawProjection { + invert(x: number, y: number): [number, number]; + } + } + + namespace svg { + export function line(): Line<[number, number]>; + export function line(): Line; + + interface Line { + (data: T[]): string; + + x(): number | ((d: T, i: number) => number); + x(x: number): Line; + x(x: (d: T, i: number) => number): Line; + + y(): number | ((d: T, i: number) => number); + y(x: number): Line; + y(y: (d: T, i: number) => number): Line; + + interpolate(): string | ((points: Array<[number, number]>) => string); + interpolate(interpolate: "linear"): Line; + interpolate(interpolate: "linear-closed"): Line; + interpolate(interpolate: "step"): Line; + interpolate(interpolate: "step-before"): Line; + interpolate(interpolate: "step-after"): Line; + interpolate(interpolate: "basis"): Line; + interpolate(interpolate: "basis-open"): Line; + interpolate(interpolate: "basis-closed"): Line; + interpolate(interpolate: "bundle"): Line; + interpolate(interpolate: "cardinal"): Line; + interpolate(interpolate: "cardinal-open"): Line; + interpolate(interpolate: "cardinal-closed"): Line; + interpolate(interpolate: "monotone"): Line; + interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Line; + + tension(): number; + tension(tension: number): Line; + + defined(): (d: T, i: number) => boolean; + defined(defined: (d: T, i: number) => boolean): Line; + } + + namespace line { + export function radial(): Radial<[number, number]>; + export function radial(): Radial; + + interface Radial { + (data: T[]): string; + + radius(): number | ((d: T, i: number) => number); + radius(radius: number): Radial; + radius(radius: (d: T, i: number) => number): Radial; + + angle(): number | ((d: T, i: number) => number); + angle(angle: number): Radial; + angle(angle: (d: T, i: number) => number): Radial; + + interpolate(): string | ((points: Array<[number, number]>) => string); + interpolate(interpolate: "linear"): Radial; + interpolate(interpolate: "linear-closed"): Radial; + interpolate(interpolate: "step"): Radial; + interpolate(interpolate: "step-before"): Radial; + interpolate(interpolate: "step-after"): Radial; + interpolate(interpolate: "basis"): Radial; + interpolate(interpolate: "basis-open"): Radial; + interpolate(interpolate: "basis-closed"): Radial; + interpolate(interpolate: "bundle"): Radial; + interpolate(interpolate: "cardinal"): Radial; + interpolate(interpolate: "cardinal-open"): Radial; + interpolate(interpolate: "cardinal-closed"): Radial; + interpolate(interpolate: "monotone"): Radial; + interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Radial; + + tension(): number; + tension(tension: number): Radial; + + defined(): (d: T, i: number) => boolean; + defined(defined: (d: T, i: number) => boolean): Radial; + } + } + + export function area(): Area<[number, number]>; + export function area(): Area; + + interface Area { + (data: T[]): string; + + x(): number | ((d: T, i: number) => number); + x(x: number): Area; + x(x: (d: T, i: number) => number): Area; + + x0(): number | ((d: T, i: number) => number); + x0(x0: number): Area; + x0(x0: (d: T, i: number) => number): Area; + + x1(): number | ((d: T, i: number) => number); + x1(x1: number): Area; + x1(x1: (d: T, i: number) => number): Area; + + y(): number | ((d: T, i: number) => number); + y(y: number): Area; + y(y: (d: T, i: number) => number): Area; + + y0(): number | ((d: T, i: number) => number); + y0(y0: number): Area; + y0(y0: (d: T, i: number) => number): Area; + + y1(): number | ((d: T, i: number) => number); + y1(y1: number): Area; + y1(y1: (d: T, i: number) => number): Area; + + interpolate(): string | ((points: Array<[number, number]>) => string); + interpolate(interpolate: "linear"): Area; + interpolate(interpolate: "step"): Area; + interpolate(interpolate: "step-before"): Area; + interpolate(interpolate: "step-after"): Area; + interpolate(interpolate: "basis"): Area; + interpolate(interpolate: "basis-open"): Area; + interpolate(interpolate: "cardinal"): Area; + interpolate(interpolate: "cardinal-open"): Area; + interpolate(interpolate: "monotone"): Area; + interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Area; + + tension(): number; + tension(tension: number): Area; + + defined(): (d: T, i: number) => boolean; + defined(defined: (d: T, i: number) => boolean): Area; + } + + namespace area { + export function radial(): Radial<[number, number]>; + export function radial(): Radial; + + interface Radial { + (data: T[]): string; + + radius(): number | ((d: T, i: number) => number); + radius(radius: number): Radial; + radius(radius: (d: T, i: number) => number): Radial; + + innerRadius(): number | ((d: T, i: number) => number); + innerRadius(innerRadius: number): Radial; + innerRadius(innerRadius: (d: T, i: number) => number): Radial; + + outerRadius(): number | ((d: T, i: number) => number); + outerRadius(outerRadius: number): Radial; + outerRadius(outerRadius: (d: T, i: number) => number): Radial; + + angle(): number | ((d: T, i: number) => number); + angle(angle: number): Radial; + angle(angle: (d: T, i: number) => number): Radial; + + startAngle(): number | ((d: T, i: number) => number); + startAngle(startAngle: number): Radial; + startAngle(startAngle: (d: T, i: number) => number): Radial; + + endAngle(): number | ((d: T, i: number) => number); + endAngle(endAngle: number): Radial; + endAngle(endAngle: (d: T, i: number) => number): Radial; + + interpolate(): string | ((points: Array<[number, number]>) => string); + interpolate(interpolate: "linear"): Radial; + interpolate(interpolate: "step"): Radial; + interpolate(interpolate: "step-before"): Radial; + interpolate(interpolate: "step-after"): Radial; + interpolate(interpolate: "basis"): Radial; + interpolate(interpolate: "basis-open"): Radial; + interpolate(interpolate: "cardinal"): Radial; + interpolate(interpolate: "cardinal-open"): Radial; + interpolate(interpolate: "monotone"): Radial; + interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Radial; + + tension(): number; + tension(tension: number): Radial; + + defined(): (d: T, i: number) => boolean; + defined(defined: (d: T, i: number) => boolean): Radial; + } + } + + export function arc(): Arc; + export function arc(): Arc; + + namespace arc { + interface Arc { + innerRadius: number; + outerRadius: number; + startAngle: number; + endAngle: number; + padAngle: number + } + } + + interface Arc { + (d: T, i?: number): string; + + innerRadius(): (d: T, i: number) => number; + innerRadius(radius: number): Arc; + innerRadius(radius: (d: T, i: number) => number): Arc; + + outerRadius(): (d: T, i: number) => number; + outerRadius(radius: number): Arc; + outerRadius(radius: (d: T, i: number) => number): Arc; + + cornerRadius(): (d: T, i: number) => number; + cornerRadius(radius: number): Arc; + cornerRadius(radius: (d: T, i: number) => number): Arc; + + padRadius(): string | ((d: T, i: number) => number); + padRadius(radius: "auto"): Arc; + padRadius(radius: string): Arc; + padRadius(radius: (d: T, i: number) => number): Arc; + + startAngle(): (d: T, i: number) => number; + startAngle(angle: number): Arc; + startAngle(angle: (d: T, i: number) => number): Arc; + + endAngle(): (d: T, i: number) => number; + endAngle(angle: number): Arc; + endAngle(angle: (d: T, i: number) => number): Arc; + + padAngle(): (d: T, i: number) => number; + padAngle(angle: number): Arc; + padAngle(angle: (d: T, i: number) => number): Arc; + + centroid(d: T, i?: number): [number, number]; + } + + export function symbol(): Symbol<{}>; + export function symbol(): Symbol; + + interface Symbol { + (d: T, i?: number): string; + + type(): (d: T, i: number) => string; + type(type: string): Symbol; + type(type: (d: T, i: number) => string): Symbol; + + size(): (d: T, i: string) => number; + size(size: number): Symbol; + size(size: (d: T, i: number) => number): Symbol; + } + + export var symbolTypes: string[]; + + export function chord(): Chord, chord.Node>; + export function chord(): Chord, Node>; + export function chord(): Chord; + + namespace chord { + interface Link { + source: Node; + target: Node; + } + + interface Node { + radius: number; + startAngle: number; + endAngle: number + } + } + + interface Chord { + (d: Link, i: number): string; + + source(): (d: Link, i: number) => Node; + source(source: Node): Chord; + source(source: (d: Link, i: number) => Node): Chord; + + target(): (d: Link, i: number) => Node; + target(target: Node): Chord; + target(target: (d: Link, i: number) => Node): Chord; + + radius(): (d: Node, i: number) => number; + radius(radius: number): Chord; + radius(radius: (d: Node, i: number) => number): Chord; + + startAngle(): (d: Node, i: number) => number; + startAngle(angle: number): Chord; + startAngle(angle: (d: Node, i: number) => number): Chord; + + endAngle(): (d: Node, i: number) => number; + endAngle(angle: number): Chord; + endAngle(angle: (d: Node, i: number) => number): Chord; + } + + export function diagonal(): Diagonal, diagonal.Node>; + export function diagonal(): Diagonal, Node>; + export function diagonal(): Diagonal; + + namespace diagonal { + interface Link { + source: Node; + target: Node; + } + + interface Node { + x: number; + y: number; + } + } + + interface Diagonal { + (d: Link, i?: number): string; + + source(): (d: Link, i: number) => Node; + source(source: Node): Diagonal; + source(source: (d: Link, i: number) => { x: number; y: number; }): Diagonal; + + target(): (d: Link, i: number) => Node; + target(target: Node): Diagonal; + target(target: (d: Link, i: number) => { x: number; y: number; }): Diagonal; + + projection(): (d: Node, i: number) => [number, number]; + projection(projection: (d: Node, i: number) => [number, number]): Diagonal; + } + + namespace diagonal { + export function radial(): Radial, Node>; + export function radial(): Radial, Node>; + export function radial(): Radial; + + interface Radial { + (d: Link, i: number): string; + + source(): (d: Link, i: number) => Node; + source(source: Node): Radial; + source(source: (d: Link, i: number) => Node): Radial; + + target(): (d: Link, i: number) => Node; + target(target: Node): Radial; + target(target: (d: Link, i: number) => Node): Radial; + + projection(): (d: Node, i: number) => [number, number]; + projection(projection: (d: Node, i: number) => [number, number]): Radial; + } + } + + export function axis(): Axis; + + interface Axis { + (selection: Selection): void; + (selection: Transition): void; + + scale(): any; + scale(scale: any): Axis; + + orient(): string; + orient(orientation: string): Axis; + + ticks(): any[]; + ticks(...args: any[]): Axis; + + tickValues(): any[]; + tickValues(values: any[]): Axis; + + tickSize(): number; + tickSize(size: number): Axis; + tickSize(inner: number, outer: number): Axis; + + innerTickSize(): number; + innerTickSize(size: number): Axis; + + outerTickSize(): number; + outerTickSize(size: number): Axis; + + tickPadding(): number; + tickPadding(padding: number): Axis; + + tickFormat(): (t: any) => string; + tickFormat(format: (t: any) => string): Axis; + tickFormat(format:string): Axis; + } + + export function brush(): Brush; + export function brush(): Brush; + + namespace brush { + interface Scale { + domain(): number[]; + domain(domain: number[]): Scale; + + range(): number[]; + range(range: number[]): Scale; + + invert?(y: number): number; + } + } + + interface Brush { + (selection: Selection): void; + (selection: Transition): void; + + event(selection: Selection): void; + event(selection: Transition): void; + + x(): brush.Scale; + x(x: brush.Scale): Brush; + + y(): brush.Scale; + y(y: brush.Scale): Brush; + + extent(): [number, number] | [[number, number], [number, number]]; + extent(extent: [number, number] | [[number, number], [number, number]]): Brush; + + clamp(): boolean | [boolean, boolean]; + clamp(clamp: boolean | [boolean, boolean]): Brush; + + clear(): void; + + empty(): boolean; + + on(type: 'brushstart'): (datum: T, index: number) => void; + on(type: 'brush'): (datum: T, index: number) => void; + on(type: 'brushend'): (datum: T, index: number) => void; + on(type: string): (datum: T, index: number) => void; + + on(type: 'brushstart', listener: (datum: T, index: number) => void): Brush; + on(type: 'brush', listener: (datum: T, index: number) => void): Brush; + on(type: 'brushend', listener: (datum: T, index: number) => void): Brush; + on(type: string, listener: (datum: T, index: number) => void): Brush; + } + } + + export function xhr(url: string, mimeType?: string, callback?: (err: any, data: any) => void): Xhr; + export function xhr(url: string, callback: (err: any, data: any) => void): Xhr; + + interface Xhr { + header(name: string): string; + header(name: string, value: string): Xhr; + + mimeType(): string; + mimeType(type: string): Xhr; + + responseType(): string; + responseType(type: string): Xhr; + + response(): (request: XMLHttpRequest) => any; + response(value: (request: XMLHttpRequest) => any): Xhr; + + get(callback?: (err: any, data: any) => void): Xhr; + + post(data?: any, callback?: (err: any, data: any) => void): Xhr; + post(callback: (err: any, data: any) => void): Xhr; + + send(method: string, data?: any, callback?: (err: any, data: any) => void): Xhr; + send(method: string, callback: (err: any, data: any) => void): Xhr; + + abort(): Xhr; + + on(type: "beforesend"): (request: XMLHttpRequest) => void; + on(type: "progress"): (request: XMLHttpRequest) => void; + on(type: "load"): (response: any) => void; + on(type: "error"): (err: any) => void; + on(type: string): (...args: any[]) => void; + + on(type: "beforesend", listener: (request: XMLHttpRequest) => void): Xhr; + on(type: "progress", listener: (request: XMLHttpRequest) => void): Xhr; + on(type: "load", listener: (response: any) => void): Xhr; + on(type: "error", listener: (err: any) => void): Xhr; + on(type: string, listener: (...args: any[]) => void): Xhr; + } + + export function text(url: string, mimeType?: string, callback?: (err: any, data: string) => void): Xhr; + export function text(url: string, callback: (err: any, data: string) => void): Xhr; + + export function json(url: string, callback?: (err: any, data: any) => void): Xhr; + + export function xml(url: string, mimeType?: string, callback?: (err: any, data: any) => void): Xhr; + export function xml(url: string, callback: (err: any, data: any) => void): Xhr; + + export function html(url: string, callback?: (err: any, data: DocumentFragment) => void): Xhr; + + export var csv: Dsv; + export var tsv: Dsv; + export function dsv(delimiter: string, mimeType: string): Dsv; + + interface Dsv { + (url: string, callback: (rows: { [key: string]: string }[]) => void): DsvXhr<{ [key: string]: string }>; + (url: string, callback: (error: any, rows: { [key: string]: string }[]) => void): DsvXhr<{ [key: string]: string }>; + (url: string): DsvXhr<{ [key: string]: string }>; + (url: string, accessor: (row: { [key: string]: string }) => T, callback: (rows: T[]) => void): DsvXhr; + (url: string, accessor: (row: { [key: string]: string }) => T, callback: (error: any, rows: T[]) => void): DsvXhr; + (url: string, accessor: (row: { [key: string]: string }) => T): DsvXhr; + + parse(string: string): { [key: string]: string }[]; + parse(string: string, accessor: (row: { [key: string]: string }, index: number) => T): T[]; + + parseRows(string: string): string[][]; + parseRows(string: string, accessor: (row: string[], index: number) => T): T[]; + + format(rows: Object[]): string; + + formatRows(rows: string[][]): string; + } + + interface DsvXhr extends Xhr { + row(): (row: { [key: string]: string }) => T; + row(accessor: (row: { [key: string]: string }) => U): DsvXhr; + + header(name: string): string; + header(name: string, value: string): DsvXhr; + + mimeType(): string; + mimeType(type: string): DsvXhr; + + responseType(): string; + responseType(type: string): DsvXhr; + + response(): (request: XMLHttpRequest) => any; + response(value: (request: XMLHttpRequest) => any): DsvXhr; + + get(callback?: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; + post(data?: any, callback?: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; + post(callback: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; + + send(method: string, data?: any, callback?: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; + send(method: string, callback: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; + + abort(): DsvXhr; + + on(type: "beforesend"): (request: XMLHttpRequest) => void; + on(type: "progress"): (request: XMLHttpRequest) => void; + on(type: "load"): (response: T[]) => void; + on(type: "error"): (err: any) => void; + on(type: string): (...args: any[]) => void; + + on(type: "beforesend", listener: (request: XMLHttpRequest) => void): DsvXhr; + on(type: "progress", listener: (request: XMLHttpRequest) => void): DsvXhr; + on(type: "load", listener: (response: T[]) => void): DsvXhr; + on(type: "error", listener: (err: any) => void): DsvXhr; + on(type: string, listener: (...args: any[]) => void): DsvXhr; + } + + export function locale(definition: LocaleDefinition): Locale; + + interface LocaleDefinition { + decimal: string; + thousands: string; + grouping: number[]; + currency: [string, string]; + dateTime: string; + date: string; + time: string; + periods: [string, string]; + days: [string, string, string, string, string, string, string]; + shortDays: [string, string, string, string, string, string, string]; + months: [string, string, string, string, string, string, string, string, string, string, string, string]; + shortMonths: [string, string, string, string, string, string, string, string, string, string, string, string]; + } + + interface Locale { + numberFormat(specifier: string): (n: number) => string; + timeFormat: { + (specifier: string): time.Format; + utc(specifier: string): time.Format; + multi(formats: Array<[string, (d: Date) => boolean|number]>): time.Format; + } + } + + namespace layout { + export function bundle(): Bundle; + export function bundle(): Bundle + + namespace bundle { + interface Node { + parent: Node; + } + + interface Link { + source: T; + target: T; + } + } + + interface Bundle { + (links: bundle.Link[]): T[][]; + } + + export function chord(): Chord; + + namespace chord { + interface Link { + source: Node; + target: Node; + } + + interface Node { + index: number; + subindex: number; + startAngle: number; + endAngle: number; + value: number; + } + + interface Group { + index: number; + startAngle: number; + endAngle: number; + value: number; + } + } + + interface Chord { + matrix(): number[][]; + matrix(matrix: number[][]): Chord; + + padding(): number; + padding(padding: number): Chord; + + sortGroups(): (a: number, b: number) => number; + sortGroups(comparator: (a: number, b: number) => number): Chord; + + sortSubgroups(): (a: number, b: number) => number; + sortSubgroups(comparator: (a: number, b: number) => number): Chord; + + sortChords(): (a: number, b: number) => number; + sortChords(comparator: (a: number, b: number) => number): Chord; + + chords(): chord.Link[]; + groups(): chord.Group[]; + } + + export function cluster(): Cluster; + export function cluster(): Cluster; + + namespace cluster { + interface Result { + parent?: Result; + children?: Result[]; + depth?: number; + x?: number; + y?: number; + } + + interface Link { + source: T; + target: T; + } + } + + interface Cluster { + (root: T): T[]; + + nodes(root: T): T[]; + + links(nodes: T[]): cluster.Link[]; + + children(): (node: T) => T[]; + children(accessor: (node: T) => T[]): Cluster; + + sort(): (a: T, b: T) => number; + sort(comparator: (a: T, b: T) => number): Cluster; + + separation(): (a: T, b: T) => number; + separation(separation: (a: T, b: T) => number): Cluster; + + size(): [number, number]; + size(size: [number, number]): Cluster; + + nodeSize(): [number, number]; + nodeSize(nodeSize: [number, number]): Cluster; + + value(): (a: T) => number; + value(value: (a: T) => number): Cluster; + } + + export function force(): Force, force.Node>; + export function force(): Force, Node>; + export function force, Node extends force.Node>(): Force; + + namespace force { + interface Link { + source: T; + target: T; + } + + interface Node { + index?: number; + x?: number; + y?: number; + px?: number; + py?: number; + fixed?: boolean; + weight?: number; + } + + interface Event { + type: string; + alpha: number; + } + } + + interface Force, Node extends force.Node> { + size(): [number, number]; + size(size: [number, number]): Force; + + linkDistance(): number | ((link: Link, index: number) => number); + linkDistance(distance: number): Force; + linkDistance(distance: (link: Link, index: number) => number): Force; + + linkStrength(): number | ((link: Link, index: number) => number); + linkStrength(strength: number): Force; + linkStrength(strength: (link: Link, index: number) => number): Force; + + friction(): number; + friction(friction: number): Force; + + charge(): number | ((node: Node, index: number) => number); + charge(charge: number): Force; + charge(charge: (node: Node, index: number) => number): Force; + + chargeDistance(): number; + chargeDistance(distance: number): Force; + + theta(): number; + theta(theta: number): Force; + + gravity(): number; + gravity(gravity: number): Force; + + nodes(): Node[]; + nodes(nodes: Node[]): Force; + + links(): Link[]; + links(links: { source: number; target: number }[]): Force; + links(links: Link[]): Force; + + start(): Force; + + tick(): Force; + + alpha(): number; + alpha(value: number): Force; + + resume(): Force; + + stop(): Force; + + on(type: string): (event: force.Event) => void; + on(type: string, listener: (event: force.Event) => void): Force; + + drag(): behavior.Drag; + drag(selection: Selection): void; + } + + export function hierarchy(): Hierarchy; + export function hierarchy(): Hierarchy; + + namespace hierarchy { + interface Result { + parent?: Result; + children?: Result[]; + value?: number; + depth?: number; + } + } + + interface Hierarchy { + (root: T): T[]; + + children(): (node: T) => T[]; + children(accessor: (node: T) => T[]): Hierarchy; + + sort(): (a: T, b: T) => number; + sort(comparator: (a: T, b: T) => number): Hierarchy; + + value(): (node: T) => number; + value(accessor: (node: T) => number): Hierarchy; + + revalue(root: T): T[]; + } + + export function histogram(): Histogram; + export function histogram(): Histogram; + + namespace histogram { + interface Bin extends Array { + x: number; + dx: number; + y: number; + } + } + + interface Histogram { + (values: T[], index?: number): histogram.Bin[]; + + value(): (datum: T, index: number) => number; + value(value: (datum: T, index: number) => number): Histogram; + + range(): (values: T[], index: number) => [number, number]; + range(range: (values: T[], index: number) => [number, number]): Histogram; + range(range: [number, number]): Histogram; + + bins(): (range: [number, number], values: T[], index: number) => number[]; + bins(count: number): Histogram; + bins(thresholds: number[]): Histogram; + bins(func: (range: [number, number], values: T[], index: number) => number[]): Histogram; + + frequency(): boolean; + frequency(frequency: boolean): Histogram; + } + + export function pack(): Pack; + export function pack(): Pack; + + namespace pack { + interface Node { + parent?: Node; + children?: Node[]; + value?: number; + depth?: number; + x?: number; + y?: number; + r?: number; + } + + interface Link { + source: Node; + target: Node; + } + } + + interface Pack { + (root: T): T[]; + + nodes(root: T): T[]; + + links(nodes: T[]): pack.Link[]; + + children(): (node: T, depth: number) => T[]; + children(children: (node: T, depth: number) => T[]): Pack; + + sort(): (a: T, b: T) => number; + sort(comparator: (a: T, b: T) => number): Pack; + + value(): (node: T) => number; + value(value: (node: T) => number): Pack; + + size(): [number, number]; + size(size: [number, number]): Pack; + + radius(): number | ((node: T) => number); + radius(radius: number): Pack; + radius(radius: (node: T) => number): Pack; + + padding(): number; + padding(padding: number): Pack; + } + + export function partition(): Partition; + export function partition(): Partition; + + namespace partition { + interface Link { + source: T; + target: T; + } + + interface Node { + parent?: Node; + children?: number; + value?: number; + depth?: number; + x?: number; + y?: number; + dx?: number; + dy?: number; + } + + } + + export interface Partition { + (root: T): T[]; + + nodes(root: T): T[]; + + links(nodes: T[]): partition.Link[]; + + children(): (node: T, depth: number) => T[]; + children(children: (node: T, depth: number) => T[]): Partition; + + sort(): (a: T, b: T) => number; + sort(comparator: (a: T, b: T) => number): Partition; + + value(): (node: T) => number; + value(value: (node: T) => number): Partition; + + size(): [number, number]; + size(size: [number, number]): Partition; + } + + export function pie(): Pie; + export function pie(): Pie; + + namespace pie { + interface Arc { + value: number; + startAngle: number; + endAngle: number; + padAngle: number; + data: T; + } + } + + interface Pie { + (data: T[], index?: number): pie.Arc[]; + + value(): (datum: T, index: number) => number; + value(accessor: (datum: T, index: number) => number): Pie; + + sort(): (a: T, b: T) => number; + sort(comparator: (a: T, b: T) => number): Pie; + + startAngle(): number | ((data: T[], index: number) => number); + startAngle(angle: number): Pie; + startAngle(angle: (data: T[], index: number) => number): Pie; + + endAngle(): number | ((data: T[], index: number) => number); + endAngle(angle: number): Pie; + endAngle(angle: (data: T[], index: number) => number): Pie; + + padAngle(): number | ((data: T[], index: number) => number); + padAngle(angle: number): Pie; + padAngle(angle: (data: T[], index: number) => number): Pie; + } + + export function stack(): Stack; + export function stack(): Stack; + export function stack(): Stack; + namespace stack { + interface Value { + x: number; + y: number; + y0?: number; + } + } + + interface Stack { + (layers: Series[], index?: number): Series[]; + + values(): (layer: Series, index: number) => Value[]; + values(accessor: (layer: Series, index: number) => Value[]): Stack; + + offset(): (data: Array<[number, number]>) => number[]; + offset(offset: "silhouette"): Stack; + offset(offset: "wiggle"): Stack; + offset(offset: "expand"): Stack; + offset(offset: "zero"): Stack; + offset(offset: string): Stack; + offset(offset: (data: Array<[number, number]>) => number[]): Stack; + + order(): (data: Array<[number, number]>) => number[]; + order(order: "inside-out"): Stack; + order(order: "reverse"): Stack; + order(order: "default"): Stack; + order(order: string): Stack; + order(order: (data: Array<[number, number]>) => number[]): Stack; + + x(): (value: Value, index: number) => number; + x(accessor: (value: Value, index: number) => number): Stack; + + y(): (value: Value, index: number) => number; + y(accesor: (value: Value, index: number) => number): Stack; + + out(): (value: Value, y0: number, y: number) => void; + out(setter: (value: Value, y0: number, y: number) => void): Stack; + } + + export function tree(): Tree; + export function tree(): Tree; + + namespace tree { + interface Link { + source: T; + target: T; + } + + interface Node { + parent?: Node; + children?: Node[]; + depth?: number; + x?: number; + y?: number; + } + } + + interface Tree { + (root: T, index?: number): T[]; + + nodes(root: T, index?: number): T[]; + + links(nodes: T[]): tree.Link[]; + + children(): (datum: T, index: number) => T[]; + children(children: (datum: T, index: number) => T[]): Tree; + + separation(): (a: T, b: T) => number; + separation(separation: (a: T, b: T) => number): Tree; + + size(): [number, number]; + size(size: [number, number]): Tree; + + nodeSize(): [number, number]; + nodeSize(size: [number, number]): Tree; + + sort(): (a: T, b: T) => number; + sort(comparator: (a: T, b: T) => number): Tree; + + value(): (datum: T, index: number) => number; + value(value: (datum: T, index: number) => number): Tree; + } + + export function treemap(): Treemap; + export function treemap(): Treemap; + + namespace treemap { + interface Node { + parent?: Node; + children?: Node[]; + value?: number; + depth?: number; + x?: number; + y?: number; + dx?: number; + dy?: number; + } + + interface Link { + source: T; + target: T; + } + + type Padding = number | [number, number, number, number]; + } + + interface Treemap { + (root: T, index?: number): T[]; + + nodes(root: T, index?: number): T[]; + + links(nodes: T[]): treemap.Link[]; + + children(): (node: T, depth: number) => T[]; + children(children: (node: T, depth: number) => T[]): Treemap; + + sort(): (a: T, b: T) => number; + sort(comparator: (a: T, b: T) => number): Treemap; + + value(): (node: T, index: number) => number; + value(value: (node: T, index: number) => number): Treemap; + + size(): [number, number]; + size(size: [number, number]): Treemap; + + padding(): (node: T, depth: number) => treemap.Padding; + padding(padding: treemap.Padding): Treemap; + padding(padding: (node: T, depth: number) => treemap.Padding): Treemap; + + round(): boolean; + round(round: boolean): Treemap; + + sticky(): boolean; + sticky(sticky: boolean): boolean; + + mode(): string; + mode(mode: "squarify"): Treemap; + mode(mode: "slice"): Treemap; + mode(mode: "dice"): Treemap; + mode(mode: "slice-dice"): Treemap; + mode(mode: string): Treemap; + + ratio(): number; + ratio(ratio: number): Treemap; + } + } + + namespace geom { + export function voronoi(): Voronoi<[number, number]>; + export function voronoi(): Voronoi; + + namespace voronoi { + interface Link { + source: T; + target: T; + } + } + + interface Voronoi { + (data: T[]): Array<[number, number]>; + + x(): (vertex: T) => number; + x(x: (vertex: T) => number): Voronoi; + + y(): (vertex: T) => number; + y(y: (vertex: T) => number): Voronoi; + + clipExtent(): [[number, number], [number, number]]; + clipExtent(extent: [[number, number], [number, number]]): Voronoi; + + links(data: T[]): voronoi.Link[]; + + triangles(data: T[]): Array<[T, T, T]>; + } + + /** + * @deprecated use d3.geom.voronoi().triangles() instead + */ + export function delaunay(vertices: Array<[number, number]>): Array<[[number, number], [number, number], [number, number]]>; + + export function quadtree(): Quadtree<[number, number]>; + export function quadtree(nodes: T[], x1?: number, y1?: number, x2?: number, y2?: number): quadtree.Quadtree; + + namespace quadtree { + interface Node { + nodes: [Node, Node, Node, Node]; + leaf: boolean; + point: T; + x: number; + y: number; + } + + interface Quadtree extends Node { + add(point: T): void; + visit(callback: (node: Node, x1: number, y1: number, x2: number, y2: number) => boolean | void): void; + find(point: [number, number]): T; + } + } + + interface Quadtree { + (points: T[]): quadtree.Quadtree; + + x(): (datum: T, index: number) => number; + x(x: number): Quadtree; + x(x: (datum: T, index: number) => number): Quadtree; + + y(): (datum: T, index: number) => number; + y(y: number): Quadtree; + y(y: (datum: T, index: number) => number): Quadtree; + + extent(): [[number, number], [number, number]]; + extent(extent: [[number, number], [number, number]]): Quadtree; + } + + export function hull(vertices: Array<[number, number]>): Array<[number, number]>; + export function hull(): Hull<[number, number]>; + export function hull(): Hull; + + interface Hull { + (vertices: T[]): Array<[number, number]>; + + x(): (datum: T) => number; + x(x: (datum: T) => number): Hull; + + y(): (datum: T) => number; + y(y: (datum: T) => number): Hull; + } + + export function polygon(vertices: Array<[number, number]>): Polygon; + + interface Polygon { + area(): number; + + centroid(): [number, number]; + + clip(subject: Array<[number, number]>): Array<[number, number]>; + } + } +} + +// we need this to exist +interface TouchList { } diff --git a/d3/index.d.ts b/d3/index.d.ts index d8469d68a3..bb5fb17b96 100644 --- a/d3/index.d.ts +++ b/d3/index.d.ts @@ -1,3375 +1,37 @@ -// Type definitions for d3JS v3.5.17 -// Project: http://d3js.org/ -// Definitions by: Alex Ford , Boris Yankov +// Type definitions for D3JS d3 standard bundle v4.3 +// Project: https://github.com/d3/d3 +// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export = d3; export as namespace d3; -declare namespace d3 { - /** - * The current version of D3.js. - */ - export var version: string; - - /** - * Find the first element that matches the given selector string. - */ - export function select(selector: string): Selection; - - /** - * Create a selection from the given node reference. - */ - export function select(node: EventTarget): Selection; - - /** - * Find all elements that match the given selector string. - */ - export function selectAll(selector: string): Selection; - - /** - * Create a selection from the given list of nodes. - */ - export function selectAll(nodes: EventTarget[]): Selection; - - /** - * Returns the root selection (as if by d3.select(document.documentElement)). This function may be used for 'instanceof' tests, and extending its prototype will add properties to all selections. - */ - export function selection(): Selection; - - namespace selection { - export var prototype: Selection; - - /** - * Selections are grouped into arrays of nodes, with the parent tracked in the 'parentNode' property. - */ - interface Group extends Array { - parentNode: EventTarget; - } - - interface Update { - /** - * Retrieve a grouped selection. - */ - [index: number]: Group; - - /** - * The number of groups in this selection. - */ - length: number; - - /** - * Retrieve the value of the given attribute for the first node in the selection. - * - * @param name The attribute name to query. May be prefixed (see d3.ns.prefix). - */ - attr(name: string): string; - - /** - * For all nodes, set the attribute to the specified constant value. Use null to remove. - * - * @param name The attribute name, optionally prefixed. - * @param value The attribute value to use. Note that this is coerced to a string automatically. - */ - attr(name: string, value: Primitive): Update; - - /** - * Derive an attribute value for each node in the selection based on bound data. - * - * @param name The attribute name, optionally prefixed. - * @param value The function of the datum (the bound data item), index (the position in the subgrouping), and outer index (overall position in nested selections) which computes the attribute value. If the function returns null, the attribute is removed. - */ - attr(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive): Update; - - /** - * Set multiple properties at once using an Object. D3 iterates over all enumerable properties and either sets or computes the attribute's value based on the corresponding entry in the Object. - * - * @param obj A key-value mapping corresponding to attributes and values. If the value is a simple string or number, it is taken as a constant. Otherwise, it is a function that derives the attribute value. - */ - attr(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }): Update; - - /** - * Returns true if the first node in this selection has the given class list. If multiple classes are specified (i.e., "foo bar"), then returns true only if all classes match. - * - * @param name The class list to query. - */ - classed(name: string): boolean; - - /** - * Adds (or removes) the given class list. - * - * @param name The class list to toggle. Spaces separate class names: "foo bar" is a list of two classes. - * @param value If true, add the classes. If false, remove them. - */ - classed(name: string, value: boolean): Update; - - /** - * Determine if the given class list should be toggled for each node in the selection. - * - * @param name The class list. Spaces separate multiple class names. - * @param value The function to run for each node. Should return true to add the class to the node, or false to remove it. - */ - classed(name: string, value: (datum: Datum, index: number, outerIndex: number) => boolean): Update; - - /** - * Set or derive classes for multiple class lists at once. - * - * @param obj An Object mapping class lists to values that are either plain booleans or functions that return booleans. - */ - classed(obj: { [key: string]: boolean | ((datum: Datum, index: number, outerIndex: number) => boolean) }): Update; - - /** - * Retrieve the computed style value for the first node in the selection. - * @param name The CSS property name to query - */ - style(name: string): string; - - /** - * Set a style property for all nodes in the selection. - * @param name the CSS property name - * @param value the property value - * @param priority if specified, either null or the string "important" (no exclamation mark) - */ - style(name: string, value: Primitive, priority?: string): Update; - - /** - * Derive a property value for each node in the selection. - * @param name the CSS property name - * @param value the function to derive the value - * @param priority if specified, either null or the string "important" (no exclamation mark) - */ - style(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive, priority?: string): Update; - - /** - * Set a large number of CSS properties from an object. - * - * @param obj an Object whose keys correspond to CSS property names and values are either constants or functions that derive property values - * @param priority if specified, either null or the string "important" (no exclamation mark) - */ - style(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }, priority?: string): Update; - - /** - * Retrieve an arbitrary node property such as the 'checked' property of checkboxes, or the 'value' of text boxes. - * - * @param name the node's property to retrieve - */ - property(name: string): any; - - /** - * For each node, set the property value. Internally, this sets the node property directly (e.g., node[name] = value), so take care not to mutate special properties like __proto__. - * - * @param name the property name - * @param value the property value - */ - property(name: string, value: any): Update; - - /** - * For each node, derive the property value. Internally, this sets the node property directly (e.g., node[name] = value), so take care not to mutate special properties like __proto__. - * - * @param name the property name - * @param value the function used to derive the property's value - */ - property(name: string, value: (datum: Datum, index: number, outerIndex: number) => any): Update; - - /** - * Set multiple node properties. Caveats apply: take care not to mutate special properties like __proto__. - * - * @param obj an Object whose keys correspond to node properties and values are either constants or functions that will compute a value. - */ - property(obj: { [key: string]: any | ((datum: Datum, index: number, outerIndex: number) => any) }): Update; - - /** - * Retrieve the textContent of the first node in the selection. - */ - text(): string; - - /** - * Set the textContent of each node in the selection. - * @param value the text to use for all nodes - */ - text(value: Primitive): Update; - - /** - * Compute the textContent of each node in the selection. - * @param value the function which will compute the text - */ - text(value: (datum: Datum, index: number, outerIndex: number) => Primitive): Update; - - /** - * Retrieve the HTML content of the first node in the selection. Uses 'innerHTML' internally and will not work with SVG or other elements without a polyfill. - */ - html(): string; - - /** - * Set the HTML content of every node in the selection. Uses 'innerHTML' internally and thus will not work with SVG or other elements without a polyfill. - * @param value the HTML content to use. - */ - html(value: string): Selection; - - /** - * Compute the HTML content for each node in the selection. Uses 'innerHTML' internally and thus will not work with SVG or other elements without a polyfill. - * @param value the function to compute HTML content - */ - html(value: (datum: Datum, index: number, outerIndex: number) => string): Selection; - - /** - * Appends a new child to each node in the selection. This child will inherit the parent's data (if available). Returns a fresh selection consisting of the newly-appended children. - * - * @param name the element name to append. May be prefixed (see d3.ns.prefix). - */ - append(name: string): Selection; - - /** - * Appends a new child to each node in the selection by computing a new node. This child will inherit the parent's data (if available). Returns a fresh selection consisting of the newly-appended children. - * - * @param name the function to compute a new element - */ - append(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; - - /** - * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. - * @param name the element name to append. May be prefixed (see d3.ns.prefix). - * @param before the selector to determine position (e.g., ":first-child") - */ - insert(name: string, before: string): Update; - - /** - * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. - * @param name the element name to append. May be prefixed (see d3.ns.prefix). - * @param before a function to determine the node to use as the next sibling - */ - insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; - - /** - * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. - * @param name the function to compute a new child - * @param before the selector to determine position (e.g., ":first-child") - */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: string): Update; - - /** - * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. - * @param name the function to compute a new child - * @param before a function to determine the node to use as the next sibling - */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; - - /** - * Removes the elements from the DOM. They are in a detached state and may be re-added (though there is currently no dedicated API for doing so). - */ - remove(): Update; - - /** - * Retrieves the data bound to the first group in this selection. - */ - data(): Datum[]; - - /** - * Binds data to this selection. - * @param data the array of data to bind to this selection - * @param key the optional function to determine the unique key for each piece of data. When unspecified, uses the index of the element. - */ - data(data: NewDatum[], key?: (datum: NewDatum, index: number, outerIndex: number) => string): Update; - - /** - * Derives data to bind to this selection. - * @param data the function to derive data. Must return an array. - * @param key the optional function to determine the unique key for each data item. When unspecified, uses the index of the element. - */ - data(data: (datum: Datum, index: number, outerIndex: number) => NewDatum[], key?: (datum: NewDatum, index: number, outerIndex: number) => string): Update; - - /** - * Filters the selection, returning only those nodes that match the given CSS selector. - * @param selector the CSS selector - */ - filter(selector: string): Update; - - /** - * Filters the selection, returning only those nodes for which the given function returned true. - * @param selector the filter function - */ - filter(selector: (datum: Datum, index: number, outerIndex: number) => boolean): Update; - - /** - * Return the data item bound to the first element in the selection. - */ - datum(): Datum; - - /** - * Derive the data item for each node in the selection. Useful for situations such as the HTML5 'dataset' attribute. - * @param value the function to compute data for each node - */ - datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update; - - /** - * Set the data item for each node in the selection. - * @param value the constant element to use for each node - */ - datum(value: NewDatum): Update; - - /** - * Reorders nodes in the selection based on the given comparator. Nodes are re-inserted into the document once sorted. - * @param comparator the comparison function, which defaults to d3.ascending - */ - sort(comparator?: (a: Datum, b: Datum) => number): Update; - - /** - * Reorders nodes in the document to match the selection order. More efficient than calling sort() if the selection is already ordered. - */ - order(): Update; - - /** - * Returns the listener (if any) for the given event. - * @param type the type of event to load the listener for. May have a namespace (e.g., ".foo") at the end. - */ - on(type: string): (datum: Datum, index: number, outerIndex: number) => any; - - /** - * Adds a listener for the specified event. If one was already registered, it is removed before the new listener is added. The return value of the listener function is ignored. - * @param type the of event to listen to. May have a namespace (e.g., ".foo") at the end. - * @param listener an event listener function, or null to unregister - * @param capture sets the DOM useCapture flag - */ - on(type: string, listener: (datum: Datum, index: number, outerIndex: number) => any, capture?: boolean): Update; - - /** - * Begins a new transition. Interrupts any active transitions of the same name. - * @param name the transition name (defaults to "") - */ - transition(name?: string): Transition; - - /** - * Interrupts the active transition of the provided name. Does not cancel scheduled transitions. - * @param name the transition name (defaults to "") - */ - interrupt(name?: string): Update; - - /** - * Creates a subselection by finding the first descendent matching the selector string. Bound data is inherited. - * @param selector the CSS selector to match against - */ - select(selector: string): Update; - - /** - * Creates a subselection by using a function to find descendent elements. Bound data is inherited. - * @param selector the function to find matching descendants - */ - select(selector: (datum: Datum, index: number, outerIndex: number) => EventTarget): Update; - - /** - * Creates a subselection by finding all descendents that match the given selector. Bound data is not inherited. - * @param selector the CSS selector to match against - */ - selectAll(selector: string): Update; - - /** - * Creates a subselection by using a function to find descendent elements. Bound data is not inherited. - * @param selector the function to find matching descendents - */ - selectAll(selector: (datum: Datum, index: number, outerIndex: number) => Array | NodeList): Update; - - /** - * Invoke the given function for each element in the selection. The return value of the function is ignored. - * @param func the function to invoke - */ - each(func: (datum: Datum, index: number, outerIndex: number) => any): Update; - - /** - * Call a function on the selection. sel.call(foo) is equivalent to foo(sel). - * @param func the function to call on the selection - * @param args any optional args - */ - call(func: (sel: Update, ...args: any[]) => any, ...args: any[]): Update; - - /** - * Returns true if the current selection is empty. - */ - empty(): boolean; - - /** - * Returns the first non-null element in the selection, or null otherwise. - */ - node(): Node; - - /** - * Returns the total number of elements in the selection. - */ - size(): number; - - /** - * Returns the placeholder nodes for each data element for which no corresponding DOM element was found. - */ - enter(): Enter; - - /** - * Returns a selection for those DOM nodes for which no new data element was found. - */ - exit(): Selection; - } - - interface Enter { - append(name: string): Selection; - append(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; - - insert(name: string, before?: string): Selection; - insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before?: string): Selection; - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; - - select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; - call(func: (selection: Enter, ...args: any[]) => any, ...args: any[]): Enter; - - empty(): boolean; - size(): number; - } - } - - /** - * Administrivia: JavaScript primitive types, or "things that toString() predictably". - */ - export type Primitive = number | string | boolean; - - /** - * Administrivia: anything with a valueOf(): number method is comparable, so we allow it in numeric operations - */ - interface Numeric { - valueOf(): number; - } - - /** - * A grouped array of nodes. - * @param Datum the data bound to this selection. - */ - interface Selection { - /** - * Retrieve a grouped selection. - */ - [index: number]: selection.Group; - - /** - * The number of groups in this selection. - */ - length: number; - - /** - * Retrieve the value of the given attribute for the first node in the selection. - * - * @param name The attribute name to query. May be prefixed (see d3.ns.prefix). - */ - attr(name: string): string; - - /** - * For all nodes, set the attribute to the specified constant value. Use null to remove. - * - * @param name The attribute name, optionally prefixed. - * @param value The attribute value to use. Note that this is coerced to a string automatically. - */ - attr(name: string, value: Primitive): Selection; - - /** - * Derive an attribute value for each node in the selection based on bound data. - * - * @param name The attribute name, optionally prefixed. - * @param value The function of the datum (the bound data item), index (the position in the subgrouping), and outer index (overall position in nested selections) which computes the attribute value. If the function returns null, the attribute is removed. - */ - attr(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive): Selection; - - /** - * Set multiple properties at once using an Object. D3 iterates over all enumerable properties and either sets or computes the attribute's value based on the corresponding entry in the Object. - * - * @param obj A key-value mapping corresponding to attributes and values. If the value is a simple string or number, it is taken as a constant. Otherwise, it is a function that derives the attribute value. - */ - attr(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }): Selection; - - /** - * Returns true if the first node in this selection has the given class list. If multiple classes are specified (i.e., "foo bar"), then returns true only if all classes match. - * - * @param name The class list to query. - */ - classed(name: string): boolean; - - /** - * Adds (or removes) the given class list. - * - * @param name The class list to toggle. Spaces separate class names: "foo bar" is a list of two classes. - * @param value If true, add the classes. If false, remove them. - */ - classed(name: string, value: boolean): Selection; - - /** - * Determine if the given class list should be toggled for each node in the selection. - * - * @param name The class list. Spaces separate multiple class names. - * @param value The function to run for each node. Should return true to add the class to the node, or false to remove it. - */ - classed(name: string, value: (datum: Datum, index: number, outerIndex: number) => boolean): Selection; - - /** - * Set or derive classes for multiple class lists at once. - * - * @param obj An Object mapping class lists to values that are either plain booleans or functions that return booleans. - */ - classed(obj: { [key: string]: boolean | ((datum: Datum, index: number, outerIndex: number) => boolean) }): Selection; - - /** - * Retrieve the computed style value for the first node in the selection. - * @param name The CSS property name to query - */ - style(name: string): string; - - /** - * Set a style property for all nodes in the selection. - * @param name the CSS property name - * @param value the property value - * @param priority if specified, either null or the string "important" (no exclamation mark) - */ - style(name: string, value: Primitive, priority?: string): Selection; - - /** - * Derive a property value for each node in the selection. - * @param name the CSS property name - * @param value the function to derive the value - * @param priority if specified, either null or the string "important" (no exclamation mark) - */ - style(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive, priority?: string): Selection; - - /** - * Set a large number of CSS properties from an object. - * - * @param obj an Object whose keys correspond to CSS property names and values are either constants or functions that derive property values - * @param priority if specified, either null or the string "important" (no exclamation mark) - */ - style(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }, priority?: string): Selection; - - /** - * Retrieve an arbitrary node property such as the 'checked' property of checkboxes, or the 'value' of text boxes. - * - * @param name the node's property to retrieve - */ - property(name: string): any; - - /** - * For each node, set the property value. Internally, this sets the node property directly (e.g., node[name] = value), so take care not to mutate special properties like __proto__. - * - * @param name the property name - * @param value the property value - */ - property(name: string, value: any): Selection; - - /** - * For each node, derive the property value. Internally, this sets the node property directly (e.g., node[name] = value), so take care not to mutate special properties like __proto__. - * - * @param name the property name - * @param value the function used to derive the property's value - */ - property(name: string, value: (datum: Datum, index: number, outerIndex: number) => any): Selection; - - /** - * Set multiple node properties. Caveats apply: take care not to mutate special properties like __proto__. - * - * @param obj an Object whose keys correspond to node properties and values are either constants or functions that will compute a value. - */ - property(obj: { [key: string]: any | ((datum: Datum, index: number, innerInder: number) => any) }): Selection; - - /** - * Retrieve the textContent of the first node in the selection. - */ - text(): string; - - /** - * Set the textContent of each node in the selection. - * @param value the text to use for all nodes - */ - text(value: Primitive): Selection; - - /** - * Compute the textContent of each node in the selection. - * @param value the function which will compute the text - */ - text(value: (datum: Datum, index: number, outerIndex: number) => Primitive): Selection; - - /** - * Retrieve the HTML content of the first node in the selection. Uses 'innerHTML' internally and will not work with SVG or other elements without a polyfill. - */ - html(): string; - - /** - * Set the HTML content of every node in the selection. Uses 'innerHTML' internally and thus will not work with SVG or other elements without a polyfill. - * @param value the HTML content to use. - */ - html(value: string): Selection; - - /** - * Compute the HTML content for each node in the selection. Uses 'innerHTML' internally and thus will not work with SVG or other elements without a polyfill. - * @param value the function to compute HTML content - */ - html(value: (datum: Datum, index: number, outerIndex: number) => string): Selection; - - /** - * Appends a new child to each node in the selection. This child will inherit the parent's data (if available). Returns a fresh selection consisting of the newly-appended children. - * - * @param name the element name to append. May be prefixed (see d3.ns.prefix). - */ - append(name: string): Selection; - - /** - * Appends a new child to each node in the selection by computing a new node. This child will inherit the parent's data (if available). Returns a fresh selection consisting of the newly-appended children. - * - * @param name the function to compute a new element - */ - append(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; - - /** - * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. - * @param name the element name to append. May be prefixed (see d3.ns.prefix). - * @param before the selector to determine position (e.g., ":first-child") - */ - insert(name: string, before: string): Selection; - - /** - * Inserts a new child to each node in the selection. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. - * @param name the element name to append. May be prefixed (see d3.ns.prefix). - * @param before a function to determine the node to use as the next sibling - */ - insert(name: string, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; - - /** - * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. - * @param name the function to compute a new child - * @param before the selector to determine position (e.g., ":first-child") - */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: string): Selection; - - /** - * Inserts a new child to the end of each node in the selection by computing a new node. This child will inherit its parent's data (if available). Returns a fresh selection consisting of the newly-inserted children. - * @param name the function to compute a new child - * @param before a function to determine the node to use as the next sibling - */ - insert(name: (datum: Datum, index: number, outerIndex: number) => EventTarget, before: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; - - /** - * Removes the elements from the DOM. They are in a detached state and may be re-added (though there is currently no dedicated API for doing so). - */ - remove(): Selection; - - /** - * Retrieves the data bound to the first group in this selection. - */ - data(): Datum[]; - - /** - * Binds data to this selection. - * @param data the array of data to bind to this selection - * @param key the optional function to determine the unique key for each piece of data. When unspecified, uses the index of the element. - */ - data(data: NewDatum[], key?: (datum: NewDatum, index: number, outerIndex: number) => string): selection.Update; - - /** - * Derives data to bind to this selection. - * @param data the function to derive data. Must return an array. - * @param key the optional function to determine the unique key for each data item. When unspecified, uses the index of the element. - */ - data(data: (datum: Datum, index: number, outerIndex: number) => NewDatum[], key?: (datum: NewDatum, index: number, outerIndex: number) => string): selection.Update; - - /** - * Filters the selection, returning only those nodes that match the given CSS selector. - * @param selector the CSS selector - */ - filter(selector: string): Selection; - - /** - * Filters the selection, returning only those nodes for which the given function returned true. - * @param selector the filter function - */ - filter(selector: (datum: Datum, index: number, outerIndex: number) => boolean): Selection; - - /** - * Return the data item bound to the first element in the selection. - */ - datum(): Datum; - - /** - * Derive the data item for each node in the selection. Useful for situations such as the HTML5 'dataset' attribute. - * @param value the function to compute data for each node - */ - datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Selection; - - /** - * Set the data item for each node in the selection. - * @param value the constant element to use for each node - */ - datum(value: NewDatum): Selection; - - /** - * Reorders nodes in the selection based on the given comparator. Nodes are re-inserted into the document once sorted. - * @param comparator the comparison function, which defaults to d3.ascending - */ - sort(comparator?: (a: Datum, b: Datum) => number): Selection; - - /** - * Reorders nodes in the document to match the selection order. More efficient than calling sort() if the selection is already ordered. - */ - order(): Selection; - - /** - * Returns the listener (if any) for the given event. - * @param type the type of event to load the listener for. May have a namespace (e.g., ".foo") at the end. - */ - on(type: string): (datum: Datum, index: number, outerIndex: number) => any; - - /** - * Adds a listener for the specified event. If one was already registered, it is removed before the new listener is added. The return value of the listener function is ignored. - * @param type the of event to listen to. May have a namespace (e.g., ".foo") at the end. - * @param listener an event listener function, or null to unregister - * @param capture sets the DOM useCapture flag - */ - on(type: string, listener: (datum: Datum, index: number, outerIndex: number) => any, capture?: boolean): Selection; - - /** - * Begins a new transition. Interrupts any active transitions of the same name. - * @param name the transition name (defaults to "") - */ - transition(name?: string): Transition; - - /** - * Interrupts the active transition of the provided name. Does not cancel scheduled transitions. - * @param name the transition name (defaults to "") - */ - interrupt(name?: string): Selection; - - /** - * Creates a subselection by finding the first descendent matching the selector string. Bound data is inherited. - * @param selector the CSS selector to match against - */ - select(selector: string): Selection; - - /** - * Creates a subselection by using a function to find descendent elements. Bound data is inherited. - * @param selector the function to find matching descendants - */ - select(selector: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; - - /** - * Creates a subselection by finding all descendents that match the given selector. Bound data is not inherited. - * @param selector the CSS selector to match against - */ - selectAll(selector: string): Selection; - - /** - * Creates a subselection by finding all descendants that match the given selector. Bound data is not inherited. - * - * Use this overload when data-binding a subselection (that is, sel.selectAll('.foo').data(d => ...)). The type will carry over. - */ - selectAll(selector: string): Selection; - - /** - * Creates a subselection by using a function to find descendent elements. Bound data is not inherited. - * @param selector the function to find matching descendents - */ - selectAll(selector: (datum: Datum, index: number, outerIndex: number) => Array | NodeList): Selection; - - /** - * Creates a subselection by using a function to find descendent elements. Bound data is not inherited. - * - * Use this overload when data-binding a subselection (that is, sel.selectAll('.foo').data(d => ...)). The type will carry over. - * @param selector the function to find matching descendents - */ - selectAll(selector: (datum: Datum, index: number, outerIndex: number) => Array | NodeList): Selection; - - /** - * Invoke the given function for each element in the selection. The return value of the function is ignored. - * @param func the function to invoke - */ - each(func: (datum: Datum, index: number, outerIndex: number) => any): Selection; - - /** - * Call a function on the selection. sel.call(foo) is equivalent to foo(sel). - * @param func the function to call on the selection - * @param args any optional args - */ - call(func: (sel: Selection, ...args: any[]) => any, ...args: any[]): Selection; - - /** - * Returns true if the current selection is empty. - */ - empty(): boolean; - - /** - * Returns the first non-null element in the selection, or null otherwise. - */ - node(): Node; - - /** - * Returns the total number of elements in the selection. - */ - size(): number; - } - - export function transition(): Transition; - namespace transition { - export var prototype: Transition; - } - - interface Transition { - - transition(): Transition; - - delay(): number; - delay(delay: number): Transition; - delay(delay: (datum: Datum, index: number, outerIndex: number) => number): Transition; - - duration(): number; - duration(duration: number): Transition; - duration(duration: (datum: Datum, index: number, outerIndex: number) => number): Transition; - - ease(): (t: number) => number; - ease(value: string, ...args: any[]): Transition; - ease(value: (t: number) => number): Transition; - - attr(name: string, value: Primitive): Transition; - attr(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive): Transition; - attr(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }): Transition; - - attrTween(name: string, tween: (datum: Datum, index: number, attr: string) => (t: number) => Primitive): Transition; - - style(name: string, value: Primitive, priority?: string): Transition; - style(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive, priority?: string): Transition; - style(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }, priority?: string): Transition; - - styleTween(name: string, tween: (datum: Datum, index: number, attr: string) => (t: number) => Primitive, priority?: string): Transition; - - text(value: Primitive): Transition; - text(value: (datum: Datum, index: number, outerIndex: number) => Primitive): Transition; - - tween(name: string, factory: () => (t: number) => any): Transition; - - remove(): Transition; - - select(selector: string): Transition; - select(selector: (d: Datum, i: number) => EventTarget): Transition; - - selectAll(selector: string): Transition; - selectAll(selector: (d: Datum, i: number) => EventTarget[]): Transition; - - filter(selector: string): Transition; - filter(selector: (d: Datum, i: number) => boolean): Transition; - - each(type: string, listener: (d: Datum, i: number) => any): Transition; - each(listener: (d: Datum, i: number) => any): Transition; - - call(func: (transition: Transition, ...args: any[]) => any, ...args: any[]): Transition; - - empty(): boolean; - node(): Node; - size(): number; - } - - export function ease(type: 'linear'): (t: number) => number; - export function ease(type: 'linear-in'): (t: number) => number; - export function ease(type: 'linear-out'): (t: number) => number; - export function ease(type: 'linear-in-out'): (t: number) => number; - export function ease(type: 'linear-out-in'): (t: number) => number; - - export function ease(type: 'poly', k: number): (t: number) => number; - export function ease(type: 'poly-in', k: number): (t: number) => number; - export function ease(type: 'poly-out', k: number): (t: number) => number; - export function ease(type: 'poly-in-out', k: number): (t: number) => number; - export function ease(type: 'poly-out-in', k: number): (t: number) => number; - - export function ease(type: 'quad'): (t: number) => number; - export function ease(type: 'quad-in'): (t: number) => number; - export function ease(type: 'quad-out'): (t: number) => number; - export function ease(type: 'quad-in-out'): (t: number) => number; - export function ease(type: 'quad-out-in'): (t: number) => number; - - export function ease(type: 'cubic'): (t: number) => number; - export function ease(type: 'cubic-in'): (t: number) => number; - export function ease(type: 'cubic-out'): (t: number) => number; - export function ease(type: 'cubic-in-out'): (t: number) => number; - export function ease(type: 'cubic-out-in'): (t: number) => number; - - export function ease(type: 'sin'): (t: number) => number; - export function ease(type: 'sin-in'): (t: number) => number; - export function ease(type: 'sin-out'): (t: number) => number; - export function ease(type: 'sin-in-out'): (t: number) => number; - export function ease(type: 'sin-out-in'): (t: number) => number; - - export function ease(type: 'circle'): (t: number) => number; - export function ease(type: 'circle-in'): (t: number) => number; - export function ease(type: 'circle-out'): (t: number) => number; - export function ease(type: 'circle-in-out'): (t: number) => number; - export function ease(type: 'circle-out-in'): (t: number) => number; - - export function ease(type: 'elastic', a?: number, b?: number): (t: number) => number; - export function ease(type: 'elastic-in', a?: number, b?: number): (t: number) => number; - export function ease(type: 'elastic-out', a?: number, b?: number): (t: number) => number; - export function ease(type: 'elastic-in-out', a?: number, b?: number): (t: number) => number; - export function ease(type: 'elastic-out-in', a?: number, b?: number): (t: number) => number; - - export function ease(type: 'back', s: number): (t: number) => number; - export function ease(type: 'back-in', s: number): (t: number) => number; - export function ease(type: 'back-out', s: number): (t: number) => number; - export function ease(type: 'back-in-out', s: number): (t: number) => number; - export function ease(type: 'back-out-in', s: number): (t: number) => number; - - export function ease(type: 'bounce'): (t: number) => number; - export function ease(type: 'bounce-in'): (t: number) => number; - export function ease(type: 'bounce-out'): (t: number) => number; - export function ease(type: 'bounce-in-out'): (t: number) => number; - export function ease(type: 'bounce-out-in'): (t: number) => number; - - export function ease(type: string, ...args: any[]): (t: number) => number; - - export function timer(func: () => any, delay?: number, time?: number): void; - - namespace timer { - export function flush(): void; - } - - interface BaseEvent { - type: string; - sourceEvent?: Event; - } - - /** - * Define a D3-specific ZoomEvent per https://github.com/mbostock/d3/wiki/Zoom-Behavior#event - */ - interface ZoomEvent extends BaseEvent { - scale: number; - translate: [number, number]; - } - - /** - * Define a D3-specific DragEvent per https://github.com/mbostock/d3/wiki/Drag-Behavior#on - */ - interface DragEvent extends BaseEvent { - x: number; - y: number; - dx: number; - dy: number; - } - - /** - * The current event's value. Use this variable in a handler registered with `selection.on`. - */ - export var event: Event | BaseEvent; - - /** - * Returns the x and y coordinates of the mouse relative to the provided container element, using d3.event for the mouse's position on the page. - * @param container the container element (e.g. an SVG element) - */ - export function mouse(container: EventTarget): [number, number]; - - /** - * Given a container element and a touch identifier, determine the x and y coordinates of the touch. - * @param container the container element (e.g., an SVG element) - * @param identifier the given touch identifier - */ - export function touch(container: EventTarget, identifer: number): [number, number]; - - /** - * Given a container element, a list of touches, and a touch identifier, determine the x and y coordinates of the touch. - * @param container the container element (e.g., an SVG element) - * @param identifier the given touch identifier - */ - export function touch(container: EventTarget, touches: TouchList, identifer: number): [number, number]; - - /** - * Given a container element and an optional list of touches, return the position of every touch relative to the container. - * @param container the container element - * @param touches an optional list of touches (defaults to d3.event.touches) - */ - export function touches(container: EventTarget, touches?: TouchList): Array<[number, number]>; - - // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. - /** - * Compares two primitive values for sorting (in ascending order). - */ - export function ascending(a: Primitive, b: Primitive): number; - - /** - * Compares two primitive values for sorting (in ascending order). - */ - export function descending(a: Primitive, b: Primitive): number; - - /** - * Return the minimum value in the array using natural order. - */ - export function min(array: number[]): number; - - /** - * Return the minimum value in the array using natural order. - */ - export function min(array: string[]): string; - - /** - * Return the minimum value in the array using natural order. - */ - export function min(array: T[]): T; - - /** - * Return the minimum value in the array using natural order. - */ - export function min(array: T[], accessor: (datum: T, index: number) => number): number; - - /** - * Return the minimum value in the array using natural order. - */ - export function min(array: T[], accessor: (datum: T, index: number) => string): string; - - /** - * Return the minimum value in the array using natural order. - */ - export function min(array: T[], accessor: (datum: T, index: number) => U): U; - - /** - * Return the maximum value in the array of numbers using natural order. - */ - export function max(array: number[]): number; - - /** - * Return the maximum value in the array of strings using natural order. - */ - export function max(array: string[]): string; - - /** - * Return the maximum value in the array of numbers using natural order. - */ - export function max(array: T[]): T; - - /** - * Return the maximum value in the array using natural order and a projection function to map values to numbers. - */ - export function max(array: T[], accessor: (datum: T, index: number) => number): number; - - /** - * Return the maximum value in the array using natural order and a projection function to map values to strings. - */ - export function max(array: T[], accessor: (datum: T, index: number) => string): string; - - /** - * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. - */ - export function max(array: T[], accessor: (datum: T, index: number) => U): U; - - /** - * Return the min and max simultaneously. - */ - export function extent(array: number[]): [number, number]; - - /** - * Return the min and max simultaneously. - */ - export function extent(array: string[]): [string, string]; - - /** - * Return the min and max simultaneously. - */ - export function extent(array: T[]): [T, T]; - - /** - * Return the min and max simultaneously. - */ - export function extent(array: Array): [T | Primitive, T | Primitive]; - - /** - * Return the min and max simultaneously. - */ - export function extent(array: T[], accessor: (datum: T, index: number) => number): [number, number]; - - /** - * Return the min and max simultaneously. - */ - export function extent(array: T[], accessor: (datum: T, index: number) => string): [string, string]; - - /** - * Return the min and max simultaneously. - */ - export function extent(array: T[], accessor: (datum: T, index: number) => Date): [Date, Date]; - - /** - * Return the min and max simultaneously. - */ - export function extent(array: T[], accessor: (datum: T, index: number) => U): [U | Primitive, U | Primitive]; - - /** - * Compute the sum of an array of numbers. - */ - export function sum(array: number[]): number; - - /** - * Compute the sum of an array, using the given accessor to convert values to numbers. - */ - export function sum(array: T[], accessor: (datum: T, index: number) => number): number; - - export function mean(array: number[]): number; - export function mean(array: T[], accessor: (datum: T, index: number) => number): number; - - /** - * Compute the median of an array of numbers (the 0.5-quantile). - */ - export function median(array: number[]): number; - export function median(datum: T[], accessor: (datum: T, index: number) => number): number; - - export function quantile(array: number[], p: number): number; - - export function variance(array: number[]): number; - export function variance(array: T[], accessor: (datum: T, index: number) => number): number; - - export function deviation(array: number[]): number; - export function deviation(array: T[], accessor: (datum: T, index: number) => number): number; - - export function bisectLeft(array: T[], x: T, lo?: number, hi?: number): number; - - export var bisect: typeof bisectRight; - - export function bisectRight(array: T[], x: T, lo?: number, hi?: number): number; - - export function bisector(accessor: (x: T) => U): { - left: (array: T[], x: U, lo?: number, hi?: number) => number; - right: (array: T[], x: U, lo?: number, hi?: number) => number; - } - - export function bisector(comparator: (a: T, b: U) => number): { - left: (array: T[], x: U, lo?: number, hi?: number) => number; - right: (array: T[], x: U, lo?: number, hi?: number) => number; - } - - export function shuffle(array: T[], lo?: number, hi?: number): T[]; - - /** - * Returns the enumerable property names of the specified object. - * @param object a JavaScript object - */ - export function keys(object: Object): string[]; - - /** - * Returns an array containing the property values of the specified object. - */ - export function values(object: { [key: string]: T }): T[]; - /** - * Returns an array containing the property values of the specified object. - */ - export function values(object: { [key: number]: T }): T[]; - /** - * Returns an array containing the property values of the specified object. - */ - export function values(object: Object): any[]; - - /** - * Returns an array of key-value pairs containing the property values of the specified object. - */ - export function entries(object: { [key: string]: T }): { key: string; value: T }[]; - - /** - * Returns an array of key-value pairs containing the property values of the specified object. - */ - export function entries(object: { [key: number]: T }): { key: string; value: T }[]; - - /** - * Returns an array of key-value pairs containing the property values of the specified object. - */ - export function entries(object: Object): { key: string; value: any }[]; - - /** - * A shim for ES6 maps. The implementation uses a JavaScript object internally, and thus keys are limited to strings. - */ - interface Map { - /** - * Does the map contain the given key? - */ - has(key: string): boolean; - - /** - * Retrieve the value for the given key. Returns undefined if there is no value stored. - */ - get(key: string): T; - - /** - * Set the value for the given key. Returns the new value. - */ - set(key: string, value: T): T; - - /** - * Remove the value for the given key. Returns true if there was a value and false otherwise. - */ - remove(key: string): boolean; - - /** - * Returns an array of all keys in arbitrary order. - */ - keys(): string[]; - - /** - * Returns an array of all values in arbitrary order. - */ - values(): T[]; - - /** - * Returns an array of key-value objects in arbitrary order. - */ - entries(): { key: string; value: T }[]; - - /** - * Calls the function for each key and value pair in the map. The 'this' context is the map itself. - */ - forEach(func: (key: string, value: T) => any): void; - - /** - * Is this map empty? - */ - empty(): boolean; - - /** - * Returns the number of elements stored in the map. - */ - size(): number; - } - - /** - * Constructs an initially empty map. - */ - export function map(): Map; - - /** - * Construct a new map by copying keys and values from the given one. - */ - export function map(object: Map): Map; - - /** - * Construct a new map by copying enumerable properties and values from the given object. - */ - export function map(object: { [key: string]: T }): Map; - - /** - * Construct a new map by copying enumerable properties and values from the given object. - */ - export function map(object: { [key: number]: T }): Map; - - /** - * Construct a new map by copying elements from the array. The key function is used to identify each object. - */ - export function map(array: T[], key: (datum: T, index: number) => string): Map; - - /** - * Construct a new map by copying enumerable properties and values from the given object. - */ - export function map(object: Object): Map; - - /** - * A shim for ES6 sets. Is only able to store strings. - */ - interface Set { - /** - * Is the given string stored in this set? - */ - has(value: string): boolean; - - /** - * Add the string to this set. Returns the value. - */ - add(value: string): string; - - /** - * Remove the given value from the set. Returns true if it was stored, and false otherwise. - */ - remove(value: string): boolean; - - /** - * Returns an array of the strings stored in this set. - */ - values(): string[]; - - /** - * Calls a given function for each value in the set. The return value of the function is ignored. The this context of the function is the set itself. - */ - forEach(func: (value: string) => any): void; - - /** - * Is this set empty? - */ - empty(): boolean; - - /** - * Returns the number of values stored in this set. - */ - size(): number; - } - - /** - * Creates an initially-empty set. - */ - export function set(): Set; - - /** - * Initializes a set from the given array of strings. - */ - export function set(array: string[]): Set; - - /** - * Merges the specified arrays into a single array. - */ - export function merge(arrays: T[][]): T[]; - - /** - * Generates a 0-based numeric sequence. The output range does not include 'stop'. - */ - export function range(stop: number): number[]; - - /** - * Generates a numeric sequence starting from the given start and stop values. 'step' defaults to 1. The output range does not include 'stop'. - */ - export function range(start: number, stop: number, step?: number): number[]; - - /** - * Given the specified array, return an array corresponding to the list of indices in 'keys'. - */ - export function permute(array: { [key: number]: T }, keys: number[]): T[]; - - /** - * Given the specified object, return an array corresponding to the list of property names in 'keys'. - */ - export function permute(object: { [key: string]: T }, keys: string[]): T[]; - - // TODO construct n-tuples from n input arrays - export function zip(...arrays: T[][]): T[][]; - - export function transpose(matrix: T[][]): T[][]; - - /** - * For each adjacent pair of elements in the specified array, returns a new array of tuples of elements i and i - 1. - * Returns the empty array if the input array has fewer than two elements. - */ - export function pairs(array: T[]): Array<[T, T]>; - - interface Nest { - key(func: (datum: T) => string): Nest; - sortKeys(comparator: (a: string, b: string) => number): Nest; - sortValues(comparator: (a: T, b: T) => number): Nest; - rollup(func: (values: T[]) => U): Nest; - map(array: T[]): { [key: string]: any }; - map(array: T[], mapType: typeof d3.map): Map; - entries(array: T[]): { key: string; values: any }[]; - } - - export function nest(): Nest; - - export module random { - export function normal(mean?: number, deviation?: number): () => number; - export function logNormal(mean?: number, deviation?: number): () => number; - export function bates(count: number): () => number; - export function irwinHall(count: number): () => number; - } - - interface Transform { - rotate: number; - translate: [number, number]; - skew: number; - scale: [number, number]; - toString(): string; - } - - export function transform(transform: string): Transform; - - export function format(specifier: string): (n: number) => string; - - interface FormatPrefix { - symbol: string; - scale(n: number): number; - } - - export function formatPrefix(value: number, precision?: number): FormatPrefix; - - export function round(x: number, n?: number): number; - - export function requote(string: string): string; - - export var rgb: { - new (r: number, g: number, b: number): Rgb; - new (color: string): Rgb; - - (r: number, g: number, b: number): Rgb; - (color: string): Rgb; - }; - - interface Rgb extends Color { - r: number; - g: number; - b: number; - - brighter(k?: number): Rgb; - darker(k?: number): Rgb; - - hsl(): Hsl; - - toString(): string; - } - - export var hsl: { - new (h: number, s: number, l: number): Hsl; - new (color: string): Hsl; - - (h: number, s: number, l: number): Hsl; - (color: string): Hsl; - }; - - interface Hsl extends Color { - h: number; - s: number; - l: number; - - brighter(k?: number): Hsl; - darker(k?: number): Hsl; - - rgb(): Rgb; - - toString(): string; - } - - export var hcl: { - new (h: number, c: number, l: number): Hcl; - new (color: string): Hcl; - - (h: number, c: number, l: number): Hcl; - (color: string): Hcl; - }; - - interface Hcl extends Color { - h: number; - c: number; - l: number; - - brighter(k?: number): Hcl; - darker(k?: number): Hcl; - } - - export var lab: { - new (l: number, a: number, b: number): Lab; - new (color: string): Lab; - - (l: number, a: number, b: number): Lab; - (color: string): Lab; - } - - interface Lab extends Color { - l: number; - a: number; - b: number; - - brighter(k?: number): Lab; - darker(k?: number): Lab; - - rgb(): Rgb; - toString(): string; - } - - export var color: { - (): Color; - new (): Color; - }; - - interface Color { - rgb(): Rgb; - } - - export module ns { - interface Qualified { - space: string; - local: string; - } - - export var prefix: { [key: string]: string }; - export function qualify(name: string): Qualified | string; - } - - export function functor(value: T): T; - export function functor(value: T): () => T; - - export function rebind(target: {}, source: {}, ...names: string[]): any; - - export function dispatch(...names: string[]): Dispatch; - - interface Dispatch { - on(type: string): (...args: any[]) => void; - on(type: string, listener: (...args: any[]) => any): Dispatch; - [event: string]: (...args: any[]) => void; - } - - export module scale { - export function identity(): Identity; - - interface Identity { - (n: number): number; - invert(n: number): number; - - domain(): number[]; - domain(numbers: number[]): Identity; - - range(): number[]; - range(numbers: number[]): Identity; - - ticks(count?: number): number[]; - - tickFormat(count?: number, format?: string): (n: number) => string; - - copy(): Identity; - } - - export function linear(): Linear; - export function linear(): Linear; - export function linear(): Linear; - - interface Linear { - (x: number): Output; - invert(y: number): number; - - domain(): number[]; - domain(numbers: number[]): Linear; - - range(): Range[]; - range(values: Range[]): Linear; - - rangeRound(values: number[]): Linear; - - interpolate(): (a: Range, b: Range) => (t: number) => Output; - interpolate(factory: (a: Range, b: Range) => (t: number) => Output): Linear; - - clamp(): boolean; - clamp(clamp: boolean): Linear; - - nice(count?: number): Linear; - - ticks(count?: number): number[]; - - tickFormat(count?: number, format?: string): (n: number) => string; - - copy(): Linear; - } - - export function sqrt(): Pow; - export function sqrt(): Pow; - export function sqrt(): Pow; - - export function pow(): Pow; - export function pow(): Pow; - export function pow(): Pow; - - interface Pow { - (x: number): Output; - - invert(y: number): number; - - domain(): number[]; - domain(numbers: number[]): Pow; - - range(): Range[]; - range(values: Range[]): Pow; - - rangeRound(values: number[]): Pow; - - exponent(): number; - exponent(k: number): Pow; - - interpolate(): (a: Range, b: Range) => (t: number) => Output; - interpolate(factory: (a: Range, b: Range) => (t: number) => Output): Pow; - - clamp(): boolean; - clamp(clamp: boolean): Pow; - - nice(m?: number): Pow; - - ticks(count?: number): number[]; - - tickFormat(count?: number, format?: string): (n: number) => string; - - copy(): Pow; - } - - export function log(): Log; - export function log(): Log; - export function log(): Log; - - interface Log { - (x: number): Output; - - invert(y: number): number; - - domain(): number[]; - domain(numbers: number[]): Log; - - range(): Range[]; - range(values: Range[]): Log; - - rangeRound(values: number[]): Log; - - base(): number; - base(base: number): Log; - - interpolate(): (a: Range, b: Range) => (t: number) => Output; - interpolate(factory: (a: Range, b: Range) => (t: number) => Output): Log; - - clamp(): boolean; - clamp(clamp: boolean): Log; - - nice(): Log; - - ticks(): number[]; - - tickFormat(count?: number, format?: string): (t: number) => string; - - copy(): Log; - } - - export function quantize(): Quantize; - - interface Quantize { - (x: number): T; - - invertExtent(y: T): [number, number]; - - domain(): number[]; - domain(numbers: number[]): Quantize; - - range(): T[]; - range(values: T[]): Quantize; - - copy(): Quantize; - } - - export function quantile(): Quantile; - - interface Quantile { - (x: number): T; - - invertExtent(y: T): [number, number]; - - domain(): number[]; - domain(numbers: number[]): Quantile; - - range(): T[]; - range(values: T[]): Quantile; - - quantiles(): number[]; - - copy(): Quantile; - } - - export function threshold(): Threshold; - export function threshold(): Threshold; - - interface Threshold { - (x: number): Range; - - invertExtent(y: Range): [Domain, Domain]; - - domain(): Domain[]; - domain(domain: Domain[]): Threshold; - - range(): Range[]; - range(values: Range[]): Threshold; - - copy(): Threshold; - } - - export function ordinal(): Ordinal; - export function ordinal(): Ordinal; - export function category10(): Ordinal; - export function category10(): Ordinal; - export function category20(): Ordinal; - export function category20(): Ordinal; - export function category20b(): Ordinal; - export function category20b(): Ordinal; - export function category20c(): Ordinal; - export function category20c(): Ordinal; - - interface Ordinal { - (x: Domain): Range; - - domain(): Domain[]; - domain(values: Domain[]): Ordinal; - - range(): Range[]; - range(values: Range[]): Ordinal; - - rangePoints(interval: [number, number], padding?: number): Ordinal; - rangeRoundPoints(interval: [number, number], padding?: number): Ordinal; - - rangeBands(interval: [number, number], padding?: number, outerPadding?: number): Ordinal; - rangeRoundBands(interval: [number, number], padding?: number, outerPadding?: number): Ordinal; - - rangeBand(): number; - rangeExtent(): [number, number]; - - copy(): Ordinal; - } - } - - export function interpolate(a: number, b: number): (t: number) => number; - export function interpolate(a: string, b: string): (t: number) => string; - export function interpolate(a: string | Color, b: Color): (t: number) => string; - export function interpolate(a: Array, b: Color[]): (t: number) => string; - export function interpolate(a: Range[], b: Output[]): (t: number) => Output[]; - export function interpolate(a: Range[], b: Range[]): (t: number) => Output[]; - export function interpolate(a: { [key: string]: string | Color }, b: { [key: string]: Color }): (t: number) => { [key: string]: string }; - export function interpolate(a: { [key: string]: Range }, b: { [key: string]: Output }): (t: number) => { [key: string]: Output }; - export function interpolate(a: { [key: string]: Range }, b: { [key: string]: Range }): (t: number) => { [key: string]: Output }; - - export function interpolateNumber(a: number, b: number): (t: number) => number; - - export function interpolateRound(a: number, b: number): (t: number) => number; - - export function interpolateString(a: string, b: string): (t: number) => string; - - export function interpolateRgb(a: string | Color, b: string | Color): (t: number) => string; - - export function interpolateHsl(a: string | Color, b: string | Color): (t: number) => string; - - export function interpolateLab(a: string | Color, b: string | Color): (t: number) => string; - - export function interpolateHcl(a: string | Color, b: string | Color): (t: number) => string; - - export function interpolateArray(a: Array, b: Color[]): (t: number) => string[]; - export function interpolateArray(a: Range[], b: Range[]): (t: number) => Output[]; - export function interpolateArray(a: Range[], b: Output[]): (t: number) => Output[]; - - export function interpolateObject(a: { [key: string]: string | Color }, b: { [key: string]: Color }): (t: number) => { [key: string]: string }; - export function interpolateObject(a: { [key: string]: Range }, b: { [key: string]: Output }): (t: number) => { [key: string]: Output }; - export function interpolateObject(a: { [key: string]: Range }, b: { [key: string]: Range }): (t: number) => { [key: string]: Output }; - - export function interpolateTransform(a: string | Transform, b: string | Transform): (t: number) => string; - - export function interpolateZoom(a: [number, number, number], b: [number, number, number]): { - (t: number): [number, number, number]; - duration: number; - }; - - export var interpolators: Array<(a: any, b: any) => (t: number) => any>; - - export module time { - export var second: Interval; - export var minute: Interval; - export var hour: Interval; - export var day: Interval; - export var week: Interval; - export var sunday: Interval; - export var monday: Interval; - export var tuesday: Interval; - export var wednesday: Interval; - export var thursday: Interval; - export var friday: Interval; - export var saturday: Interval; - export var month: Interval; - export var year: Interval; - - interface Interval { - (d: Date): Date; - - floor(d: Date): Date; - - round(d: Date): Date; - - ceil(d: Date): Date; - - range(start: Date, stop: Date, step?: number): Date[]; - - offset(date: Date, step: number): Date; - - utc: { - (d: Date): Date; - - floor(d: Date): Date; - - round(d: Date): Date; - - ceil(d: Date): Date; - - range(start: Date, stop: Date, step?: number): Date[]; - - offset(date: Date, step: number): Date; - } - } - - export function seconds(start: Date, stop: Date, step?: number): Date[]; - export function minutes(start: Date, stop: Date, step?: number): Date[]; - export function hours(start: Date, stop: Date, step?: number): Date[]; - export function days(start: Date, stop: Date, step?: number): Date[]; - export function weeks(start: Date, stop: Date, step?: number): Date[]; - export function sundays(start: Date, stop: Date, step?: number): Date[]; - export function mondays(start: Date, stop: Date, step?: number): Date[]; - export function tuesdays(start: Date, stop: Date, step?: number): Date[]; - export function wednesdays(start: Date, stop: Date, step?: number): Date[]; - export function thursdays(start: Date, stop: Date, step?: number): Date[]; - export function fridays(start: Date, stop: Date, step?: number): Date[]; - export function saturdays(start: Date, stop: Date, step?: number): Date[]; - export function months(start: Date, stop: Date, step?: number): Date[]; - export function years(start: Date, stop: Date, step?: number): Date[]; - - export function dayOfYear(d: Date): number; - export function weekOfYear(d: Date): number; - export function sundayOfYear(d: Date): number; - export function mondayOfYear(d: Date): number; - export function tuesdayOfYear(d: Date): number; - export function wednesdayOfYear(d: Date): number; - export function fridayOfYear(d: Date): number; - export function saturdayOfYear(d: Date): number; - - export function format(specifier: string): Format; - - export module format { - export function multi(formats: Array<[string, (d: Date) => boolean|number]>): Format; - export function utc(specifier: string): Format; - namespace utc { - export function multi(formats: Array<[string, (d: Date) => boolean|number]>): Format; - } - - export var iso: Format; - } - - interface Format { - (d: Date): string; - parse(input: string): Date; - } - - export function scale(): Scale; - export function scale(): Scale; - export function scale(): Scale; - - export module scale { - export function utc(): Scale; - export function utc(): Scale; - export function utc(): Scale; - } - - - interface Scale { - (x: Date): Output; - - invert(y: number): Date; - - domain(): Date[]; - domain(dates: number[]): Scale; - domain(dates: Date[]): Scale; - - nice(): Scale; - nice(interval: Interval, step?: number): Scale; - - range(): Range[]; - range(values: Range[]): Scale; - - rangeRound(values: number[]): Scale; - - interpolate(): (a: Range, b: Range) => (t: number) => Output; - interpolate(factory: (a: Range, b: Range) => (t: number) => Output): Scale; - - clamp(): boolean; - clamp(clamp: boolean): Scale; - - ticks(): Date[]; - ticks(interval: Interval, step?: number): Date[]; - ticks(count: number): Date[]; - - tickFormat(count: number): (d: Date) => string; - - copy(): Scale; - } - } - - export module behavior { - export function drag(): Drag; - - interface Drag { - (selection: Selection): void; - - on(type: string): (d: Datum, i: number) => any; - on(type: string, listener: (d: Datum, i: number) => any): Drag; - - origin(): (d: Datum, i: number) => { x: number; y: number }; - origin(accessor: (d: Datum, i: number) => { x: number; y: number }): Drag; - } - - export function zoom(): Zoom; - - namespace zoom { - interface Scale { - domain(): number[]; - domain(values: number[]): Scale; - - invert(y: number): number; - - range(values: number[]): Scale; - range(): number[]; - } - } - - interface Zoom { - (selection: Selection): void; - - translate(): [number, number]; - translate(translate: [number, number]): Zoom; - - scale(): number; - scale(scale: number): Zoom; - - scaleExtent(): [number, number]; - scaleExtent(extent: [number, number]): Zoom; - - center(): [number, number]; - center(center: [number, number]): Zoom; - - size(): [number, number]; - size(size: [number, number]): Zoom; - - x(): zoom.Scale; - x(x: zoom.Scale): Zoom; - - y(): zoom.Scale; - y(y: zoom.Scale): Zoom; - - on(type: string): (d: Datum, i: number) => any; - on(type: string, listener: (d: Datum, i: number) => any): Zoom; - - event(selection: Selection): void; - event(transition: Transition): void; - } - } - - export module geo { - export function path(): Path; - - interface Path { - (feature: any, index?: number): string; - - area(feature: any): number; - - centroid(feature: any): [number, number]; - - bounds(feature: any): [[number, number], [number, number]]; - - projection(): Transform | ((coordinates: [number, number]) => [number, number]); - projection(stream: Transform): Path; - projection(projection: (coordinates: [number, number]) => [number, number]): Path; - - pointRadius(): number | ((datum: any, index: number) => number); - pointRadius(radius: number): Path; - pointRadius(radius: (datum: any, index: number) => number): Path; - - context(): CanvasRenderingContext2D; - context(context: CanvasRenderingContext2D): Path; - } - - export function graticule(): Graticule; - - interface Graticule { - (): any; - - lines(): any[]; - - outline(): any; - - extent(): [[number, number], [number, number]]; - extent(extent: [[number, number], [number, number]]): Graticule; - - majorExtent(): [[number, number], [number, number]]; - majorExtent(extent: [[number, number], [number, number]]): Graticule; - - minorExtent(): [[number, number], [number, number]]; - minorExtent(extent: [[number, number], [number, number]]): Graticule; - - step(): [number, number]; - step(step: [number, number]): Graticule; - - majorStep(): [number, number]; - majorStep(step: [number, number]): Graticule; - - minorStep(): [number, number]; - minorStep(step: [number, number]): Graticule; - - precision(): number; - precision(precision: number): Graticule; - } - - export function circle(): Circle; - - interface Circle { - (...args: any[]): any; - - origin(): [number, number] | ((...args: any[]) => [number, number]); - origin(origin: [number, number]): Circle; - origin(origin: (...args: any[]) => [number, number]): Circle; - - angle(): number; - angle(angle: number): Circle; - - precision(): number; - precision(precision: number): Circle; - } - - export function area(feature: any): number; - export function centroid(feature: any): [number, number]; - export function bounds(feature: any): [[number, number], [number, number]]; - export function distance(a: [number, number], b: [number, number]): number; - export function length(feature: any): number; - export function interpolate(a: [number, number], b: [number, number]): (t: number) => [number, number]; - - export function rotation(rotate: [number, number] | [number, number, number]): Rotation; - - interface Rotation { - (location: [number, number]): [number, number]; - invert(location: [number, number]): [number, number]; - } - - export function stream(object: any, listener: Listener): void; - - interface Listener { - point(x: number, y: number, z: number): void; - lineStart(): void; - lineEnd(): void; - polygonStart(): void; - polygonEnd(): void; - sphere(): void; - } - - export function transform(methods: TransformMethods): Transform; - - interface TransformMethods { - point?(x: number, y: number, z: number): void; - lineStart?(): void; - lineEnd?(): void; - polygonStart?(): void; - polygonEnd?(): void; - sphere?(): void; - } - - interface Transform { - stream(stream: Listener): Listener; - } - - export function clipExtent(): ClipExtent; - - interface ClipExtent extends Transform { - extent(): [[number, number], [number, number]]; - extent(extent: [[number, number], [number, number]]): ClipExtent; - } - - export function projection(raw: RawInvertibleProjection): InvertibleProjection; - export function projection(raw: RawProjection): Projection; - - export function projectionMutator(factory: (...args: any[]) => RawInvertibleProjection): (...args: any[]) => InvertibleProjection; - export function projectionMutator(factory: (...args: any[]) => RawProjection): (...args: any[]) => Projection; - - export function albers(): ConicProjection; - export function albersUsa(): ConicProjection; - export function azimuthalEqualArea(): InvertibleProjection; - namespace azimuthalEqualArea { - export function raw(lambda: number, phi: number): [number, number]; - namespace raw { - export function invert(x: number, y: number): [number, number]; - } - } - - export function azimuthalEquidistant(): InvertibleProjection; - namespace azimuthalEquidistant { - export function raw(lambda: number, phi: number): [number, number]; - namespace raw { - export function invert(x: number, y: number): [number, number]; - } - } - - export function conicConformal(): ConicProjection; - namespace conicConformal { - export function raw(phi0: number, phi1: number): RawInvertibleProjection; - } - - export function conicEqualArea(): ConicProjection; - namespace conicEqualArea { - export function raw(phi0: number, phi1: number): RawInvertibleProjection; - } - - export function conicEquidistant(): ConicProjection; - namespace conicEquidistant { - export function raw(phi0: number, phi1: number): RawInvertibleProjection; - } - - export function equirectangular(): InvertibleProjection; - namespace equirectangular { - export function raw(lambda: number, phi: number): [number, number]; - namespace raw { - export function invert(x: number, y: number): [number, number]; - } - } - - export function gnomonic(): InvertibleProjection; - namespace gnomonic { - export function raw(lambda: number, phi: number): [number, number]; - namespace raw { - export function invert(x: number, y: number): [number, number]; - } - } - - export function mercator(): InvertibleProjection; - namespace mercator { - export function raw(lambda: number, phi: number): [number, number]; - namespace raw { - export function invert(x: number, y: number): [number, number]; - } - } - - export function orthographic(): InvertibleProjection; - namespace orthographic { - export function raw(lambda: number, phi: number): [number, number]; - namespace raw { - export function invert(x: number, y: number): [number, number]; - } - } - - export function stereographic(): InvertibleProjection; - namespace stereographic { - export function raw(lambda: number, phi: number): [number, number]; - namespace raw { - export function invert(x: number, y: number): [number, number]; - } - } - - export function transverseMercator(): InvertibleProjection; - namespace transverseMercator { - export function raw(lambda: number, phi: number): [number, number]; - namespace raw { - export function invert(x: number, y: number): [number, number]; - } - } - - interface Projection { - (location: [number, number]): [number, number]; - - rotate(): [number, number, number]; - rotate(rotation: [number, number, number]): Projection; - - center(): [number, number]; - center(location: [number, number]): Projection; - - translate(): [number, number]; - translate(point: [number, number]): Projection; - - scale(): number; - scale(scale: number): Projection; - - clipAngle(): number; - clipAngle(angle: number): Projection; - - clipExtent(): [[number, number], [number, number]]; - clipExtent(extent: [[number, number], [number, number]]): Projection; - - precision(): number; - precision(precision: number): Projection; - - stream(listener: Listener): Listener; - } - - interface InvertibleProjection extends Projection { - invert(point: [number, number]): [number, number]; - } - - interface ConicProjection extends InvertibleProjection { - parallels(): [number, number]; - parallels(parallels: [number, number]): ConicProjection; - - rotate(): [number, number, number]; - rotate(rotation: [number, number, number]): ConicProjection; - - center(): [number, number]; - center(location: [number, number]): ConicProjection; - - translate(): [number, number]; - translate(point: [number, number]): ConicProjection; - - scale(): number; - scale(scale: number): ConicProjection; - - clipAngle(): number; - clipAngle(angle: number): ConicProjection; - - clipExtent(): [[number, number], [number, number]]; - clipExtent(extent: [[number, number], [number, number]]): ConicProjection; - - precision(): number; - precision(precision: number): ConicProjection; - } - - interface RawProjection { - (lambda: number, phi: number): [number, number]; - } - - interface RawInvertibleProjection extends RawProjection { - invert(x: number, y: number): [number, number]; - } - } - - namespace svg { - export function line(): Line<[number, number]>; - export function line(): Line; - - interface Line { - (data: T[]): string; - - x(): number | ((d: T, i: number) => number); - x(x: number): Line; - x(x: (d: T, i: number) => number): Line; - - y(): number | ((d: T, i: number) => number); - y(x: number): Line; - y(y: (d: T, i: number) => number): Line; - - interpolate(): string | ((points: Array<[number, number]>) => string); - interpolate(interpolate: "linear"): Line; - interpolate(interpolate: "linear-closed"): Line; - interpolate(interpolate: "step"): Line; - interpolate(interpolate: "step-before"): Line; - interpolate(interpolate: "step-after"): Line; - interpolate(interpolate: "basis"): Line; - interpolate(interpolate: "basis-open"): Line; - interpolate(interpolate: "basis-closed"): Line; - interpolate(interpolate: "bundle"): Line; - interpolate(interpolate: "cardinal"): Line; - interpolate(interpolate: "cardinal-open"): Line; - interpolate(interpolate: "cardinal-closed"): Line; - interpolate(interpolate: "monotone"): Line; - interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Line; - - tension(): number; - tension(tension: number): Line; - - defined(): (d: T, i: number) => boolean; - defined(defined: (d: T, i: number) => boolean): Line; - } - - namespace line { - export function radial(): Radial<[number, number]>; - export function radial(): Radial; - - interface Radial { - (data: T[]): string; - - radius(): number | ((d: T, i: number) => number); - radius(radius: number): Radial; - radius(radius: (d: T, i: number) => number): Radial; - - angle(): number | ((d: T, i: number) => number); - angle(angle: number): Radial; - angle(angle: (d: T, i: number) => number): Radial; - - interpolate(): string | ((points: Array<[number, number]>) => string); - interpolate(interpolate: "linear"): Radial; - interpolate(interpolate: "linear-closed"): Radial; - interpolate(interpolate: "step"): Radial; - interpolate(interpolate: "step-before"): Radial; - interpolate(interpolate: "step-after"): Radial; - interpolate(interpolate: "basis"): Radial; - interpolate(interpolate: "basis-open"): Radial; - interpolate(interpolate: "basis-closed"): Radial; - interpolate(interpolate: "bundle"): Radial; - interpolate(interpolate: "cardinal"): Radial; - interpolate(interpolate: "cardinal-open"): Radial; - interpolate(interpolate: "cardinal-closed"): Radial; - interpolate(interpolate: "monotone"): Radial; - interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Radial; - - tension(): number; - tension(tension: number): Radial; - - defined(): (d: T, i: number) => boolean; - defined(defined: (d: T, i: number) => boolean): Radial; - } - } - - export function area(): Area<[number, number]>; - export function area(): Area; - - interface Area { - (data: T[]): string; - - x(): number | ((d: T, i: number) => number); - x(x: number): Area; - x(x: (d: T, i: number) => number): Area; - - x0(): number | ((d: T, i: number) => number); - x0(x0: number): Area; - x0(x0: (d: T, i: number) => number): Area; - - x1(): number | ((d: T, i: number) => number); - x1(x1: number): Area; - x1(x1: (d: T, i: number) => number): Area; - - y(): number | ((d: T, i: number) => number); - y(y: number): Area; - y(y: (d: T, i: number) => number): Area; - - y0(): number | ((d: T, i: number) => number); - y0(y0: number): Area; - y0(y0: (d: T, i: number) => number): Area; - - y1(): number | ((d: T, i: number) => number); - y1(y1: number): Area; - y1(y1: (d: T, i: number) => number): Area; - - interpolate(): string | ((points: Array<[number, number]>) => string); - interpolate(interpolate: "linear"): Area; - interpolate(interpolate: "step"): Area; - interpolate(interpolate: "step-before"): Area; - interpolate(interpolate: "step-after"): Area; - interpolate(interpolate: "basis"): Area; - interpolate(interpolate: "basis-open"): Area; - interpolate(interpolate: "cardinal"): Area; - interpolate(interpolate: "cardinal-open"): Area; - interpolate(interpolate: "monotone"): Area; - interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Area; - - tension(): number; - tension(tension: number): Area; - - defined(): (d: T, i: number) => boolean; - defined(defined: (d: T, i: number) => boolean): Area; - } - - namespace area { - export function radial(): Radial<[number, number]>; - export function radial(): Radial; - - interface Radial { - (data: T[]): string; - - radius(): number | ((d: T, i: number) => number); - radius(radius: number): Radial; - radius(radius: (d: T, i: number) => number): Radial; - - innerRadius(): number | ((d: T, i: number) => number); - innerRadius(innerRadius: number): Radial; - innerRadius(innerRadius: (d: T, i: number) => number): Radial; - - outerRadius(): number | ((d: T, i: number) => number); - outerRadius(outerRadius: number): Radial; - outerRadius(outerRadius: (d: T, i: number) => number): Radial; - - angle(): number | ((d: T, i: number) => number); - angle(angle: number): Radial; - angle(angle: (d: T, i: number) => number): Radial; - - startAngle(): number | ((d: T, i: number) => number); - startAngle(startAngle: number): Radial; - startAngle(startAngle: (d: T, i: number) => number): Radial; - - endAngle(): number | ((d: T, i: number) => number); - endAngle(endAngle: number): Radial; - endAngle(endAngle: (d: T, i: number) => number): Radial; - - interpolate(): string | ((points: Array<[number, number]>) => string); - interpolate(interpolate: "linear"): Radial; - interpolate(interpolate: "step"): Radial; - interpolate(interpolate: "step-before"): Radial; - interpolate(interpolate: "step-after"): Radial; - interpolate(interpolate: "basis"): Radial; - interpolate(interpolate: "basis-open"): Radial; - interpolate(interpolate: "cardinal"): Radial; - interpolate(interpolate: "cardinal-open"): Radial; - interpolate(interpolate: "monotone"): Radial; - interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Radial; - - tension(): number; - tension(tension: number): Radial; - - defined(): (d: T, i: number) => boolean; - defined(defined: (d: T, i: number) => boolean): Radial; - } - } - - export function arc(): Arc; - export function arc(): Arc; - - namespace arc { - interface Arc { - innerRadius: number; - outerRadius: number; - startAngle: number; - endAngle: number; - padAngle: number - } - } - - interface Arc { - (d: T, i?: number): string; - - innerRadius(): (d: T, i: number) => number; - innerRadius(radius: number): Arc; - innerRadius(radius: (d: T, i: number) => number): Arc; - - outerRadius(): (d: T, i: number) => number; - outerRadius(radius: number): Arc; - outerRadius(radius: (d: T, i: number) => number): Arc; - - cornerRadius(): (d: T, i: number) => number; - cornerRadius(radius: number): Arc; - cornerRadius(radius: (d: T, i: number) => number): Arc; - - padRadius(): string | ((d: T, i: number) => number); - padRadius(radius: "auto"): Arc; - padRadius(radius: string): Arc; - padRadius(radius: (d: T, i: number) => number): Arc; - - startAngle(): (d: T, i: number) => number; - startAngle(angle: number): Arc; - startAngle(angle: (d: T, i: number) => number): Arc; - - endAngle(): (d: T, i: number) => number; - endAngle(angle: number): Arc; - endAngle(angle: (d: T, i: number) => number): Arc; - - padAngle(): (d: T, i: number) => number; - padAngle(angle: number): Arc; - padAngle(angle: (d: T, i: number) => number): Arc; - - centroid(d: T, i?: number): [number, number]; - } - - export function symbol(): Symbol<{}>; - export function symbol(): Symbol; - - interface Symbol { - (d: T, i?: number): string; - - type(): (d: T, i: number) => string; - type(type: string): Symbol; - type(type: (d: T, i: number) => string): Symbol; - - size(): (d: T, i: string) => number; - size(size: number): Symbol; - size(size: (d: T, i: number) => number): Symbol; - } - - export var symbolTypes: string[]; - - export function chord(): Chord, chord.Node>; - export function chord(): Chord, Node>; - export function chord(): Chord; - - namespace chord { - interface Link { - source: Node; - target: Node; - } - - interface Node { - radius: number; - startAngle: number; - endAngle: number - } - } - - interface Chord { - (d: Link, i: number): string; - - source(): (d: Link, i: number) => Node; - source(source: Node): Chord; - source(source: (d: Link, i: number) => Node): Chord; - - target(): (d: Link, i: number) => Node; - target(target: Node): Chord; - target(target: (d: Link, i: number) => Node): Chord; - - radius(): (d: Node, i: number) => number; - radius(radius: number): Chord; - radius(radius: (d: Node, i: number) => number): Chord; - - startAngle(): (d: Node, i: number) => number; - startAngle(angle: number): Chord; - startAngle(angle: (d: Node, i: number) => number): Chord; - - endAngle(): (d: Node, i: number) => number; - endAngle(angle: number): Chord; - endAngle(angle: (d: Node, i: number) => number): Chord; - } - - export function diagonal(): Diagonal, diagonal.Node>; - export function diagonal(): Diagonal, Node>; - export function diagonal(): Diagonal; - - namespace diagonal { - interface Link { - source: Node; - target: Node; - } - - interface Node { - x: number; - y: number; - } - } - - interface Diagonal { - (d: Link, i?: number): string; - - source(): (d: Link, i: number) => Node; - source(source: Node): Diagonal; - source(source: (d: Link, i: number) => { x: number; y: number; }): Diagonal; - - target(): (d: Link, i: number) => Node; - target(target: Node): Diagonal; - target(target: (d: Link, i: number) => { x: number; y: number; }): Diagonal; - - projection(): (d: Node, i: number) => [number, number]; - projection(projection: (d: Node, i: number) => [number, number]): Diagonal; - } - - namespace diagonal { - export function radial(): Radial, Node>; - export function radial(): Radial, Node>; - export function radial(): Radial; - - interface Radial { - (d: Link, i: number): string; - - source(): (d: Link, i: number) => Node; - source(source: Node): Radial; - source(source: (d: Link, i: number) => Node): Radial; - - target(): (d: Link, i: number) => Node; - target(target: Node): Radial; - target(target: (d: Link, i: number) => Node): Radial; - - projection(): (d: Node, i: number) => [number, number]; - projection(projection: (d: Node, i: number) => [number, number]): Radial; - } - } - - export function axis(): Axis; - - interface Axis { - (selection: Selection): void; - (selection: Transition): void; - - scale(): any; - scale(scale: any): Axis; - - orient(): string; - orient(orientation: string): Axis; - - ticks(): any[]; - ticks(...args: any[]): Axis; - - tickValues(): any[]; - tickValues(values: any[]): Axis; - - tickSize(): number; - tickSize(size: number): Axis; - tickSize(inner: number, outer: number): Axis; - - innerTickSize(): number; - innerTickSize(size: number): Axis; - - outerTickSize(): number; - outerTickSize(size: number): Axis; - - tickPadding(): number; - tickPadding(padding: number): Axis; - - tickFormat(): (t: any) => string; - tickFormat(format: (t: any) => string): Axis; - tickFormat(format:string): Axis; - } - - export function brush(): Brush; - export function brush(): Brush; - - namespace brush { - interface Scale { - domain(): number[]; - domain(domain: number[]): Scale; - - range(): number[]; - range(range: number[]): Scale; - - invert?(y: number): number; - } - } - - interface Brush { - (selection: Selection): void; - (selection: Transition): void; - - event(selection: Selection): void; - event(selection: Transition): void; - - x(): brush.Scale; - x(x: brush.Scale): Brush; - - y(): brush.Scale; - y(y: brush.Scale): Brush; - - extent(): [number, number] | [[number, number], [number, number]]; - extent(extent: [number, number] | [[number, number], [number, number]]): Brush; - - clamp(): boolean | [boolean, boolean]; - clamp(clamp: boolean | [boolean, boolean]): Brush; - - clear(): void; - - empty(): boolean; - - on(type: 'brushstart'): (datum: T, index: number) => void; - on(type: 'brush'): (datum: T, index: number) => void; - on(type: 'brushend'): (datum: T, index: number) => void; - on(type: string): (datum: T, index: number) => void; - - on(type: 'brushstart', listener: (datum: T, index: number) => void): Brush; - on(type: 'brush', listener: (datum: T, index: number) => void): Brush; - on(type: 'brushend', listener: (datum: T, index: number) => void): Brush; - on(type: string, listener: (datum: T, index: number) => void): Brush; - } - } - - export function xhr(url: string, mimeType?: string, callback?: (err: any, data: any) => void): Xhr; - export function xhr(url: string, callback: (err: any, data: any) => void): Xhr; - - interface Xhr { - header(name: string): string; - header(name: string, value: string): Xhr; - - mimeType(): string; - mimeType(type: string): Xhr; - - responseType(): string; - responseType(type: string): Xhr; - - response(): (request: XMLHttpRequest) => any; - response(value: (request: XMLHttpRequest) => any): Xhr; - - get(callback?: (err: any, data: any) => void): Xhr; - - post(data?: any, callback?: (err: any, data: any) => void): Xhr; - post(callback: (err: any, data: any) => void): Xhr; - - send(method: string, data?: any, callback?: (err: any, data: any) => void): Xhr; - send(method: string, callback: (err: any, data: any) => void): Xhr; - - abort(): Xhr; - - on(type: "beforesend"): (request: XMLHttpRequest) => void; - on(type: "progress"): (request: XMLHttpRequest) => void; - on(type: "load"): (response: any) => void; - on(type: "error"): (err: any) => void; - on(type: string): (...args: any[]) => void; - - on(type: "beforesend", listener: (request: XMLHttpRequest) => void): Xhr; - on(type: "progress", listener: (request: XMLHttpRequest) => void): Xhr; - on(type: "load", listener: (response: any) => void): Xhr; - on(type: "error", listener: (err: any) => void): Xhr; - on(type: string, listener: (...args: any[]) => void): Xhr; - } - - export function text(url: string, mimeType?: string, callback?: (err: any, data: string) => void): Xhr; - export function text(url: string, callback: (err: any, data: string) => void): Xhr; - - export function json(url: string, callback?: (err: any, data: any) => void): Xhr; - - export function xml(url: string, mimeType?: string, callback?: (err: any, data: any) => void): Xhr; - export function xml(url: string, callback: (err: any, data: any) => void): Xhr; - - export function html(url: string, callback?: (err: any, data: DocumentFragment) => void): Xhr; - - export var csv: Dsv; - export var tsv: Dsv; - export function dsv(delimiter: string, mimeType: string): Dsv; - - interface Dsv { - (url: string, callback: (rows: { [key: string]: string }[]) => void): DsvXhr<{ [key: string]: string }>; - (url: string, callback: (error: any, rows: { [key: string]: string }[]) => void): DsvXhr<{ [key: string]: string }>; - (url: string): DsvXhr<{ [key: string]: string }>; - (url: string, accessor: (row: { [key: string]: string }) => T, callback: (rows: T[]) => void): DsvXhr; - (url: string, accessor: (row: { [key: string]: string }) => T, callback: (error: any, rows: T[]) => void): DsvXhr; - (url: string, accessor: (row: { [key: string]: string }) => T): DsvXhr; - - parse(string: string): { [key: string]: string }[]; - parse(string: string, accessor: (row: { [key: string]: string }, index: number) => T): T[]; - - parseRows(string: string): string[][]; - parseRows(string: string, accessor: (row: string[], index: number) => T): T[]; - - format(rows: Object[]): string; - - formatRows(rows: string[][]): string; - } - - interface DsvXhr extends Xhr { - row(): (row: { [key: string]: string }) => T; - row(accessor: (row: { [key: string]: string }) => U): DsvXhr; - - header(name: string): string; - header(name: string, value: string): DsvXhr; - - mimeType(): string; - mimeType(type: string): DsvXhr; - - responseType(): string; - responseType(type: string): DsvXhr; - - response(): (request: XMLHttpRequest) => any; - response(value: (request: XMLHttpRequest) => any): DsvXhr; - - get(callback?: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; - post(data?: any, callback?: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; - post(callback: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; - - send(method: string, data?: any, callback?: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; - send(method: string, callback: (err: XMLHttpRequest, data: T[]) => void): DsvXhr; - - abort(): DsvXhr; - - on(type: "beforesend"): (request: XMLHttpRequest) => void; - on(type: "progress"): (request: XMLHttpRequest) => void; - on(type: "load"): (response: T[]) => void; - on(type: "error"): (err: any) => void; - on(type: string): (...args: any[]) => void; - - on(type: "beforesend", listener: (request: XMLHttpRequest) => void): DsvXhr; - on(type: "progress", listener: (request: XMLHttpRequest) => void): DsvXhr; - on(type: "load", listener: (response: T[]) => void): DsvXhr; - on(type: "error", listener: (err: any) => void): DsvXhr; - on(type: string, listener: (...args: any[]) => void): DsvXhr; - } - - export function locale(definition: LocaleDefinition): Locale; - - interface LocaleDefinition { - decimal: string; - thousands: string; - grouping: number[]; - currency: [string, string]; - dateTime: string; - date: string; - time: string; - periods: [string, string]; - days: [string, string, string, string, string, string, string]; - shortDays: [string, string, string, string, string, string, string]; - months: [string, string, string, string, string, string, string, string, string, string, string, string]; - shortMonths: [string, string, string, string, string, string, string, string, string, string, string, string]; - } - - interface Locale { - numberFormat(specifier: string): (n: number) => string; - timeFormat: { - (specifier: string): time.Format; - utc(specifier: string): time.Format; - multi(formats: Array<[string, (d: Date) => boolean|number]>): time.Format; - } - } - - namespace layout { - export function bundle(): Bundle; - export function bundle(): Bundle - - namespace bundle { - interface Node { - parent: Node; - } - - interface Link { - source: T; - target: T; - } - } - - interface Bundle { - (links: bundle.Link[]): T[][]; - } - - export function chord(): Chord; - - namespace chord { - interface Link { - source: Node; - target: Node; - } - - interface Node { - index: number; - subindex: number; - startAngle: number; - endAngle: number; - value: number; - } - - interface Group { - index: number; - startAngle: number; - endAngle: number; - value: number; - } - } - - interface Chord { - matrix(): number[][]; - matrix(matrix: number[][]): Chord; - - padding(): number; - padding(padding: number): Chord; - - sortGroups(): (a: number, b: number) => number; - sortGroups(comparator: (a: number, b: number) => number): Chord; - - sortSubgroups(): (a: number, b: number) => number; - sortSubgroups(comparator: (a: number, b: number) => number): Chord; - - sortChords(): (a: number, b: number) => number; - sortChords(comparator: (a: number, b: number) => number): Chord; - - chords(): chord.Link[]; - groups(): chord.Group[]; - } - - export function cluster(): Cluster; - export function cluster(): Cluster; - - namespace cluster { - interface Result { - parent?: Result; - children?: Result[]; - depth?: number; - x?: number; - y?: number; - } - - interface Link { - source: T; - target: T; - } - } - - interface Cluster { - (root: T): T[]; - - nodes(root: T): T[]; - - links(nodes: T[]): cluster.Link[]; - - children(): (node: T) => T[]; - children(accessor: (node: T) => T[]): Cluster; - - sort(): (a: T, b: T) => number; - sort(comparator: (a: T, b: T) => number): Cluster; - - separation(): (a: T, b: T) => number; - separation(separation: (a: T, b: T) => number): Cluster; - - size(): [number, number]; - size(size: [number, number]): Cluster; - - nodeSize(): [number, number]; - nodeSize(nodeSize: [number, number]): Cluster; - - value(): (a: T) => number; - value(value: (a: T) => number): Cluster; - } - - export function force(): Force, force.Node>; - export function force(): Force, Node>; - export function force, Node extends force.Node>(): Force; - - namespace force { - interface Link { - source: T; - target: T; - } - - interface Node { - index?: number; - x?: number; - y?: number; - px?: number; - py?: number; - fixed?: boolean; - weight?: number; - } - - interface Event { - type: string; - alpha: number; - } - } - - interface Force, Node extends force.Node> { - size(): [number, number]; - size(size: [number, number]): Force; - - linkDistance(): number | ((link: Link, index: number) => number); - linkDistance(distance: number): Force; - linkDistance(distance: (link: Link, index: number) => number): Force; - - linkStrength(): number | ((link: Link, index: number) => number); - linkStrength(strength: number): Force; - linkStrength(strength: (link: Link, index: number) => number): Force; - - friction(): number; - friction(friction: number): Force; - - charge(): number | ((node: Node, index: number) => number); - charge(charge: number): Force; - charge(charge: (node: Node, index: number) => number): Force; - - chargeDistance(): number; - chargeDistance(distance: number): Force; - - theta(): number; - theta(theta: number): Force; - - gravity(): number; - gravity(gravity: number): Force; - - nodes(): Node[]; - nodes(nodes: Node[]): Force; - - links(): Link[]; - links(links: { source: number; target: number }[]): Force; - links(links: Link[]): Force; - - start(): Force; - - tick(): Force; - - alpha(): number; - alpha(value: number): Force; - - resume(): Force; - - stop(): Force; - - on(type: string): (event: force.Event) => void; - on(type: string, listener: (event: force.Event) => void): Force; - - drag(): behavior.Drag; - drag(selection: Selection): void; - } - - export function hierarchy(): Hierarchy; - export function hierarchy(): Hierarchy; - - namespace hierarchy { - interface Result { - parent?: Result; - children?: Result[]; - value?: number; - depth?: number; - } - } - - interface Hierarchy { - (root: T): T[]; - - children(): (node: T) => T[]; - children(accessor: (node: T) => T[]): Hierarchy; - - sort(): (a: T, b: T) => number; - sort(comparator: (a: T, b: T) => number): Hierarchy; - - value(): (node: T) => number; - value(accessor: (node: T) => number): Hierarchy; - - revalue(root: T): T[]; - } - - export function histogram(): Histogram; - export function histogram(): Histogram; - - namespace histogram { - interface Bin extends Array { - x: number; - dx: number; - y: number; - } - } - - interface Histogram { - (values: T[], index?: number): histogram.Bin[]; - - value(): (datum: T, index: number) => number; - value(value: (datum: T, index: number) => number): Histogram; - - range(): (values: T[], index: number) => [number, number]; - range(range: (values: T[], index: number) => [number, number]): Histogram; - range(range: [number, number]): Histogram; - - bins(): (range: [number, number], values: T[], index: number) => number[]; - bins(count: number): Histogram; - bins(thresholds: number[]): Histogram; - bins(func: (range: [number, number], values: T[], index: number) => number[]): Histogram; - - frequency(): boolean; - frequency(frequency: boolean): Histogram; - } - - export function pack(): Pack; - export function pack(): Pack; - - namespace pack { - interface Node { - parent?: Node; - children?: Node[]; - value?: number; - depth?: number; - x?: number; - y?: number; - r?: number; - } - - interface Link { - source: Node; - target: Node; - } - } - - interface Pack { - (root: T): T[]; - - nodes(root: T): T[]; - - links(nodes: T[]): pack.Link[]; - - children(): (node: T, depth: number) => T[]; - children(children: (node: T, depth: number) => T[]): Pack; - - sort(): (a: T, b: T) => number; - sort(comparator: (a: T, b: T) => number): Pack; - - value(): (node: T) => number; - value(value: (node: T) => number): Pack; - - size(): [number, number]; - size(size: [number, number]): Pack; - - radius(): number | ((node: T) => number); - radius(radius: number): Pack; - radius(radius: (node: T) => number): Pack; - - padding(): number; - padding(padding: number): Pack; - } - - export function partition(): Partition; - export function partition(): Partition; - - namespace partition { - interface Link { - source: T; - target: T; - } - - interface Node { - parent?: Node; - children?: number; - value?: number; - depth?: number; - x?: number; - y?: number; - dx?: number; - dy?: number; - } - - } - - export interface Partition { - (root: T): T[]; - - nodes(root: T): T[]; - - links(nodes: T[]): partition.Link[]; - - children(): (node: T, depth: number) => T[]; - children(children: (node: T, depth: number) => T[]): Partition; - - sort(): (a: T, b: T) => number; - sort(comparator: (a: T, b: T) => number): Partition; - - value(): (node: T) => number; - value(value: (node: T) => number): Partition; - - size(): [number, number]; - size(size: [number, number]): Partition; - } - - export function pie(): Pie; - export function pie(): Pie; - - namespace pie { - interface Arc { - value: number; - startAngle: number; - endAngle: number; - padAngle: number; - data: T; - } - } - - interface Pie { - (data: T[], index?: number): pie.Arc[]; - - value(): (datum: T, index: number) => number; - value(accessor: (datum: T, index: number) => number): Pie; - - sort(): (a: T, b: T) => number; - sort(comparator: (a: T, b: T) => number): Pie; - - startAngle(): number | ((data: T[], index: number) => number); - startAngle(angle: number): Pie; - startAngle(angle: (data: T[], index: number) => number): Pie; - - endAngle(): number | ((data: T[], index: number) => number); - endAngle(angle: number): Pie; - endAngle(angle: (data: T[], index: number) => number): Pie; - - padAngle(): number | ((data: T[], index: number) => number); - padAngle(angle: number): Pie; - padAngle(angle: (data: T[], index: number) => number): Pie; - } - - export function stack(): Stack; - export function stack(): Stack; - export function stack(): Stack; - namespace stack { - interface Value { - x: number; - y: number; - y0?: number; - } - } - - interface Stack { - (layers: Series[], index?: number): Series[]; - - values(): (layer: Series, index: number) => Value[]; - values(accessor: (layer: Series, index: number) => Value[]): Stack; - - offset(): (data: Array<[number, number]>) => number[]; - offset(offset: "silhouette"): Stack; - offset(offset: "wiggle"): Stack; - offset(offset: "expand"): Stack; - offset(offset: "zero"): Stack; - offset(offset: string): Stack; - offset(offset: (data: Array<[number, number]>) => number[]): Stack; - - order(): (data: Array<[number, number]>) => number[]; - order(order: "inside-out"): Stack; - order(order: "reverse"): Stack; - order(order: "default"): Stack; - order(order: string): Stack; - order(order: (data: Array<[number, number]>) => number[]): Stack; - - x(): (value: Value, index: number) => number; - x(accessor: (value: Value, index: number) => number): Stack; - - y(): (value: Value, index: number) => number; - y(accesor: (value: Value, index: number) => number): Stack; - - out(): (value: Value, y0: number, y: number) => void; - out(setter: (value: Value, y0: number, y: number) => void): Stack; - } - - export function tree(): Tree; - export function tree(): Tree; - - namespace tree { - interface Link { - source: T; - target: T; - } - - interface Node { - parent?: Node; - children?: Node[]; - depth?: number; - x?: number; - y?: number; - } - } - - interface Tree { - (root: T, index?: number): T[]; - - nodes(root: T, index?: number): T[]; - - links(nodes: T[]): tree.Link[]; - - children(): (datum: T, index: number) => T[]; - children(children: (datum: T, index: number) => T[]): Tree; - - separation(): (a: T, b: T) => number; - separation(separation: (a: T, b: T) => number): Tree; - - size(): [number, number]; - size(size: [number, number]): Tree; - - nodeSize(): [number, number]; - nodeSize(size: [number, number]): Tree; - - sort(): (a: T, b: T) => number; - sort(comparator: (a: T, b: T) => number): Tree; - - value(): (datum: T, index: number) => number; - value(value: (datum: T, index: number) => number): Tree; - } - - export function treemap(): Treemap; - export function treemap(): Treemap; - - namespace treemap { - interface Node { - parent?: Node; - children?: Node[]; - value?: number; - depth?: number; - x?: number; - y?: number; - dx?: number; - dy?: number; - } - - interface Link { - source: T; - target: T; - } - - type Padding = number | [number, number, number, number]; - } - - interface Treemap { - (root: T, index?: number): T[]; - - nodes(root: T, index?: number): T[]; - - links(nodes: T[]): treemap.Link[]; - - children(): (node: T, depth: number) => T[]; - children(children: (node: T, depth: number) => T[]): Treemap; - - sort(): (a: T, b: T) => number; - sort(comparator: (a: T, b: T) => number): Treemap; - - value(): (node: T, index: number) => number; - value(value: (node: T, index: number) => number): Treemap; - - size(): [number, number]; - size(size: [number, number]): Treemap; - - padding(): (node: T, depth: number) => treemap.Padding; - padding(padding: treemap.Padding): Treemap; - padding(padding: (node: T, depth: number) => treemap.Padding): Treemap; - - round(): boolean; - round(round: boolean): Treemap; - - sticky(): boolean; - sticky(sticky: boolean): boolean; - - mode(): string; - mode(mode: "squarify"): Treemap; - mode(mode: "slice"): Treemap; - mode(mode: "dice"): Treemap; - mode(mode: "slice-dice"): Treemap; - mode(mode: string): Treemap; - - ratio(): number; - ratio(ratio: number): Treemap; - } - } - - namespace geom { - export function voronoi(): Voronoi<[number, number]>; - export function voronoi(): Voronoi; - - namespace voronoi { - interface Link { - source: T; - target: T; - } - } - - interface Voronoi { - (data: T[]): Array<[number, number]>; - - x(): (vertex: T) => number; - x(x: (vertex: T) => number): Voronoi; - - y(): (vertex: T) => number; - y(y: (vertex: T) => number): Voronoi; - - clipExtent(): [[number, number], [number, number]]; - clipExtent(extent: [[number, number], [number, number]]): Voronoi; - - links(data: T[]): voronoi.Link[]; - - triangles(data: T[]): Array<[T, T, T]>; - } - - /** - * @deprecated use d3.geom.voronoi().triangles() instead - */ - export function delaunay(vertices: Array<[number, number]>): Array<[[number, number], [number, number], [number, number]]>; - - export function quadtree(): Quadtree<[number, number]>; - export function quadtree(nodes: T[], x1?: number, y1?: number, x2?: number, y2?: number): quadtree.Quadtree; - - namespace quadtree { - interface Node { - nodes: [Node, Node, Node, Node]; - leaf: boolean; - point: T; - x: number; - y: number; - } - - interface Quadtree extends Node { - add(point: T): void; - visit(callback: (node: Node, x1: number, y1: number, x2: number, y2: number) => boolean | void): void; - find(point: [number, number]): T; - } - } - - interface Quadtree { - (points: T[]): quadtree.Quadtree; - - x(): (datum: T, index: number) => number; - x(x: number): Quadtree; - x(x: (datum: T, index: number) => number): Quadtree; - - y(): (datum: T, index: number) => number; - y(y: number): Quadtree; - y(y: (datum: T, index: number) => number): Quadtree; - - extent(): [[number, number], [number, number]]; - extent(extent: [[number, number], [number, number]]): Quadtree; - } - - export function hull(vertices: Array<[number, number]>): Array<[number, number]>; - export function hull(): Hull<[number, number]>; - export function hull(): Hull; - - interface Hull { - (vertices: T[]): Array<[number, number]>; - - x(): (datum: T) => number; - x(x: (datum: T) => number): Hull; - - y(): (datum: T) => number; - y(y: (datum: T) => number): Hull; - } - - export function polygon(vertices: Array<[number, number]>): Polygon; - - interface Polygon { - area(): number; - - centroid(): [number, number]; - - clip(subject: Array<[number, number]>): Array<[number, number]>; - } - } -} - -// we need this to exist -interface TouchList { } +export * from 'd3-array'; +export * from 'd3-axis'; +export * from 'd3-brush'; +export * from 'd3-chord'; +export * from 'd3-collection'; +export * from 'd3-color'; +export * from 'd3-dispatch'; +export * from 'd3-drag'; +export * from 'd3-dsv'; +export * from 'd3-ease'; +export * from 'd3-force'; +export * from 'd3-format'; +export * from 'd3-geo'; +export * from 'd3-hierarchy'; +export * from 'd3-interpolate'; +export * from 'd3-path'; +export * from 'd3-polygon'; +export * from 'd3-quadtree'; +export * from 'd3-queue'; +export * from 'd3-random'; +export * from 'd3-request'; +export * from 'd3-scale'; +export * from 'd3-selection'; +export * from 'd3-shape'; +export * from 'd3-time'; +export * from 'd3-time-format'; +export * from 'd3-timer'; +export * from 'd3-transition'; +export * from 'd3-voronoi'; +export * from 'd3-zoom'; diff --git a/d3/plugins/d3.superformula-tests.ts b/d3/legacy/plugins/d3.superformula-tests.ts similarity index 100% rename from d3/plugins/d3.superformula-tests.ts rename to d3/legacy/plugins/d3.superformula-tests.ts diff --git a/d3/plugins/index.d.ts b/d3/legacy/plugins/index.d.ts similarity index 100% rename from d3/plugins/index.d.ts rename to d3/legacy/plugins/index.d.ts diff --git a/d3/legacy/plugins/package.json b/d3/legacy/plugins/package.json new file mode 100644 index 0000000000..9996a98ea5 --- /dev/null +++ b/d3/legacy/plugins/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/d3": ">=3.5.36 <4.0.0" + } +} diff --git a/d3/package.json b/d3/package.json new file mode 100644 index 0000000000..e06dc77245 --- /dev/null +++ b/d3/package.json @@ -0,0 +1,34 @@ +{ + "dependencies": { + "@types/d3-array": "1.0", + "@types/d3-axis": "1.0", + "@types/d3-brush": "1.0", + "@types/d3-chord": "1.0", + "@types/d3-collection": "1.0", + "@types/d3-color": "1.0", + "@types/d3-dispatch": "1.0", + "@types/d3-drag": "1.0", + "@types/d3-dsv": "1.0", + "@types/d3-ease": "1.0", + "@types/d3-force": "1.0", + "@types/d3-format": "1.0", + "@types/d3-geo": "1.3", + "@types/d3-hierarchy": "1.0", + "@types/d3-interpolate": "1.1", + "@types/d3-path": "1.0", + "@types/d3-polygon": "1.0", + "@types/d3-quadtree": "1.0", + "@types/d3-queue": "3.0", + "@types/d3-random": "1.0", + "@types/d3-request": "1.0", + "@types/d3-scale": "1.0", + "@types/d3-selection": "1.0", + "@types/d3-shape": "1.0", + "@types/d3-time": "1.0", + "@types/d3-time-format": "2.0", + "@types/d3-timer": "1.0", + "@types/d3-transition": "1.0", + "@types/d3-voronoi": "1.1", + "@types/d3-zoom": "1.0" + } +} diff --git a/d3/plugins/tsconfig.json b/d3/plugins/tsconfig.json deleted file mode 100644 index c51065c21b..0000000000 --- a/d3/plugins/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../../", - "typesRoot": "../../", - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "d3.superformula-tests.ts" - ] -} \ No newline at end of file diff --git a/d3/tsconfig.json b/d3/tsconfig.json index 0d664ce882..6aa6325d68 100644 --- a/d3/tsconfig.json +++ b/d3/tsconfig.json @@ -6,6 +6,7 @@ "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ + "node_modules/@types", "../" ], "types": [], @@ -16,4 +17,4 @@ "index.d.ts", "d3-tests.ts" ] -} \ No newline at end of file +} diff --git a/d3kit/d3kit.d.ts b/d3kit/d3kit.d.ts index d5033d32df..ef6405b04d 100644 --- a/d3kit/d3kit.d.ts +++ b/d3kit/d3kit.d.ts @@ -152,4 +152,4 @@ declare namespace d3kit { declare module 'd3kit' { export = d3kit; -} \ No newline at end of file +} diff --git a/d3kit/package.json b/d3kit/package.json new file mode 100644 index 0000000000..5e771f4dcd --- /dev/null +++ b/d3kit/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/d3": "^3.5.36" + } +} diff --git a/d3kit/tsconfig.json b/d3kit/tsconfig.json index 67ab2f9e8c..1937b920e2 100644 --- a/d3kit/tsconfig.json +++ b/d3kit/tsconfig.json @@ -1,19 +1,20 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "d3kit.d.ts", - "d3kit-tests.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "node_modules/@types", + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "d3kit.d.ts", + "d3kit-tests.ts" + ] +} diff --git a/dagre-d3/dagre-d3-tests.ts b/dagre-d3/dagre-d3-tests.ts index d564d3ae43..30f9f682de 100644 --- a/dagre-d3/dagre-d3-tests.ts +++ b/dagre-d3/dagre-d3-tests.ts @@ -1,3 +1,4 @@ + namespace DagreD3Tests { const gDagre = new dagreD3.graphlib.Graph(); const graph = gDagre.graph(); diff --git a/dagre-d3/index.d.ts b/dagre-d3/index.d.ts index de2afa21c6..a502251124 100644 --- a/dagre-d3/index.d.ts +++ b/dagre-d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for dagre-d3.core.js +// Type definitions for dagre-d3.core.js v0.4.10 // Project: https://github.com/cpettitt/dagre-d3 // Definitions by: Mark Wong Siang Kai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/dagre-d3/package.json b/dagre-d3/package.json new file mode 100644 index 0000000000..5e771f4dcd --- /dev/null +++ b/dagre-d3/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/d3": "^3.5.36" + } +} diff --git a/dagre-d3/tsconfig.json b/dagre-d3/tsconfig.json index 35dbecf685..435af492e8 100644 --- a/dagre-d3/tsconfig.json +++ b/dagre-d3/tsconfig.json @@ -1,19 +1,20 @@ { - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "dagre-d3-tests.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "node_modules/@types", + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dagre-d3-tests.ts" + ] +} diff --git a/dat-gui/index.d.ts b/dat-gui/index.d.ts index 5a902b228b..7d1e2147d7 100644 --- a/dat-gui/index.d.ts +++ b/dat-gui/index.d.ts @@ -1,7 +1,7 @@ -// Type definitions for dat.GUI v0.5 +// Type definitions for dat.GUI v0.6.1 // Project: https://github.com/dataarts/dat.gui -// Definitions by: Satoru Kimura -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions by: Satoru Kimura , ZongJing Lu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace dat { export class GUI { @@ -23,11 +23,40 @@ declare namespace dat { addColor(target: Object, propName:string, rgba: number[]): GUIController; // rgb or rgba addColor(target: Object, propName:string, hsv:{h:number; s:number; v:number}): GUIController; + remove(controller: GUIController): void; + destroy(): void; + addFolder(propName:string): GUI; - close(): void; open(): void; - remember(target: Object): void; + close(): void; + + remember(target: Object, ...additionalTargets: Object[]): void; + getRoot(): GUI; + + getSaveObject(): Object; + save(): void; + saveAs(presetName:string): void; + revert(gui:GUI): void; + + listen(controller: GUIController): void; + updateDisplay(): void; + + // gui properties in dat/gui/GUI.js + parent(): GUI; + scrollable(): boolean; + autoPlace(): boolean; + preset(): string; + preset(s: string): void; + width(): number; + width(n: number): void; + name(): string; + name(s: string): void; + closed(): boolean; + closed(b: boolean): void; + load(): Object; + useLocalStorage(): boolean; + useLocalStorage(b: boolean): void; } export interface GUIParams{ @@ -41,17 +70,28 @@ declare namespace dat { export class GUIController { destroy(): void; - fire(): GUIController; - getValue(): any; - isModified(): boolean; - listen(): GUIController; - min(n: number): GUIController; - remove(target: GUIController): void; - setValue(value: any): GUIController; - step(n: number): GUIController; - updateDisplay(): void; + // Controller onChange: (value?: any) => void; onFinishChange: (value?: any) => void; + + setValue(value: any): GUIController; + getValue(): any; + updateDisplay(): void; + isModified(): boolean; + + // NumberController + min(n: number): GUIController; + max(n: number): GUIController; + step(n: number): GUIController; + + // FunctionController + fire(): GUIController; + + // augmentController in dat/gui/GUI.js + options(option:any):GUIController; + name(s: string): GUIController; + listen(): GUIController; + remove(): GUIController; } } diff --git a/date-fns/index.d.ts b/date-fns/index.d.ts index d0582c2571..bb78fe74e2 100644 --- a/date-fns/index.d.ts +++ b/date-fns/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for date-fns +// Type definitions for date-fns v2.5.1 // Project: https://date-fns.org/ // Definitions by: Matt Lewis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/dc/package.json b/dc/package.json new file mode 100644 index 0000000000..5e771f4dcd --- /dev/null +++ b/dc/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "@types/d3": "^3.5.36" + } +} diff --git a/dc/tsconfig.json b/dc/tsconfig.json index 2c29960d5b..21ec9c0d67 100644 --- a/dc/tsconfig.json +++ b/dc/tsconfig.json @@ -10,10 +10,11 @@ "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ + "node_modules/@types", "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/deep-assign/deep-assign-tests.ts b/deep-assign/deep-assign-tests.ts new file mode 100644 index 0000000000..f38a1fc378 --- /dev/null +++ b/deep-assign/deep-assign-tests.ts @@ -0,0 +1,10 @@ +import * as deepAssign from 'deep-assign'; + +deepAssign({a: 1}); +deepAssign({a: 1}, {b: 2}); +deepAssign({a: 1, b: {c: 2}}, {b: {e: 33}, x: 11}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}, {d: 4}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}, {f: 6}); +deepAssign({}, {a: 1}, {b: 2}, {c: 3}, {d: 4}, {e: 5}, {f: 6}, {g: 7}); diff --git a/deep-assign/index.d.ts b/deep-assign/index.d.ts new file mode 100644 index 0000000000..46d4cf09f2 --- /dev/null +++ b/deep-assign/index.d.ts @@ -0,0 +1,77 @@ +// Type definitions for clone 0.1.11 +// Project: https://github.com/sindresorhus/deep-assign +// Definitions by: Ionut Costica +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Pretty much just returns the target object + * @param target Base object + */ +declare function deepAssign(target: T): T; +/** + * Deeply assigns all the properties of the source object to the + * target object + * @param target Base object + * @param source Extending object + */ +declare function deepAssign(target: T, source: U): T & U; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + */ +declare function deepAssign(target: T, source1: U, source2: V): T & U & V; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + * @param source3 Third extending object + */ +declare function deepAssign(target: T, source1: U, source2: V, source3: W): T & U & V & W; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + * @param source3 Third extending object + * @param source4 Fourth extending object + */ +declare function deepAssign(target: T, source1: U, source2: V, source3: W, source4: X): T & U & V & W & X; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + * @param source3 Third extending object + * @param source4 Fourth extending object + * @param source5 Fifth extending object + */ +declare function deepAssign(target: T, source1: U, source2: V, source3: W, source4: X, source5: Y): T & U & V & W & X & Y; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param source1 First extending object + * @param source2 Second extending object + * @param source3 Third extending object + * @param source4 Fourth extending object + * @param source5 Fifth extending object + * @param source6 Sixth extending object + */ +declare function deepAssign(target: T, source1: U, source2: V, source3: W, source4: X, source5: Y, source6: Z): T & U & V & W & X & Y & Z; +/** + * Deeply assigns all the properties of the source objects to the + * target object + * @param target Base object + * @param sources Extending objects + */ +declare function deepAssign(target: any, ...sources: any[]): any; + +declare namespace deepAssign {} +export = deepAssign; diff --git a/deep-assign/tsconfig.json b/deep-assign/tsconfig.json new file mode 100644 index 0000000000..5f80a3df8f --- /dev/null +++ b/deep-assign/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "deep-assign-tests.ts" + ] +} diff --git a/deep-extend/deep-extend-tests.ts b/deep-extend/deep-extend-tests.ts index a69d60cfcc..7c909e74c8 100644 --- a/deep-extend/deep-extend-tests.ts +++ b/deep-extend/deep-extend-tests.ts @@ -1,5 +1,5 @@ -import deepExtend = require('deep-extend'); +import * as deepExtend from 'deep-extend'; var obj1 = { a: 1, b: 2, diff --git a/deep-extend/index.d.ts b/deep-extend/index.d.ts index a23daa519b..8c03cb9d10 100644 --- a/deep-extend/index.d.ts +++ b/deep-extend/index.d.ts @@ -11,4 +11,5 @@ declare function deepExtend(target: T, source: U): T & U; declare function deepExtend(target: T, source1: U, source2: V): T & U & V; declare function deepExtend(target: T, source1: U, source2: V, source3: W): T & U & V & W; declare function deepExtend(target: any, ...sources: any[]): any; +declare namespace deepExtend {} export = deepExtend; diff --git a/deep-extend/tsconfig.json b/deep-extend/tsconfig.json index 3b80dbec25..461af90b1b 100644 --- a/deep-extend/tsconfig.json +++ b/deep-extend/tsconfig.json @@ -16,4 +16,4 @@ "index.d.ts", "deep-extend-tests.ts" ] -} \ No newline at end of file +} diff --git a/deku/deku-tests.ts b/deku/deku-tests.ts new file mode 100644 index 0000000000..d123c7b8f7 --- /dev/null +++ b/deku/deku-tests.ts @@ -0,0 +1,208 @@ +// Example from deku/examples/basic +(function (){ + const {h, createApp} = deku + + function view(state = { count: 0 }, dispatch: Function){ + return ( + h('div', {}, [ + h('div', {}, 'Counter: ' + state.count), + h('button', {onClick: increment(dispatch)}, 'Increment'), + h('button', {onClick: decrement(dispatch)}, 'Decrement') + ]) + ) + } + + function increment(dispatch: Function){ + return () => dispatch({ + type: 'INCREMENT' + }) + } + + function decrement(dispatch: Function){ + return () => dispatch({ + type: 'DECREMENT' + }) + } + + let render = createApp(document.body) + + function main(state: any){ + let vnode = view(state, (action: any) => main({ count: 0 })) + + render(vnode) + } + + main({ count: 0 }) +})(); + +// Example from deku/docs/api/create-app +(function (){ + const {createApp, element} = deku + + const App = ({ props = { size: 'medium' } }) => { + return element('div', { class: `size-${ props.size }` }) + } + + const render = createApp(document.body) + + render(element(App, { size: 'small' })) + + render(element(App, { size: 'large' })) +})(); + +// Example from deku/docs/api/string +(function (){ + const { h } = deku + + const html = deku.string.render(h('div', {}, [ + h('header'), + h('sidebar'), + h('app'), + ])) +})(); + +// Example from deku/docs/api/element +(function (){ + const { element } = deku + + // Native elements + element('div', { class: 'greeting' }, [ + element('span', {}, ['Hello']) + ]) + + // Components + let App = { + render: ({ props = { name: '' } }) => element('div', {}, `Hello ${ props.name }!`) + } + + element(App, { name: 'Tom' }) +})(); + +// deku.createApp +(function (){ + const { createApp, element } = deku + + let render: Function = createApp(document.body) + + render(element('div')) + + render = createApp(document.body, (action: any) => { + render(element('div')) + }) + + render(element('div')) +})(); + +// deku.dom +(function (){ + const { dom, element } = deku + + let el: HTMLElement = dom.create(element('div'), '0.0', ()=>{}, {}) + + const update: (DOMElement: HTMLElement, action: any) => HTMLElement = dom.update(()=>{}, {}) + + el = update(el, {}) +})(); + +// deku.string +(function (){ + const { element } = deku + + let html: string = deku.string.render(element('div')) + + html = deku.string.render(element('div'), {}) +})(); + +// deku.element +(function (){ + const { element } = deku + + let v: deku.VirtualElement = element('div') + + v = element('div', {}) + + v = element('div', {}, []) + + v = element('div', {}, ['foo', 0, 'bar']) + + v = element('div', {}, 'foo') + + v = element('div', {}, 0) + + v = element('div', {}, 'foo', 'bar') + + let Component = { + render({}){ + return element('div') + } + } + + v = element(Component) + + v = element(Component, {}) + + v = element(Component, {}, []) +})(); + +// deku.diff +(function (){ + const { diff, element } = deku + + const { Actions } = diff + + let diffs: any[] = diff.diffNode(element('div'), element('span')) + + let actions: deku.diff.Actions[] = [ + Actions.setAttribute('class', 'foo', 'bar'), + Actions.removeAttribute('foo', {}), + Actions.insertChild({}, 0, '0.0'), + Actions.removeChild(0), + Actions.updateChild(0, []), + Actions.updateChildren([]), + Actions.insertBefore(0), + Actions.replaceNode({}, {}, '0.0'), + Actions.removeNode({}), + Actions.sameNode(), + Actions.updateThunk({}, {}, '0.0') + ] + + actions.forEach(action => { + Actions.case({ + setAttribute: (name: string, value: any, previousValue: any) => { + }, + _: () => { + } + }, action) + }) +})(); + +// deku.vnode +(function (){ + const { vnode, element } = deku + + let v: deku.VirtualElement = vnode.create('div') + + v = vnode.createTextElement('foo') + + const Component = { + render({}){ + return element('div') + } + } + + v = vnode.createThunkElement(Component.render, '', Component, [], {}) + + v = vnode.createEmptyElement() + + let b: boolean = vnode.isThunk(v) + + b = vnode.isText(v) + + b = vnode.isEmpty(v) + + b = vnode.isSameThunk(v, v) + + let path: string = vnode.createPath('0', '1', '2', '3') + + path = vnode.createPath(0, 1, 2, 3) +})(); diff --git a/deku/index.d.ts b/deku/index.d.ts new file mode 100644 index 0000000000..ff5a68f8bb --- /dev/null +++ b/deku/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for deku v2.0 +// Project: https://github.com/anthonyshort/deku +// Definitions by: Sho Fuji +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = deku; +export as namespace deku; + +declare namespace deku { + + interface VirtualElement { + type: string; + } + + /** + * Create a DOM renderer using a container element. + * Everything will be rendered inside of that container. + * Returns a function that accepts new state that can replace what is currently rendered. + */ + function createApp(el: HTMLElement, dispatch?: Dispatch): Render; + + namespace dom { + /** + * Create a real DOM element from a virtual element, recursively looping down. + * When it finds custom elements it will render them, cache them, and keep going, + * so they are treated like any other native element. + */ + function create(vnode: VirtualElement, path: string, dispatch: Dispatch, context: C): HTMLElement; + + /** + * Modify a DOM element given an array of actions. + */ + function update(dispatch: Dispatch, context: C): (DOMElement: HTMLElement, action: A) => HTMLElement; + } + + namespace string { + /** + * Render a virtual element to a string. You can pass in an option state context object that will be given to all components. + */ + function render(vnode: VirtualElement): string; + function render(vnode: VirtualElement, context: C): string; + } + + /** + * This function lets us create virtual nodes using a simple syntax. + * It is compatible with JSX transforms so you can use JSX to write nodes that will compile to this function. + */ + function element(type: string): VirtualElement; + function element(type: string, attributes: A, ...children: any[]): VirtualElement; + + function element(type: Thunk): VirtualElement; + function element(type: Thunk, attributes: A, ...children: any[]): VirtualElement; + + var h: typeof element; + + namespace diff { + /** + * Compare two virtual nodes and return an array of changes to turn the left into the right. + */ + function diffNode(prevNode: VirtualElement, nextNode: VirtualElement): any[]; + + class Actions { + private _keys: string[]; + private _name: string; + + static setAttribute(a: string, b: any, c: any): Actions; + static removeAttribute(a: string, b: any): Actions; + static insertChild(a: any, b: number, c: string): Actions; + static removeChild(a: number): Actions; + static updateChild(a: number, b: any[]): Actions; + static updateChildren(a: any[]): Actions; + static insertBefore(a: number): Actions; + static replaceNode(a: any, b: any, c: string): Actions; + static removeNode(a: any): Actions; + static sameNode(): Actions; + static updateThunk(a: any, b: any, c: string): Actions; + + static case(pat: any, action: Actions): any; + } + } + + namespace vnode { + var create: typeof element; + + /** + * Text nodes are stored as objects to keep things simple + */ + function createTextElement(text: string): VirtualElement; + + /** + * Lazily-rendered virtual nodes + */ + function createThunkElement(fn: (model: Model) => VirtualElement, key: string, props: P, children: T[], options: O): VirtualElement; + + function createEmptyElement(): VirtualElement; + + function isThunk(vnode: VirtualElement): boolean; + + function isText(vnode: VirtualElement): boolean; + + function isEmpty(vnode: VirtualElement): boolean; + + function isSameThunk(prevNode: VirtualElement, nextNode: VirtualElement): boolean; + + // function isValidAttribute(value: A): boolean; + + /** + * Create a node path, eg. (23,5,2,4) => '23.5.2.4' + */ + function createPath(...paths: (number|string)[]): string; + } +} + +interface Model { + props?: any, + children?: any[], + path?: string, + dispatch?: Dispatch, + context?: any +} + +interface Component { + render: (model: Model) => deku.VirtualElement; + onCreate?: (model: Model) => any; + onUpdate?: (model: Model) => any; + onRemove?: (model: Model) => any; +} + +/** + * Thunk object passed to `element` + */ +type Thunk = Component | ((model: Model) => deku.VirtualElement); + +type Render = (vnode: deku.VirtualElement, context?: any) => void; + +type Dispatch = (action: any) => any; diff --git a/deku/tsconfig.json b/deku/tsconfig.json new file mode 100644 index 0000000000..3a18954e88 --- /dev/null +++ b/deku/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "deku-tests.ts" + ] +} diff --git a/dojo/index.d.ts b/dojo/index.d.ts index 11f8a27fbb..b3af7dd779 100644 --- a/dojo/index.d.ts +++ b/dojo/index.d.ts @@ -3,9 +3,6 @@ // Definitions by: Michael Van Sickle // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function define(dependencies: String[], factory: Function): any; -declare function require(config?:Object, dependencies?: String[], callback?: Function): any; - declare namespace dojox.dtl { interface __StringArgs { } interface __ObjectArgs { } @@ -16124,8 +16121,12 @@ declare namespace dojo { */ interface instrumentation{(Deferred: any): void} + interface Thenable { + then(onFulfilled?: (value?: T) => Thenable | U, onRejected?: (error?: Error) => Thenable | U): Thenable; + } + interface Callback { - (arg: T): U|Promise; + (arg: T): U|Thenable; } /** @@ -16136,7 +16137,7 @@ declare namespace dojo { * instances of this class. * */ - interface Promise { + interface Promise extends Thenable { /** * Add a callback to be invoked when the promise is resolved * or rejected. @@ -28291,6 +28292,10 @@ declare module "dojo/promise/Promise" { interface Promise extends dojo.promise.Promise { } export = Promise; } +declare module "dojo/promise/Thenable" { + interface Thenable extends dojo.promise.Thenable { } + export = Thenable; +} declare module "dojo/rpc/JsonpService" { var exp: typeof dojo.rpc.JsonpService export=exp; diff --git a/dotenv/dotenv-tests.ts b/dotenv/dotenv-tests.ts index ea54a99b6d..3d9af0f52e 100644 --- a/dotenv/dotenv-tests.ts +++ b/dotenv/dotenv-tests.ts @@ -1,15 +1,19 @@ - - import dotenv = require('dotenv'); -dotenv.config({ +// typically, result will be an Object +let env = dotenv.config({ silent: true }); +// ... but it might also be `false` +let result = dotenv.config({ + path: '.non-existing-env' +}); + dotenv.config({ path: '.env' -}) +}); dotenv.config({ encoding: 'utf8' -}) \ No newline at end of file +}); diff --git a/dotenv/index.d.ts b/dotenv/index.d.ts index 7391133781..a326ceaa58 100644 --- a/dotenv/index.d.ts +++ b/dotenv/index.d.ts @@ -1,12 +1,35 @@ // Type definitions for dotenv 2.0.0 // Project: https://github.com/motdotla/dotenv -// Definitions by: Jussi Kinnula -// Definitions: https://github.com/jussikinnula/DefinitelyTyped +// Definitions by: Jussi Kinnula , Borek Bernard +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function config(options?: dotenvOptions): boolean; +/** + * Loads `.env` into `process.env`. + * + * @param options + * @return Object Object with the parsed keys and values, e.g., 'KEY=value' becomes { KEY: 'value' } + */ +export function config(options?: DotenvOptions): Object | false; -interface dotenvOptions { +export interface DotenvOptions { + /** + * Dotenv outputs a warning to your console if missing a .env file. Suppress this warning using silent. + * + * @default false + */ silent?: boolean; + + /** + * You can specify a custom path if your file containing environment variables is named or located differently. + * + * @default '.env' + */ path?: string; + + /** + * You may specify the encoding of your file containing environment variables using this option. + * + * @default 'utf8' + */ encoding?: string; } diff --git a/dotenv/tsconfig.json b/dotenv/tsconfig.json index bbd1c438e6..fcecbfabaf 100644 --- a/dotenv/tsconfig.json +++ b/dotenv/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -16,4 +16,4 @@ "index.d.ts", "dotenv-tests.ts" ] -} \ No newline at end of file +} diff --git a/easeljs/index.d.ts b/easeljs/index.d.ts index 55f3143195..a5916a56f2 100644 --- a/easeljs/index.d.ts +++ b/easeljs/index.d.ts @@ -53,6 +53,21 @@ declare namespace createjs { clone(): Bitmap; } + export class ScaleBitmap extends DisplayObject { + constructor(imageOrUrl: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | Object | string, scale9Grid: Rectangle); + + // properties + image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement; + sourceRect: Rectangle; + drawWidth: number; + drawHeight: number; + scale9Grid: Rectangle; + snapToPixel: boolean; + + // methods + setDrawSize (newWidth: number, newHeight: number): void; + clone(): ScaleBitmap; + } export class BitmapText extends DisplayObject { constructor(text?:string, spriteSheet?:SpriteSheet); @@ -608,6 +623,7 @@ declare namespace createjs { primary: boolean; rawX: number; rawY: number; + relatedTarget: DisplayObject; stageX: number; stageY: number; mouseMoveOutside: boolean; diff --git a/ej.web.all/ej.web.all-tests.ts b/ej.web.all/ej.web.all-tests.ts index 389d152c44..faf5a48e0f 100644 --- a/ej.web.all/ej.web.all-tests.ts +++ b/ej.web.all/ej.web.all-tests.ts @@ -2,7 +2,7 @@ /// - + module AccordionComponent { $(function () { var sample = new ej.Accordion($("#basicAccordion"), { @@ -247,63 +247,6 @@ module ChartComponent { - - -module circulargaugecomponent { - $(function () { - var circularsample = new ej.datavisualization.CircularGauge($("#CircularGauge"), { - enableAnimation: false, - isResponsive: true, - backgroundColor: "transparent", width: 500, - scales: [{ - showRanges: true, - startAngle: 122, sweepAngle: 296, radius: 130, showScaleBar: true, size: 1, maximum: 120, majorIntervalValue: 20, minorIntervalValue: 10, - border: { - width: 0.5, - }, - pointers: [{ - value: 60, - showBackNeedle: true, - backNeedleLength: 20, - length: 95, - width: 7, - pointerCap: { radius: 12 } - }], - ticks: [{ - type: "major", - distanceFromScale: 2, - height: 16, - width: 1, color: "#8c8c8c" - }, { type: "minor", height: 8, width: 1, distanceFromScale: 2, color: "#8c8c8c" }], - labels: [{ - color: "#8c8c8c" - }], - ranges: [{ - distanceFromScale: -30, - startValue: 0, - endValue: 70 - }, { - distanceFromScale: -30, - startValue: 70, - endValue: 110, - backgroundColor: "#fc0606", - border: { color: "#fc0606" } - }, - { - distanceFromScale: -30, - startValue: 110, - endValue: 120, - backgroundColor: "#f5b43f", - border: { color: "#f5b43f" } - }] - }] - }); - }); -} - - - - module ColorPickerComponent { $(function () { var colorSample = new ej.ColorPicker($("#colorpick"), { @@ -1027,357 +970,9 @@ module PDFViewerComponent { -module PivotChartOlap { - $(function () { - var sample = new ej.PivotChart($("#PivotChart"),{ - dataSource: { - data: "http://bi.syncfusion.com/olap/msmdpump.dll", - catalog: "Adventure Works DW 2008 SE", - cube: "Adventure Works", - rows: [ - { - fieldName: "[Date].[Fiscal]" - } - ], - columns: [ - { - fieldName: "[Customer].[Customer Geography]" - } - ], - values: [ - { - measures: [ - { - fieldName: "[Measures].[Internet Sales Amount]" - } - ], - axis: "columns" - } - ], - filters:[] - }, - isResponsive: true, - commonSeriesOptions: { - enableAnimation: true, - type: "column", tooltip: { visible: true } - }, - size: { height: "460px", width: "950px" }, - primaryXAxis: { title: { text: "Date - Fiscal" }, labelRotation: 0 }, - primaryYAxis: { title: { text: "Internet Sales Amount" } }, - legend: { visible: true, rowCount: 2 } - }); - }); -} -var pivot_dataset = [ - { Amount: 100, Country: "Canada", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Alberta" }, - { Amount: 200, Country: "Canada", Date: "FY 2006", Product: "Van", Quantity: 3, State: "British Columbia" }, - { Amount: 300, Country: "Canada", Date: "FY 2007", Product: "Car", Quantity: 4, State: "Brunswick" }, - { Amount: 150, Country: "Canada", Date: "FY 2008", Product: "Bike", Quantity: 3, State: "Manitoba" }, - { Amount: 200, Country: "Canada", Date: "FY 2006", Product: "Car", Quantity: 4, State: "Ontario" }, - { Amount: 100, Country: "Canada", Date: "FY 2007", Product: "Van", Quantity: 1, State: "Quebec" }, - { Amount: 200, Country: "France", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Charente-Maritime" }, - { Amount: 250, Country: "France", Date: "FY 2006", Product: "Van", Quantity: 4, State: "Essonne" }, - { Amount: 300, Country: "France", Date: "FY 2007", Product: "Car", Quantity: 3, State: "Garonne (Haute)" }, - { Amount: 150, Country: "France", Date: "FY 2008", Product: "Van", Quantity: 2, State: "Gers" }, - { Amount: 200, Country: "Germany", Date: "FY 2006", Product: "Van", Quantity: 3, State: "Bayern" }, - { Amount: 250, Country: "Germany", Date: "FY 2007", Product: "Car", Quantity: 3, State: "Brandenburg" }, - { Amount: 150, Country: "Germany", Date: "FY 2008", Product: "Car", Quantity: 4, State: "Hamburg" }, - { Amount: 200, Country: "Germany", Date: "FY 2008", Product: "Bike", Quantity: 4, State: "Hessen" }, - { Amount: 150, Country: "Germany", Date: "FY 2007", Product: "Van", Quantity: 3, State: "Nordrhein-Westfalen" }, - { Amount: 100, Country: "Germany", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Saarland" }, - { Amount: 150, Country: "United Kingdom", Date: "FY 2008", Product: "Bike", Quantity: 5, State: "England" }, - { Amount: 250, Country: "United States", Date: "FY 2007", Product: "Car", Quantity: 4, State: "Alabama" }, - { Amount: 200, Country: "United States", Date: "FY 2005", Product: "Van", Quantity: 4, State: "California" }, - { Amount: 100, Country: "United States", Date: "FY 2006", Product: "Bike", Quantity: 2, State: "Colorado" }, - { Amount: 150, Country: "United States", Date: "FY 2008", Product: "Car", Quantity: 3, State: "New Mexico" }, - { Amount: 200, Country: "United States", Date: "FY 2005", Product: "Bike", Quantity: 4, State: "New York" }, - { Amount: 250, Country: "United States", Date: "FY 2008", Product: "Car", Quantity: 3, State: "North Carolina" }, - { Amount: 300, Country: "United States", Date: "FY 2007", Product: "Van", Quantity: 4, State: "South Carolina" } -] - -module PivotChartRelational { - - $(function () { - var sample = new ej.PivotChart($("#PivotChart"),{ - dataSource: { - data: pivot_dataset, - rows: [ - { - fieldName: "Country", - fieldCaption: "Country" - }, - { - fieldName: "State", - fieldCaption: "State" - }, - { - fieldName: "Date", - fieldCaption: "Date" - } - ], - columns: [ - { - fieldName: "Product", - fieldCaption: "Product" - } - ], - values: [ - { - fieldName: "Amount", - fieldCaption: "Amount" - } - ], - filters:[] - }, - isResponsive: true, - commonSeriesOptions: { - enableAnimation: true, - type: "column", tooltip: { visible: true } - }, - size: { height: "460px", width: "950px" }, - primaryYAxis: { title: { text: "Amount" } }, - legend: { visible: true } - }); - }); -} - - - -module PivotGaugeOlap { - - $(function () { - var sample = new ej.PivotGauge($("#PivotGauge"),{ - dataSource: { - data: "http://bi.syncfusion.com/olap/msmdpump.dll", - catalog: "Adventure Works DW 2008 SE", - cube: "Adventure Works", - rows: [ - { - fieldName: "[Date].[Fiscal]", - filterItems: { filterType: "include", values: ["[Date].[Fiscal].[Fiscal Year].&[2004]"] } - }, - ], - columns: [ - { - fieldName: "[Customer].[Customer Geography]" - } - ], - values: [ - { - measures: [ - { - fieldName: "[Measures].[Internet Sales Amount]" - }, - { - fieldName: "[Measures].[Internet Revenue Status]" - }, - { - fieldName: "[Measures].[Internet Revenue Trend]" - }, - { - fieldName: "[Measures].[Internet Revenue Goal]" - }, - ], - axis: "columns" - } - ], - filters:[] - }, - enableTooltip: true, isResponsive: true, - backgroundColor: "transparent", - labelFormatSettings: { decimalPlaces: 2 }, - scales: [{ - showRanges: true, - radius: 150, showScaleBar: true, size: 1, - border: { - width: 0.5 - }, - showIndicators: true, showLabels: true, - pointers: [{ - showBackNeedle: true, - backNeedleLength: 20, - length: 120, - width: 7 - }, - { - type: "marker", - markerType: "diamond", - distanceFromScale: 5, - placement: "center", - backgroundColor: "#29A4D9", - length: 25, - width: 15 - }], - ticks: [{ - type: "major", - distanceFromScale: 2, - height: 16, - width: 1, color: "#8c8c8c" - }, - { - type: "minor", - height: 6, - width: 1, - distanceFromScale: 2, - color: "#8c8c8c" - }], - labels: [{ - color: "#8c8c8c" - }], - ranges: [{ - distanceFromScale: -5, - backgroundColor: "#fc0606", - border: { color: "#fc0606" } - }, - { - distanceFromScale: -5 - }], - customLabels: [{ - position: { x: 180, y: 290 }, - font: { size: "10px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" - }, - { - position: { x: 180, y: 320 }, - font: { size: "10px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" - }, - { - position: { x: 180, y: 150 }, - font: { size: "12px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" - }] - }] - }); - }); -} - - - -var pivot_dataset = [ - { Amount: 100, Country: "Canada", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Alberta" }, - { Amount: 200, Country: "Canada", Date: "FY 2006", Product: "Van", Quantity: 3, State: "British Columbia" }, - { Amount: 300, Country: "Canada", Date: "FY 2007", Product: "Car", Quantity: 4, State: "Brunswick" }, - { Amount: 150, Country: "Canada", Date: "FY 2008", Product: "Bike", Quantity: 3, State: "Manitoba" }, - { Amount: 200, Country: "Canada", Date: "FY 2006", Product: "Car", Quantity: 4, State: "Ontario" }, - { Amount: 100, Country: "Canada", Date: "FY 2007", Product: "Van", Quantity: 1, State: "Quebec" }, - { Amount: 200, Country: "France", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Charente-Maritime" }, - { Amount: 250, Country: "France", Date: "FY 2006", Product: "Van", Quantity: 4, State: "Essonne" }, - { Amount: 300, Country: "France", Date: "FY 2007", Product: "Car", Quantity: 3, State: "Garonne (Haute)" }, - { Amount: 150, Country: "France", Date: "FY 2008", Product: "Van", Quantity: 2, State: "Gers" }, - { Amount: 200, Country: "Germany", Date: "FY 2006", Product: "Van", Quantity: 3, State: "Bayern" }, - { Amount: 250, Country: "Germany", Date: "FY 2007", Product: "Car", Quantity: 3, State: "Brandenburg" }, - { Amount: 150, Country: "Germany", Date: "FY 2008", Product: "Car", Quantity: 4, State: "Hamburg" }, - { Amount: 200, Country: "Germany", Date: "FY 2008", Product: "Bike", Quantity: 4, State: "Hessen" }, - { Amount: 150, Country: "Germany", Date: "FY 2007", Product: "Van", Quantity: 3, State: "Nordrhein-Westfalen" }, - { Amount: 100, Country: "Germany", Date: "FY 2005", Product: "Bike", Quantity: 2, State: "Saarland" }, - { Amount: 150, Country: "United Kingdom", Date: "FY 2008", Product: "Bike", Quantity: 5, State: "England" }, - { Amount: 250, Country: "United States", Date: "FY 2007", Product: "Car", Quantity: 4, State: "Alabama" }, - { Amount: 200, Country: "United States", Date: "FY 2005", Product: "Van", Quantity: 4, State: "California" }, - { Amount: 100, Country: "United States", Date: "FY 2006", Product: "Bike", Quantity: 2, State: "Colorado" }, - { Amount: 150, Country: "United States", Date: "FY 2008", Product: "Car", Quantity: 3, State: "New Mexico" }, - { Amount: 200, Country: "United States", Date: "FY 2005", Product: "Bike", Quantity: 4, State: "New York" }, - { Amount: 250, Country: "United States", Date: "FY 2008", Product: "Car", Quantity: 3, State: "North Carolina" }, - { Amount: 300, Country: "United States", Date: "FY 2007", Product: "Van", Quantity: 4, State: "South Carolina" } -] - -module PivotGaugeRelational { - $(function () { - var sample = new ej.PivotGauge($("#PivotGauge"),{ - dataSource: { - data: pivot_dataset, - rows: [ - { - fieldName: "Country", - fieldCaption: "Country" - }, - { - fieldName: "State", - fieldCaption: "State" - } - ], - columns: [ - { - fieldName: "Product", - fieldCaption: "Product" - } - ], - values: [ - { - fieldName: "Amount", - fieldCaption: "Amount" - }, - { - fieldName: "Quantity", - fieldCaption: "Quantity" - } - ] - }, - enableTooltip: true, isResponsive: true, - backgroundColor: "transparent", - labelFormatSettings: { decimalPlaces: 2 }, - scales: [{ - showRanges: true, - radius: 150, showScaleBar: true, size: 1, - border: { - width: 0.5 - }, - showIndicators: true, showLabels: true, - pointers: [{ - showBackNeedle: true, - backNeedleLength: 20, - length: 120, - width: 7 - }, - { - type: "marker", - markerType: "diamond", - distanceFromScale: 5, - placement: "center", - backgroundColor: "#29A4D9", - length: 25, - width: 15 - }], - ticks: [{ - type: "major", - distanceFromScale: 2, - height: 16, - width: 1, color: "#8c8c8c" - }, - { - type: "minor", - height: 6, - width: 1, - distanceFromScale: 2, - color: "#8c8c8c" - }], - labels: [{ - color: "#8c8c8c" - }], - ranges: [{ - distanceFromScale: -5, - backgroundColor: "#fc0606", - border: { color: "#fc0606" } - }, - { - distanceFromScale: -5 - }], - customLabels: [{ - position: { x: 180, y: 290 }, - font: { size: "10px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" - }, - { - position: { x: 180, y: 320 }, - font: { size: "10px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" - }, - { - position: { x: 180, y: 150 }, - font: { size: "12px", fontFamily: "Segoe UI", fontStyle: "Normal" }, color: "#666666" - }] - }] - }); - }); -} diff --git a/ej.web.all/index.d.ts b/ej.web.all/index.d.ts index 85eb18fe46..71d773d5b7 100644 --- a/ej.web.all/index.d.ts +++ b/ej.web.all/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ej.web.all v14.3.0.49 +// Type definitions for ej.web.all v14.3.0.52 // Project: http://help.syncfusion.com/js/typescript // Definitions by: Syncfusion // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,7 +7,7 @@ /*! * filename: ej.web.all.d.ts -* version : 14.3.0.49 +* version : 14.3.0.52 * Copyright Syncfusion Inc. 2001 - 2016. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -34,7 +34,8 @@ declare module ej { function cancelEvent(): string; function copyObject(): string; function createObject(nameSpace: string, value: Object, initIn: any): JQuery; - function createObject(element : any , eventEmitter :any, model : any): any; + function createObject(element: any, eventEmitter: any, model: any): any; + function setCulture(culture: string): void; function getObject(element :string, model :any ): T; function defineClass(className: string, constructor:any, proto: Object, replace: boolean): Object; function destroyWidgets(element: Object): void; @@ -500,10 +501,15 @@ declare module ej { Overlay, Slide } + enum SortOrder{ + Ascending, + Descending + } class Draggable extends ej.Widget { static fn: Draggable; constructor(element: JQuery, options?: Draggable.Model); constructor(element: Element, options?: Draggable.Model); + static Locale: any; model:Draggable.Model; defaults:Draggable.Model; @@ -662,6 +668,7 @@ class Droppable extends ej.Widget { static fn: Droppable; constructor(element: JQuery, options?: Droppable.Model); constructor(element: Element, options?: Droppable.Model); + static Locale: any; model:Droppable.Model; defaults:Droppable.Model; @@ -756,6 +763,7 @@ class Resizable extends ej.Widget { static fn: Resizable; constructor(element: JQuery, options?: Resizable.Model); constructor(element: Element, options?: Resizable.Model); + static Locale: any; model:Resizable.Model; defaults:Resizable.Model; @@ -930,6 +938,7 @@ class Scroller extends ej.Widget { static fn: Scroller; constructor(element: JQuery, options?: Scroller.Model); constructor(element: Element, options?: Scroller.Model); + static Locale: any; model:Scroller.Model; defaults:Scroller.Model; @@ -963,15 +972,21 @@ class Scroller extends ej.Widget { */ refresh(): void; - /** Scroller moves to given pixel in X (left) position. We can also specify the animation speed,in which the scroller has to move while re-positioning it. + /** Horizontal scroller moves to given pixel from its origin position. We can also specify the animation speed,in which the scroller has to move while re-positioning it. + * @param {number|string} Horizontal scroller moves to the specified pixel. + * @param {boolean} Specifies to enable/disable the animation. + * @param {number} Specifies the animation speed when scrolling, if animation is enabled. * @returns {void} */ - scrollX(): void; + scrollX(pixel: number|string, disableAnimation: boolean, animationSpeed: number): void; - /** Scroller moves to given pixel in Y (top) position. We can also specify the animation speed,in which the scroller has to move while re-positioning it. + /** Vertical scroller moves to given pixel from its origin position. We can also specify the animation speed,in which the scroller has to move while re-positioning it. + * @param {number|string} Vertical scroller moves to the specified pixel. + * @param {boolean} Specifies to enable/disable the animation. + * @param {number} Specifies the animation speed when scrolling, if animation is enabled. * @returns {void} */ - scrollY(): void; + scrollY(pixel: number|string, disableAnimation: boolean, animationSpeed: number): void; } export module Scroller{ @@ -1053,12 +1068,21 @@ export interface Model { /** Fires when Scroller control is destroyed. */ destroy? (e: DestroyEventArgs): void; + /** Fires when a thumb point is moved along the touch surface. */ + thumbMove? (e: ThumbMoveEventArgs): void; + + /** Fires when a thumb point is placed on the touch surface. */ + thumbStart? (e: ThumbStartEventArgs): void; + + /** Fires when a thumb point is removed from the touch surface. */ + thumbEnd? (e: ThumbEndEventArgs): void; + + /** It fires whenever the mouse wheel is rotated either in upwards or downwards. */ + wheelMove? (e: WheelMoveEventArgs): void; + /** It will fire when mouse trackball has been start to wheel. */ wheelStart? (e: WheelStartEventArgs): void; - /** It fires whenever the mouse wheel is rotated either in upwards or downwards */ - wheelMove? (e: WheelMoveEventArgs): void; - /** It will fire when mouse trackball has been stop to wheel. */ wheelStop? (e: WheelStopEventArgs): void; } @@ -1089,7 +1113,53 @@ export interface DestroyEventArgs { type?: string; } -export interface WheelStartEventArgs { +export interface ThumbMoveEventArgs { + + /** if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** returns the scroller model + */ + model?: ej.Scroller.Model; + + /** returns the original event name and its event properties of the current event. + */ + originalEvent?: any; + + /** returns the current data related to the event. + */ + scrollData?: any; + + /** returns the name of the event. + */ + type?: string; +} + +export interface ThumbStartEventArgs { + + /** if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** returns the scroller model + */ + model?: ej.Scroller.Model; + + /** returns the original event name and its event properties of the current event. + */ + originalEvent?: any; + + /** returns the current data related to the event. + */ + scrollData?: any; + + /** returns the name of the event. + */ + type?: string; +} + +export interface ThumbEndEventArgs { /** if the event should be canceled; otherwise, false. */ @@ -1127,6 +1197,29 @@ export interface WheelMoveEventArgs { originalEvent?: any; } +export interface WheelStartEventArgs { + + /** if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** returns the scroller model + */ + model?: ej.Scroller.Model; + + /** returns the original event name and its event properties of the current event. + */ + originalEvent?: any; + + /** returns the current data related to the event. + */ + scrollData?: any; + + /** returns the name of the event. + */ + type?: string; +} + export interface WheelStopEventArgs { /** if the event should be canceled; otherwise, false. @@ -1151,6 +1244,7 @@ class Accordion extends ej.Widget { static fn: Accordion; constructor(element: JQuery, options?: Accordion.Model); constructor(element: Element, options?: Accordion.Model); + static Locale: any; model:Accordion.Model; defaults:Accordion.Model; @@ -1248,7 +1342,7 @@ export interface Model { /** Accordion headers can be expanded and collapsed on keyboard action. * @Default {true} */ - allowKeyboardNavigation?: boolean; + allowKeyboardNavigation?: Boolean; /** To set the Accordion headers Collapse Speed. * @Default {300} @@ -1262,7 +1356,7 @@ export interface Model { /** Sets the root CSS class for Accordion theme, which is used customize. */ - cssClass?: string; + cssClass?: String; /** Allows you to set the custom header Icon. It accepts two key values “header”, ”selectedHeader”. * @Default {{ header: e-collapse, selectedHeader: e-expand }} @@ -1277,12 +1371,12 @@ export interface Model { /** Specifies the animation behavior in accordion. * @Default {true} */ - enableAnimation?: boolean; + enableAnimation?: Boolean; /** With this enabled property, you can enable or disable the Accordion. * @Default {true} */ - enabled?: boolean; + enabled?: Boolean; /** Used to enable the disabled items in accordion. * @Default {[]} @@ -1292,22 +1386,22 @@ export interface Model { /** Multiple content panels to activate at a time. * @Default {false} */ - enableMultipleOpen?: boolean; + enableMultipleOpen?: Boolean; /** Save current model value to browser cookies for maintaining states. When refreshing the accordion control page, the model value is applied from browser cookies or HTML 5local storage. * @Default {false} */ - enablePersistence?: boolean; + enablePersistence?: Boolean; /** Display headers and panel text from right-to-left. * @Default {false} */ - enableRTL?: boolean; + enableRTL?: Boolean; /** The events API binds the action for activating the accordion header. Users can activate the header by using mouse actions such as mouse-over, mouse-up, mouse-down, and soon. * @Default {click} */ - events?: string; + events?: String; /** To set the Accordion headers Expand Speed. * @Default {300} @@ -1346,7 +1440,7 @@ export interface Model { /** Used to determines the close button visibility an each accordion items. This close button helps to remove the accordion item from the control. * @Default {false} */ - showCloseButton?: boolean; + showCloseButton?: Boolean; /** Displays rounded corner borders on the Accordion control's panels and headers. * @Default {false} @@ -1611,15 +1705,15 @@ export interface AjaxSettings { /** It specifies, whether to enable or disable asynchronous request. */ - async?: boolean; + async?: Boolean; /** It specifies the page will be cached in the web browser. */ - cache?: boolean; + cache?: Boolean; /** It specifies the type of data is send in the query string. */ - contentType?: string; + contentType?: String; /** It specifies the data as an object, will be passed in the query string. */ @@ -1627,22 +1721,22 @@ export interface AjaxSettings { /** It specifies the type of data that you're expecting back from the response. */ - dataType?: string; + dataType?: String; /** It specifies the HTTP request type. */ - type?: string; + type?: String; } export interface CustomIcon { /** This class name set to collapsing header. */ - header?: string; + header?: String; /** This class name set to expanded (active) header. */ - selectedHeader?: string; + selectedHeader?: String; } enum HeightAdjustMode{ @@ -1663,6 +1757,7 @@ class Autocomplete extends ej.Widget { static fn: Autocomplete; constructor(element: JQuery, options?: Autocomplete.Model); constructor(element: Element, options?: Autocomplete.Model); + static Locale: any; model:Autocomplete.Model; defaults:Autocomplete.Model; @@ -1730,17 +1825,17 @@ export interface Model { /** Customize "Add New" text (label) to be added in the autocomplete popup list for the entered text when there are no suggestions for it. * @Default {Add New} */ - addNewText?: boolean; + addNewText?: Boolean; /** Allows new values to be added to the autocomplete input other than the values in the suggestion list. Normally, when there are no suggestions it will display “No suggestions” label in the popup. * @Default {false} */ - allowAddNew?: boolean; + allowAddNew?: Boolean; /** Enables or disables the sorting of suggestion list item. The default sort order is ascending order. You customize sort order. * @Default {true} */ - allowSorting?: boolean; + allowSorting?: Boolean; /** Enables or disables selecting the animation style for the popup list. Animation types can be selected through either of the following options, * @Default {slide} @@ -1750,17 +1845,17 @@ export interface Model { /** To focus the items in the suggestion list when the popup is shown. By default first item will be focused. * @Default {false} */ - autoFocus?: boolean; + autoFocus?: Boolean; /** Enables or disables the case sensitive search. * @Default {false} */ - caseSensitiveSearch?: boolean; + caseSensitiveSearch?: Boolean; /** The root class for the Autocomplete textbox widget which helps in customizing its theme. * @Default {””} */ - cssClass?: string; + cssClass?: String; /** The data source contains the list of data for the suggestions list. It can be a string array or JSON array. * @Default {null} @@ -1770,42 +1865,42 @@ export interface Model { /** The time delay (in milliseconds) after which the suggestion popup will be shown. * @Default {200} */ - delaySuggestionTimeout?: number; + delaySuggestionTimeout?: Number; /** The special character which acts as a separator for the given words for multi-mode search i.e. the text after the delimiter are considered as a separate word or query for search operation. * @Default {’,’} */ - delimiterChar?: string; + delimiterChar?: String; /** The text to be displayed in the popup when there are no suggestions available for the entered text. * @Default {“No suggestions”} */ - emptyResultText?: string; + emptyResultText?: String; /** Fills the autocomplete textbox with the first matched item from the suggestion list automatically based on the entered text when enabled. * @Default {false} */ - enableAutoFill?: boolean; + enableAutoFill?: Boolean; /** Enables or disables the Autocomplete textbox widget. * @Default {true} */ - enabled?: boolean; + enabled?: Boolean; /** Enables or disables displaying the duplicate names present in the search result. * @Default {false} */ - enableDistinct?: boolean; + enableDistinct?: Boolean; /** Allows the current model values to be saved in local storage or browser cookies for state maintenance when it is set to true. While refreshing the page, it retains the model value from browser cookies or local storage. * @Default {false} */ - enablePersistence?: boolean; + enablePersistence?: Boolean; /** Displays the Autocomplete widget’s content from right to left when enabled. * @Default {false} */ - enableRTL?: boolean; + enableRTL?: Boolean; /** Mapping fields for the suggestion items of the Autocomplete textbox widget. * @Default {null} @@ -1815,27 +1910,27 @@ export interface Model { /** Specifies the search filter type. There are several types of search filter available such as ‘startswith’, ‘contains’, ‘endswith’, ‘lessthan’, ‘lessthanorequal’, ‘greaterthan’, ‘greaterthanorequal’, ‘equal’, ‘notequal’. * @Default {ej.filterType.StartsWith} */ - filterType?: string; + filterType?: String; /** The height of the Autocomplete textbox. * @Default {null} */ - height?: string; + height?: String; /** The search text can be highlighted in the AutoComplete suggestion list when enabled. * @Default {false} */ - highlightSearch?: boolean; + highlightSearch?: Boolean; /** Number of items to be displayed in the suggestion list. * @Default {0} */ - itemsCount?: number; + itemsCount?: Number; /** Minimum number of character to be entered in the Autocomplete textbox to show the suggestion list. * @Default {1} */ - minCharacter?: number; + minCharacter?: Number; /** An Autocomplete column collection can be defined and customized through the multiColumnSettings property.Column's header, field, and stringFormat can be define via multiColumnSettings properties. */ @@ -1849,12 +1944,12 @@ export interface Model { /** The height of the suggestion list. * @Default {“152px”} */ - popupHeight?: string; + popupHeight?: String; /** The width of the suggestion list. * @Default {“auto”} */ - popupWidth?: string; + popupWidth?: String; /** The query to retrieve the data from the data source. * @Default {null} @@ -1864,36 +1959,36 @@ export interface Model { /** Indicates that the autocomplete textbox values can only be readable. * @Default {false} */ - readOnly?: boolean; + readOnly?: Boolean; /** Sets the value for the Autocomplete textbox based on the given input key value. */ - selectValueByKey?: number; + selectValueByKey?: Number; /** Enables or disables showing the message when there are no suggestions for the entered text. * @Default {true} */ - showEmptyResultText?: boolean; + showEmptyResultText?: Boolean; /** Enables or disables the loading icon to intimate the searching operation. The loading icon is visible when there is a time delay to perform the search. * @Default {true} */ - showLoadingIcon?: boolean; + showLoadingIcon?: Boolean; /** Enables the showPopup button in autocomplete textbox. When the showPopup button is clicked, it displays all the available data from the data source. * @Default {false} */ - showPopupButton?: boolean; + showPopupButton?: Boolean; /** Enables or disables rounded corner. * @Default {false} */ - showRoundedCorner?: boolean; + showRoundedCorner?: Boolean; /** Enables or disables reset icon to clear the textbox values. * @Default {false} */ - showResetIcon?: boolean; + showResetIcon?: Boolean; /** Sort order specifies whether the suggestion list values has to be displayed in ascending or descending order. * @Default {ej.SortOrder.Ascending} @@ -1903,7 +1998,7 @@ export interface Model { /** The template to display the suggestion list items with customized appearance. * @Default {null} */ - template?: string; + template?: String; /** The jQuery validation error message to be displayed on form validation. * @Default {null} @@ -1918,22 +2013,22 @@ export interface Model { /** The value to be displayed in the autocomplete textbox. * @Default {null} */ - value?: string; + value?: String; /** Enables or disables the visibility of the autocomplete textbox. * @Default {true} */ - visible?: boolean; + visible?: Boolean; /** The text to be displayed when the value of the autocomplete textbox is empty. * @Default {null} */ - watermarkText?: string; + watermarkText?: String; /** The width of the Autocomplete textbox. * @Default {null} */ - width?: string; + width?: String; /** Triggers when the AJAX requests Begins. */ actionBegin? (e: ActionBeginEventArgs): void; @@ -1988,7 +2083,7 @@ export interface ChangeEventArgs { /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** Instance of the autocomplete model object. */ @@ -1996,11 +2091,11 @@ export interface ChangeEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** Value of the autocomplete textbox. */ - value?: string; + value?: String; } export interface CloseEventArgs { @@ -2015,7 +2110,7 @@ export interface CloseEventArgs { /** Name of the event. */ - type?: string; + type?: String; } export interface CreateEventArgs { @@ -2163,7 +2258,7 @@ export interface MultiColumnSettingsColumn { /** Gets or sets a value that indicates to render the multicolumn with custom theme. */ - cssClass?: string; + cssClass?: String; /** Specifies the search data type. There are four types of data types available such as string, ‘number’, ‘boolean’ and ‘date’. * @Default {ej.Type.String} @@ -2245,6 +2340,7 @@ class Button extends ej.Widget { static fn: Button; constructor(element: JQuery, options?: Button.Model); constructor(element: Element, options?: Button.Model); + static Locale: any; model:Button.Model; defaults:Button.Model; @@ -2460,6 +2556,7 @@ class Captcha extends ej.Widget { static fn: Captcha; constructor(element: JQuery, options?: Captcha.Model); constructor(element: Element, options?: Captcha.Model); + static Locale: any; model:Captcha.Model; defaults:Captcha.Model; } @@ -2690,6 +2787,7 @@ class ListBox extends ej.Widget { static fn: ListBox; constructor(element: JQuery, options?: ListBox.Model); constructor(element: Element, options?: ListBox.Model); + static Locale: any; model:ListBox.Model; defaults:ListBox.Model; @@ -2723,10 +2821,10 @@ class ListBox extends ej.Widget { disable(): void; /** Disables a list item by passing the item text as parameter. - * @param {string} Text of the listbox item to be disabled. + * @param {String} Text of the listbox item to be disabled. * @returns {void} */ - disableItem(text: string): void; + disableItem(text: String): void; /** Disables a list Item using its index value. * @param {number} Index of the listbox item to be disabled. @@ -2818,10 +2916,10 @@ class ListBox extends ej.Widget { moveUp(): void; /** Refreshes the ListBox widget. - * @param {boolean} Refreshes both the datasource and the dimensions of the ListBox widget when the parameter is passed as true, otherwise only the ListBox dimensions will be refreshed. + * @param {Boolean} Refreshes both the datasource and the dimensions of the ListBox widget when the parameter is passed as true, otherwise only the ListBox dimensions will be refreshed. * @returns {void} */ - refresh(refreshData: boolean): void; + refresh(refreshData: Boolean): void; /** Removes all the list items from listbox. * @returns {void} @@ -2857,10 +2955,10 @@ class ListBox extends ej.Widget { selectItemByText(text: string): void; /** Selects list item using its value property. - * @param {string} Value of the listbox item to be selected. + * @param {String} Value of the listbox item to be selected. * @returns {void} */ - selectItemByValue(value: string): void; + selectItemByValue(value: String): void; /** Selects list item using its index value. * @param {number} Index of the listbox item to be selected. @@ -2950,16 +3048,16 @@ class ListBox extends ej.Widget { hideItemsByValues(values: Array): void; /** Shows a hidden list item using its value. - * @param {string} Value of the listbox item to be shown. + * @param {String} Value of the listbox item to be shown. * @returns {void} */ - showItemByValue(value: string): void; + showItemByValue(value: String): void; /** Hide a list item using its value. - * @param {string} Value of the listbox item to be hidden. + * @param {String} Value of the listbox item to be hidden. * @returns {void} */ - hideItemByValue(value: string): void; + hideItemByValue(value: String): void; /** Shows a hidden list item using its index value. * @param {number} Index of the listbox item to be shown. @@ -3216,7 +3314,7 @@ export interface ActionBeforeSuccessEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** List of actual object. */ @@ -3228,7 +3326,7 @@ export interface ActionBeforeSuccessEventArgs { /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** List of array object */ @@ -3247,7 +3345,7 @@ export interface ChangeEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** List item object. */ @@ -3259,31 +3357,31 @@ export interface ChangeEventArgs { /** List item’s index. */ - index?: number; + index?: Number; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** Boolean value based on whether the list item is checked or not. */ - isChecked?: boolean; + isChecked?: Boolean; /** Boolean value based on whether the list item is selected or not. */ - isSelected?: boolean; + isSelected?: Boolean; /** Boolean value based on the list item is enabled or not. */ - isEnabled?: boolean; + isEnabled?: Boolean; /** List item’s text (label). */ - text?: string; + text?: String; /** List item’s value. */ - value?: string; + value?: String; } export interface CheckChangeEventArgs { @@ -3294,7 +3392,7 @@ export interface CheckChangeEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** List item object. */ @@ -3306,31 +3404,31 @@ export interface CheckChangeEventArgs { /** List item’s index. */ - index?: number; + index?: Number; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** Boolean value based on whether the list item is checked or not. */ - isChecked?: boolean; + isChecked?: Boolean; /** Boolean value based on whether the list item is selected or not. */ - isSelected?: boolean; + isSelected?: Boolean; /** Boolean value based on the list item is enabled or not. */ - isEnabled?: boolean; + isEnabled?: Boolean; /** List item’s text (label). */ - text?: string; + text?: String; /** List item’s value. */ - value?: string; + value?: String; } export interface CreateEventArgs { @@ -3345,7 +3443,7 @@ export interface CreateEventArgs { /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; } export interface DestroyEventArgs { @@ -3356,11 +3454,11 @@ export interface DestroyEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; } export interface FocusInEventArgs { @@ -3371,11 +3469,11 @@ export interface FocusInEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; } export interface FocusOutEventArgs { @@ -3386,11 +3484,11 @@ export interface FocusOutEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; } export interface ItemDragEventArgs { @@ -3401,11 +3499,11 @@ export interface ItemDragEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** The Datasource of the listbox. */ @@ -3413,27 +3511,27 @@ export interface ItemDragEventArgs { /** List item’s index. */ - index?: number; + index?: Number; /** Boolean value based on whether the list item is checked or not. */ - isChecked?: boolean; + isChecked?: Boolean; /** Boolean value based on whether the list item is selected or not. */ - isSelected?: boolean; + isSelected?: Boolean; /** Boolean value based on whether the list item is enabled or not. */ - isEnabled?: boolean; + isEnabled?: Boolean; /** List item’s text (label). */ - text?: string; + text?: String; /** List item’s value. */ - value?: string; + value?: String; } export interface ItemDragStartEventArgs { @@ -3444,11 +3542,11 @@ export interface ItemDragStartEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** The Datasource of the listbox. */ @@ -3456,27 +3554,27 @@ export interface ItemDragStartEventArgs { /** List item’s index. */ - index?: number; + index?: Number; /** Boolean value based on whether the list item is checked or not. */ - isChecked?: boolean; + isChecked?: Boolean; /** Boolean value based on whether the list item is selected or not. */ - isSelected?: boolean; + isSelected?: Boolean; /** Boolean value based on whether the list item is enabled or not. */ - isEnabled?: boolean; + isEnabled?: Boolean; /** List item’s text (label). */ - text?: string; + text?: String; /** List item’s value. */ - value?: string; + value?: String; } export interface ItemDragStopEventArgs { @@ -3487,11 +3585,11 @@ export interface ItemDragStopEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** The Datasource of the listbox. */ @@ -3499,27 +3597,27 @@ export interface ItemDragStopEventArgs { /** List item’s index. */ - index?: number; + index?: Number; /** Boolean value based on whether the list item is checked or not. */ - isChecked?: boolean; + isChecked?: Boolean; /** Boolean value based on whether the list item is selected or not. */ - isSelected?: boolean; + isSelected?: Boolean; /** Boolean value based on whether the list item is enabled or not. */ - isEnabled?: boolean; + isEnabled?: Boolean; /** List item’s text (label). */ - text?: string; + text?: String; /** List item’s value. */ - value?: string; + value?: String; } export interface ItemDropEventArgs { @@ -3530,11 +3628,11 @@ export interface ItemDropEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** The Datasource of the listbox. */ @@ -3542,27 +3640,27 @@ export interface ItemDropEventArgs { /** List item’s index. */ - index?: number; + index?: Number; /** Boolean value based on whether the list item is checked or not. */ - isChecked?: boolean; + isChecked?: Boolean; /** Boolean value based on whether the list item is selected or not. */ - isSelected?: boolean; + isSelected?: Boolean; /** Boolean value based on whether the list item is enabled or not. */ - isEnabled?: boolean; + isEnabled?: Boolean; /** List item’s text (label). */ - text?: string; + text?: String; /** List item’s value. */ - value?: string; + value?: String; } export interface SelectEventArgs { @@ -3573,7 +3671,7 @@ export interface SelectEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** List item object. */ @@ -3585,31 +3683,31 @@ export interface SelectEventArgs { /** List item’s index. */ - index?: number; + index?: Number; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** Boolean value based on whether the list item is checked or not. */ - isChecked?: boolean; + isChecked?: Boolean; /** Boolean value based on whether the list item is selected or not. */ - isSelected?: boolean; + isSelected?: Boolean; /** Boolean value based on the list item is enabled or not. */ - isEnabled?: boolean; + isEnabled?: Boolean; /** List item’s text (label). */ - text?: string; + text?: String; /** List item’s value. */ - value?: string; + value?: String; } export interface UnselectEventArgs { @@ -3620,7 +3718,7 @@ export interface UnselectEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** List item object. */ @@ -3632,31 +3730,31 @@ export interface UnselectEventArgs { /** List item’s index. */ - index?: number; + index?: Number; /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** Boolean value based on whether the list item is checked or not. */ - isChecked?: boolean; + isChecked?: Boolean; /** Boolean value based on whether the list item is selected or not. */ - isSelected?: boolean; + isSelected?: Boolean; /** Boolean value based on the list item is enabled or not. */ - isEnabled?: boolean; + isEnabled?: Boolean; /** List item’s text (label). */ - text?: string; + text?: String; /** List item’s value. */ - value?: string; + value?: String; } export interface Fields { @@ -3711,6 +3809,7 @@ class Calculate { static fn: Calculate; constructor(element: JQuery, options?: Calculate.Model); constructor(element: Element, options?: Calculate.Model); + static Locale: any; model:Calculate.Model; defaults:Calculate.Model; @@ -3773,6 +3872,7 @@ class CheckBox extends ej.Widget { static fn: CheckBox; constructor(element: JQuery, options?: CheckBox.Model); constructor(element: Element, options?: CheckBox.Model); + static Locale: any; model:CheckBox.Model; defaults:CheckBox.Model; @@ -3997,6 +4097,7 @@ class ColorPicker extends ej.Widget { static fn: ColorPicker; constructor(element: JQuery, options?: ColorPicker.Model); constructor(element: Element, options?: ColorPicker.Model); + static Locale: any; model:ColorPicker.Model; defaults:ColorPicker.Model; @@ -4431,6 +4532,7 @@ class FileExplorer extends ej.Widget { static fn: FileExplorer; constructor(element: JQuery, options?: FileExplorer.Model); constructor(element: Element, options?: FileExplorer.Model); + static Locale: any; model:FileExplorer.Model; defaults:FileExplorer.Model; @@ -4497,6 +4599,11 @@ export interface Model { */ allowDragAndDrop?: boolean; + /** Gets or sets a value that indicates whether to enable keyboard support for FileExplorer actions. + * @Default {true} + */ + allowKeyboardNavigation?: boolean; + /** The FileExplorer allows to select multiple files by enabling the allowMultiSelection property. You can perform multi selection by pressing the Ctrl key or Shift key. * @Default {true} */ @@ -4626,12 +4733,12 @@ export interface Model { showNavigationPane?: boolean; /** The tools property is used to configure and group required toolbar items in FileExplorer control. - * @Default {{ creation: [NewFolder], navigation: [Back, Forward, Upward], addressBar: [Addressbar], editing: [Refresh, Upload, Delete, Rename, Download], copyPaste: [Cut, Copy, Paste], getProperties: [Details], searchBar: [Searchbar], layout: [Layout]}} + * @Default {{ creation: [NewFolder], navigation: [Back, Forward, Upward], addressBar: [Addressbar], editing: [Refresh, Upload, Delete, Rename, Download], copyPaste: [Cut, Copy, Paste], getProperties: [Details], searchBar: [Searchbar], layout: [Layout], sortBy: [SortBy]}} */ tools?: any; /** The toolsList property is used to arrange the toolbar items in the FileExplorer control. - * @Default {[layout, creation, navigation, addressBar, editing, copyPaste, getProperties, searchBar]} + * @Default {[layout, creation, navigation, addressBar, editing, copyPaste, sortBy, getProperties, searchBar]} */ toolsList?: Array; @@ -4689,6 +4796,9 @@ export interface Model { /** Fires after loading the requested image from server. Using this event, you can get the details of loaded image. */ getImage? (e: GetImageEventArgs): void; + /** Fires when keydown in FileExplorer control. */ + keydown? (e: KeydownEventArgs): void; + /** Fires when the file view type is changed. */ layoutChange? (e: LayoutChangeEventArgs): void; } @@ -5078,6 +5188,41 @@ export interface GetImageEventArgs { type?: string; } +export interface KeydownEventArgs { + + /** Set to true when the event has to be canceled, else false. + */ + cancel?: boolean; + + /** returns the downed key keyCode value + */ + keyCode?: number; + + /** returns altKey value. + */ + altKey?: boolean; + + /** returns shiftKey value. + */ + shiftKey?: boolean; + + /** returns ctrlKey value. + */ + ctrlKey?: boolean; + + /** returns the event object. + */ + originalArgs?: any; + + /** returns the FileExplorer model. + */ + model?: ej.FileExplorer.Model; + + /** returns the name of the event. + */ + type?: string; +} + export interface LayoutChangeEventArgs { /** Set to true when the event has to be canceled, else false. @@ -5100,7 +5245,7 @@ export interface LayoutChangeEventArgs { export interface ContextMenuSettings { /** The items property is used to configure and group the required ContextMenu items in FileExplorer control. - * @Default {{% highlight javascript %}{navbar: [NewFolder, Upload, |, Delete, Rename, |, Cut, Copy, Paste, |, Getinfo],cwd: [Refresh, Paste,|, Sortby, |, NewFolder, Upload, |, Getinfo],files: [Open, Download, |, Upload, |, Delete, Rename, |, Cut, Copy, Paste, |, OpenFolderLocation, Getinfo]}{% endhighlight %}} + * @Default {{% highlight javascript %}{navbar: [NewFolder, Upload, |, Delete, Rename, |, Cut, Copy, Paste, |, Getinfo],cwd: [Refresh, Paste,|, SortBy, |, NewFolder, Upload, |, Getinfo],files: [Open, Download, |, Upload, |, Delete, Rename, |, Cut, Copy, Paste, |, OpenFolderLocation, Getinfo]}{% endhighlight %}} */ items?: any; @@ -5182,6 +5327,7 @@ class DatePicker extends ej.Widget { static fn: DatePicker; constructor(element: JQuery, options?: DatePicker.Model); constructor(element: Element, options?: DatePicker.Model); + static Locale: any; model:DatePicker.Model; defaults:DatePicker.Model; @@ -5796,6 +5942,7 @@ class DateTimePicker extends ej.Widget { static fn: DateTimePicker; constructor(element: JQuery, options?: DateTimePicker.Model); constructor(element: Element, options?: DateTimePicker.Model); + static Locale: any; model:DateTimePicker.Model; defaults:DateTimePicker.Model; @@ -6264,6 +6411,7 @@ class Dialog extends ej.Widget { static fn: Dialog; constructor(element: JQuery, options?: Dialog.Model); constructor(element: Element, options?: Dialog.Model); + static Locale: any; model:Dialog.Model; defaults:Dialog.Model; @@ -6345,15 +6493,15 @@ export interface Model { /** Adds action buttons like close, minimize, pin, maximize in the dialog header. */ - actionButtons?: string[]; + actionButtons?: String[]; /** Enables or disables draggable. */ - allowDraggable?: boolean; + allowDraggable?: Boolean; /** Enables or disables keyboard interaction. */ - allowKeyboardNavigation?: boolean; + allowKeyboardNavigation?: Boolean; /** Customizes the Dialog widget animations. The Dialog widget can be animated while opening and closing the dialog. In order to customize animation effects, you need to set “enableAnimation” as true. It contains the following sub properties. */ @@ -6361,79 +6509,79 @@ export interface Model { /** Closes the dialog widget on pressing the ESC key when it is set to true. */ - closeOnEscape?: boolean; + closeOnEscape?: Boolean; /** The selector for the container element. If the property is set, then dialog will append to the selected element and it is restricted to move only within the specified container element. */ - containment?: string; + containment?: String; /** The content type to load the dialog content at run time. The possible values are null, AJAX, iframe and image. When it is null (default value), the content inside dialog element will be displayed as content and when it is not null, the content will be loaded from the URL specified in the contentUrl property. */ - contentType?: string; + contentType?: String; /** The URL to load the dialog content (such as AJAX, image, and iframe). In order to load content from URL, you need to set contentType as ‘ajax’ or ‘iframe’ or ‘image’. */ - contentUrl?: string; + contentUrl?: String; /** The root class for the Dialog widget to customize the existing theme. */ - cssClass?: string; + cssClass?: String; /** Enable or disables animation when the dialog is opened or closed. */ - enableAnimation?: boolean; + enableAnimation?: Boolean; /** Enables or disables the Dialog widget. */ - enabled?: boolean; + enabled?: Boolean; /** Enable or disables modal dialog. The modal dialog acts like a child window that is displayed on top of the main window/screen and disables the main window interaction until it is closed. */ - enableModal?: boolean; + enableModal?: Boolean; /** Allows the current model values to be saved in local storage or browser cookies for state maintenance when it is set to true. */ - enablePersistence?: boolean; + enablePersistence?: Boolean; /** Allows the dialog to be resized. The dialog cannot be resized less than the minimum height, width values and greater than the maximum height and width. */ - enableResize?: boolean; + enableResize?: Boolean; /** Displays dialog content from right to left when set to true. */ - enableRTL?: boolean; + enableRTL?: Boolean; /** The CSS class name to display the favicon in the dialog header. In order to display favicon, you need to set showHeader as true since the favicon will be displayed in the dialog header. */ - faviconCSS?: string; + faviconCSS?: String; /** Sets the height for the dialog widget. It accepts both string and integer values. For example, it can accepts values like “auto”, “100%”, “100px” as string type and “100”, “500” as integer type. */ - height?: string|number; + height?: String|Number; /** Enable or disables responsive behavior. */ - isResponsive?: boolean; + isResponsive?: Boolean; /** Set the localization culture for Dialog Widget. */ - locale?: number; + locale?: Number; /** Sets the maximum height for the dialog widget. */ - maxHeight?: number; + maxHeight?: Number; /** Sets the maximum width for the dialog widget. */ - maxWidth?: number; + maxWidth?: Number; /** Sets the minimum height for the dialog widget. */ - minHeight?: number; + minHeight?: Number; /** Sets the minimum width for the dialog widget. */ - minWidth?: number; + minWidth?: Number; /** Displays the Dialog widget at the given X and Y position. */ @@ -6441,23 +6589,23 @@ export interface Model { /** Shows or hides the dialog header. */ - showHeader?: boolean; + showHeader?: Boolean; /** The Dialog widget can be opened by default i.e. on initialization, when it is set to true. */ - showOnInit?: boolean; + showOnInit?: Boolean; /** Enables or disables the rounder corner. */ - showRoundedCorner?: boolean; + showRoundedCorner?: Boolean; /** The selector for the container element. If this property is set, the dialog will be displayed (positioned) based on its container. */ - target?: string; + target?: String; /** The title text to be displayed in the dialog header. In order to set title, you need to set showHeader as true since the title will be displayed in the dialog header. */ - title?: string; + title?: String; /** Add or configure the tooltip text for actionButtons in the dialog header. */ @@ -6465,19 +6613,19 @@ export interface Model { /** Sets the height for the dialog widget. It accepts both string and integer values. For example, it can accepts values like “auto”, “100%”, “100px” as string type and “100”, “500” as integer type. */ - width?: string|number; + width?: String|Number; /** Sets the z-index value for the Dialog widget. */ - zIndex?: number; + zIndex?: Number; /** Sets the Footer for the Dialog widget. */ - showFooter?: boolean; + showFooter?: Boolean; /** Sets the FooterTemplate for the Dialog widget. */ - footerTemplateId?: string; + footerTemplateId?: String; /** This event is triggered before the dialog widgets gets open. */ beforeOpen? (e: BeforeOpenEventArgs): void; @@ -6546,7 +6694,7 @@ export interface BeforeOpenEventArgs { /** Name of the event */ - type?: string; + type?: String; } export interface AjaxErrorEventArgs { @@ -6638,7 +6786,7 @@ export interface CloseEventArgs { /** Name of the event */ - type?: string; + type?: String; } export interface ContentLoadEventArgs { @@ -6653,11 +6801,11 @@ export interface ContentLoadEventArgs { /** Name of the event. */ - type?: string; + type?: String; /** URL of the content. */ - URL?: string; + URL?: String; /** Content type */ @@ -6808,7 +6956,7 @@ export interface ResizeStopEventArgs { /** Set this option to true to cancel the event. */ - cancel?: boolean; + cancel?: Boolean; /** Instance of the dialog model object. */ @@ -6816,7 +6964,7 @@ export interface ResizeStopEventArgs { /** Name of the event */ - type?: string; + type?: String; /** Current event object. */ @@ -6877,10 +7025,149 @@ export interface ActionButtonClickEventArgs { } } +class DocumentEditor extends ej.Widget { + static fn: DocumentEditor; + constructor(element: JQuery, options?: DocumentEditor.Model); + constructor(element: Element, options?: DocumentEditor.Model); + static Locale: any; + model:DocumentEditor.Model; + defaults:DocumentEditor.Model; + + /** Loads the document from specified path using web API provided by importUrl. + * @param {String} Specifies the file path. + * @returns {void} + */ + load(Path: String): void; + + /** Gets the page number of current selection in the document. + * @returns {void} + */ + getCurrentPageNumber(): void; + + /** Gets the total number of pages in the document. + * @returns {void} + */ + getPageCount(): void; + + /** Gets the current zoom factor value of the document container. + * @returns {void} + */ + getZoomFactor(): void; + + /** Scales the document container with the specified zoom factor. The range of zoom factor should be 0.10 to 5.00. + * @returns {void} + */ + setZoomFactor(): void; + + /** Prints the document content as page by page. + * @returns {void} + */ + print(): void; + + /** Finds the first occurrence of specified text from current selection and highlights the result. If the document end is reached, find operation will occur from the document start position. + * @param {String} Specifies the text to search in a document. + * @returns {void} + */ + find(Text: String): void; +} +export module DocumentEditor{ + +export interface Model { + + /** Gets or sets an object that indicates initialization of importing and exporting documents in document editor. + */ + importExportSettings?: ImportExportSettings; + + /** Triggers when the document changes. */ + onDocumentChange? (e: OnDocumentChangeEventArgs): void; + + /** Triggers when the selection changes. */ + onSelectionChange? (e: OnSelectionChangeEventArgs): void; + + /** Triggers when the zoom factor changes. */ + onZoomFactorChange? (e: OnZoomFactorChangeEventArgs): void; + + /** Triggers when the hyperlink is clicked. */ + onRequestNavigate? (e: OnRequestNavigateEventArgs): void; +} + +export interface OnDocumentChangeEventArgs { + + /** True, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the document editor model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface OnSelectionChangeEventArgs { + + /** True, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the document editor model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface OnZoomFactorChangeEventArgs { + + /** True, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the document editor model. + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface OnRequestNavigateEventArgs { + + /** true, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the document editor model. + */ + model?: any; + + /** Returns the link type and navigation link. + */ + hyperlink?: any; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface ImportExportSettings { + + /** Gets or sets URL of Web API that should be used to parse the document while loading. + */ + importUrl?: string; +} +} + class DropDownList extends ej.Widget { static fn: DropDownList; constructor(element: JQuery, options?: DropDownList.Model); constructor(element: Element, options?: DropDownList.Model); + static Locale: any; model:DropDownList.Model; defaults:DropDownList.Model; @@ -7178,7 +7465,7 @@ export interface Model { showRoundedCorner?: boolean; /** When the enableSorting property value is set to true, this property helps to sort the items either in ascending or descending order - * @Default {ej.sortOrder.Ascending} + * @Default {ej.SortOrder.Ascending} */ sortOrder?: ej.SortOrder|string; @@ -7845,13 +8132,6 @@ Delimiter, // can select multiple items and it's show's like visual box in textbox VisualMode, } -enum SortOrder -{ -// Sort the data in ascending order -Ascending, -//Sort the data in descending order -Descending, -} enum VirtualScrollMode { // The data is loaded only to the corresponding page (display items). When scrolling some other position, it enables the load on demand with the DropDownList. @@ -7864,6 +8144,7 @@ class Tooltip extends ej.Widget { static fn: Tooltip; constructor(element: JQuery, options?: Tooltip.Model); constructor(element: Element, options?: Tooltip.Model); + static Locale: any; model:Tooltip.Model; defaults:Tooltip.Model; @@ -8319,6 +8600,7 @@ class Editor extends ej.Widget { static fn: Editor; constructor(element: JQuery, options?: Editor.Model); constructor(element: Element, options?: Editor.Model); + static Locale: any; model:Editor.Model; defaults:Editor.Model; @@ -8390,14 +8672,14 @@ export interface Model { groupSize?: string; /** It provides the options to get the customized character to separate the digits. If not set, the separator defined by the current culture. - * @Default {null} + * @Default {Based on the culture} */ groupSeparator?: string; /** Specifies the height of the editor. * @Default {30} */ - height?: number|string; + height?: string; /** It allows to define the characteristics of the Editors control. It will helps to extend the capability of an HTML element. * @Default {{}} @@ -8475,13 +8757,14 @@ export interface Model { value?: number|string; /** Specifies the watermark text to editor. + * @Default {Based on the culture.} */ watermarkText?: string; /** Specifies the width of the editor. * @Default {143} */ - width?: number|string; + width?: string; /** Fires after Editor control value is changed. */ change? (e: ChangeEventArgs): void; @@ -8595,6 +8878,7 @@ class ListView extends ej.Widget { static fn: ListView; constructor(element: JQuery, options?: ListView.Model); constructor(element: Element, options?: ListView.Model); + static Locale: any; model:ListView.Model; defaults:ListView.Model; @@ -8805,7 +9089,7 @@ export interface Model { /** Specifies the height. * @Default {null} */ - height?: string|number; + height?: String|Number; /** Specifies whether to retain the selection of the item. * @Default {false} @@ -8845,7 +9129,7 @@ export interface Model { /** Specifies the width. * @Default {null} */ - width?: string|number; + width?: String|Number; /** Event triggers before the AJAX request happens. */ ajaxBeforeLoad? (e: AjaxBeforeLoadEventArgs): void; @@ -8869,7 +9153,7 @@ export interface Model { mouseDown? (e: MouseDownEventArgs): void; /** Event triggers when mouse up happens on the item. */ - mouseUP? (e: MouseUPEventArgs): void; + mouseUp? (e: MouseUpEventArgs): void; } export interface AjaxBeforeLoadEventArgs { @@ -9049,7 +9333,7 @@ export interface MouseDownEventArgs { checkedItemsText?: string; } -export interface MouseUPEventArgs { +export interface MouseUpEventArgs { /** returns true if the event should be canceled; otherwise, false. */ @@ -9097,6 +9381,7 @@ class MaskEdit extends ej.Widget { static fn: MaskEdit; constructor(element: JQuery, options?: MaskEdit.Model); constructor(element: Element, options?: MaskEdit.Model); + static Locale: any; model:MaskEdit.Model; defaults:MaskEdit.Model; @@ -9496,6 +9781,7 @@ class Menu extends ej.Widget { static fn: Menu; constructor(element: JQuery, options?: Menu.Model); constructor(element: Element, options?: Menu.Model); + static Locale: any; model:Menu.Model; defaults:Menu.Model; @@ -9970,6 +10256,7 @@ class Pager extends ej.Widget { static fn: Pager; constructor(element: JQuery, options?: Pager.Model); constructor(element: Element, options?: Pager.Model); + static Locale: any; model:Pager.Model; defaults:Pager.Model; @@ -9990,61 +10277,61 @@ export interface Model { /** Gets or sets a value that indicates whether to display the custom text message in Pager. */ - customText?: string; + customText?: String; /** Gets or sets a value that indicates whether to define which page to display currently in pager. * @Default {1} */ - currentPage?: number; + currentPage?: Number; /** Gets or sets a value that indicates whether to display the external Message in Pager. * @Default {false} */ - enableExternalMessage?: boolean; + enableExternalMessage?: Boolean; /** Gets or sets a value that indicates whether to pass the current page information as a query string along with the URL while navigating to other page. * @Default {false} */ - enableQueryString?: boolean; + enableQueryString?: Boolean; /** Align content in the pager control from right to left by setting the property as true. * @Default {false} */ - enableRTL?: boolean; + enableRTL?: Boolean; /** Gets or sets a value that indicates whether to display the external Message in Pager. */ - externalMessage?: string; + externalMessage?: String; /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific to a particular country or region. * @Default {en-US} */ - locale?: string; + locale?: String; /** Gets or sets a value that indicates whether to define the number of pages displayed in the pager for navigation. * @Default {10} */ - pageCount?: number; + pageCount?: Number; /** Gets or sets a value that indicates whether to define the number of records displayed per page. * @Default {12} */ - pageSize?: number; + pageSize?: Number; /** Get or sets a value of total number of pages in the pager. The totalPages value is calculated based on page size and total records. * @Default {null} */ - totalPages?: number; + totalPages?: Number; /** Get the value of total number of records which is bound to a data item. * @Default {null} */ - totalRecordsCount?: number; + totalRecordsCount?: Number; /** Shows or hides the current page information in pager footer. * @Default {true} */ - showPageInfo?: boolean; + showPageInfo?: Boolean; /** Triggered when pager numeric item is clicked in pager control. */ click? (e: ClickEventArgs): void; @@ -10078,6 +10365,7 @@ class ProgressBar extends ej.Widget { static fn: ProgressBar; constructor(element: JQuery, options?: ProgressBar.Model); constructor(element: Element, options?: ProgressBar.Model); + static Locale: any; model:ProgressBar.Model; defaults:ProgressBar.Model; @@ -10295,6 +10583,7 @@ class RadioButton extends ej.Widget { static fn: RadioButton; constructor(element: JQuery, options?: RadioButton.Model); constructor(element: Element, options?: RadioButton.Model); + static Locale: any; model:RadioButton.Model; defaults:RadioButton.Model; @@ -10481,6 +10770,7 @@ class Rating extends ej.Widget { static fn: Rating; constructor(element: JQuery, options?: Rating.Model); constructor(element: Element, options?: Rating.Model); + static Locale: any; model:Rating.Model; defaults:Rating.Model; @@ -10771,6 +11061,7 @@ class Ribbon extends ej.Widget { static fn: Ribbon; constructor(element: JQuery, options?: Ribbon.Model); constructor(element: Element, options?: Ribbon.Model); + static Locale: any; model:Ribbon.Model; defaults:Ribbon.Model; @@ -10836,9 +11127,9 @@ class Ribbon extends ej.Widget { /** Gets text of the given index tab in the ribbon control. * @param {number} index of the tab item. - * @returns {string} + * @returns {String} */ - getTabText(index: number): string; + getTabText(index: number): String; /** Hides the given text tab in the ribbon control. * @param {string} text of the tab item. @@ -10848,15 +11139,15 @@ class Ribbon extends ej.Widget { /** Checks whether the given text tab in the ribbon control is enabled or not. * @param {string} text of the tab item. - * @returns {boolean} + * @returns {Boolean} */ - isEnable(text: string): boolean; + isEnable(text: string): Boolean; /** Checks whether the given text tab in the ribbon control is visible or not. * @param {string} text of the tab item. - * @returns {boolean} + * @returns {Boolean} */ - isVisible(text: string): boolean; + isVisible(text: string): Boolean; /** Removes the given index tab item from the ribbon control. * @param {number} index of tab item. @@ -11889,6 +12180,7 @@ class Kanban extends ej.Widget { static fn: Kanban; constructor(element: JQuery, options?: Kanban.Model); constructor(element: Element, options?: Kanban.Model); + static Locale: any; model:Kanban.Model; defaults:Kanban.Model; @@ -11935,14 +12227,14 @@ class Kanban extends ej.Widget { /** Get the column details based on the given header text in Kanban. * @param {string} Pass the header text of the column to get the corresponding column object - * @returns {string} + * @returns {String} */ - getColumnByHeaderText(headerText: string): string; + getColumnByHeaderText(headerText: string): String; /** Get the table details based on the given header table in Kanban. - * @returns {string} + * @returns {String} */ - getHeaderTable(): string; + getHeaderTable(): String; /** Hide columns from the Kanban based on the header text * @param {Array|string} you can pass either array of header text of various columns or a header text of a column to hide @@ -12168,7 +12460,7 @@ export interface Model { /** To perform kanban functionalities with touch interaction. * @Default {true} */ - enableTouch?: boolean; + enableTouch?: Boolean; /** Align content in the Kanban control align from right to left by setting the property as true. * @Default {false} @@ -12252,7 +12544,7 @@ export interface Model { /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific to a particular country or region. * @Default {en-US} */ - locale?: string; + locale?: String; /** Triggered for every Kanban action before its starts. */ actionBegin? (e: ActionBeginEventArgs): void; @@ -12749,7 +13041,7 @@ export interface ContextMenuSettingsCustomMenuItem { /** Gets the template to render custom context menu item. * @Default {null} */ - template?: string; + template?: String; } export interface ContextMenuSettings { @@ -12915,7 +13207,7 @@ export interface EditSettings { /** This specifies the id of the template which is require to be edited using the Dialog Box. * @Default {null} */ - dialogTemplate?: string; + dialogTemplate?: String; /** Get or sets an object that indicates whether to customize the editMode of the Kanban. * @Default {ej.Kanban.EditMode.Dialog} @@ -12930,7 +13222,7 @@ export interface EditSettings { /** This specifies the id of the template which is require to be edited using the External edit form. * @Default {null} */ - externalFormTemplate?: string; + externalFormTemplate?: String; /** This specifies to set the position of an External edit form either in the right or bottom of the Kanban. * @Default {ej.Kanban.FormPosition.Bottom} @@ -13168,6 +13460,7 @@ class Rotator extends ej.Widget { static fn: Rotator; constructor(element: JQuery, options?: Rotator.Model); constructor(element: Element, options?: Rotator.Model); + static Locale: any; model:Rotator.Model; defaults:Rotator.Model; @@ -13585,6 +13878,7 @@ class RTE extends ej.Widget { static fn: RTE; constructor(element: JQuery, options?: RTE.Model); constructor(element: Element, options?: RTE.Model); + static Locale: any; model:RTE.Model; defaults:RTE.Model; @@ -14356,6 +14650,7 @@ class Slider extends ej.Widget { static fn: Slider; constructor(element: JQuery, options?: Slider.Model); constructor(element: Element, options?: Slider.Model); + static Locale: any; model:Slider.Model; defaults:Slider.Model; @@ -14374,7 +14669,7 @@ class Slider extends ej.Widget { */ getValue(): number; - /** To set value to slider handle.By defaut animation is false while set the value. If you want to enable the animation, pass the enableAnimation as true to this method. + /** To set value to slider handle.By default animation is false while set the value. If you want to enable the animation, pass the enableAnimation as true to this method. * @returns {void} */ setValue(): void; @@ -14686,6 +14981,7 @@ class SplitButton extends ej.Widget { static fn: SplitButton; constructor(element: JQuery, options?: SplitButton.Model); constructor(element: Element, options?: SplitButton.Model); + static Locale: any; model:SplitButton.Model; defaults:SplitButton.Model; @@ -14931,11 +15227,11 @@ export interface ItemMouseOutEvent { /** return the menu item id */ - ID?: string; + ID?: String; /** return the clicked menu item text */ - Text?: string; + Text?: String; } export interface ItemMouseOverEventArgs { @@ -14965,11 +15261,11 @@ export interface ItemMouseOverEvent { /** return the menu item id */ - ID?: string; + ID?: String; /** return the clicked menu item text */ - Text?: string; + Text?: String; } export interface ItemSelectedEventArgs { @@ -14996,11 +15292,11 @@ export interface ItemSelectedEventArgs { /** return the menu id */ - menuId?: string; + menuId?: String; /** return the clicked menu item text */ - menuText?: string; + menuText?: String; } export interface OpenEventArgs { @@ -15034,6 +15330,7 @@ class Splitter extends ej.Widget { static fn: Splitter; constructor(element: JQuery, options?: Splitter.Model); constructor(element: Element, options?: Splitter.Model); + static Locale: any; model:Splitter.Model; defaults:Splitter.Model; @@ -15259,6 +15556,7 @@ class Tab extends ej.Widget { static fn: Tab; constructor(element: JQuery, options?: Tab.Model); constructor(element: Element, options?: Tab.Model); + static Locale: any; model:Tab.Model; defaults:Tab.Model; @@ -15830,6 +16128,7 @@ class TagCloud extends ej.Widget { static fn: TagCloud; constructor(element: JQuery, options?: TagCloud.Model); constructor(element: Element, options?: TagCloud.Model); + static Locale: any; model:TagCloud.Model; defaults:TagCloud.Model; @@ -16067,6 +16366,7 @@ class TimePicker extends ej.Widget { static fn: TimePicker; constructor(element: JQuery, options?: TimePicker.Model); constructor(element: Element, options?: TimePicker.Model); + static Locale: any; model:TimePicker.Model; defaults:TimePicker.Model; @@ -16471,6 +16771,7 @@ class ToggleButton extends ej.Widget { static fn: ToggleButton; constructor(element: JQuery, options?: ToggleButton.Model); constructor(element: Element, options?: ToggleButton.Model); + static Locale: any; model:ToggleButton.Model; defaults:ToggleButton.Model; @@ -16678,6 +16979,7 @@ class Toolbar extends ej.Widget { static fn: Toolbar; constructor(element: JQuery, options?: Toolbar.Model); constructor(element: Element, options?: Toolbar.Model); + static Locale: any; model:Toolbar.Model; defaults:Toolbar.Model; @@ -17023,6 +17325,7 @@ class TreeView extends ej.Widget { static fn: TreeView; constructor(element: JQuery, options?: TreeView.Model); constructor(element: Element, options?: TreeView.Model); + static Locale: any; model:TreeView.Model; defaults:TreeView.Model; @@ -17051,11 +17354,12 @@ class TreeView extends ej.Widget { */ checkNode(element: string|any): void; - /** This method is used to collapse all nodes in TreeView control. If you want to collapse all nodes up to the specific level in TreeView control then we need to pass level as argument to this method. + /** This method is used to collapse all nodes in TreeView control. If you want to collapse all nodes up to the specific level in TreeView control then we need to pass levelUntil as argument to this method. * @param {number} TreeView nodes will collapse until the given level + * @param {boolean} Weather exclude the hidden nodes of TreeView while collapse all nodes * @returns {void} */ - collapseAll(levelUntil?: number): void; + collapseAll(levelUntil?: number, excludeHiddenNodes?: boolean): void; /** To collapse a particular node in TreeView. * @param {string|any} ID of TreeView node|object of TreeView node @@ -17081,11 +17385,12 @@ class TreeView extends ej.Widget { */ ensureVisible(element: string|any): boolean; - /** This method is used to expand all nodes in TreeView control. If you want to expand all nodes up to the specific level in TreeView control then we need to pass level as argument to this method. + /** This method is used to expand all nodes in TreeView control. If you want to expand all nodes up to the specific level in TreeView control then we need to pass levelUntil as argument to this method. * @param {number} TreeView nodes will expand until the given level + * @param {boolean} Weather exclude the hidden nodes of TreeView while expand all nodes * @returns {void} */ - expandAll(levelUntil?: number): void; + expandAll(levelUntil?: number, excludeHiddenNodes?: boolean): void; /** To expandNode particular node in TreeView. * @param {string|any} ID of TreeView node/object of TreeView node @@ -18089,11 +18394,11 @@ export interface NodeClickEventArgs { */ currentElement?: any; - /** returns the id of current element + /** returns the id of currently clicked TreeView node */ id?: string; - /** returns the parentId of current element + /** returns the parentId of currently clicked TreeView node */ parentId?: string; } @@ -18616,11 +18921,11 @@ export interface Fields { /** Specifies the node to be in expanded state. */ - expanded?: boolean; + expanded?: string; /** Its allow us to indicate whether the node has child or not in load on demand */ - hasChild?: boolean; + hasChild?: string; /** Specifies the HTML Attributes to "li" item list. */ @@ -18640,7 +18945,7 @@ export interface Fields { /** If its true Checkbox node will be checked when rendered with checkbox. */ - isChecked?: boolean; + isChecked?: string; /** Specifies the link attribute to “a” tag in item list. */ @@ -18656,7 +18961,7 @@ export interface Fields { /** Allow us to specify the node to be in selected state */ - selected?: boolean; + selected?: string; /** Specifies the sprite CSS class to "li" item list. */ @@ -18696,6 +19001,7 @@ class Uploadbox extends ej.Widget { static fn: Uploadbox; constructor(element: JQuery, options?: Uploadbox.Model); constructor(element: Element, options?: Uploadbox.Model); + static Locale: any; model:Uploadbox.Model; defaults:Uploadbox.Model; @@ -18874,7 +19180,7 @@ export interface Model { /** Fires when the file upload progress is completed. */ complete? (e: CompleteEventArgs): void; - /** Fires when the file upload progress is successed. */ + /** Fires when the file upload progress is succeeded. */ success? (e: SuccessEventArgs): void; /** Fires when the Uploadbox control is created. */ @@ -19198,6 +19504,7 @@ class WaitingPopup extends ej.Widget { static fn: WaitingPopup; constructor(element: JQuery, options?: WaitingPopup.Model); constructor(element: Element, options?: WaitingPopup.Model); + static Locale: any; model:WaitingPopup.Model; defaults:WaitingPopup.Model; @@ -19302,6 +19609,7 @@ class Grid extends ej.Widget { static fn: Grid; constructor(element: JQuery, options?: Grid.Model); constructor(element: Element, options?: Grid.Model); + static Locale: any; model:Grid.Model; defaults:Grid.Model; @@ -19344,22 +19652,22 @@ class Grid extends ej.Widget { cancelEditCell(): void; /** It is used to clear all the cell selection. - * @returns {boolean} + * @returns {Boolean} */ - clearCellSelection(): boolean; + clearCellSelection(): Boolean; /** It is used to clear specified cell selection based on the rowIndex and columnIndex provided. * @param {number} It is used to pass the row index of the cell * @param {number} It is used to pass the column index of the cell. - * @returns {boolean} + * @returns {Boolean} */ - clearCellSelection(rowIndex: number, columnIndex: number): boolean; + clearCellSelection(rowIndex: number, columnIndex: number): Boolean; /** It is used to clear all the row selection or at specific row selection based on the index provided. * @param {number} optional If index of the column is specified then it will remove the selection from the particular column else it will clears all of the column selection - * @returns {boolean} + * @returns {Boolean} */ - clearColumnSelection(index?: number): boolean; + clearColumnSelection(index?: number): Boolean; /** It is used to clear all the filtering done. * @param {string} If field of the column is specified then it will clear the particular filtering column @@ -19374,9 +19682,9 @@ class Grid extends ej.Widget { /** Clear all the row selection or at specific row selection based on the index provided * @param {number} optional If index of the row is specified then it will remove the selection from the particular row else it will clears all of the row selection - * @returns {boolean} + * @returns {Boolean} */ - clearSelection(index?: number): boolean; + clearSelection(index?: number): Boolean; /** Clear the sorting from columns in the grid * @returns {void} @@ -19516,9 +19824,9 @@ class Grid extends ej.Widget { /** Get the column index of the given field in grid. * @param {string} Pass the field name of the column to get the corresponding column index - * @returns {number} + * @returns {Number} */ - getColumnIndexByField(fieldName: string): number; + getColumnIndexByField(fieldName: string): Number; /** Get the content div element of grid. * @returns {HTMLElement} @@ -19526,9 +19834,9 @@ class Grid extends ej.Widget { getContent(): HTMLElement; /** Get the content table element of grid - * @returns {HTMLElement} + * @returns {Array} */ - getContentTable(): HTMLElement; + getContentTable(): Array; /** Get the data of currently edited cell value in "batch" edit mode * @returns {any} @@ -19536,9 +19844,9 @@ class Grid extends ej.Widget { getCurrentEditCellData(): any; /** Get the current page index in grid pager. - * @returns {number} + * @returns {Number} */ - getCurrentIndex(): number; + getCurrentIndex(): Number; /** Get the current page data source of grid. * @returns {Array} @@ -19547,9 +19855,9 @@ class Grid extends ej.Widget { /** Get the column field name from the given header text in grid. * @param {string} Pass header text of the column to get its corresponding field name - * @returns {string} + * @returns {String} */ - getFieldNameByHeaderText(headerText: string): string; + getFieldNameByHeaderText(headerText: string): String; /** Get the filter bar of grid * @returns {HTMLElement} @@ -19583,9 +19891,9 @@ class Grid extends ej.Widget { /** Get the column header text from the given field name in grid. * @param {string} Pass field name of the column to get its corresponding header text - * @returns {string} + * @returns {String} */ - getHeaderTextByFieldName(field: string): string; + getHeaderTextByFieldName(field: string): String; /** Get the names of all the hidden column collections in grid. * @returns {Array} @@ -19594,9 +19902,9 @@ class Grid extends ej.Widget { /** Get the row index based on the given tr element in grid. * @param {JQuery} Pass the tr element in grid content to get its row index - * @returns {number} + * @returns {Number} */ - getIndexByRow($tr: JQuery): number; + getIndexByRow($tr: JQuery): Number; /** Get the pager of grid. * @returns {HTMLElement} @@ -19616,9 +19924,9 @@ class Grid extends ej.Widget { getRowByIndex(from: number, to: number): HTMLElement; /** Get the row height of grid. - * @returns {number} + * @returns {Number} */ - getRowHeight(): number; + getRowHeight(): Number; /** Get the rows(tr element)of grid which is displayed in the current page. * @returns {HTMLElement} @@ -19626,21 +19934,21 @@ class Grid extends ej.Widget { getRows(): HTMLElement; /** Get the scroller object of grid. - * @returns {any} + * @returns {ej.Scroller} */ - getScrollObject(): any; + getScrollObject(): ej.Scroller; /** Get the selected records details in grid. - * @returns {void} + * @returns {Array} */ - getSelectedRecords(): void; + getSelectedRecords(): Array; /** Get the calculated summary values of JSON data passed to it * @param {any} Pass Summary Column details * @param {any} Pass JSON Array for which its field values to be calculated - * @returns {number} + * @returns {Number} */ - getSummaryValues(summaryCol: any, summaryData: any): number; + getSummaryValues(summaryCol: any, summaryData: any): Number; /** Get the names of all the visible column collections in grid * @returns {Array} @@ -19727,9 +20035,9 @@ class Grid extends ej.Widget { rowHeightRefresh(): void; /** Save the particular edited cell in grid. - * @returns {boolean} + * @returns {Boolean} */ - saveCell(): boolean; + saveCell(): Boolean; /** We can prevent the client side cellSave event triggering by passing the preventSaveEvent argument as true. * @param {boolean} optionalIf we pass preventSaveEvent as true, it prevents the client side cellSave event triggering @@ -19770,9 +20078,9 @@ class Grid extends ej.Widget { /** Select the specified columns in grid based on Index provided. * @param {number} It is used to set the starting index of column for selecting columns. * @param {number} optionalIt is used to set the ending index of column for selecting columns. - * @returns {boolean} + * @returns {Boolean} */ - selectColumns(columnIndex: number, toIndex?: number): boolean; + selectColumns(columnIndex: number, toIndex?: number): Boolean; /** Select rows in grid. * @param {number} It is used to set the starting index of row for selecting rows. @@ -19808,6 +20116,12 @@ class Grid extends ej.Widget { */ setCellValue(Index: number, fieldName: string, value: any): void; + /** The grid rows has to be rendered as detail view in mobile mode based on given value. + * @param {number} It is used to render grid rows as details view in mobile mode. + * @returns {void} + */ + setPhoneModeMaxWidth(Index: number): void; + /** Set validation to a field during editing. * @param {string} Specify the field name of the column to set validation rules * @param {any} Specify the validation rules for the field @@ -19859,86 +20173,86 @@ export interface Model { /** Gets or sets a value that indicates whether to customizing cell based on our needs. * @Default {false} */ - allowCellMerging?: boolean; + allowCellMerging?: Boolean; /** Gets or sets a value that indicates whether to enable dynamic grouping behavior. Grouping can be done by drag on drop desired columns to grid’s GroupDropArea. This can be further customized through “groupSettings” property. * @Default {false} */ - allowGrouping?: boolean; + allowGrouping?: Boolean; /** Gets or sets a value that indicates whether to enable keyboard support for performing grid actions. selectionType – Gets or sets a value that indicates whether to enable single row or multiple rows selection behavior in grid. Multiple selection can be done through by holding CTRL and clicking the grid rows * @Default {true} */ - allowKeyboardNavigation?: boolean; + allowKeyboardNavigation?: Boolean; /** Gets or sets a value that indicates whether to enable dynamic filtering behavior on grid. Filtering can be used to limit the records displayed using required criteria and this can be further customized through “filterSettings” property * @Default {false} */ - allowFiltering?: boolean; + allowFiltering?: Boolean; /** Gets or sets a value that indicates whether to enable the dynamic sorting behavior on grid data. Sorting can be done through clicking on particular column header. * @Default {false} */ - allowSorting?: boolean; + allowSorting?: Boolean; /** Gets or sets a value that indicates whether to enable multi columns sorting behavior in grid. Sort multiple columns by holding CTRL and click on the corresponding column header. * @Default {false} */ - allowMultiSorting?: boolean; + allowMultiSorting?: Boolean; /** This specifies the grid to show the paginated data. Also enables pager control at the bottom of grid for dynamic navigation through data source. Paging can be further customized through “pageSettings” property. * @Default {false} */ - allowPaging?: boolean; + allowPaging?: Boolean; /** Gets or sets a value that indicates whether to enable the columns reordering behavior in the grid. Reordering can be done through by drag and drop the particular column from one index to another index within the grid. * @Default {false} */ - allowReordering?: boolean; + allowReordering?: Boolean; /** Gets or sets a value that indicates whether the column is non resizable. Column width is set automatically based on the content or header text which is large. * @Default {false} */ - allowResizeToFit?: boolean; + allowResizeToFit?: Boolean; /** Gets or sets a value that indicates whether to enable dynamic resizable of columns. Resize the width of the columns by simply click and move the particular column header line * @Default {false} */ - allowResizing?: boolean; + allowResizing?: Boolean; /** Gets or sets a value that indicates whether to enable the rows reordering in Grid and drag & drop rows between multiple Grid. * @Default {false} */ - allowRowDragAndDrop?: boolean; + allowRowDragAndDrop?: Boolean; /** Gets or sets a value that indicates whether to enable the scrollbar in the grid and view the records by scroll through the grid manually * @Default {false} */ - allowScrolling?: boolean; + allowScrolling?: Boolean; /** Gets or sets a value that indicates whether to enable dynamic searching behavior in grid. Currently search box can be enabled through “toolbarSettings” * @Default {false} */ - allowSearching?: boolean; + allowSearching?: Boolean; /** Gets or sets a value that indicates whether user can select rows on grid. On enabling feature, selected row will be highlighted. * @Default {true} */ - allowSelection?: boolean; + allowSelection?: Boolean; /** Gets or sets a value that indicates whether the Content will wrap to the next line if the content exceeds the boundary of the Column Cells. * @Default {false} */ - allowTextWrap?: boolean; + allowTextWrap?: Boolean; /** Gets or sets a value that indicates whether to enable the multiple exporting behavior on grid data. * @Default {false} */ - allowMultipleExporting?: boolean; + allowMultipleExporting?: Boolean; /** Gets or sets a value that indicates to define common width for all the columns in the grid. */ - commonWidth?: number; + commonWidth?: Number; /** Gets or sets a value that indicates to enable the visibility of the grid lines. * @Default {ej.Grid.GridLines.Both} @@ -19966,7 +20280,7 @@ export interface Model { /** Gets or sets a value that indicates to render the grid with custom theme. */ - cssClass?: string; + cssClass?: String; /** Gets or sets the data to render the grid with records * @Default {null} @@ -19976,7 +20290,7 @@ export interface Model { /** This specifies the grid to add the details row for the corresponding master row * @Default {null} */ - detailsTemplate?: string; + detailsTemplate?: String; /** Gets or sets an object that indicates whether to customize the editing behavior of the grid. */ @@ -19985,42 +20299,42 @@ export interface Model { /** Gets or sets a value that indicates whether to enable the alternative rows differentiation in the grid records based on corresponding theme. * @Default {true} */ - enableAltRow?: boolean; + enableAltRow?: Boolean; /** Gets or sets a value that indicates whether to enable the save action in the grid through row selection * @Default {true} */ - enableAutoSaveOnSelectionChange?: boolean; + enableAutoSaveOnSelectionChange?: Boolean; /** Gets or sets a value that indicates whether to enable mouse over effect on the corresponding column header cell of the grid * @Default {false} */ - enableHeaderHover?: boolean; + enableHeaderHover?: Boolean; /** Gets or sets a value that indicates whether to persist the grid model state in page using applicable medium i.e., HTML5 localStorage or cookies * @Default {false} */ - enablePersistence?: boolean; + enablePersistence?: Boolean; /** Gets or sets a value that indicates whether the grid rows has to be rendered as detail view in mobile mode * @Default {false} */ - enableResponsiveRow?: boolean; + enableResponsiveRow?: Boolean; /** Gets or sets a value that indicates whether to enable mouse over effect on corresponding grid row. * @Default {true} */ - enableRowHover?: boolean; + enableRowHover?: Boolean; /** Align content in the grid control from right to left by setting the property as true. * @Default {false} */ - enableRTL?: boolean; + enableRTL?: Boolean; /** To Disable the mouse swipe property as false. * @Default {true} */ - enableTouch?: boolean; + enableTouch?: Boolean; /** Gets or sets an object that indicates whether to customize the filtering behavior of the grid */ @@ -20033,7 +20347,7 @@ export interface Model { /** Gets or sets a value that indicates whether the grid design has be to made responsive. * @Default {false} */ - isResponsive?: boolean; + isResponsive?: Boolean; /** This specifies to change the key in keyboard interaction to grid control * @Default {null} @@ -20043,12 +20357,12 @@ export interface Model { /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data i.e. in a language and culture specific to a particular country or region. * @Default {en-US} */ - locale?: string; + locale?: String; /** Gets or sets a value that indicates whether to set the minimum width of the responsive grid while isResponsive property is true and enableResponsiveRow property is set as false. * @Default {0} */ - minWidth?: number; + minWidth?: Number; /** Gets or sets an object that indicates whether to modify the pager default configuration. */ @@ -20059,14 +20373,14 @@ export interface Model { */ query?: any; - /** Gets or sets an object that indicates whether to modify the resizing behaviour. + /** Gets or sets an object that indicates whether to modify the resizing behavior. */ resizeSettings?: ResizeSettings; /** Gets or sets a value that indicates to render the grid with template rows. The template row must be a table row. That table row must have the JavaScript render binding format ({{:columnName}}) then the grid data source binds the data to the corresponding table row of the template. * @Default {null} */ - rowTemplate?: string; + rowTemplate?: String; /** Gets or sets an object that indicates whether to customize the drag and drop behavior of the grid rows */ @@ -20084,7 +20398,12 @@ export interface Model { /** Gets or sets a value that indicates to select the row while initializing the grid * @Default {-1} */ - selectedRowIndex?: number; + selectedRowIndex?: Number; + + /** Gets or sets a value that indicates the selected rows in grid + * @Default {[]} + */ + selectedRowIndices?: Array; /** This property is used to configure the selection behavior of the grid. */ @@ -20102,17 +20421,17 @@ export interface Model { /** Gets or sets a value that indicates whether to enable column chooser on grid. On enabling feature able to show/hide grid columns * @Default {false} */ - showColumnChooser?: boolean; + showColumnChooser?: Boolean; /** Gets or sets a value that indicates stacked header should be shown on grid layout when the property “stackedHeaderRows” is set. * @Default {false} */ - showStackedHeader?: boolean; + showStackedHeader?: Boolean; /** Gets or sets a value that indicates summary rows should be shown on grid layout when the property “summaryRows” is set * @Default {false} */ - showSummary?: boolean; + showSummary?: Boolean; /** Gets or sets a value that indicates whether to customize the sorting behavior of the grid. */ @@ -21954,27 +22273,27 @@ export interface Column { /** Gets or sets a value that indicates whether to enable editing behavior for particular column. * @Default {true} */ - allowEditing?: boolean; + allowEditing?: Boolean; /** Gets or sets a value that indicates whether to enable dynamic filtering behavior for particular column. * @Default {true} */ - allowFiltering?: boolean; + allowFiltering?: Boolean; /** Gets or sets a value that indicates whether to enable dynamic grouping behavior for particular column. * @Default {true} */ - allowGrouping?: boolean; + allowGrouping?: Boolean; /** Gets or sets a value that indicates whether to enable dynamic sorting behavior for particular column. * @Default {true} */ - allowSorting?: boolean; + allowSorting?: Boolean; /** Gets or sets a value that indicates whether to enable dynamic resizable for particular column. * @Default {true} */ - allowResizing?: boolean; + allowResizing?: Boolean; /** Gets or sets an object that indicates to define a command column in the grid. * @Default {[]} @@ -21983,7 +22302,7 @@ export interface Column { /** Gets or sets a value that indicates to provide custom CSS for an individual column. */ - cssClass?: string; + cssClass?: String; /** Gets or sets a value that indicates the attribute values to the td element of a particular column */ @@ -21996,17 +22315,17 @@ export interface Column { /** Gets or sets a value that indicates to display the specified default value while adding a new record to the grid */ - defaultValue?: string|number|boolean|Date; + defaultValue?: String|Number|Boolean|Date; /** Gets or sets a value that indicates to render the grid content and header with an HTML elements * @Default {false} */ - disableHtmlEncode?: boolean; + disableHtmlEncode?: Boolean; /** Gets or sets a value that indicates to display a column value as checkbox or string * @Default {true} */ - displayAsCheckBox?: boolean; + displayAsCheckBox?: Boolean; /** Gets or sets a value that indicates to customize ejNumericTextbox of an editable column. See editingType */ @@ -22022,32 +22341,37 @@ export interface Column { */ editType?: ej.Grid.EditingType|string; + /** Gets or sets a value that indicates to groups the column based on its column format. + * @Default {false} + */ + enableGroupByFormat?: Boolean; + /** Gets or sets a value that indicates to display the columns in the grid mapping with column name of the dataSource. */ - field?: string; + field?: String; /** Gets or sets a value that indicates to define foreign key field name of the grid datasource. * @Default {null} */ - foreignKeyField?: string; + foreignKeyField?: String; /** Gets or sets a value that indicates to bind the field which is in foreign column datasource based on the foreignKeyField * @Default {null} */ - foreignKeyValue?: string; + foreignKeyValue?: String; /** Gets or sets a value that indicates the format for the text applied on the column */ - format?: string; + format?: String; /** Gets or sets a value that indicates to add the template within the header element of the particular column. * @Default {null} */ - headerTemplateID?: string; + headerTemplateID?: String; /** Gets or sets a value that indicates to display the title of that particular column. */ - headerText?: string; + headerText?: String; /** This defines the text alignment of a particular column header cell value. See headerTextAlign * @Default {ej.TextAlign.Left} @@ -22057,32 +22381,32 @@ export interface Column { /** You can use this property to freeze selected columns in grid at the time of scrolling. * @Default {false} */ - isFrozen?: boolean; + isFrozen?: Boolean; /** Gets or sets a value that indicates the column has an identity in the database. * @Default {false} */ - isIdentity?: boolean; + isIdentity?: Boolean; /** Gets or sets a value that indicates the column is act as a primary key(read-only) of the grid. The editing is performed based on the primary key column * @Default {false} */ - isPrimaryKey?: boolean; + isPrimaryKey?: Boolean; /** Gets or sets a value that indicates the order of Column that are to be hidden or visible when Grid element is in responsive mode and could not occupy all columns. * @Default {null} */ - priority?: number; + priority?: Number; /** Used to hide the particular column in column chooser by giving value as false. * @Default {true} */ - showInColumnChooser?: boolean; + showInColumnChooser?: Boolean; /** Gets or sets a value that indicates whether to enables column template for a particular column. * @Default {false} */ - template?: boolean|string; + template?: Boolean|String; /** Gets or sets a value that indicates to align the text within the column. See textAlign * @Default {ej.TextAlign.Left} @@ -22095,7 +22419,7 @@ export interface Column { /** Gets or sets a value that indicates to specify the data type of the specified columns. */ - type?: string; + type?: String; /** Gets or sets a value that indicates to define constraints for saving data to the database. */ @@ -22104,11 +22428,11 @@ export interface Column { /** Gets or sets a value that indicates whether this column is visible in the grid. * @Default {true} */ - visible?: boolean; + visible?: Boolean; /** Gets or sets a value that indicates to define the width for a particular column in the grid. */ - width?: number; + width?: Number; } export interface ContextMenuSettingsSubContextMenu { @@ -22139,7 +22463,7 @@ export interface ContextMenuSettings { /** Gets or sets a value that indicates whether to enable the context menu action in the grid. * @Default {false} */ - enableContextMenu?: boolean; + enableContextMenu?: Boolean; /** Used to get or set the subMenu to the corresponding custom context menu item. */ @@ -22148,7 +22472,7 @@ export interface ContextMenuSettings { /** Gets or sets a value that indicates whether to disable the default context menu items in the grid. * @Default {false} */ - disableDefaultItems?: boolean; + disableDefaultItems?: Boolean; } export interface EditSettings { @@ -22156,27 +22480,27 @@ export interface EditSettings { /** Gets or sets a value that indicates whether to enable insert action in the editing mode. * @Default {false} */ - allowAdding?: boolean; + allowAdding?: Boolean; /** Gets or sets a value that indicates whether to enable the delete action in the editing mode. * @Default {false} */ - allowDeleting?: boolean; + allowDeleting?: Boolean; /** Gets or sets a value that indicates whether to enable the edit action in the editing mode. * @Default {false} */ - allowEditing?: boolean; + allowEditing?: Boolean; /** Gets or sets a value that indicates whether to enable the editing action while double click on the record * @Default {true} */ - allowEditOnDblClick?: boolean; + allowEditOnDblClick?: Boolean; /** This specifies the id of the template. This template can be used to display the data that you require to be edited using the Dialog Box * @Default {null} */ - dialogEditorTemplateID?: string; + dialogEditorTemplateID?: String; /** Gets or sets a value that indicates whether to define the mode of editing See editMode * @Default {ej.Grid.EditMode.Normal} @@ -22186,7 +22510,7 @@ export interface EditSettings { /** This specifies the id of the template. This template can be used to display the data that you require to be edited using the External edit form * @Default {null} */ - externalFormTemplateID?: string; + externalFormTemplateID?: String; /** This specifies to set the position of an External edit form either in the top-right or bottom-left of the grid * @Default {ej.Grid.FormPosition.BottomLeft} @@ -22196,7 +22520,7 @@ export interface EditSettings { /** This specifies the id of the template. This template can be used to display the data that you require to be edited using the Inline edit form * @Default {null} */ - inlineFormTemplateID?: string; + inlineFormTemplateID?: String; /** This specifies to set the position of an adding new row either in the top or bottom of the grid * @Default {ej.Grid.RowPosition.Top} @@ -22206,22 +22530,22 @@ export interface EditSettings { /** Gets or sets a value that indicates whether the confirm dialog has to be shown while saving or discarding the batch changes * @Default {true} */ - showConfirmDialog?: boolean; + showConfirmDialog?: Boolean; /** Gets or sets a value that indicates whether the confirm dialog has to be shown while deleting record * @Default {false} */ - showDeleteConfirmDialog?: boolean; + showDeleteConfirmDialog?: Boolean; /** Gets or sets a value that indicates whether the title for edit form is different from the primarykey column. * @Default {null} */ - titleColumn?: string; + titleColumn?: String; /** Gets or sets a value that indicates whether to display the add new form by default in the grid. * @Default {false} */ - showAddNewRow?: boolean; + showAddNewRow?: Boolean; } export interface FilterSettingsFilteredColumn { @@ -22248,7 +22572,7 @@ export interface FilterSettings { /** Gets or sets a value that indicates to perform the filter operation with case sensitive in excel styled filter menu mode * @Default {false} */ - enableCaseSensitivity?: boolean; + enableCaseSensitivity?: Boolean; /** This specifies the grid to starts the filter action while typing in the filterBar or after pressing the enter key. based on the filterBarMode. See filterBarMode * @Default {ej.Grid.FilterBarMode.Immediate} @@ -22268,17 +22592,17 @@ export interface FilterSettings { /** Gets or sets a value that indicates the maximum number of filter choices that can be showed in the excel styled filter menu. * @Default {1000} */ - maxFilterChoices?: number; + maxFilterChoices?: Number; /** This specifies the grid to show the filter text within the grid pager itself. * @Default {true} */ - showFilterBarMessage?: boolean; + showFilterBarMessage?: Boolean; /** Gets or sets a value that indicates whether to enable the predicate options in the filtering menu * @Default {false} */ - showPredicate?: boolean; + showPredicate?: Boolean; } export interface GroupSettings { @@ -22286,12 +22610,12 @@ export interface GroupSettings { /** Gets or sets a value that customize the group caption format. * @Default {null} */ - captionFormat?: string; + captionFormat?: String; /** Gets or sets a value that indicates whether to enable animation button option in the group drop area of the grid. * @Default {false} */ - enableDropAreaAutoSizing?: boolean; + enableDropAreaAutoSizing?: Boolean; /** Gets or sets a value that indicates whether to add grouped columns programmatically at initial load * @Default {[]} @@ -22301,22 +22625,22 @@ export interface GroupSettings { /** Gets or sets a value that indicates whether to show the group drop area just above the column header. It can be used to avoid ungrouping the already grouped column using groupSettings. * @Default {true} */ - showDropArea?: boolean; + showDropArea?: Boolean; /** Gets or sets a value that indicates whether to hide the grouped columns from the grid * @Default {false} */ - showGroupedColumn?: boolean; + showGroupedColumn?: Boolean; /** Gets or sets a value that indicates whether to show the group button image(toggle button)in the column header and also in the grouped column in the group drop area . It can be used to group/ungroup the columns by click on the toggle button. * @Default {false} */ - showToggleButton?: boolean; + showToggleButton?: Boolean; /** Gets or sets a value that indicates whether to enable the close button in the grouped column which is in the group drop area to ungroup the grouped column * @Default {false} */ - showUngroupButton?: boolean; + showUngroupButton?: Boolean; } export interface PageSettings { @@ -22324,47 +22648,47 @@ export interface PageSettings { /** Gets or sets a value that indicates whether to define which page to display currently in the grid * @Default {1} */ - currentPage?: number; + currentPage?: Number; /** Gets or sets a value that indicates whether to pass the current page information as a query string along with the URL while navigating to other page. * @Default {false} */ - enableQueryString?: boolean; + enableQueryString?: Boolean; /** Gets or sets a value that indicates whether to enables pager template for the grid. * @Default {false} */ - enableTemplates?: boolean; + enableTemplates?: Boolean; /** Gets or sets a value that indicates whether to define the number of pages displayed in the pager for navigation * @Default {8} */ - pageCount?: number; + pageCount?: Number; /** Gets or sets a value that indicates whether to define the number of records displayed per page * @Default {12} */ - pageSize?: number; + pageSize?: Number; /** Gets or sets a value that indicates whether to enables default pager for the grid. * @Default {false} */ - showDefaults?: boolean; + showDefaults?: Boolean; /** Gets or sets a value that indicates to add the template as a pager template for grid. * @Default {null} */ - template?: string; + template?: String; /** Get the value of total number of pages in the grid. The totalPages value is calculated based on page size and total records of grid * @Default {null} */ - totalPages?: number; + totalPages?: Number; /** Get the value of total number of records which is bound to the grid. The totalRecordsCount value is calculated based on dataSource bound to the grid. * @Default {null} */ - totalRecordsCount?: number; + totalRecordsCount?: Number; /** Gets or sets a value that indicates whether to define the number of pages to print * @Default {ej.Grid.PrintMode.AllPages} @@ -22374,7 +22698,7 @@ export interface PageSettings { export interface ResizeSettings { - /** Gets or sets a value that indicates whether to define the mode of resizing.Accepting types are "normal", "nextcolumn" and "control". + /** Gets or sets a value that indicates whether to define the mode of resizing. * @Default {ej.Grid.ResizeMode.Normal} */ resizeMode?: ej.Grid.ResizeMode|string; @@ -22425,7 +22749,7 @@ export interface SelectionSettings { /** Gets or sets a value that indicates whether to enable the toggle selection behavior for row, cell and column. * @Default {false} */ - enableToggle?: boolean; + enableToggle?: Boolean; /** Gets or sets a value that indicates whether to add the default selection actions as a selection mode.See selectionMode * @Default {[row]} @@ -22438,27 +22762,27 @@ export interface ScrollSettings { /** This specify the grid to to view data that you require without buffering the entire load of a huge database * @Default {false} */ - allowVirtualScrolling?: boolean; + allowVirtualScrolling?: Boolean; /** This specify the grid to enable/disable touch control for scrolling. * @Default {true} */ - enableTouchScroll?: boolean; + enableTouchScroll?: Boolean; /** This specify the grid to freeze particular columns at the time of scrolling. * @Default {0} */ - frozenColumns?: number; + frozenColumns?: Number; /** This specify the grid to freeze particular rows at the time of scrolling. * @Default {0} */ - frozenRows?: number; + frozenRows?: Number; /** This specify the grid to show the vertical scroll bar, to scroll and view the grid contents. * @Default {0} */ - height?: string|number; + height?: String|Number; /** This is used to define the mode of virtual scrolling in grid. See virtualScrollMode * @Default {ej.Grid.VirtualScrollMode.Normal} @@ -22468,28 +22792,28 @@ export interface ScrollSettings { /** This is used to enable the enhanced virtual scrolling in Grid. * @Default {false} */ - enableVirtualization?: boolean; + enableVirtualization?: Boolean; /** This specify the grid to show the horizontal scroll bar, to scroll and view the grid contents * @Default {250} */ - width?: string|number; + width?: String|Number; /** This specify the scroll down pixel of mouse wheel, to scroll mouse wheel and view the grid contents. * @Default {57} */ - scrollOneStepBy?: number; + scrollOneStepBy?: Number; } export interface SortSettingsSortedColumn { /** Gets or sets a value that indicates whether to define the direction to sort the column. */ - direction?: string; + direction?: String; /** Gets or sets a value that indicates whether to define the field name of the column to be sort */ - field?: string; + field?: String; } export interface SortSettings { @@ -22509,17 +22833,17 @@ export interface StackedHeaderRowsStackedHeaderColumn { /** Gets or sets a value that indicates class to the corresponding stackedHeaderColumn. * @Default {null} */ - cssClass?: string; + cssClass?: String; /** Gets or sets a value that indicates the header text for the particular stacked header column. * @Default {null} */ - headerText?: string; + headerText?: String; /** Gets or sets a value that indicates the text alignment of the corresponding headerText. * @Default {ej.TextAlign.Left} */ - textAlign?: string; + textAlign?: String; } export interface StackedHeaderRow { @@ -22535,32 +22859,32 @@ export interface SummaryRowsSummaryColumn { /** Gets or sets a value that indicates the text displayed in the summary column as a value * @Default {null} */ - customSummaryValue?: string; + customSummaryValue?: String; /** This specifies summary column used to perform the summary calculation * @Default {null} */ - dataMember?: string; + dataMember?: String; /** Gets or sets a value that indicates to define the target column at which to display the summary. * @Default {null} */ - displayColumn?: string; + displayColumn?: String; /** Gets or sets a value that indicates the format for the text applied on the column * @Default {null} */ - format?: string; + format?: String; /** Gets or sets a value that indicates the text displayed before the summary column value * @Default {null} */ - prefix?: string; + prefix?: String; /** Gets or sets a value that indicates the text displayed after the summary column value * @Default {null} */ - suffix?: string; + suffix?: String; /** Gets or sets a value that indicates the type of calculations to be performed for the corresponding summary column * @Default {[]} @@ -22570,7 +22894,7 @@ export interface SummaryRowsSummaryColumn { /** Gets or sets a value that indicates to add the template for the summary value of dataMember given. * @Default {null} */ - template?: string; + template?: String; } export interface SummaryRow { @@ -22578,17 +22902,17 @@ export interface SummaryRow { /** Gets or sets a value that indicates whether to show the summary value within the group caption area for the corresponding summary column while grouping the column * @Default {false} */ - showCaptionSummary?: boolean; + showCaptionSummary?: Boolean; /** Gets or sets a value that indicates whether to show the group summary value for the corresponding summary column while grouping a column * @Default {false} */ - showGroupSummary?: boolean; + showGroupSummary?: Boolean; /** Gets or sets a value that indicates whether to show the total summary value the for the corresponding summary column. The summary row is added after the grid content. * @Default {true} */ - showTotalSummary?: boolean; + showTotalSummary?: Boolean; /** Gets or sets a value that indicates whether to add summary columns into the summary rows. * @Default {[]} @@ -22597,12 +22921,12 @@ export interface SummaryRow { /** This specifies the grid to show the title for the summary rows. */ - title?: string; + title?: String; /** This specifies the grid to show the title of summary row in the specified column. * @Default {null} */ - titleColumn?: string; + titleColumn?: String; } export interface TextWrapSettings { @@ -22623,7 +22947,7 @@ export interface ToolbarSettings { /** Gets or sets a value that indicates whether to enable toolbar in the grid. * @Default {false} */ - showToolbar?: boolean; + showToolbar?: Boolean; /** Gets or sets a value that indicates whether to add the default editing actions as a toolbar items * @Default {[]} @@ -22868,6 +23192,7 @@ class Sparkline extends ej.Widget { static fn: Sparkline; constructor(element: JQuery, options?: Sparkline.Model); constructor(element: Element, options?: Sparkline.Model); + static Locale: any; model:Sparkline.Model; defaults:Sparkline.Model; @@ -23464,20 +23789,21 @@ class PivotGrid extends ej.Widget { static fn: PivotGrid; constructor(element: JQuery, options?: PivotGrid.Model); constructor(element: Element, options?: PivotGrid.Model); + static Locale: any; model:PivotGrid.Model; defaults:PivotGrid.Model; - /** Perform an asynchronous HTTP (AJAX) request. + /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} */ doAjaxPost(): void; - /** Perform an asynchronous HTTP (FullPost) submit. + /** Performs an asynchronous HTTP (FullPost) submit. * @returns {void} */ doPostBack(): void; - /** Exports the PivotGrid to an appropriate format based on the parameter passed. + /** Exports the PivotGrid to the specified format. * @returns {void} */ exportPivotGrid(): void; @@ -23487,11 +23813,61 @@ class PivotGrid extends ej.Widget { */ refreshPagedPivotGrid(): void; - /** This function is helps to update or refresh the PivotGrid with modified data source in client-mode. + /** This function refreshes the PivotGrid with modified data input in client-mode. * @returns {void} */ refreshPivotGrid(): void; + /** This function re-renders the control with the report available at that instant. + * @returns {void} + */ + refreshControl(): void; + + /** This function returns the height of all rows and width each and every column. + * @returns {void} + */ + calculateCellWidths(): void; + + /** This function creates the conditional formatting dialog to apply conditional formatting for PivotGrid control. + * @returns {void} + */ + createConditionalDialog(): void; + + /** This function saves the current report to the database/local storage. + * @returns {void} + */ + saveReport(): void; + + /** This function loads the specified report from the database/local storage. + * @returns {void} + */ + loadReport(): void; + + /** This function reconstructs the JSON data formed for rendering PivotGrid in excel-like layout format. + * @returns {void} + */ + excelLikeLayout(): void; + + /** Returns the OlapReport string maintained along with the axis elements information. + * @returns {void} + */ + getOlapReport(): void; + + /** Sets the OlapReport string along with the axis information. + * @returns {void} + */ + setOlapReport(): void; + + /** Returns the JSON records formed to render the control. + * @returns {void} + */ + getJSONRecords(): void; + + /** Sets the JSON records formed to render the control. + * @returns {void} + */ + setJSONRecords(): void; + /** This function allows user to change the caption of the Pivot Item (name displayed in UI) on-demand for relational datasource in client-mode. * @returns {void} */ @@ -23507,51 +23883,51 @@ export module PivotGrid{ export interface Model { /** Sets the mode for the PivotGrid widget for binding either OLAP or relational data source. - * @Default {ej.PivotGrid.AnalysisMode.Olap} + * @Default {ej.Pivot.AnalysisMode.Pivot} */ - analysisMode?: ej.PivotGrid.AnalysisMode|string; + analysisMode?: ej.Pivot.AnalysisMode|string; /** Specifies the CSS class to PivotGrid to achieve custom theme. * @Default {“”} */ cssClass?: string; - /** Contains the serialized OlapReport at that instant. - * @Default {“”} - */ - currentReport?: string; - /** Initializes the data source for the PivotGrid widget, when it functions completely on client-side. * @Default {{}} */ dataSource?: DataSource; - /** Used to bind the drilled members by default through report. - * @Default {[]} + /** Object that holds the settings of frozen headers. + * @Default {{}} */ - drilledItems?: Array; + frozenHeaderSettings?: FrozenHeaderSettings; - /** Object utilized to pass additional information between client-end and service-end. + /** Object utilized to pass additional information between client-end and service-end on operating the control in server mode. * @Default {null} */ customObject?: any; + /** Allows the user to collapsed the specified members in each field by default. + * @Default {null} + */ + collapsedMembers?: any; + /** Allows the user to access each cell on mouse right-click. * @Default {false} */ enableCellContext?: boolean; - /** Enables the cell selection for a specified range of value cells. And, the individual row/column cells can be selected by clicking its headers. + /** Enables the cell selection for a specific range of value cells. * @Default {false} */ enableCellSelection?: boolean; - /** Enables the Drill-Through feature which retrieves the raw items that are used to create a specified cell in PivotGrid. This is only applicable in server mode component. + /** Enables the Drill-Through feature which retrieves the raw items that are used to create the specific cell in PivotGrid. This is only applicable in server mode component. * @Default {false} */ enableDrillThrough?: boolean; - /** Allows user to get the cell details in JSON format when double clicking the cell. + /** Allows user to get the cell details in JSON format on double clicking the cell. * @Default {false} */ enableCellDoubleClick?: boolean; @@ -23561,12 +23937,12 @@ export interface Model { */ enableCellEditing?: boolean; - /** Collapses the Pivot Items along rows and columns by default. It works only for relational data source. + /** Collapses the Pivot items along rows and columns by default. It works only for relational data source. * @Default {false} */ enableCollapseByDefault?: boolean; - /** Enables the display of grand total for all the columns. + /** Enables/Disables the display of grand total for all the columns. * @Default {true} */ enableColumnGrandTotal?: boolean; @@ -23581,12 +23957,12 @@ export interface Model { */ enableDeferUpdate?: boolean; - /** Enables the display of GroupingBar allowing you to filter, sort and remove fields obtained from relational datasource. + /** Enables the display of GroupingBar allowing you to filter, sort and remove fields obtained from datasource. * @Default {false} */ enableGroupingBar?: boolean; - /** Enables the display of grand total for rows and columns. + /** Enables/Disables the display of grand total for rows and columns. * @Default {true} */ enableGrandTotal?: boolean; @@ -23596,7 +23972,7 @@ export interface Model { */ enableJSONRendering?: boolean; - /** Enables rendering of PivotGrid widget along with the PivotTable Field List, which allows UI operation. + /** Enables rendering of PivotGrid widget along with the PivotTable Field List, which allows UI operations. * @Default {true} */ enablePivotFieldList?: boolean; @@ -23621,32 +23997,36 @@ export interface Model { */ enableToolTipAnimation?: boolean; + /** Allows the user to adjust the width of the columns dynamically. + * @Default {false} + */ + enableColumnResizing?: boolean; + /** Allows the user to view large amount of data through virtual scrolling. * @Default {false} */ enableVirtualScrolling?: boolean; + /** Allows the user to view large amount of data by applying paging. + * @Default {false} + */ + enablePaging?: boolean; + /** Allows the user to configure hyperlink settings of PivotGrid control. * @Default {{}} */ hyperlinkSettings?: HyperlinkSettings; - /** This is used for identifying whether the member is Named Set or not. - * @Default {false} - */ - isNamedSets?: boolean; - /** Allows the user to enable PivotGrid’s responsiveness in the browser layout. * @Default {false} */ isResponsive?: boolean; /** Contains the serialized JSON string which renders PivotGrid. - * @Default {“”} */ jsonRecords?: string; - /** Sets the summary layout for PivotGrid. Following are the ways in which summary can be positioned: normal summary (bottom), top summary, no summary and excel-like summary. + /** Sets the summary layout for PivotGrid.Following are the ways in which summary can be positioned: normal summary (bottom), top summary, no summary and excel-like summary. * @Default {ej.PivotGrid.Layout.Normal} */ layout?: ej.PivotGrid.Layout|string; @@ -23657,9 +24037,9 @@ export interface Model { locale?: string; /** Sets the mode for the PivotGrid widget for binding data source either in server-side or client-side. - * @Default {ej.PivotGrid.OperationalMode.ClientMode} + * @Default {ej.Pivot.OperationalMode.ClientMode} */ - operationalMode?: ej.PivotGrid.OperationalMode|string; + operationalMode?: ej.Pivot.OperationalMode|string; /** Allows the user to set custom name for the methods at service-end, communicated during AJAX post. * @Default {{}} @@ -23718,114 +24098,74 @@ export interface Model { /** Triggers when the hyperlink of value cell is clicked. */ valueCellHyperlinkClick? (e: ValueCellHyperlinkClickEventArgs): void; + + /** Triggers before saving the current report to database. */ + saveReport? (e: SaveReportEventArgs): void; + + /** Triggers before loading a report from database. */ + loadReport? (e: LoadReportEventArgs): void; + + /** Triggers before performing exporting in pivot grid. */ + beforeExport? (e: BeforeExportEventArgs): void; + + /** Triggers before editing the cells. */ + cellEdit? (e: CellEditEventArgs): void; } export interface AfterServiceInvokeEventArgs { - /** return the current action of PivotGrid control. + /** returns the current action of PivotGrid control. */ action?: string; - /** return the custom object bounds with PivotGrid control. + /** returns the custom object bound with PivotGrid control. */ customObject?: any; - /** return the outer HTML of PivotGrid control. + /** returns the HTML element of PivotGrid control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGrid model - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event - */ - type?: string; + element?: any; } export interface BeforeServiceInvokeEventArgs { - /** return the current action of PivotGrid control. + /** returns the current action of PivotGrid control. */ action?: string; - /** return the custom object bounds with PivotGrid control. + /** returns the custom object bound with PivotGrid control. */ customObject?: any; - /** return the outer HTML of PivotGrid control. + /** returns the HTML element of PivotGrid control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGrid model - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event - */ - type?: string; + element?: any; } export interface BeforePivotEnginePopulateEventArgs { /** returns the PivotGrid object */ - pivotObject?: any; - - /** returns the PivotGrid model - */ - model?: ej.PivotGrid.Model; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the name of the event - */ - type?: string; + pivotGridObject?: any; } export interface CellDoubleClickEventArgs { - /** return the JSON details of the double clicked cell. + /** returns the JSON details of the double clicked cell. */ - selectedData?: any; + selectedData?: Array; - /** return the custom object bounds with PivotGrid widget. + /** returns the custom object bound with PivotGrid control. */ customObject?: any; - /** return the outer HTML of PivotGrid control. + /** returns the HTML element of PivotGrid control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGrid model - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event - */ - type?: string; + element?: any; } export interface CellContextEventArgs { - /** returns the original event args. - */ - args?: any; - /** returns the cell position (row index and column index) in table. */ cellPosition?: string; @@ -23834,78 +24174,66 @@ export interface CellContextEventArgs { */ cellType?: string; - /** returns the serialized data of the header cells. + /** returns the content of the cell. */ - rowData?: string; + cellValue?: string; /** returns the unique name of levels/members. */ uniqueName?: string; + + /** returns the role of the cell in PivotGrid. + */ + role?: string; + + /** returns JSON record corresponding to the selected cell. + */ + rawdata?: any; + + /** returns the original event object. + */ + args?: any; } export interface CellSelectionEventArgs { - /** returns the original event args. + /** returns the JSON records of the selected range of cells. */ - args?: any; + JSONRecords?: any; - /** Returns the selected cell values. + /** Returns the row headers corresponding to the selected value cells. */ - cellvalue?: any; + rowheader?: any; - /** Returns the selected value cells row headers. + /** Returns the column headers corresponding to the selected value cells. */ - rowheaders?: any; + columnheader?: any; - /** Returns the selected value cells column headers. + /** Returns the information about the measure associated with the selected cell. */ - colheaders?: any; - - /** Returns the selected value cells measure. - */ - measure?: any; - - /** Return the row and column measure count. - */ - measureValue?: any; + measureCount?: string; } export interface ColumnHeaderHyperlinkClickEventArgs { - /** returns the original event args. + /** returns the information about the clicked cell */ args?: any; - /** returns the cell position (row index and column index) in table. + /** returns the HTML element of the control. */ - cellPosition?: string; + element?: any; - /** returns the type of the cell. + /** returns the custom object bound to the control. */ - cellType?: string; - - /** returns the serialized data of the header cells. - */ - rowData?: string; - - /** returns the unique name of levels/members. - */ - uniqueName?: string; + customObject?: any; } export interface DrillSuccessEventArgs { - /** if the event should be canceled; otherwise, false. + /** returns the HTML element of the control. */ - cancel?: boolean; - - /** returns the PivotGrid model - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event - */ - type?: string; + args?: any; } export interface DrillThroughEventArgs { @@ -23914,241 +24242,192 @@ export interface DrillThroughEventArgs { */ data?: any; - /** return the outer HTML of PivotGrid control. + /** returns the HTML element of PivotGrid control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGrid model - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event - */ - type?: string; + element?: any; } export interface LoadEventArgs { - /** returns the original event args. - */ - args?: any; - - /** returns the current action of PivotGrid control. - */ - action?: string; - - /** returns the custom object bounded with the control. + /** returns the custom object bound with the control. */ customObject?: any; - /** returns the HTML of PivotGrid control. + /** returns the HTML element of PivotGrid control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGrid model. - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface RenderCompleteEventArgs { - /** returns the original event args. - */ - args?: any; - /** returns the current action of PivotGrid control. */ action?: string; - /** returns the custom object bounded with the control. + /** returns the custom object bound with the control. */ customObject?: any; - /** returns the HTML of PivotGrid control. + /** returns the HTML element of PivotGrid control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGrid model. - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface RenderFailureEventArgs { - /** returns the original event args. - */ - args?: any; - /** returns the current action of PivotGrid control. */ action?: string; - /** returns the custom object bounded with the control. + /** returns the custom object bound with the control. */ customObject?: any; - /** returns the HTML of PivotGrid control. + /** returns the HTML element of PivotGrid control. */ - element?: string; + element?: any; /** returns the error message with error code. */ - message?: any; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGrid model. - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event. - */ - type?: string; + message?: string; } export interface RenderSuccessEventArgs { - /** returns the original event args. - */ - args?: any; - /** returns the current action of PivotGrid control. */ action?: string; - /** returns the custom object bounded with the control. + /** returns the custom object bound with the control. */ customObject?: any; - /** returns the HTML of PivotGrid control. + /** returns the HTML element of PivotGrid control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGrid model. - */ - model?: ej.PivotGrid.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface RowHeaderHyperlinkClickEventArgs { - /** returns the original event args. + /** returns the information about the clicked cell */ args?: any; - /** returns the cell position (row index and column index) in table. + /** returns the HTML element of the control. */ - cellPosition?: string; + element?: any; - /** returns the type of the cell. + /** returns the custom object bound to the control. */ - cellType?: string; - - /** returns the serialized data of the header cells. - */ - rowData?: string; - - /** returns the unique name of levels/members. - */ - uniqueName?: string; + customObject?: any; } export interface SummaryCellHyperlinkClickEventArgs { - /** returns the original event args. + /** returns the information about the clicked cell */ args?: any; - /** returns the cell position (row index and column index) in table. + /** returns the HTML element of the control. */ - cellPosition?: string; + element?: any; - /** returns the type of the cell. + /** returns the custom object bound to the control. */ - cellType?: string; - - /** returns the serialized data of the header cells. - */ - rowData?: string; - - /** returns the unique name of levels/members. - */ - uniqueName?: string; + customObject?: any; } export interface ValueCellHyperlinkClickEventArgs { - /** returns the original event args. + /** returns the information about the clicked cell */ args?: any; - /** returns the cell position (row index and column index) in table. + /** returns the HTML element of the control. */ - cellPosition?: string; + element?: any; - /** returns the type of the cell. + /** returns the custom object bound to the control. */ - cellType?: string; + customObject?: any; +} - /** returns the serialized data of the header cells. - */ - rowData?: string; +export interface SaveReportEventArgs { - /** returns the unique name of levels/members. + /** returns the report to be stored in database. */ - uniqueName?: string; + report?: any; +} + +export interface LoadReportEventArgs { + + /** returns the PivotGrid object. + */ + targetControl?: any; + + /** returns whether the control is bound with OLAP or Relational data source. + */ + dataModel?: string; +} + +export interface BeforeExportEventArgs { + + /** contains the url of the service responsible for exporting. + */ + url?: string; + + /** contains the name of the exporting file. + */ + fileName?: string; +} + +export interface CellEditEventArgs { + + /** contains the array of cells selected for editing. + */ + editCellsInfo?: Array; } export interface DataSourceColumnsAdvancedFilter { - /** Allows the user to provide level unique name to do advanced filtering (excel-like) for OLAP data source in client-mode. + /** Allows the user to provide level unique name to perform advanced filtering. */ name?: string; - /** Allows the user to set the operator for label filtering to do advanced filtering (excel-like) for OLAP data source in client-mode. + /** Allows the user to set the operator to perform Label Filtering. + * @Default {none} */ labelFilterOperator?: string; - /** Allows the user to set the operator for value filtering to do advanced filtering (excel-like) for OLAP data source in client-mode. + /** Allows the user to set the operator to perform Value Filtering. + * @Default {none} */ valueFilterOperator?: string; - /** Allows the user to set the filtering type while doing advanced filtering (excel-like) for OLAP data source in client-mode. + /** Allows the user to set the filtering type while performing advanced filtering. */ advancedFilterType?: string; - /** Allows the user to holds the filter value in advanced filtering (excel-like) option for OLAP data source in client-mode. + /** In case of value filtering, this property contains the measure name to which the filter is applied. */ - values?: string; + measure?: string; + + /** Allows the user to hold the filter operand values in advanced filtering. + */ + values?: Array; +} + +export interface DataSourceColumnsFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; } export interface DataSourceColumn { @@ -24157,7 +24436,7 @@ export interface DataSourceColumn { */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Allows the user to set the display caption for an item. */ fieldCaption?: string; @@ -24166,33 +24445,72 @@ export interface DataSourceColumn { */ advancedFilter?: Array; - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. + /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} */ isNamedSets?: boolean; + + /** Shows/Hides the sub-total of the field in PivotGrid. + * @Default {true} + */ + showSubTotal?: boolean; + + /** Allows the user to set the sorting order of the members of the field. + * @Default {ej.PivotAnalysis.SortOrder.Ascending} + */ + sortOrder?: ej.PivotAnalysis.SortOrder|string; + + /** Contains the list of members need to be drilled down by default in the field. + * @Default {[]} + */ + drilledItems?: Array; + + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceColumnsFilterItems; } export interface DataSourceRowsAdvancedFilter { - /** Allows the user to provide level unique name to do advanced filtering (excel-like) for OLAP data source in client-mode. + /** Allows the user to provide level unique name to perform advanced filtering. */ name?: string; - /** Allows the user to set the operator for label filtering to do advanced filtering (excel-like) for OLAP data source in client-mode. + /** Allows the user to set the operator to perform Label Filtering. + * @Default {none} */ labelFilterOperator?: string; - /** Allows the user to set the operator for value filtering to do advanced filtering (excel-like) for OLAP data source in client-mode. + /** Allows the user to set the operator to perform Value Filtering. + * @Default {none} */ valueFilterOperator?: string; - /** Allows the user to set the filtering type while doing advanced filtering (excel-like) for OLAP data source in client-mode. + /** Allows the user to set the filtering type while performing advanced filtering. */ advancedFilterType?: string; - /** Allows the user to holds the filter value in advanced filtering (excel-like) option for OLAP data source in client-mode. + /** In case of value filtering, this property contains the measure name to which the filter is applied. */ - values?: string; + measure?: string; + + /** Allows the user to hold the filter operand values in advanced filtering. + */ + values?: Array; +} + +export interface DataSourceRowsFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; } export interface DataSourceRow { @@ -24201,7 +24519,7 @@ export interface DataSourceRow { */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Allows the user to set the display caption for an item. */ fieldCaption?: string; @@ -24210,42 +24528,95 @@ export interface DataSourceRow { */ advancedFilter?: Array; - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. + /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} */ isNamedSets?: boolean; + + /** Shows/Hides the sub-total of the field. + * @Default {true} + */ + showSubTotal?: boolean; + + /** Allows the user to set the sorting order of the members of the field. + * @Default {ej.PivotAnalysis.SortOrder.Ascending} + */ + sortOrder?: ej.PivotAnalysis.SortOrder|string; + + /** Contains the list of members need to be drilled down by default in the field. + * @Default {[]} + */ + drilledItems?: Array; + + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceRowsFilterItems; +} + +export interface DataSourceValuesMeasure { + + /** Allows the user to bind the measure from OLAP datasource by using its unique name as field name. + */ + fieldName?: string; } export interface DataSourceValue { - /** This holds the measures unique name to bind them from the Cube. - * @Default {[]} - */ - measures?: Array; - - /** Allows to set the axis name to place the measures items. - * @Default {“”} - */ - axis?: string; - - /** Allows the user to bind the item by using its unique name as field name. + /** Allows the user to bind the item by using its unique name as field name for Relational datasource. */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Allows the user to set the display caption for an item for Relational datasource. */ fieldCaption?: string; - /** Allows the user to create new fields by enabling the calculated field option for relational data source at client-side. + /** This holds the list of unique names of measures to bind them from the OLAP cube. + * @Default {[]} + */ + measures?: Array; + + /** Allows to set the axis name to place the measures items. + * @Default {rows} + */ + axis?: string; + + /** Indicates whether the field is a calculated field or not with Relational datasource. * @Default {false} */ isCalculatedField?: boolean; - /** Allows the user to apply the formula as an expression in-order to create new field using calculated field option (in code-behind) for relational data source at client-side. + /** Allows to set the type of PivotGrid summary calculation for the value field with Relational datasource. + * @Default {ej.PivotAnalysis.SummaryType.Sum} + */ + summaryType?: ej.PivotAnalysis.SummaryType|string; + + /** Allows to set the format of the values. + */ + format?: string; + + /** This property sets type of display of date. + */ + formatString?: string; + + /** Allows to set the formula for calculation of values for calculated members in Relational datasource. */ formula?: string; } +export interface DataSourceFiltersFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; +} + export interface DataSourceFilter { /** Allows the user to bind the item by using its unique name as field name. @@ -24256,35 +24627,43 @@ export interface DataSourceFilter { */ fieldCaption?: string; - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. - * @Default {false} + /** Applies filter to the field members. + * @Default {null} */ - isNamedSets?: boolean; + filterItems?: DataSourceFiltersFilterItems; +} + +export interface DataSourcePagerOptions { + + /** Allows to set the number of categorical columns to be displayed in each page on applying paging. + * @Default {0} + */ + categoricalPageSize?: number; + + /** Allows to set the number of series rows to be displayed in each page on applying paging. + * @Default {0} + */ + seriesPageSize?: number; + + /** Allows to set the page number in categorical axis to be loaded by default. + * @Default {1} + */ + categoricalCurrentPage?: number; + + /** Allows to set the page number in series axis to be loaded by default. + * @Default {1} + */ + seriesCurrentPage?: number; } export interface DataSource { - /** Contains the database name as string type to fetch the data from the given connection string. - * @Default {“”} - */ - catalog?: string; - - /** Lists out the items to be arranged in column section of PivotGrid. + /** Lists out the items to be arranged in columns section of PivotGrid. * @Default {[]} */ columns?: Array; - /** Contains the respective Cube name from database as string type. - * @Default {“”} - */ - cube?: string; - - /** Provides the raw data source for the PivotGrid. - * @Default {null} - */ - data?: any; - - /** Lists out the items to be arranged in row section of PivotGrid. + /** Lists out the items to be arranged in rows section of PivotGrid. * @Default {[]} */ rows?: Array; @@ -24294,15 +24673,57 @@ export interface DataSource { */ values?: Array; - /** Allows user to filter the members (by its name and values) by enable the advanced filtering (excel-like) option for OLAP data source in client-mode. + /** Lists out the items which supports filtering of values without displaying the members in UI in PivotGrid. + * @Default {[]} + */ + filters?: Array; + + /** Contains the respective cube name from OLAP database as string type. + * @Default {“”} + */ + cube?: string; + + /** Provides the raw data source for the PivotGrid. + * @Default {null} + */ + data?: any; + + /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. + * @Default {“”} + */ + catalog?: string; + + /** Allows user to filter the members (by its name and values) through advanced filtering (excel-like) option for OLAP data source in client-mode. * @Default {false} */ enableAdvancedFilter?: boolean; - /** Lists out the items which supports filtering of values in PivotGrid. - * @Default {[]} + /** Sets a name to the report bound to the control. */ - filters?: Array; + reportName?: string; + + /** Allows to set the page size and current page number for each axis on applying paging. + * @Default {{}} + */ + pagerOptions?: DataSourcePagerOptions; +} + +export interface FrozenHeaderSettings { + + /** Allows the user to freeze the row headers alone on scrolling the horizontal scroll bar. + * @Default {false} + */ + enableFrozenRowHeaders?: boolean; + + /** Allows the user to freeze the column headers alone on scrolling the vertical scroll bar. + * @Default {false} + */ + enableFrozenColumnHeaders?: boolean; + + /** Allows the user to freeze both the row headers and column headers on scrolling. + * @Default {false} + */ + enableFrozenHeaders?: boolean; } export interface HyperlinkSettings { @@ -24330,77 +24751,97 @@ export interface HyperlinkSettings { export interface ServiceMethodSettings { - /** Allows the user to set the custom name for the service method that's responsible for drill up/down operation in PivotGrid. + /** Allows the user to set the custom name for the service method responsible for drill up/down operation in PivotGrid. * @Default {DrillGrid} */ drillDown?: string; - /** Allows the user to set the custom name for the service method that’s responsible for exporting. + /** Allows the user to set the custom name for the service method responsible for exporting. * @Default {Export} */ exportPivotGrid?: string; - /** Allows the user to set the custom name for the service method that’s responsible for performing server-side actions on defer update. + /** Allows the user to set the custom name for the service method responsible for performing server-side actions on defer update. * @Default {DeferUpdate} */ deferUpdate?: string; - /** Allows the user to set the custom name for the service method that’s responsible to getting the values for the tree-view inside filter dialog. + /** Allows the user to set the custom name for the service method responsible for getting the values for the tree-view inside filter dialog. * @Default {FetchMembers} */ fetchMembers?: string; - /** Allows the user to set the custom name for the service method that's responsible for filtering operation in PivotGrid. + /** Allows the user to set the custom name for the service method responsible for filtering operation in PivotGrid. * @Default {Filtering} */ filtering?: string; - /** Allows the user to set the custom name for the service method that's responsible for initializing PivotGrid. + /** Allows the user to set the custom name for the service method responsible for initializing PivotGrid. * @Default {InitializeGrid} */ initialize?: string; - /** Allows the user to set the custom name for the service method that's responsible for the server-side action, on dropping a node into Field List. + /** Allows the user to set the custom name for the service method responsible for the server-side action, on dropping a node from Field List. * @Default {NodeDropped} */ nodeDropped?: string; - /** Allows the user to set the custom name for the service method that’s responsible for the server-side action on changing the checked state of a node in Field List. + /** Allows the user to set the custom name for the service method responsible for the server-side action on changing the checked state of a node in Field List. * @Default {NodeStateModified} */ nodeStateModified?: string; - /** Allows the user to set the custom name for the service method that's responsible for performing paging operation in PivotGrid. + /** Allows the user to set the custom name for the service method responsible for performing paging operation in PivotGrid. * @Default {Paging} */ paging?: string; - /** Allows the user to set the custom name for the service method that's responsible for sorting operation in PivotGrid. + /** Allows the user to set the custom name for the service method responsible for sorting operation in PivotGrid. * @Default {Sorting} */ sorting?: string; - /** Allows the user to set the custom name for the service method that’s responsible for expanding members inside member editor. + /** Allows the user to set the custom name for the service method responsible for expanding members inside member editor. * @Default {MemberExpanded} */ memberExpand?: string; - /** Allows the user to set the custom name for the service method that’s responsible for write-back operation in OLAP Cube. This is only applicable in server-side component. + /** Allows the user to set the custom name for the service method responsible for editing the cells. + * @Default {CellEditing} + */ + cellEditing?: string; + + /** Allows the user to set the custom name for the service method responsible for saving the current report to database. + * @Default {SaveReport} + */ + saveReport?: string; + + /** Allows the user to set the custom name for the service method responsible for loading a report from database. + * @Default {LoadReportFromDB} + */ + loadReport?: string; + + /** Allows the user to set the custom name for the service method responsible for adding a calculated field to the report. + * @Default {CalculatedField} + */ + calculatedField?: string; + + /** Allows the user to set the custom name for the service method responsible for performing drill through operation. + * @Default {DrillThroughHierarchies} + */ + drillThroughHierarchies?: string; + + /** Allows the user to set the custom name for the service method responsible for performing drill through operation in data table. + * @Default {DrillThroughDataTable} + */ + drillThroughDataTable?: string; + + /** Allows the user to set the custom name for the service method responsible for write-back operation in OLAP Cube. This is only applicable in server-side component. * @Default {WriteBack} */ writeBack?: string; } -enum AnalysisMode{ - - ///To bind an OLAP data source to PivotGrid. - OLAP, - - ///To bind a relational data source to PivotGrid. - Relational -} - - enum Layout{ ///To set normal summary layout in PivotGrid. @@ -24416,29 +24857,83 @@ enum Layout{ ExcelLikeLayout } - -enum OperationalMode{ - - ///To bind data source completely from client-side. - ClientMode, - - ///To bind data source completely from server-side. - ServerMode } - +module Pivot +{ +enum AnalysisMode +{ +//To bind an OLAP data source to PivotGrid. +OLAP, +//To bind a relational data source to PivotGrid. +Pivot, +} +} +module PivotAnalysis +{ +enum SortOrder +{ +//Sorts the members of the field in ascending order. +Ascending, +//Sorts the members of the field in descending order. +Descending, +//Displays the members without sorting in any order. +None, +} +} +module PivotAnalysis +{ +enum FilterType +{ +//Excludes the specified values among the members of the field. +Exclude, +//Includes the specified values alone among the members of the field. +Include, +} +} +module PivotAnalysis +{ +enum SummaryType +{ +//Calculates the summary as the total of all values. +Sum, +//Displays the average of all values as the summaries. +Average, +//Displays the count of items in summaries. +Count, +//Displays the minimum value of all the items in the summary. +Min, +//Displays the maximum value of all the items in the summary. +Max, +} +} +module Pivot +{ +enum OperationalMode +{ +//To bind data source completely from client-side. +ClientMode, +//To bind data source completely from server-side. +ServerMode, +} } class PivotSchemaDesigner extends ej.Widget { static fn: PivotSchemaDesigner; constructor(element: JQuery, options?: PivotSchemaDesigner.Model); constructor(element: Element, options?: PivotSchemaDesigner.Model); + static Locale: any; model:PivotSchemaDesigner.Model; defaults:PivotSchemaDesigner.Model; - /** Perform an asynchronous HTTP (AJAX) request. + /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} */ doAjaxPost(): void; + + /** Re-renders the control with the data source bound to the pivot control at that instant. + * @returns {void} + */ + refreshControl(): void; } export module PivotSchemaDesigner{ @@ -24454,7 +24949,7 @@ export interface Model { */ customObject?: any; - /** For ASP.NET and MVC Wrapper, Pivots Schema Designer will be initialized and rendered empty initially. Once PivotGrid widget is rendered completely, Pivots Schema Designer will just be populated with data source by setting this property to “true”. + /** For ASP.NET and MVC Wrapper, PivotSchemaDesigner will be initialized and rendered empty initially. Once the connected pivot control widget is rendered completely, PivotSchemaDesigner will just be populated with data source by setting this property to “true”. * @Default {false} */ enableWrapper?: boolean; @@ -24464,26 +24959,16 @@ export interface Model { */ enableRTL?: boolean; - /** Allows the user to view the KPI elements in tree-view inside PivotTable Field List. This is only applicable for OLAP datasource. - * @Default {false} + /** Sets the visibility of OLAP elements in PivotTable Field List. This is only applicable for OLAP datasource. + * @Default {null} */ - showKPI?: boolean; + olap?: Olap; - /** Allows the user to view the named sets in tree-view inside PivotTable Field List. This is only applicable for OLAP datasource. - * @Default {false} - */ - showNamedSets?: boolean; - - /** Allows the user to restrict drag and drop operation within the PivotTable Field List. + /** Allows the user to enable/disable drag and drop operations within the PivotTable Field List. * @Default {true} */ enableDragDrop?: boolean; - /** Allows the user to set the list of filters in filter section. - * @Default {newArray()} - */ - filters?: Array; - /** Sets the height for PivotSchemaDesigner. * @Default {“”} */ @@ -24494,31 +24979,11 @@ export interface Model { */ locale?: string; - /** Allows the user to set list of PivotCalculations in values section. - * @Default {newArray()} - */ - pivotCalculations?: Array; - - /** Allows the user to set the list of PivotItems in column section. - * @Default {newArray()} - */ - pivotColumns?: Array; - /** Sets the Pivot control bound with this PivotSchemaDesigner. * @Default {null} */ pivotControl?: any; - /** Allows the user to set the list of PivotItems in row section. - * @Default {newArray()} - */ - pivotRows?: Array; - - /** Allows the user to arrange the fields inside Field List of PivotSchemaDesigner. - * @Default {newArray()} - */ - pivotTableFields?: Array; - /** Allows the user to set custom name for the methods at service-end, communicated during AJAX post. * @Default {{}} */ @@ -24534,6 +24999,11 @@ export interface Model { */ width?: string; + /** Sets the layout for PivotSchemaDesigner. + * @Default {ej.PivotSchemaDesigner.Layouts.Excel} + */ + layout?: ej.PivotSchemaDesigner.Layouts|string; + /** Triggers when it reaches client-side after any AJAX request. */ afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; @@ -24546,61 +25016,37 @@ export interface Model { export interface AfterServiceInvokeEventArgs { - /** return the current action of PivotSchemaDesigner control. + /** returns the current action of PivotSchemaDesigner control. */ action?: string; - /** return the custom object bounds with PivotSchemaDesigner control. + /** returns the custom object bound with PivotSchemaDesigner control. */ customObject?: any; - /** return the outer HTML of PivotSchemaDesigner control. + /** returns the HTML element of PivotSchemaDesigner control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotSchemaDesigner model - */ - model?: ej.PivotSchemaDesigner.Model; - - /** returns the name of the event - */ - type?: string; + element?: any; } export interface BeforeServiceInvokeEventArgs { - /** return the current action of PivotSchemaDesigner control. + /** returns the current action of PivotSchemaDesigner control. */ action?: string; - /** return the custom object bounds with PivotSchemaDesigner control. + /** returns the custom object bound with PivotSchemaDesigner control. */ customObject?: any; - /** return the outer HTML of PivotSchemaDesigner control. + /** returns the HTML element of PivotSchemaDesigner control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotSchemaDesigner model - */ - model?: ej.PivotSchemaDesigner.Model; - - /** returns the name of the event - */ - type?: string; + element?: any; } export interface DragMoveEventArgs { - /** return the HTML of the dragged field from PivotSchemaDesigner. + /** returns the HTML element of the dragged field from PivotSchemaDesigner. */ dragTarget?: any; @@ -24614,47 +25060,74 @@ export interface DragMoveEventArgs { /** returns the PivotSchemaDesigner model */ - model?: ej.PivotSchemaDesigner.Model; + model?: any; +} + +export interface Olap { + + /** Allows the user to view the KPI elements in tree-view inside PivotTable Field List. This is only applicable for OLAP datasource. + * @Default {false} + */ + showKPI?: boolean; + + /** Allows the user to view the named sets in tree-view inside PivotTable Field List. This is only applicable for OLAP datasource. + * @Default {false} + */ + showNamedSets?: boolean; } export interface ServiceMethod { - /** Allows the user to set the custom name for the service method that’s responsible for getting the values for the tree-view inside filter dialog. + /** Allows the user to set the custom name for the service method responsible for getting the values for the tree-view inside filter dialog. * @Default {FetchMembers} */ fetchMembers?: string; - /** Allows the user to set the custom name for the service method that’s responsible for filtering operation in Field List. + /** Allows the user to set the custom name for the service method responsible for filtering operation in Field List. * @Default {Filtering} */ filtering?: string; - /** Allows the user to set the custom name for the service method that’s responsible for the server-side action, on expanding members in Field List. + /** Allows the user to set the custom name for the service method responsible for the server-side action, on expanding members in Field List. * @Default {MemberExpanded} */ memberExpand?: string; - /** Allows the user to set the custom name for the service method that’s responsible for the server-side action, on dropping a node into Field List. + /** Allows the user to set the custom name for the service method responsible for the server-side action, on dropping a node into Field List. * @Default {NodeDropped} */ nodeDropped?: string; - /** Allows the user to set the custom name for the service method that’s responsible for the server-side action on changing the checked state of a node in Field List. + /** Allows the user to set the custom name for the service method responsible for the server-side action on changing the checked state of a node in Field List. * @Default {NodeStateModified} */ nodeStateModified?: string; - /** Allows the user to set the custom name for the service method that’s responsible for remove operation in Field List. + /** Allows the user to set the custom name for the service method responsible for button removing operation in Field List. * @Default {RemoveButton} */ removeButton?: string; } + +enum Layouts{ + + ///To set the layout as same in the Excel. + Excel, + + ///To set normal layout for Field List. + Normal, + + ///To set layout with the axes one above the other. + OneByOne +} + } class PivotPager extends ej.Widget { static fn: PivotPager; constructor(element: JQuery, options?: PivotPager.Model); constructor(element: Element, options?: PivotPager.Model); + static Locale: any; model:PivotPager.Model; defaults:PivotPager.Model; @@ -24721,10 +25194,11 @@ class PivotChart extends ej.Widget { static fn: PivotChart; constructor(element: JQuery, options?: PivotChart.Model); constructor(element: Element, options?: PivotChart.Model); + static Locale: any; model:PivotChart.Model; defaults:PivotChart.Model; - /** Perform an asynchronous HTTP (AJAX) request. + /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} */ doAjaxPost(): void; @@ -24734,12 +25208,12 @@ class PivotChart extends ej.Widget { */ doPostBack(): void; - /** Exports the PivotChart to an appropriate format based on the parameter passed. + /** Exports the PivotChart to the format specified in the parameter. * @returns {void} */ exportPivotChart(): void; - /** This function receives the JSON formatted datasource to render the PivotChart control. + /** This function renders the PivotChart control with the JSON formatted datasource. * @returns {void} */ renderChartFromJSON(): void; @@ -24748,15 +25222,60 @@ class PivotChart extends ej.Widget { * @returns {void} */ renderControlSuccess(): void; + + /** Returns the OlapReport string maintained along with the axis elements information. + * @returns {void} + */ + getOlapReport(): void; + + /** Sets the OlapReport string along with the axis information and maintains it in a property. + * @returns {void} + */ + setOlapReport(): void; + + /** Returns the JSON records formed to render the control. + * @returns {void} + */ + getJSONRecords(): void; + + /** Sets the JSON records to render the control. + * @returns {void} + */ + setJSONRecords(): void; + + /** Returns the PivotEngine formed to render the control. + * @returns {void} + */ + getPivotEngine(): void; + + /** Sets the PivotEngine required to render the control. + * @returns {void} + */ + setPivotEngine(): void; + + /** Re-renders the control with the data source at the instant. + * @returns {void} + */ + refreshControl(): void; + + /** Renders the control with the pivot engine obtained from olap cube. + * @returns {void} + */ + generateJSON(): void; + + /** Navigates to the specified page number in specified axis. + * @returns {void} + */ + refreshPagedPivotChart(): void; } export module PivotChart{ export interface Model { /** Sets the mode for the PivotChart widget for binding either OLAP or Relational data source. - * @Default {ej.PivotChart.AnalysisMode.Olap} + * @Default {ej.Pivot.AnalysisMode.Pivot} */ - analysisMode?: any; + analysisMode?: ej.Pivot.AnalysisMode|string; /** Specifies the CSS class to PivotChart to achieve custom theme. * @Default {“”} @@ -24766,19 +25285,14 @@ export interface Model { /** Options available to configure the properties of entire series. You can also override the options for specific series by using series collection. * @Default {{}} */ - commonSeriesOptions?: any; - - /** Contains the serialized OlapReport at that instant, that is, current OlapReport. - * @Default {“”} - */ - currentReport?: string; + commonSeriesOptions?: CommonSeriesOptions; /** Initializes the data source for the PivotChart widget, when it functions completely on client-side. * @Default {{}} */ dataSource?: DataSource; - /** Object utilized to pass additional information between client-end and service-end. + /** Object utilized to pass additional information between client-end and service-end on operating the control in server mode. * @Default {{}} */ customObject?: any; @@ -24798,7 +25312,7 @@ export interface Model { */ isResponsive?: boolean; - /** Options available to customize the legend items and its title. + /** Lets the user to customize the legend items and their labels. * @Default {{}} */ legend?: any; @@ -24809,9 +25323,9 @@ export interface Model { locale?: string; /** Sets the mode for the PivotChart widget for binding data source either in server-side or client-side. - * @Default {ej.PivotChart.OperationalMode.ClientMode} + * @Default {ej.Pivot.OperationalMode.ClientMode} */ - operationalMode?: any; + operationalMode?: ej.Pivot.OperationalMode|string; /** This is a horizontal axis that contains options to configure axis and it is the primary x axis for all the series in series array. To override x axis for particular series, create an axis object by providing unique name by using name property and add it to axes array. Then, assign the name to the series’s xAxisName property to link both axis and series. * @Default {{}} @@ -24833,12 +25347,12 @@ export interface Model { */ serviceMethodSettings?: ServiceMethodSettings; - /** Options to customize the Chart size. + /** Options to customize the size of the PivotChart control. * @Default {{}} */ size?: any; - /** Connects the service using the specified URL for any server updates. + /** Connects the service using the specified URL for any server updates on operating the control in server mode. * @Default {“”} */ url?: string; @@ -24852,7 +25366,7 @@ export interface Model { /** Triggers before any AJAX request is passed from PivotChart to service methods. */ beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; - /** Triggers when drill up/down happens in PivotChart control. */ + /** Triggers on performing drill up/down in PivotChart control. */ drillSuccess? (e: DrillSuccessEventArgs): void; /** Triggers when PivotChart widget completes all operations at client-side after any AJAX request. */ @@ -24867,183 +25381,128 @@ export interface Model { export interface LoadEventArgs { - /** return the current action of PivotChart control. + /** returns the current action of PivotChart control. */ action?: string; - /** return the custom object bounds with PivotChart control. + /** returns the custom object bound with PivotChart control. */ customObject?: any; - /** return the outer HTML of PivotChart control. + /** returns the HTML element of PivotChart control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotChart model. - */ - model?: ej.PivotChart.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface AfterServiceInvokeEventArgs { - /** return the current action of PivotChart control. + /** returns the current action of PivotChart control. */ action?: string; - /** return the custom object bounds with PivotChart control. + /** returns the custom object bound with PivotChart control. */ customObject?: any; - /** return the outer HTML of PivotChart control. + /** returns the HTML element of PivotChart control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotChart model. - */ - model?: ej.PivotChart.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface BeforeServiceInvokeEventArgs { - /** return the current action of PivotChart control. + /** returns the current action of PivotChart control. */ action?: string; - /** return the custom object bounds with PivotChart control. + /** returns the custom object bound with PivotChart control. */ customObject?: any; - /** return the outer HTML of PivotChart control. + /** returns the HTML element of PivotChart control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotChart model. - */ - model?: ej.PivotChart.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface DrillSuccessEventArgs { - /** if the event should be canceled; otherwise, false. + /** returns the current instance of PivotChart. */ - cancel?: boolean; + chartObj?: any; - /** returns the PivotChart model. + /** returns the drill action of PivotChart. */ - model?: ej.PivotChart.Model; + drillAction?: string; - /** returns the name of the event. + /** contains the name of the member drilled. */ - type?: string; + drilledMember?: string; + + /** returns the event object. + */ + event?: any; } export interface RenderCompleteEventArgs { - /** return the current action of PivotChart control. + /** returns the current action of PivotChart control. */ action?: string; - /** return the custom object bounds with PivotChart control. + /** returns the custom object bound with PivotChart control. */ customObject?: any; - /** return the outer HTML of PivotChart control. + /** returns the HTML element of PivotChart control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotChart model. - */ - model?: ej.PivotChart.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface RenderFailureEventArgs { - /** return the current action of PivotChart control. + /** returns the current action of PivotChart control. */ action?: string; - /** return the custom object bounds with PivotChart control. + /** returns the custom object bound with PivotChart control. */ customObject?: any; - /** return the error stack trace of the original exception. + /** returns the HTML element of PivotChart control. */ - message?: any; + element?: any; - /** return the outer HTML of PivotChart control. + /** returns the error stack trace of the original exception. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotChart model. - */ - model?: ej.PivotChart.Model; - - /** returns the name of the event. - */ - type?: string; + message?: string; } export interface RenderSuccessEventArgs { - /** return the current action of PivotChart control. + /** returns the current instance of PivotChart. */ - action?: string; + args?: any; +} - /** return the custom object bounds with PivotChart control. - */ - customObject?: any; +export interface CommonSeriesOptions { - /** return the outer HTML of PivotChart control. + /** Allows the user to set the specific chart type for PivotChart widget. + * @Default {ej.PivotChart.ChartTypes.Column} */ - element?: string; + type?: ej.PivotChart.ChartTypes|string; +} - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; +export interface DataSourceColumnsFilterItems { - /** returns the PivotChart model. + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} */ - model?: ej.PivotChart.Model; + filterType?: ej.PivotAnalysis.FilterType|string; - /** returns the name of the event. + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} */ - type?: string; + values?: Array; } export interface DataSourceColumn { @@ -25052,14 +25511,37 @@ export interface DataSourceColumn { */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Allows the user to set the display caption for an item. */ fieldCaption?: string; - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. + /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} */ isNamedSets?: boolean; + + /** Allows the user to set the sorting order of the members of the field. + * @Default {ej.PivotAnalysis.SortOrder.Ascending} + */ + sortOrder?: ej.PivotAnalysis.SortOrder|string; + + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceColumnsFilterItems; +} + +export interface DataSourceRowsFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; } export interface DataSourceRow { @@ -25068,35 +25550,792 @@ export interface DataSourceRow { */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Allows the user to set the display caption for an item. */ fieldCaption?: string; - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. + /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} */ isNamedSets?: boolean; + + /** Allows the user to set the sorting order of the members of the field. + * @Default {ej.PivotAnalysis.SortOrder.Ascending} + */ + sortOrder?: ej.PivotAnalysis.SortOrder|string; + + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceRowsFilterItems; +} + +export interface DataSourceValuesMeasure { + + /** Allows the user to bind the measure from OLAP datasource by using its unique name as field name. + */ + fieldName?: string; } export interface DataSourceValue { - /** This holds the measures unique name to bind them from the Cube. + /** Allows the user to bind the item by using its unique name as field name for Relational datasource. + */ + fieldName?: string; + + /** Allows the user to set the display caption for an item for Relational datasource. + */ + fieldCaption?: string; + + /** This holds the list of unique names of measures to bind them from the OLAP cube. * @Default {[]} */ - measures?: Array; + measures?: Array; /** Allows to set the axis name to place the measures items. - * @Default {“”} + * @Default {rows} */ axis?: string; + /** Indicates whether the field is a calculated field or not with Relational datasource. + * @Default {false} + */ + isCalculatedField?: boolean; + + /** Allows to set the formula for calculation of values for calculated members in Relational datasource. + */ + formula?: string; +} + +export interface DataSourceFiltersFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; +} + +export interface DataSourceFilter { + /** Allows the user to bind the item by using its unique name as field name. */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceFiltersFilterItems; +} + +export interface DataSource { + + /** Contains the respective cube name from OLAP database as string type. + * @Default {“”} + */ + cube?: string; + + /** Provides the raw data source for the PivotChart. + * @Default {null} + */ + data?: any; + + /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. + * @Default {“”} + */ + catalog?: string; + + /** Lists out the items to be displayed as series of PivotChart. + * @Default {[]} + */ + columns?: Array; + + /** Lists out the items to be displayed as segments of PivotChart. + * @Default {[]} + */ + rows?: Array; + + /** Lists out the items supports calculation in PivotChart. + * @Default {[]} + */ + values?: Array; + + /** Lists out the items which supports filtering of values without displaying the members in UI in PivotChart. + * @Default {[]} + */ + filters?: Array; +} + +export interface ServiceMethodSettings { + + /** Allows the user to set the custom name for the service method responsible for drilling up/down operation in PivotChart. + * @Default {DrillChart} + */ + drillDown?: string; + + /** Allows the user to set the custom name for the service method responsible for exporting. + * @Default {Export} + */ + exportPivotChart?: string; + + /** Allows the user to set the custom name for the service method responsible for initializing PivotChart. + * @Default {InitializeChart} + */ + initialize?: string; + + /** Allows the user to set the custom name for the service method responsible for navigating between pages in paged PivotChart. + * @Default {Paging} + */ + paging?: string; +} + +enum ChartTypes{ + + ///To render a Line type PivotChart. + Line, + + ///To render a Spline type PivotChart. + Spline, + + ///To render a Column type PivotChart. + Column, + + ///To render an Area type PivotChart. + Area, + + ///To render a SplineArea type PivotChart. + SplineArea, + + ///To render a StepLine type PivotChart. + StepLine, + + ///To render a StepArea type PivotChart. + StepArea, + + ///To render a Pie type PivotChart. + Pie, + + ///To render a Bar type PivotChart. + Bar, + + ///To render a StackingArea type PivotChart. + StackingArea, + + ///To render a StackingColumn type PivotChart. + StackingColumn, + + ///To render a StackingBar type PivotChart. + StackingBar, + + ///To render a Pyramid type PivotChart. + Pyramid, + + ///To render a Funnel type PivotChart. + Funnel, + + ///To render a Doughnut type PivotChart. + Doughnut, + + ///To render a Scatter type PivotChart. + Scatter, + + ///To render a Bubble type PivotChart. + Bubble +} + +} + +class PivotClient extends ej.Widget { + static fn: PivotClient; + constructor(element: JQuery, options?: PivotClient.Model); + constructor(element: Element, options?: PivotClient.Model); + static Locale: any; + model:PivotClient.Model; + defaults:PivotClient.Model; + + /** Performs an asynchronous HTTP (AJAX) request. + * @returns {void} + */ + doAjaxPost(): void; + + /** Performs an asynchronous HTTP (FullPost) submit. + * @returns {void} + */ + doPostBack(): void; + + /** Navigates to the specified page in specified axis. + * @returns {void} + */ + refreshPagedPivotClient(): void; + + /** Updates the PivotClient component with the JSON data fetched from the service on navigating between pages. + * @returns {void} + */ + refreshPagedPivotClientSuccess(): void; + + /** Renders the PivotChart and PivotGrid with the JSON data provided. + * @returns {void} + */ + generateJSON(): void; + + /** Re-renders the control with the report at that instant. + * @returns {void} + */ + refreshControl(): void; + + /** Returns the OlapReport string maintained along with the axis elements information. + * @returns {void} + */ + getOlapReport(): void; + + /** Sets the OlapReport string along with the axis information and maintains it in a property. + * @returns {void} + */ + setOlapReport(): void; + + /** Returns the JSON records formed to render the control. + * @returns {void} + */ + getJSONRecords(): void; + + /** Sets the JSON records formed to render the control to a property. + * @returns {void} + */ + setJSONRecords(): void; +} +export module PivotClient{ + +export interface Model { + + /** Sets the mode for the PivotClient widget for binding either OLAP or Relational data source. + * @Default {ej.Pivot.AnalysisMode.Pivot} + */ + analysisMode?: ej.Pivot.AnalysisMode|string; + + /** Allows the user to set the specific chart type for PivotChart inside PivotClient widget. + * @Default {ej.PivotChart.ChartTypes.Column} + */ + chartType?: ej.PivotChart.ChartTypes|string; + + /** Allows the user to set the content on exporting the PivotClient widget. + * @Default {ej.PivotClient.ClientExportMode.ChartAndGrid} + */ + clientExportMode?: ej.PivotClient.ClientExportMode|string; + + /** Specifies the CSS class to PivotClient to achieve custom theme. + * @Default {“”} + */ + cssClass?: string; + + /** Object utilized to pass additional information between client-end and service-end when the control functions in server-mode. + * @Default {{}} + */ + customObject?: any; + + /** Initializes the data source for the PivotClient widget, when it functions completely on client-side. + * @Default {{}} + */ + dataSource?: DataSource; + + /** Allows the user to customize the widget's layout and appearance. + * @Default {{}} + */ + displaySettings?: DisplaySettings; + + /** Enables the advanced filtering options Value Filtering, Label Filtering and Sorting for each dimensions on binding OLAP data in server mode. + * @Default {false} + */ + enableAdvancedFilter?: boolean; + + /** Allows the user to refresh the control on-demand and not during every UI operation. + * @Default {false} + */ + enableDeferUpdate?: boolean; + + /** Lets the user to save and load reports in a customized way with the help of events. + * @Default {false} + */ + enableLocalStorage?: boolean; + + /** Allows the user to enable paging for both the PivotChart and PivotGrid components for the ease of viewing large data. + * @Default {false} + */ + enablePaging?: boolean; + + /** Allows the user to include the PivotTreeMap component as one of the chart types. + * @Default {false} + */ + enablePivotTreeMap?: boolean; + + /** Allows the user to view the layout of PivotClient from right to left. + * @Default {false} + */ + enableRTL?: boolean; + + /** Enables/disables the visibility of measure group selector drop-down in Cube Browser. + * @Default {false} + */ + enableMeasureGroups?: boolean; + + /** Allows the user to enable virtual scrolling for both the PivotChart and PivotGrid components for the ease of viewing large data. + * @Default {false} + */ + enableVirtualScrolling?: boolean; + + /** Enables/Disables paging in Member Editor for viewing the large count of members in pages. + * @Default {false} + */ + enableMemberEditorPaging?: boolean; + + /** Allows the user to set the number of members to be displayed in each page of Member Editor on applying paging in it. + * @Default {100} + */ + memberEditorPageSize?: number; + + /** Sets the summary layout for PivotGrid. Following are the ways in which summary can be positioned: normal summary (bottom), top summary, no summary and excel-like summary. + * @Default {ej.PivotGrid.Layout.Normal} + */ + gridLayout?: ej.PivotGrid.Layout|string; + + /** Allows the user to set the localized language for the widget. + * @Default {en-US} + */ + locale?: string; + + /** Sets the mode for the PivotClient widget for binding data source either in server-side or client-side. + * @Default {ej.Pivot.OperationalMode.ClientMode} + */ + operationalMode?: ej.Pivot.OperationalMode|string; + + /** Allows the user to set custom name for the methods at service-end, communicated during AJAX post. + * @Default {{}} + */ + serviceMethodSettings?: ServiceMethodSettings; + + /** Sets the title for PivotClient widget. + */ + title?: string; + + /** Connects the service using the specified URL for any server updates. + */ + url?: string; + + /** Triggers when it reaches client-side after any AJAX request. */ + afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; + + /** Triggers before any AJAX request is passed from client-side to service methods. */ + beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + + /** Triggers before saving the current collection of reports. */ + saveReport? (e: SaveReportEventArgs): void; + + /** Triggers before loading a saved collection of reports. */ + loadReport? (e: LoadReportEventArgs): void; + + /** Triggers before fetching the report collection from storage. */ + fetchReport? (e: FetchReportEventArgs): void; + + /** Triggers before exporting the control. */ + beforeExport? (e: BeforeExportEventArgs): void; + + /** Triggers before rendering the PivotChart. */ + chartLoad? (e: ChartLoadEventArgs): void; + + /** Triggers before rendering the PivotTreeMap. */ + treeMapLoad? (e: TreeMapLoadEventArgs): void; + + /** Triggers while we initiate loading of the widget. */ + load? (e: LoadEventArgs): void; + + /** Triggers when PivotClient widget completes all operations at client-end after any AJAX request. */ + renderComplete? (e: RenderCompleteEventArgs): void; + + /** Triggers when any error occurred during AJAX request. */ + renderFailure? (e: RenderFailureEventArgs): void; + + /** Triggers when PivotClient successfully completes rendering. */ + renderSuccess? (e: RenderSuccessEventArgs): void; +} + +export interface AfterServiceInvokeEventArgs { + + /** returns the current action of PivotClient control. + */ + action?: string; + + /** returns the custom object bounds with PivotClient control. + */ + customObject?: any; + + /** returns the HTML element of PivotClient control. + */ + element?: any; +} + +export interface BeforeServiceInvokeEventArgs { + + /** returns the current action of PivotClient control. + */ + action?: string; + + /** returns the custom object bounds with PivotClient control. + */ + customObject?: any; + + /** returns the HTML element of PivotClient control. + */ + element?: any; +} + +export interface SaveReportEventArgs { + + /** returns the current instance of PivotClient control. + */ + targetControl?: any; + + /** returns the object which holds the necessary parameters required for saving the report collection. + */ + saveReportSetting?: any; +} + +export interface LoadReportEventArgs { + + /** returns the current instance of PivotClient control. + */ + targetControl?: any; + + /** returns the object which holds the necessary parameters required for loading a report collection from database. + */ + loadReportSetting?: any; +} + +export interface FetchReportEventArgs { + + /** returns the current instance of PivotClient control. + */ + targetControl?: any; + + /** returns the object which holds the necessary parameters required for fetching the report names stored in database. + */ + fetchReportSetting?: any; +} + +export interface BeforeExportEventArgs { + + /** holds the url of the service method responsible for exporting the PivotClient control. + */ + url?: string; + + /** holds the name of the file to be exported. + */ + fileName?: string; +} + +export interface ChartLoadEventArgs { + + /** returns the current action of PivotChart control. + */ + action?: string; + + /** returns the custom object bound with PivotChart control. + */ + customObject?: any; + + /** returns the HTML element of PivotChart control. + */ + element?: any; +} + +export interface TreeMapLoadEventArgs { + + /** returns the current action of PivotTreeMap control. + */ + action?: string; + + /** returns the custom object bound with PivotTreeMap control. + */ + customObject?: any; + + /** returns the HTML element of PivotTreeMap control. + */ + element?: any; +} + +export interface LoadEventArgs { + + /** returns the HTML element of PivotClient component. + */ + element?: any; + + /** returns the custom object bound with PivotTreeMap control. + */ + customObject?: any; +} + +export interface RenderCompleteEventArgs { + + /** returns the HTML element of PivotClient component. + */ + element?: any; + + /** returns the custom object bound with PivotTreeMap control. + */ + customObject?: any; +} + +export interface RenderFailureEventArgs { + + /** returns the custom object bound with the control. + */ + customObject?: any; + + /** returns the HTML element of PivotClient control. + */ + element?: any; + + /** returns the error message with error code. + */ + message?: string; +} + +export interface RenderSuccessEventArgs { + + /** returns the object of PivotClient control at that instant. + */ + args?: any; +} + +export interface DataSourceColumnsAdvancedFilter { + + /** Allows the user to provide level unique name to perform advanced filtering. + */ + name?: string; + + /** Allows the user to set the operator to perform Label Filtering. + * @Default {none} + */ + labelFilterOperator?: string; + + /** Allows the user to set the operator to perform Value Filtering. + * @Default {none} + */ + valueFilterOperator?: string; + + /** Allows the user to set the filtering type while performing advanced filtering. + */ + advancedFilterType?: string; + + /** In case of value filtering, this property contains the measure name to which the filter is applied. + */ + measure?: string; + + /** Allows the user to hold the filter operand values in advanced filtering. + */ + values?: Array; +} + +export interface DataSourceColumnsFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; +} + +export interface DataSourceColumn { + + /** Allows the user to bind the item by using its unique name as field name. + */ + fieldName?: string; + + /** Allows the user to set the display caption for an item. */ fieldCaption?: string; + + /** Allows the user to filter the report by default using advanced filtering (excel-like) option for OLAP data source in client-mode. + * @Default {[]} + */ + advancedFilter?: Array; + + /** Allows the user to indicate whether the added item is a named set or not. + * @Default {false} + */ + isNamedSets?: boolean; + + /** Shows/Hides the sub-total of the field in PivotGrid. + * @Default {true} + */ + showSubTotal?: boolean; + + /** Allows the user to set the sorting order of the members of the field. + * @Default {ej.PivotAnalysis.SortOrder.Ascending} + */ + sortOrder?: ej.PivotAnalysis.SortOrder|string; + + /** Contains the list of members need to be drilled down by default in the field. + * @Default {[]} + */ + drilledItems?: Array; + + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceColumnsFilterItems; +} + +export interface DataSourceRowsAdvancedFilter { + + /** Allows the user to provide level unique name to perform advanced filtering. + */ + name?: string; + + /** Allows the user to set the operator to perform Label Filtering. + * @Default {none} + */ + labelFilterOperator?: string; + + /** Allows the user to set the operator to perform Value Filtering. + * @Default {none} + */ + valueFilterOperator?: string; + + /** Allows the user to set the filtering type while performing advanced filtering. + */ + advancedFilterType?: string; + + /** In case of value filtering, this property contains the measure name to which the filter is applied. + */ + measure?: string; + + /** Allows the user to hold the filter operand values in advanced filtering. + */ + values?: Array; +} + +export interface DataSourceRowsFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; +} + +export interface DataSourceRow { + + /** Allows the user to bind the item by using its unique name as field name. + */ + fieldName?: string; + + /** Allows the user to set the display caption for an item. + */ + fieldCaption?: string; + + /** Allows the user to filter the report by default using advanced filtering (excel-like) option for OLAP data source in client-mode. + * @Default {[]} + */ + advancedFilter?: Array; + + /** Allows the user to indicate whether the added item is a named set or not. + * @Default {false} + */ + isNamedSets?: boolean; + + /** Shows/Hides the sub-total of the field. + * @Default {true} + */ + showSubTotal?: boolean; + + /** Allows the user to set the sorting order of the members of the field. + * @Default {ej.PivotAnalysis.SortOrder.Ascending} + */ + sortOrder?: ej.PivotAnalysis.SortOrder|string; + + /** Contains the list of members need to be drilled down by default in the field. + * @Default {[]} + */ + drilledItems?: Array; + + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceRowsFilterItems; +} + +export interface DataSourceValuesMeasure { + + /** Allows the user to bind the measure from OLAP datasource by using its unique name as field name. + */ + fieldName?: string; +} + +export interface DataSourceValue { + + /** Allows the user to bind the item by using its unique name as field name for Relational datasource. + */ + fieldName?: string; + + /** Allows the user to set the display caption for an item for Relational datasource. + */ + fieldCaption?: string; + + /** This holds the list of unique names of measures to bind them from the OLAP cube. + * @Default {[]} + */ + measures?: Array; + + /** Allows to set the axis name to place the measures items. + * @Default {rows} + */ + axis?: string; + + /** Indicates whether the field is a calculated field or not with Relational datasource. + * @Default {false} + */ + isCalculatedField?: boolean; + + /** Allows to set the type of PivotGrid summary calculation for the value field with Relational datasource. + * @Default {ej.PivotAnalysis.SummaryType.Sum} + */ + summaryType?: ej.PivotAnalysis.SummaryType|string; + + /** Allows to set the format of the values. + */ + format?: string; + + /** This property sets type of display of date. + */ + formatString?: string; + + /** Allows to set the formula for calculation of values for calculated members in Relational datasource. + */ + formula?: string; +} + +export interface DataSourceFiltersFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; } export interface DataSourceFilter { @@ -25109,368 +26348,105 @@ export interface DataSourceFilter { */ fieldCaption?: string; - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. - * @Default {false} + /** Applies filter to the field members. + * @Default {null} */ - isNamedSets?: boolean; + filterItems?: DataSourceFiltersFilterItems; +} + +export interface DataSourcePagerOptions { + + /** Allows to set the number of categorical columns to be displayed in each page on applying paging. + * @Default {0} + */ + categoricalPageSize?: number; + + /** Allows to set the number of series rows to be displayed in each page on applying paging. + * @Default {0} + */ + seriesPageSize?: number; + + /** Allows to set the page number in categorical axis to be loaded by default. + * @Default {1} + */ + categoricalCurrentPage?: number; + + /** Allows to set the page number in series axis to be loaded by default. + * @Default {1} + */ + seriesCurrentPage?: number; } export interface DataSource { - /** Contains the database name as string type to fetch the data from the given connection string. - * @Default {“”} - */ - catalog?: string; - - /** Lists out the items to be arranged in column section of PivotChart. + /** Lists out the items to be arranged in columns section of PivotClient. * @Default {[]} */ columns?: Array; - /** Contains the respective Cube name from database as string type. - * @Default {“”} - */ - cube?: string; - - /** Provides the raw data source for the PivotChart. - * @Default {null} - */ - data?: any; - - /** Lists out the items to be arranged in row section of PivotChart. + /** Lists out the items to be arranged in rows section of PivotClient. * @Default {[]} */ rows?: Array; - /** Lists out the items which supports calculation in PivotChart. + /** Lists out the items which supports calculation in PivotClient. * @Default {[]} */ values?: Array; - /** Lists out the items which supports filtering of values in PivotChart. + /** Lists out the items which supports filtering of values without displaying the members in UI in PivotClient. * @Default {[]} */ filters?: Array; -} -export interface ServiceMethodSettings { - - /** Allows the user to set the custom name for the service method that’s responsible for drilling up/down operation in PivotChart. - * @Default {DrillChart} - */ - drillDown?: string; - - /** Allows the user to set the custom name for the service method that’s responsible for exporting. - * @Default {Export} - */ - exportPivotChart?: string; - - /** Allows the user to set the custom name for the service method that’s responsible for initializing PivotChart. - * @Default {InitializeChart} - */ - initialize?: string; -} -} - -class PivotClient extends ej.Widget { - static fn: PivotClient; - constructor(element: JQuery, options?: PivotClient.Model); - constructor(element: Element, options?: PivotClient.Model); - model:PivotClient.Model; - defaults:PivotClient.Model; - - /** Perform an asynchronous HTTP (AJAX) request. - * @returns {void} - */ - doAjaxPost(): void; - - /** Perform an asynchronous HTTP (FullPost) submit. - * @returns {void} - */ - doPostBack(): void; -} -export module PivotClient{ - -export interface Model { - - /** Allows the user to set the specific chart type for PivotChart. - * @Default {ej.PivotChart.ChartTypes.Column} - */ - chartType?: ej.PivotChart.ChartTypes|string; - - /** Sets the mode to export the OLAP visualization components such as PivotChart and PivotGrid in PivotClient. Based on the option, either Chart or Grid or both gets exported. - * @Default {ej.PivotClient.ClientExportMode.ChartAndGrid} - */ - clientExportMode?: string; - - /** Specifies the CSS class to PivotClient to achieve custom theme. + /** Contains the respective cube name from OLAP database as string type. * @Default {“”} */ - cssClass?: string; + cube?: string; - /** Object utilized to pass additional information between client-end and service-end. - * @Default {{}} - */ - customObject?: any; - - /** Allows the user to customize the widgets layout and appearance. - * @Default {{}} - */ - displaySettings?: DisplaySettings; - - /** Allows the user to refresh the control on-demand and not during every UI operation. - * @Default {false} - */ - enableDeferUpdate?: boolean; - - /** Allows the user to view the layout of PivotClient from right to left. - * @Default {false} - */ - enableRTL?: boolean; - - /** Enables/disables the visibility of measure group selector drop-down in Cube Browser. - * @Default {false} - */ - enableMeasureGroups?: boolean; - - /** Sets the summary layout for PivotGrid. Following are the ways in which summary can be positioned: normal summary (bottom), top summary, no summary and excel-like summary. - * @Default {ej.PivotGrid.Layout.Normal} - */ - gridLayout?: ej.PivotGrid.Layout|string; - - /** Allows the user to set the localized language for the widget. - * @Default {en-US} - */ - locale?: string; - - /** Allows the user to set custom name for the methods at service-end, communicated during AJAX post. - * @Default {{}} - */ - serviceMethodSettings?: ServiceMethodSettings; - - /** Sets the title for PivotClient widget. + /** Provides the raw data source for the PivotClient. * @Default {null} */ - title?: string; + data?: any; - /** Connects the service using the specified URL for any server updates. - * @Default {null} + /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. + * @Default {“”} */ - url?: string; + catalog?: string; - /** Triggers when it reaches client-side after any AJAX request. */ - afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; - - /** Triggers before any AJAX request is passed from PivotClient to service methods. */ - beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; - - /** Triggers before rendering the PivotChart. */ - chartLoad? (e: ChartLoadEventArgs): void; - - /** Triggers while we initiate loading of the widget. */ - load? (e: LoadEventArgs): void; - - /** Triggers when PivotClient widget completes all operations at client-end after any AJAX request. */ - renderComplete? (e: RenderCompleteEventArgs): void; - - /** Triggers when any error occurred during AJAX request. */ - renderFailure? (e: RenderFailureEventArgs): void; - - /** Triggers when PivotClient successfully reaches client-side after any AJAX request. */ - renderSuccess? (e: RenderSuccessEventArgs): void; -} - -export interface AfterServiceInvokeEventArgs { - - /** return the current action of PivotClient control. + /** Allows user to filter the members (by its name and values) through advanced filtering (excel-like) option for OLAP data source in client-mode. + * @Default {false} */ - action?: string; + enableAdvancedFilter?: boolean; - /** return the custom object bounds with PivotClient control. + /** Sets a name to the report bound to the control. */ - customObject?: any; + reportName?: string; - /** return the outer HTML of PivotClient control. + /** Allows to set the page size and current page number for each axis on applying paging. + * @Default {{}} */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotClient model. - */ - model?: ej.PivotClient.Model; - - /** returns the name of the event. - */ - type?: string; -} - -export interface BeforeServiceInvokeEventArgs { - - /** return the current action of PivotClient control. - */ - action?: string; - - /** return the custom object bounds with PivotClient control. - */ - customObject?: any; - - /** return the outer HTML of PivotClient control. - */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotClient model. - */ - model?: ej.PivotClient.Model; - - /** returns the name of the event. - */ - type?: string; -} - -export interface ChartLoadEventArgs { - - /** return the current action of PivotChart control. - */ - action?: string; - - /** return the custom object bounds with PivotChart control. - */ - customObject?: any; - - /** return the outer HTML of PivotChart control. - */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotChart model. - */ - model?: ej.PivotClient.Model; - - /** returns the name of the event. - */ - type?: string; -} - -export interface LoadEventArgs { - - /** returns the outer HTML of PivotClient component. - */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotClient model. - */ - model?: ej.PivotClient.Model; - - /** returns the name of the event. - */ - type?: string; -} - -export interface RenderCompleteEventArgs { - - /** returns the custom object bounded with the control. - */ - customObject?: any; - - /** returns the outer HTML of PivotClient control. - */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotClient model. - */ - model?: ej.PivotClient.Model; - - /** returns the name of the event. - */ - type?: string; -} - -export interface RenderFailureEventArgs { - - /** returns the custom object bounded with the control. - */ - customObject?: any; - - /** returns the outer HTML of PivotClient control. - */ - element?: string; - - /** returns the error message with error code. - */ - message?: any; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotClient model. - */ - model?: ej.PivotClient.Model; - - /** returns the name of the event. - */ - type?: string; -} - -export interface RenderSuccessEventArgs { - - /** returns the custom object bounded with the control. - */ - customObject?: any; - - /** returns the outer HTML of PivotClient control. - */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotClient model. - */ - model?: ej.PivotClient.Model; - - /** returns the name of the event. - */ - type?: string; + pagerOptions?: DataSourcePagerOptions; } export interface DisplaySettings { - /** Let’s the user to customize the display of PivotChart and PivotGrid widgets, either in tab view or in tile view. + /** Lets the user to customize the display of PivotChart and PivotGrid widgets, either in tabs or tiles. * @Default {ej.PivotClient.ControlPlacement.Tab} */ controlPlacement?: ej.PivotClient.ControlPlacement|string; - /** Let’s the user to set either Chart or Grid as the start-up widget. + /** Lets the user to set either Chart or Grid as the start-up widget. * @Default {ej.PivotClient.DefaultView.Grid} */ defaultView?: ej.PivotClient.DefaultView|string; - /** Enables/disables the full screen view of PivotChart and PivotGrid in PivotClient. + /** Lets the user to have an option for switching to full screen view of PivotChart and PivotGrid from default view in PivotClient. * @Default {false} */ enableFullScreen?: boolean; - /** Enhances the space for PivotGrid and PivotChart, by hiding Cube Browser and Axis Element Builder. + /** Enables an option to enhance the space for PivotGrid and PivotChart by hiding Cube Browser and Axis Element Builder. * @Default {false} */ enableTogglePanel?: boolean; @@ -25488,103 +26464,121 @@ export interface DisplaySettings { export interface ServiceMethodSettings { - /** Allows the user to set the custom name for the service method that’s responsible for updating the entire report and widget, while changing the Cube. + /** Allows the user to set the custom name for the service method responsible for updating the entire report and widget, while changing the Cube. * @Default {CubeChanged} */ cubeChanged?: string; - /** Allows the user to set the custom name for the service method that’s responsible for exporting. + /** Allows the user to set the custom name for the service method responsible for exporting. * @Default {Export} */ exportPivotClient?: string; - /** Allows the user to set the custom name for the service method that’s responsible to get the members, for the tree-view inside member-editor dialog. + /** Allows the user to set the custom name for the service method responsible to get the members for the tree-view, inside member-editor dialog. * @Default {FetchMemberTreeNodes} */ fetchMemberTreeNodes?: string; - /** Allows the user to set the custom name for the service method that’s responsible for fetching the report names from the database. + /** Allows the user to set the custom name for the service method responsible for fetching the report names from the database. * @Default {FetchReportListFromDB} */ fetchReportList?: string; - /** Allows the user to set the custom name for the service method that’s responsible for updating report while filtering members. + /** Allows the user to set the custom name for the service method responsible for updating report while filtering members. * @Default {FilterElement} */ filterElement?: string; - /** Allows the user to set the custom name for the service method that’s responsible for initializing PivotClient. + /** Allows the user to set the custom name for the service method responsible for initializing PivotClient. * @Default {InitializeClient} */ initialize?: string; - /** Allows the user to set the custom name for the service method that’s responsible for loading the report collection from the database. + /** Allows the user to set the custom name for the service method responsible for loading a report collection from the database. * @Default {LoadReportFromDB} */ loadReport?: string; - /** Allows the user to set the custom name for the service method that’s responsible for retrieving the MDX query for the current report. + /** Allows the user to set the custom name for the service method responsible for retrieving the MDX query for the current report. * @Default {GetMDXQuery} */ mdxQuery?: string; - /** Allows the user to set the custom name for the service method that’s responsible for updating the tree-view inside Cube Browser, while changing the measure group. + /** Allows the user to set the custom name for the service method responsible for updating the tree-view inside Cube Browser, while changing the measure group. * @Default {MeasureGroupChanged} */ measureGroupChanged?: string; - /** Allows the user to set the custom name for the service method that’s responsible to get the child members, on tree-view node expansion. + /** Allows the user to set the custom name for the service method responsible to get the child members, on tree-view node expansion. * @Default {MemberExpanded} */ memberExpand?: string; - /** Allows the user to set the custom name for the service method that’s responsible for updating report while dropping a node/SplitButton inside Axis Element Builder. + /** Allows the user to set the custom name for the service method responsible for updating report while dropping a node/SplitButton inside Axis Element Builder. * @Default {NodeDropped} */ nodeDropped?: string; - /** Allows the user to set the custom name for the service method that’s responsible for updating report while removing SplitButton from Axis Element Builder. + /** Allows the user to set the custom name for the service method responsible for updating report while removing SplitButton from Axis Element Builder. * @Default {RemoveSplitButton} */ removeSplitButton?: string; - /** Allows the user to set the custom name for the service method that’s responsible for saving the report collection to database. + /** Allows the user to set the custom name for the service method responsible for saving the report collection to database. * @Default {SaveReportToDB} */ saveReport?: string; - /** Allows the user to set the custom name for the service method that’s responsible for toggling the elements in row and column axes. + /** Allows the user to set the custom name for the service method responsible for toggling the elements in row and column axes. * @Default {ToggleAxis} */ toggleAxis?: string; - /** Allows the user to set the custom name for the service method that’s responsible for any toolbar operation. + /** Allows the user to set the custom name for the service method responsible for all the toolbar operations. * @Default {ToolbarOperations} */ toolbarServices?: string; - /** Allows the user to set the custom name for the service method that’s responsible for updating report collection. + /** Allows the user to set the custom name for the service method responsible for updating report collection. * @Default {UpdateReport} */ updateReport?: string; + + /** Allows the user to set the custom name for the service method responsible on navigating between pages in paged PivotClient. + * @Default {Paging} + */ + paging?: string; } +enum ClientExportMode{ + + ///Exports both the PivotChart and PivotGrid on exporting. + ChartAndGrid, + + ///Exports the PivotChart control alone on exporting. + ChartOnly, + + ///Exports the PivotGrid control alone on exporting. + GridOnly +} + + enum ControlPlacement{ - ///To display PivotChart and PivotGrid widgets in tab view. + ///Displays PivotChart and PivotGrid widgets in separate tabs. Tab, - ///To display PivotChart and PivotGrid widgets within the same view, one below the other. + ///Displays PivotChart and PivotGrid widgets one above the other. Tile } enum DefaultView{ - ///To set PivotChart as a default control in view when the PivotClient widget is loaded for the first time. + ///To set PivotChart as a default control in view. Chart, - ///To set PivotGrid as a default control in view when the PivotClient widget is loaded for the first time. + ///To set PivotGrid as a default control in view. Grid } @@ -25601,56 +26595,17 @@ enum DisplayMode{ ChartAndGrid } -} -module PivotChart -{ -enum ChartTypes -{ -//To render a Line type for PivotChart. -Line, -//To render a Spline type for PivotChart. -Spline, -//To render a Column type for PivotChart. -Column, -//To render a Area type for PivotChart. -Area, -//To render a SplineArea type for PivotChart. -SplineArea, -//To render a StepLine type for PivotChart. -StepLine, -//To render a StepArea type for PivotChart. -StepArea, -//To render a Pie type for PivotChart. -Pie, -//To render a Bar type for PivotChart. -Bar, -//To render a StackingArea type for PivotChart. -StackingArea, -//To render a StackingColumn type for PivotChart. -StackingColumn, -//To render a StackingBar type for PivotChart. -StackingBar, -//To render a Pyramid type for PivotChart. -Pyramid, -//To render a Funnel type for PivotChart. -Funnel, -//To render a Doughnut type for PivotChart. -Doughnut, -//To render a Scatter type for PivotChart. -Scatter, -//To render a Bubble type for PivotChart. -Bubble, -} } class PivotGauge extends ej.Widget { static fn: PivotGauge; constructor(element: JQuery, options?: PivotGauge.Model); constructor(element: Element, options?: PivotGauge.Model); + static Locale: any; model:PivotGauge.Model; defaults:PivotGauge.Model; - /** Perform an asynchronous HTTP (AJAX) request. + /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} */ doAjaxPost(): void; @@ -25660,36 +26615,56 @@ class PivotGauge extends ej.Widget { */ refresh(): void; - /** This function removes the KPI related images from PivotGauge. + /** This function removes the KPI related images from PivotGauge on binding OLAP datasource. * @returns {void} */ removeImg(): void; - /** This function receives the JSON formatted datasource to render the PivotGauge control. + /** This function receives the JSON formatted datasource and renders the PivotGauge control. * @returns {void} */ renderControlFromJSON(): void; + + /** Returns the OlapReport string maintained along with the axis elements information. + * @returns {void} + */ + getOlapReport(): void; + + /** Sets the OlapReport string along with the axis information and maintains it in a property. + * @returns {void} + */ + setOlapReport(): void; + + /** Returns the JSON records formed to render the control. + * @returns {void} + */ + getJSONRecords(): void; + + /** Sets the JSON records to render the control. + * @returns {void} + */ + setJSONRecords(): void; + + /** Returns the JSON records required to render the PivotGauge on performing any action with OLAP data source. + * @returns {void} + */ + getJSONData(): void; } export module PivotGauge{ export interface Model { - /** Specifies the background color of pivot gauge. - * @Default {null} - */ - backgroundColor?: string; - - /** Sets the number of column count to arrange the PivotGauge's. + /** Sets the number of columns to arrange the Pivot Gauges. * @Default {0} */ columnsCount?: number; - /** Specify the CSS class to PivotGauge to achieve custom theme. + /** Specifies the CSS class to PivotGauge to achieve custom theme. * @Default {“”} */ cssClass?: string; - /** Object utilized to pass additional information between client-end and service-end. + /** Object utilized to pass additional information between client-end and service-end on operating in server mode. * @Default {{}} */ customObject?: any; @@ -25699,6 +26674,11 @@ export interface Model { */ dataSource?: DataSource; + /** Enables/disables the animation of pointer in PivotGauge. + * @Default {false} + */ + enableAnimation?: boolean; + /** Enables/disables tooltip visibility in PivotGauge. * @Default {false} */ @@ -25724,7 +26704,7 @@ export interface Model { */ locale?: string; - /** Sets the number of row count to arrange the PivotGauge's. + /** Sets the number of rows to arrange the Pivot Gauges. * @Default {0} */ rowsCount?: number; @@ -25744,17 +26724,30 @@ export interface Model { */ showHeaderLabel?: boolean; - /** Connects the service using the specified URL for any server updates. + /** Connects the service using the specified URL for any server updates on server mode operation. * @Default {“”} */ url?: string; + /** Sets the mode for the PivotGauge widget for binding either OLAP or Relational data source. + * @Default {ej.Pivot.AnalysisMode.Pivot} + */ + analysisMode?: ej.Pivot.AnalysisMode|string; + + /** Sets the mode for the PivotGauge widget for binding data source either in server-side or client-side. + * @Default {ej.Pivot.OperationalMode.ClientMode} + */ + operationalMode?: ej.Pivot.OperationalMode|string; + /** Triggers when it reaches client-side after any AJAX request. */ afterServiceInvoke? (e: AfterServiceInvokeEventArgs): void; /** Triggers before any AJAX request is passed from PivotGauge to service methods. */ beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + /** Triggers before populating the pivot engine on operating in client mode. */ + beforePivotEnginePopulate? (e: BeforePivotEnginePopulateEventArgs): void; + /** Triggers when PivotGauge started loading at client-side. */ load? (e: LoadEventArgs): void; @@ -25770,148 +26763,100 @@ export interface Model { export interface AfterServiceInvokeEventArgs { - /** return the current action of PivotGauge control. - */ - action?: string; - - /** return the custom object bounds with PivotGauge control. + /** returns the custom object bound with PivotGauge control. */ customObject?: any; - /** return the outer HTML of PivotGauge control. + /** returns the HTML element of PivotGauge control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGauge model. - */ - model?: ej.PivotGauge.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface BeforeServiceInvokeEventArgs { - /** return the current action of PivotGauge control. - */ - action?: string; - - /** return the custom object bounds with PivotGauge control. + /** returns the custom object bound with PivotGauge control. */ customObject?: any; - /** return the outer HTML of PivotGauge control. + /** returns the HTML element of PivotGauge control. */ - element?: string; + element?: any; +} - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; +export interface BeforePivotEnginePopulateEventArgs { - /** returns the PivotGauge model. + /** returns the current instance of PivotGauge control. */ - model?: ej.PivotGauge.Model; - - /** returns the name of the event. - */ - type?: string; + gaugeObject?: any; } export interface LoadEventArgs { - /** if the event should be canceled; otherwise, false. + /** returns the current action of PivotGauge control. */ - cancel?: boolean; + action?: string; - /** returns the PivotGauge model. + /** returns the model of PivotGauge control. */ - model?: ej.PivotGauge.Model; + model?: any; - /** returns the name of the event. + /** returns the HTML element of the widget. */ - type?: string; + element?: any; + + /** returns the custom object bound to the control. + */ + customObject?: any; } export interface RenderCompleteEventArgs { - /** returns the outer HTML of PivotGauge control. - */ - element?: string; - - /** returns the custom object bounded with the control. + /** returns the custom object bound with PivotGauge control. */ customObject?: any; - /** if the event should be canceled; otherwise, false. + /** returns the HTML element of PivotGauge control. */ - cancel?: boolean; - - /** returns the PivotGauge model. - */ - model?: ej.PivotGauge.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface RenderFailureEventArgs { - /** returns the outer HTML of PivotGauge control. + /** returns the HTML element of PivotGauge control. */ - element?: string; + element?: any; - /** returns the custom object bounded with the control. + /** returns the custom object bound with the control. */ customObject?: any; /** returns the error message with error code. */ - message?: any; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotGauge model. - */ - model?: ej.PivotGauge.Model; - - /** returns the name of the event. - */ - type?: string; - - /** returns the JSON formatted response while error occurs. - */ - responseJSON?: any; + message?: string; } export interface RenderSuccessEventArgs { - /** returns the outer HTML of PivotGauge control. + /** returns the HTML element of PivotGauge control. */ - element?: string; + element?: any; - /** returns the custom object bounded with the control. + /** returns the custom object bound with the control. */ customObject?: any; +} - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; +export interface DataSourceColumnsFilterItems { - /** returns the PivotGauge model. + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} */ - model?: ej.PivotGauge.Model; + filterType?: ej.PivotAnalysis.FilterType|string; - /** returns the name of the event. + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} */ - type?: string; + values?: Array; } export interface DataSourceColumn { @@ -25920,24 +26865,20 @@ export interface DataSourceColumn { */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Applies filter to the field members. + * @Default {null} */ - fieldCaption?: string; - - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. - * @Default {false} - */ - isNamedSets?: boolean; + filterItems?: DataSourceColumnsFilterItems; } export interface DataSourceRowsFilterItems { - /** Allows the user to set the type of filtering for an item. - * @Default {exclude} + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} */ - filterType?: string; + filterType?: ej.PivotAnalysis.FilterType|string; - /** Allows the user to set the values for filtering an item. + /** Contains the collection of items to be included/excluded among the field members. * @Default {[]} */ values?: Array; @@ -25949,40 +26890,60 @@ export interface DataSourceRow { */ fieldName?: string; - /** Allows the user to set the display name for an item. - */ - fieldCaption?: string; - - /** Allows the user to set the filtering values name for an item. + /** Applies filter to the field members. * @Default {null} */ filterItems?: DataSourceRowsFilterItems; +} - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. - * @Default {false} +export interface DataSourceValuesMeasure { + + /** Allows the user to bind the measure from OLAP datasource by using its unique name as field name. */ - isNamedSets?: boolean; + fieldName?: string; } export interface DataSourceValue { - /** This holds the measures unique name to bind them from the Cube. - * @Default {[]} - */ - measures?: Array; - - /** Allows to set the axis name to place the measures items. - * @Default {“”} - */ - axis?: string; - - /** Allows the user to bind the item by using its unique name as field name. + /** Allows the user to bind the item by using its unique name as field name for Relational datasource. */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Allows the user to set the display caption for an item for Relational datasource. */ fieldCaption?: string; + + /** This holds the list of unique names of measures to bind them from the OLAP cube. + * @Default {[]} + */ + measures?: Array; + + /** Allows to set the axis name to place the measures items. + * @Default {rows} + */ + axis?: string; + + /** Indicates whether the field is a calculated field or not with Relational datasource. + * @Default {false} + */ + isCalculatedField?: boolean; + + /** Allows to set the formula for calculation of values for calculated members in Relational datasource. + */ + formula?: string; +} + +export interface DataSourceFiltersFilterItems { + + /** Sets the type of filter whether to include/exclude the mentioned values. + * @Default {ej.PivotAnalysis.FilterType.Exclude} + */ + filterType?: ej.PivotAnalysis.FilterType|string; + + /** Contains the collection of items to be included/excluded among the field members. + * @Default {[]} + */ + values?: Array; } export interface DataSourceFilter { @@ -25991,29 +26952,15 @@ export interface DataSourceFilter { */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Applies filter to the field members. + * @Default {null} */ - fieldCaption?: string; - - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. - * @Default {false} - */ - isNamedSets?: boolean; + filterItems?: DataSourceFiltersFilterItems; } export interface DataSource { - /** Contains the database name as string type to fetch the data from the given connection string. - * @Default {“”} - */ - catalog?: string; - - /** Lists out the items to be arranged in column section of PivotGauge. - * @Default {[]} - */ - columns?: Array; - - /** Contains the respective Cube name from database as string type. + /** Contains the respective cube name from OLAP database as string type. * @Default {“”} */ cube?: string; @@ -26023,17 +26970,27 @@ export interface DataSource { */ data?: any; - /** Lists out the items to be arranged in row section of PivotGauge. + /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. + * @Default {“”} + */ + catalog?: string; + + /** Lists out the items to bind in columns section. + * @Default {[]} + */ + columns?: Array; + + /** Lists out the items to bind in rows section. * @Default {[]} */ rows?: Array; - /** Lists out the items which supports calculation in PivotGauge. + /** Lists out the items supports calculation in PivotGauge. * @Default {[]} */ values?: Array; - /** Lists out the items which supports filtering of values in PivotGauge. + /** Lists out the items which supports filtering of values without displaying the members in UI in PivotGauge. * @Default {[]} */ filters?: Array; @@ -26046,7 +27003,7 @@ export interface LabelFormatSettings { */ numberFormat?: ej.PivotGauge.NumberFormat|string; - /** Allows you to change the position of a digit on the right-hand side of the decimal point for label value. + /** Allows you to set the number of digits displayed after decimal point. * @Default {5} */ decimalPlaces?: number; @@ -26062,7 +27019,7 @@ export interface LabelFormatSettings { export interface ServiceMethodSettings { - /** Allows the user to set the custom name for the service method that’s responsible for initializing PivotGauge. + /** Allows the user to set the custom name for the service method responsible for initializing PivotGauge. * @Default {InitializeGauge} */ initialize?: string; @@ -26098,18 +27055,39 @@ class PivotTreeMap extends ej.Widget { static fn: PivotTreeMap; constructor(element: JQuery, options?: PivotTreeMap.Model); constructor(element: Element, options?: PivotTreeMap.Model); + static Locale: any; model:PivotTreeMap.Model; defaults:PivotTreeMap.Model; - /** Perform an asynchronous HTTP (AJAX) request. + /** Performs an asynchronous HTTP (AJAX) request. * @returns {void} */ doAjaxPost(): void; - /** Perform an asynchronous HTTP (FullPost) submit. + /** Returns the OlapReport string maintained along with the axis elements information. * @returns {void} */ - doPostBack(): void; + getOlapReport(): void; + + /** Sets the OlapReport string along with the axis information and maintains it in a property. + * @returns {void} + */ + setOlapReport(): void; + + /** Returns the JSON records formed to render the control. + * @returns {void} + */ + getJSONRecords(): void; + + /** Sets the JSON records to render the control. + * @returns {void} + */ + setJSONRecords(): void; + + /** Renders the control with the pivot engine obtained from OLAP cube. + * @returns {void} + */ + generateJSON(): void; /** This function receives the JSON formatted datasource to render the PivotTreeMap control. * @returns {void} @@ -26130,11 +27108,6 @@ export interface Model { */ cssClass?: string; - /** Contains the serialized Report at that instant, that is, current Report. - * @Default {“”} - */ - currentReport?: string; - /** Initializes the data source for the PivotTreeMap widget, when it functions completely on client-side. * @Default {{}} */ @@ -26145,11 +27118,6 @@ export interface Model { */ customObject?: any; - /** Allows the user to view the layout of PivotTreeMap from right to left. - * @Default {false} - */ - enableRTL?: boolean; - /** Allows the user to enable PivotTreeMap’s responsiveness in the browser layout. * @Default {false} */ @@ -26161,9 +27129,9 @@ export interface Model { locale?: string; /** Sets the mode for the PivotTreeMap widget for binding data source either in server-side or client-side. - * @Default {ej.PivotTreeMap.OperationalMode.ClientMode} + * @Default {ej.Pivot.OperationalMode.ClientMode} */ - operationalMode?: any; + operationalMode?: ej.Pivot.OperationalMode|string; /** Allows the user to set custom name for the methods at service-end, communicated on AJAX post. * @Default {{}} @@ -26181,6 +27149,12 @@ export interface Model { /** Triggers before any AJAX request is passed from PivotTreeMap to service methods. */ beforeServiceInvoke? (e: BeforeServiceInvokeEventArgs): void; + /** Triggers when PivotTreeMap starts to render. */ + load? (e: LoadEventArgs): void; + + /** Triggers before populating the pivot engine from datasource. */ + beforePivotEnginePopulate? (e: BeforePivotEnginePopulateEventArgs): void; + /** Triggers when drill up/down happens in PivotTreeMap control. And it returns the outer HTML of PivotTreeMap control. */ drillSuccess? (e: DrillSuccessEventArgs): void; @@ -26196,144 +27170,118 @@ export interface Model { export interface AfterServiceInvokeEventArgs { - /** return the current action of PivotTreeMap control. + /** returns the current action of PivotTreeMap control. */ action?: string; - /** return the custom object bounds with PivotTreeMap control. + /** returns the custom object bound with PivotTreeMap control. */ customObject?: any; - /** return the outer HTML of PivotTreeMap control. + /** returns the HTML element of PivotTreeMap control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotTreeMap model. - */ - model?: ej.PivotTreeMap.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface BeforeServiceInvokeEventArgs { - /** return the current action of PivotTreeMap control. + /** returns the current action of PivotTreeMap control. */ action?: string; - /** return the custom object bounds with PivotTreeMap control. + /** returns the custom object bound with PivotTreeMap control. */ customObject?: any; - /** return the outer HTML of PivotTreeMap control. + /** returns the HTML element of PivotTreeMap control. */ - element?: string; + element?: any; +} - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; +export interface LoadEventArgs { - /** returns the PivotTreeMap model. + /** returns the current action of PivotTreeMap control. */ - model?: ej.PivotTreeMap.Model; + action?: string; - /** returns the name of the event. + /** returns the custom object bound with PivotTreeMap control. */ - type?: string; + customObject?: any; + + /** returns the HTML element of PivotTreeMap control. + */ + element?: any; +} + +export interface BeforePivotEnginePopulateEventArgs { + + /** returns the current instance of PivotTreeMap control. + */ + treeMapObject?: any; } export interface DrillSuccessEventArgs { + + /** return the HTML element of PivotTreeMap control. + */ + element?: any; } export interface RenderCompleteEventArgs { - /** return the current action of PivotTreeMap control. + /** returns the current action of PivotTreeMap control. */ action?: string; - /** return the custom object bounds with PivotTreeMap control. + /** returns the custom object bound with PivotTreeMap control. */ customObject?: any; - /** return the outer HTML of PivotTreeMap control. + /** returns the HTML element of PivotTreeMap control. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotTreeMap model. - */ - model?: ej.PivotTreeMap.Model; - - /** returns the name of the event. - */ - type?: string; + element?: any; } export interface RenderFailureEventArgs { - /** return the current action of PivotTreeMap control. + /** returns the current action of PivotTreeMap control. */ action?: string; - /** return the custom object bounds with PivotTreeMap control. + /** returns the custom object bound with PivotTreeMap control. */ customObject?: any; - /** return the error stack trace of the original exception. + /** returns the HTML element of PivotTreeMap control. */ - message?: any; + element?: any; - /** return the outer HTML of PivotTreeMap control. + /** returns the error stack trace of the original exception. */ - element?: string; - - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; - - /** returns the PivotTreeMap model. - */ - model?: ej.PivotTreeMap.Model; - - /** returns the name of the event. - */ - type?: string; + message?: string; } export interface RenderSuccessEventArgs { - /** return the current action of PivotTreeMap control. + /** returns the current action of PivotTreeMap control. */ action?: string; - /** return the custom object bounds with PivotTreeMap control. + /** returns the custom object bound with PivotTreeMap control. */ customObject?: any; - /** return the outer HTML of PivotTreeMap control. + /** returns the HTML element of PivotTreeMap control. */ - element?: string; + element?: any; +} - /** if the event should be canceled; otherwise, false. - */ - cancel?: boolean; +export interface DataSourceColumnsFilterItems { - /** returns the PivotTreeMap model. + /** Contains the collection of items to be excluded among the field members. + * @Default {[]} */ - model?: ej.PivotTreeMap.Model; - - /** returns the name of the event. - */ - type?: string; + values?: Array; } export interface DataSourceColumn { @@ -26342,14 +27290,23 @@ export interface DataSourceColumn { */ fieldName?: string; - /** Allows the user to set the display name for an item. - */ - fieldCaption?: string; - - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. + /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} */ isNamedSets?: boolean; + + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceColumnsFilterItems; +} + +export interface DataSourceRowsFilterItems { + + /** Contains the collection of items to be excluded among the field members. + * @Default {[]} + */ + values?: Array; } export interface DataSourceRow { @@ -26358,35 +27315,43 @@ export interface DataSourceRow { */ fieldName?: string; - /** Allows the user to set the display name for an item. - */ - fieldCaption?: string; - - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. + /** Allows the user to indicate whether the added item is a named set or not. * @Default {false} */ isNamedSets?: boolean; + + /** Applies filter to the field members. + * @Default {null} + */ + filterItems?: DataSourceRowsFilterItems; +} + +export interface DataSourceValuesMeasure { + + /** Allows the user to bind the measure from OLAP datasource by using its unique name as field name. + */ + fieldName?: string; } export interface DataSourceValue { - /** This holds the measures unique name to bind them from the Cube. + /** This holds the list of unique names of measures to bind them from the OLAP cube. * @Default {[]} */ - measures?: Array; + measures?: Array; /** Allows to set the axis name to place the measures items. - * @Default {“”} + * @Default {rows} */ axis?: string; +} - /** Allows the user to bind the item by using its unique name as field name. - */ - fieldName?: string; +export interface DataSourceFiltersFilterItems { - /** Allows the user to set the display name for an item. + /** Contains the collection of items to be excluded among the field members. + * @Default {[]} */ - fieldCaption?: string; + values?: Array; } export interface DataSourceFilter { @@ -26395,49 +27360,45 @@ export interface DataSourceFilter { */ fieldName?: string; - /** Allows the user to set the display name for an item. + /** Applies filter to the field members. + * @Default {null} */ - fieldCaption?: string; - - /** Allows the user to enable the usage of named set items in respective axis. This is only applicable for OLAP datasource. - * @Default {false} - */ - isNamedSets?: boolean; + filterItems?: DataSourceFiltersFilterItems; } export interface DataSource { - /** Contains the database name as string type to fetch the data from the given connection string. - * @Default {“”} - */ - catalog?: string; - - /** Lists out the items to be arranged in column section of PivotTreeMap. - * @Default {[]} - */ - columns?: Array; - - /** Contains the respective Cube name from database as string type. - * @Default {“”} - */ - cube?: string; - /** Provides the raw data source for the PivotTreeMap. * @Default {null} */ data?: any; - /** Lists out the items to be arranged in row section of PivotTreeMap. + /** Contains the respective cube name from OLAP database as string type. + * @Default {“”} + */ + cube?: string; + + /** In connection with an OLAP database, this property contains the database name as string to fetch the data from the given connection string. + * @Default {“”} + */ + catalog?: string; + + /** Lists out the items to be displayed as series of PivotTreeMap. + * @Default {[]} + */ + columns?: Array; + + /** Lists out the items to be displayed as segments of PivotTreeMap. * @Default {[]} */ rows?: Array; - /** Lists out the items which supports calculation in PivotTreeMap. + /** Lists out the items supports calculation in PivotTreeMap. * @Default {[]} */ values?: Array; - /** Lists out the items which supports filtering of values in PivotTreeMap. + /** Lists out the items which supports filtering of values without displaying the members in UI in PivotTreeMap. * @Default {[]} */ filters?: Array; @@ -26445,12 +27406,12 @@ export interface DataSource { export interface ServiceMethodSettings { - /** Allows the user to set the custom name for the service method that’s responsible for initializing PivotTreeMap. + /** Allows the user to set the custom name for the service method responsible for initializing PivotTreeMap. * @Default {InitializeTreemap} */ initialize?: string; - /** Allows the user to set the custom name for the service method that’s responsible for drilling up/down operation in PivotTreeMap. + /** Allows the user to set the custom name for the service method responsible for drilling up/down operation in PivotTreeMap. * @Default {DrillTreeMap} */ drillDown?: string; @@ -26461,6 +27422,7 @@ class Schedule extends ej.Widget { static fn: Schedule; constructor(element: JQuery, options?: Schedule.Model); constructor(element: Element, options?: Schedule.Model); + static Locale: any; model:Schedule.Model; defaults:Schedule.Model; @@ -26540,6 +27502,11 @@ class Schedule extends ej.Widget { * @returns {void} */ refreshAppointments(): void; + + /** Passes the server-side action and data to the client-side for rendering the modified appointment list on the Schedule control. + * @returns {void} + */ + notifyChanges(): void; } export module Schedule{ @@ -28176,6 +29143,7 @@ class RecurrenceEditor extends ej.Widget { static fn: RecurrenceEditor; constructor(element: JQuery, options?: RecurrenceEditor.Model); constructor(element: Element, options?: RecurrenceEditor.Model); + static Locale: any; model:RecurrenceEditor.Model; defaults:RecurrenceEditor.Model; @@ -28283,6 +29251,7 @@ class Gantt extends ej.Widget { static fn: Gantt; constructor(element: JQuery, options?: Gantt.Model); constructor(element: Element, options?: Gantt.Model); + static Locale: any; model:Gantt.Model; defaults:Gantt.Model; @@ -28301,10 +29270,10 @@ class Gantt extends ej.Widget { selectCells(Indexes: Array, preservePreviousSelectedCell: boolean): void; /** Positions the splitter by the specified column index. - * @param {number} Set the splitter position based on column index. + * @param {Number} Set the splitter position based on column index. * @returns {void} */ - setSplitterIndex(index: number): void; + setSplitterIndex(index: Number): void; /** To cancel the edited state of an item in Gantt * @returns {void} @@ -28332,10 +29301,10 @@ class Gantt extends ej.Widget { expandAllItems(): void; /** To expand and collapse an item in Gantt using item's ID - * @param {number} Expand or Collapse a record based on task id. + * @param {Number} Expand or Collapse a record based on task id. * @returns {void} */ - expandCollapseRecord(taskId: number): void; + expandCollapseRecord(taskId: Number): void; /** To hide the column by using header text * @param {string} you can pass a header text of a column to hide @@ -28619,6 +29588,21 @@ export interface Model { */ parentTaskbarTemplate?: string; + /** Specifies the nature of a task for caluculating the work, and it can fixed duration, fixed work and fixed resource unit + * @Default {ej.Gantt.TaskType.FixedUnit} + */ + taskType?: ej.Gantt.TaskType|string; + + /** Specifies the unit for the work involved in a task and it can be day, hour or minute + * @Default {ej.Gantt.WorkUnit.Hour} + */ + workUnit?: ej.Gantt.WorkUnit|string; + + /** Specifies the task scheduling mode for a project and this will be set to all the tasks available in the project + * @Default {ej.Gantt.TaskSchedulingMode.Auto} + */ + taskSchedulingMode?: ej.Gantt.TaskSchedulingMode|string; + /** Specifies the row selection type. * @Default {ej.Gantt.SelectionType.Single} */ @@ -28628,6 +29612,23 @@ export interface Model { */ parentProgressbarBackground?: string; + /** Specifies the mapping property path for resource's percent effort involved in a task in datasource + */ + resourceUnitMapping?: string; + + /** Specifies the mapping property path for the task description in datasource + */ + notesMapping?: string; + + /** Specifies the mapping property path for the task scheuling mode for a task in datasource + * @Default {auto} + */ + taskSchedulingModeMapping?: string; + + /** Specifies the mapping property path for task duration unit in datasoruce + */ + durationUnitMapping?: string; + /** Specifies the background of parent taskbar in Gantt */ parentTaskbarBackground?: string; @@ -28673,6 +29674,11 @@ export interface Model { */ renderBaseline?: boolean; + /** Enables or disables the schedule date validation while connecting a manually scheduled task with predecessor + * @Default {false} + */ + validateManaulTasksOnLinking?: boolean; + /** Specifies the mapping property name for resource ID in resource Collection in Gantt */ resourceIdMapping?: string; @@ -29205,7 +30211,7 @@ export interface CollapsedEventArgs { /** Returns the row index of collapsed record. */ - recordIndex?: number; + recordIndex?: Number; /** Returns the data of collapsed record. */ @@ -29228,7 +30234,7 @@ export interface CollapsingEventArgs { /** Returns the row index of collapsing record. */ - recordIndex?: number; + recordIndex?: Number; /** Returns the data of edited cell record.. */ @@ -29753,6 +30759,45 @@ enum BeginEditAction{ } +enum TaskType{ + + ///Resource unit reamins constant while editing the work and duration values. + FixedUnit, + + ///Work value of a task remains constant while editing duration and resoruce unit values. + FixedWork, + + ///Duration value remains constant while editing work and resoruce unit values. + FixedDuration +} + + +enum WorkUnit{ + + ///Dislays the work involved in a task in days. + Day, + + ///Dislays the work involved in a task in hours. + Hour, + + ///Dislays the work involved in a task in minutes + Minute +} + + +enum TaskSchedulingMode{ + + ///All the tasks in the project will be displayed in auto scheduled mode, where the tasks are scheduled automatically over non-working days and holidays. + Auto, + + ///All the tasks in the project will be displayed in manually scheduled mode. + Manual, + + ///Project consists of tasks with both auto and manually scheduled modes, based on the datasource values + Custom +} + + enum SelectionType{ ///you can select a single row. @@ -29842,6 +30887,7 @@ class ReportViewer extends ej.Widget { static fn: ReportViewer; constructor(element: JQuery, options?: ReportViewer.Model); constructor(element: Element, options?: ReportViewer.Model); + static Locale: any; model:ReportViewer.Model; defaults:ReportViewer.Model; @@ -29927,7 +30973,7 @@ export interface Model { /** Enables or disables the page cache of report. * @Default {false} */ - enablePageCache?: boolean; + enablePageCache?: Boolean; /** Specifies the export settings. */ @@ -29936,12 +30982,12 @@ export interface Model { /** When set to true, adapts the report layout to fit the screen size of devices on which it renders. * @Default {true} */ - isResponsive?: boolean; + isResponsive?: Boolean; /** Specifies the locale for report viewer. * @Default {en-US} */ - locale?: string; + locale?: String; /** Specifies the page settings. */ @@ -29955,7 +31001,7 @@ export interface Model { /** Enables and disables the print mode. * @Default {false} */ - printMode?: boolean; + printMode?: Boolean; /** Specifies the print option of the report. * @Default {ej.ReportViewer.PrintOptions.Default} @@ -29975,17 +31021,17 @@ export interface Model { /** Gets or sets the path of the report file. * @Default {empty} */ - reportPath?: string; + reportPath?: String; /** Gets or sets the reports server URL. * @Default {empty} */ - reportServerUrl?: string; + reportServerUrl?: String; /** Specifies the report Web API service URL. * @Default {empty} */ - reportServiceUrl?: string; + reportServiceUrl?: String; /** Specifies the toolbar settings. */ @@ -29994,7 +31040,7 @@ export interface Model { /** Gets or sets the zoom factor for report viewer. * @Default {1} */ - zoomFactor?: number; + zoomFactor?: Number; /** Fires when the report viewer is destroyed successfully.If you want to perform any operation after destroying the reportviewer control,you can make use of the destroy event. */ destroy? (e: DestroyEventArgs): void; @@ -30162,7 +31208,7 @@ export interface DataSource { /** Gets or sets the name of the data source. * @Default {empty} */ - name?: string; + name?: String; /** Gets or sets the values of data source. * @Default {[]} @@ -30211,17 +31257,17 @@ export interface Parameter { /** Gets or sets the name of the parameter. * @Default {empty} */ - name?: string; + name?: String; /** Gets or sets whether the parameter allows nullable value or not. * @Default {false} */ - nullable?: boolean; + nullable?: Boolean; /** Gets or sets the prompt message associated with the specified parameter. * @Default {empty} */ - prompt?: string; + prompt?: String; /** Gets or sets the parameter values. * @Default {[]} @@ -30234,7 +31280,7 @@ export interface ToolbarSettings { /** Fires when user click on toolbar item in the toolbar. * @Default {empty} */ - click?: string; + click?: String; /** Specifies the toolbar items. * @Default {ej.ReportViewer.ToolbarItems.All} @@ -30244,17 +31290,17 @@ export interface ToolbarSettings { /** Shows or hides the toolbar. * @Default {true} */ - showToolbar?: boolean; + showToolbar?: Boolean; /** Shows or hides the tooltip of toolbar items. * @Default {true} */ - showTooltip?: boolean; + showTooltip?: Boolean; /** Specifies the toolbar template ID. * @Default {empty} */ - templateId?: string; + templateId?: String; } enum ExportOptions{ @@ -30478,6 +31524,7 @@ class TreeGrid extends ej.Widget { static fn: TreeGrid; constructor(element: JQuery, options?: TreeGrid.Model); constructor(element: Element, options?: TreeGrid.Model); + static Locale: any; model:TreeGrid.Model; defaults:TreeGrid.Model; @@ -30706,7 +31753,7 @@ export interface Model { */ isResponsive?: boolean; - /** Specifies the name of the field in the dataSource, which contains the parent’s id. This is necessary to form a parent-child hierarchy, if the dataSource contains self-referential data. + /** Specifies the name of the field in the dataSource, which contains the parent's id. This is necessary to form a parent-child hierarchy, if the dataSource contains self-referential data. */ parentIdMapping?: string; @@ -30738,22 +31785,16 @@ export interface Model { */ selectedRowIndex?: number; - /** Specifies the type of selection whether to select row or cell. - * @Default {ej.TreeGrid.SelectionMode.Row} + /** Specifies the settings for row and cell selection. */ - selectionMode?: ej.TreeGrid.SelectionMode|string; - - /** Specifies the type of selection whether to select single row or multiple rows. - * @Default {ej.TreeGrid.SelectionType.Single} - */ - selectionType?: ej.TreeGrid.SelectionType|string; + selectionSettings?: SelectionSettings; /** Enables/disables the options for inserting , deleting and renaming columns. * @Default {false} */ showColumnOptions?: boolean; - /** Controls the visibility of the menu button, which is displayed on the column header. Clicking on this button will show a popup menu. When you choose “Columns” item from this popup, a list box with column names will be shown, from which you can select/deselect a column name to control the visibility of the respective columns. + /** Controls the visibility of the menu button, which is displayed on the column header. Clicking on this button will show a popup menu. When you choose Columns item from this popup, a list box with column names will be shown, from which you can select/deselect a column name to control the visibility of the respective columns. * @Default {false} */ showColumnChooser?: boolean; @@ -31604,6 +32645,11 @@ export interface Column { */ headerText?: string; + /** Enables or disables the checkbox visibility in a column to make it as a checkbox column + * @Default {false} + */ + showCheckbox?: boolean; + /** Controls the visibility of the column. * @Default {true} */ @@ -31611,7 +32657,7 @@ export interface Column { /** Specifies the header template value for the column header */ - headerTemplateID?: string; + headerTemplateID?: String; /** Specifies the display format of a column * @Default {null} @@ -31640,7 +32686,7 @@ export interface Column { /** Specifies the template for the TreeGrid column */ - templateID?: string; + templateID?: String; /** Enables or disables the ability to edit a row or cell. * @Default {false} @@ -31763,6 +32809,29 @@ export interface PageSettings { template?: string; } +export interface SelectionSettings { + + /** Specifies the type of selection whether to select row or cell. + * @Default {ej.TreeGrid.SelectionMode.Row} + */ + selectionMode?: ej.TreeGrid.SelectionMode|string; + + /** Specifies the type of selection whether single, multiple or checkbox. + * @Default {ej.TreeGrid.SelectionType.Single} + */ + selectionType?: ej.TreeGrid.SelectionType|string; + + /** Enables or disables the selection by hierarchy in check box selection + * @Default {true} + */ + enableHierarchySelection?: boolean; + + /** Toggles the visibility of the checkbox in column header, using which all the check boxes can be selected or unselected. + * @Default {true} + */ + enableSelectAll?: boolean; +} + export interface SizeSettings { /** Height of the TreeGrid. @@ -31887,7 +32956,10 @@ enum SelectionType{ Single, ///you can select a multiple row. - Multiple + Multiple, + + ///you can select rows using checkbox. + Checkbox } } @@ -31896,6 +32968,7 @@ class GroupButton extends ej.Widget { static fn: GroupButton; constructor(element: JQuery, options?: GroupButton.Model); constructor(element: Element, options?: GroupButton.Model); + static Locale: any; model:GroupButton.Model; defaults:GroupButton.Model; @@ -31956,14 +33029,14 @@ class GroupButton extends ej.Widget { hideItem(element: JQuery): void; /** Returns the disabled state of the specified element button element in GroupButton as Boolean. - * @returns {boolean} + * @returns {Boolean} */ - isDisabled(): boolean; + isDisabled(): Boolean; /** Returns the state of the specified button element as Boolean. - * @returns {boolean} + * @returns {Boolean} */ - isSelected(): boolean; + isSelected(): Boolean; /** Public method used to select the specified button element from the ejGroupButton control. * @param {JQuery} Specific button element @@ -32229,6 +33302,7 @@ class NavigationDrawer extends ej.Widget { static fn: NavigationDrawer; constructor(element: JQuery, options?: NavigationDrawer.Model); constructor(element: Element, options?: NavigationDrawer.Model); + static Locale: any; model:NavigationDrawer.Model; defaults:NavigationDrawer.Model; @@ -32358,6 +33432,7 @@ class RadialMenu extends ej.Widget { static fn: RadialMenu; constructor(element: JQuery, options?: RadialMenu.Model); constructor(element: Element, options?: RadialMenu.Model); + static Locale: any; model:RadialMenu.Model; defaults:RadialMenu.Model; @@ -32506,7 +33581,7 @@ export interface ClickEventArgs { /** returns the name of item */ - itemName?: string; + itemName?: String; } export interface OpenEventArgs { @@ -32605,6 +33680,7 @@ class Tile extends ej.Widget { static fn: Tile; constructor(element: JQuery, options?: Tile.Model); constructor(element: Element, options?: Tile.Model); + static Locale: any; model:Tile.Model; defaults:Tile.Model; @@ -32945,10 +34021,227 @@ enum TileSize{ } +class Signature extends ej.Widget { + static fn: Signature; + constructor(element: JQuery, options?: Signature.Model); + constructor(element: Element, options?: Signature.Model); + static Locale: any; + model:Signature.Model; + defaults:Signature.Model; + + /** Clears the strokes in the signature. + * @returns {void} + */ + clear(): void; + + /** Destroys the signature widget. + * @returns {void} + */ + destroy(): void; + + /** Disables the signature widget. + * @returns {void} + */ + disable(): void; + + /** Enables the signature widget. + * @returns {void} + */ + enable(): void; + + /** Hides the signature widget. + * @returns {void} + */ + hide(): void; + + /** redo the last drawn stroke of the signature + * @returns {void} + */ + redo(): void; + + /** used to save the drawn image. + * @returns {void} + */ + save(): void; + + /** Used to Show the signature widget, if it is already hided. + * @returns {void} + */ + show(): void; + + /** undo the last drawn stroke of the signature. + * @returns {void} + */ + undo(): void; +} +export module Signature{ + +export interface Model { + + /** This property is used to set the background color for the signature. + * @Default {#ffffff} + */ + backgroundColor?: string; + + /** This property is used to set the background image for the signature. + */ + backgroundImage?: string; + + /** Enables or disables the Signature textbox widget. + * @Default {true} + */ + enabled?: Boolean; + + /** Sets the height of the Signature control. + * @Default {100%} + */ + height?: string; + + /** Enables/disables responsive support for the signature control (i.e) maintain the signature drawing during the window resizing time. + * @Default {false} + */ + isResponsive?: Boolean; + + /** Allows the type of the image format to be saved when the signature image is saved. + */ + saveImageFormat?: ej.Signature.SaveImageFormat|string; + + /** Allows the signature image to be saved along with its background. + * @Default {false} + */ + saveWithBackground?: Boolean; + + /** Enables or disables rounded corner. + * @Default {true} + */ + showRoundedCorner?: Boolean; + + /** Sets the stroke color for the stroke of the signature. + * @Default {#000000} + */ + strokeColor?: string; + + /** Sets the stroke width for the stroke of the signature. + * @Default {2} + */ + strokeWidth?: Number; + + /** Sets the width of the Signature control. + * @Default {100%} + */ + width?: string; + + /** Triggers when the stroke is changed. */ + change? (e: ChangeEventArgs): void; + + /** Triggered when the pointer is clicked or touched in the signature canvas. */ + mouseDown? (e: MouseDownEventArgs): void; + + /** Triggered when the pointer is moved in the signature canvas. */ + mouseMove? (e: MouseMoveEventArgs): void; + + /** Triggered when the pointer is released after click or touch in the signature canvas. */ + mouseUp? (e: MouseUpEventArgs): void; +} + +export interface ChangeEventArgs { + + /** Set this option to true to cancel the event. + */ + cancel?: Boolean; + + /** Instance of the signature model object. + */ + model?: any; + + /** Name of the event. + */ + type?: String; + + /** Gives the last stored image + */ + lastImage?: String; +} + +export interface MouseDownEventArgs { + + /** Set this option to true to cancel the event. + */ + cancel?: Boolean; + + /** Instance of the signature model object. + */ + model?: any; + + /** Name of the event. + */ + type?: String; + + /** returns all the event values + */ + value?: any; +} + +export interface MouseMoveEventArgs { + + /** Set this option to true to cancel the event. + */ + cancel?: Boolean; + + /** Instance of the signature model object. + */ + model?: any; + + /** Name of the event. + */ + type?: String; + + /** returns all the event values + */ + value?: any; +} + +export interface MouseUpEventArgs { + + /** Set this option to true to cancel the event. + */ + cancel?: Boolean; + + /** Instance of the signature model object. + */ + model?: any; + + /** Name of the event. + */ + type?: String; + + /** returns all the event values + */ + value?: any; +} + +enum SaveImageFormat{ + + ///To save the signature image with PNG format only. + PNG, + + ///To save the signature image with JPG format only. + JPG, + + ///To save the signature image with BMP format only. + BMP, + + ///To save the signature image with TIFF format only. + TIFF +} + +} + class RadialSlider extends ej.Widget { static fn: RadialSlider; constructor(element: JQuery, options?: RadialSlider.Model); constructor(element: Element, options?: RadialSlider.Model); + static Locale: any; model:RadialSlider.Model; defaults:RadialSlider.Model; @@ -32969,66 +34262,66 @@ export interface Model { /** To show the RadialSlider in initial render. * @Default {false} */ - autoOpen?: boolean; + autoOpen?: Boolean; /** Sets the root class for RadialSlider theme. This cssClass API helps to use custom skinning option for RadialSlider control. By defining the root class using this API, we need to include this root class in CSS. */ - cssClass?: string; + cssClass?: String; /** To enable Animation for Radial Slider. * @Default {true} */ - enableAnimation?: boolean; + enableAnimation?: Boolean; /** Enable/Disable the Roundoff property of RadialSlider * @Default {true} */ - enableRoundOff?: boolean; + enableRoundOff?: Boolean; /** Specifies the endAngle value for radial slider circle. * @Default {360} */ - endAngle?: number; + endAngle?: Number; /** Specifies the inline for label show or not on given radius. * @Default {false} */ - inline?: boolean; + inline?: Boolean; /** Specifies innerCircleImageClass, using this property we can give images for center radial circle through CSS classes. * @Default {null} */ - innerCircleImageClass?: string; + innerCircleImageClass?: String; /** Specifies the file name of center circle icon * @Default {null} */ - innerCircleImageUrl?: string; + innerCircleImageUrl?: String; /** Specifies the Space between the radial slider element and the label. * @Default {30} */ - labelSpace?: number; + labelSpace?: Number; /** Specifies the radius of radial slider * @Default {200} */ - radius?: number; + radius?: Number; /** To show the RadialSlider inner circle. * @Default {true} */ - showInnerCircle?: boolean; + showInnerCircle?: Boolean; /** Specifies the endAngle value for radial slider circle. * @Default {0} */ - startAngle?: number; + startAngle?: Number; /** Specifies the strokeWidth for customize the needle, outer circle and inner circle. * @Default {2} */ - strokeWidth?: number; + strokeWidth?: Number; /** Specifies the ticks value of radial slider */ @@ -33037,7 +34330,7 @@ export interface Model { /** Specifies the value of radial slider * @Default {10} */ - value?: number; + value?: Number; /** Event triggers when the change occurs. */ change? (e: ChangeEventArgs): void; @@ -33070,7 +34363,7 @@ export interface ChangeEventArgs { /** returns the initial value of Radial slider */ - oldValue?: number; + oldValue?: Number; /** returns the name of the event */ @@ -33078,7 +34371,7 @@ export interface ChangeEventArgs { /** returns the current value of the Radial slider */ - value?: number; + value?: Number; } export interface CreateEventArgs { @@ -33108,7 +34401,7 @@ export interface MouseoverEventArgs { /** returns the value selected */ - selectedValue?: number; + selectedValue?: Number; /** returns the name of the event */ @@ -33116,7 +34409,7 @@ export interface MouseoverEventArgs { /** returns the current value selected in Radial slider */ - value?: number; + value?: Number; } export interface SlideEventArgs { @@ -33131,7 +34424,7 @@ export interface SlideEventArgs { /** returns the value selected in Radial slider */ - selectedValue?: number; + selectedValue?: Number; /** returns the name of the event */ @@ -33139,7 +34432,7 @@ export interface SlideEventArgs { /** returns the currently selected value */ - value?: number; + value?: Number; } export interface StartEventArgs { @@ -33158,7 +34451,7 @@ export interface StartEventArgs { /** returns the current value selected in Radial slider */ - value?: number; + value?: Number; } export interface StopEventArgs { @@ -33177,7 +34470,7 @@ export interface StopEventArgs { /** returns the current value selected in Radial slider */ - value?: number; + value?: Number; } } @@ -33185,15 +34478,16 @@ class Spreadsheet extends ej.Widget { static fn: Spreadsheet; constructor(element: JQuery, options?: Spreadsheet.Model); constructor(element: Element, options?: Spreadsheet.Model); + static Locale: any; model:Spreadsheet.Model; defaults:Spreadsheet.Model; /** This method is used to add custom formulas in Spreadsheet. - * @param {string} Pass the name of the formula. - * @param {string} Pass the name of the function. + * @param {String} Pass the name of the formula. + * @param {String} Pass the name of the function. * @returns {void} */ - addCustomFormula(formulaName: string, functionName: string): void; + addCustomFormula(formulaName: String, functionName: String): void; /** This method is used to add a new sheet in the last position of the sheet container. * @returns {void} @@ -33308,9 +34602,9 @@ class Spreadsheet extends ej.Widget { getActiveCellElem(sheetIdx?: number): HTMLElement; /** This method is used to get the current active sheet index in Spreadsheet. - * @returns {number} + * @returns {Number} */ - getActiveSheetIndex(): number; + getActiveSheetIndex(): Number; /** This method is used to get the auto fill element in Spreadsheet. * @returns {HTMLElement} @@ -33327,21 +34621,21 @@ class Spreadsheet extends ej.Widget { /** This method is used to get the data settings in the Spreadsheet. * @param {number} Pass the sheet index. - * @returns {number} + * @returns {Number} */ - getDataSettings(sheetIdx: number): number; + getDataSettings(sheetIdx: number): Number; /** This method is used to get the frozen columns index in the Spreadsheet. * @param {number} Pass the sheet index. - * @returns {number} + * @returns {Number} */ - getFrozenColumns(sheetIdx: number): number; + getFrozenColumns(sheetIdx: number): Number; /** This method is used to get the frozen row index in Spreadsheet. * @param {number} Pass the sheet index. - * @returns {number} + * @returns {Number} */ - getFrozenRows(sheetIdx: number): number; + getFrozenRows(sheetIdx: number): Number; /** This method is used to get the hyperlink data as object from the specified cell in Spreadsheet. * @param {HTMLElement} Pass the DOM element to get hyperlink @@ -33498,11 +34792,11 @@ class Spreadsheet extends ej.Widget { refreshSpreadsheet(): void; /** This method is used to remove custom formulae in Spreadsheet. - * @param {string} Pass the name of the formula. - * @param {string} Pass the name of the function. + * @param {String} Pass the name of the formula. + * @param {String} Pass the name of the function. * @returns {void} */ - removeCustomFormula(formulaName: string, functionName: string): void; + removeCustomFormula(formulaName: String, functionName: String): void; /** This method is used to remove the hyperlink from selected cells of current sheet. * @param {string} Hyperlink remove from the specified range. @@ -33817,14 +35111,14 @@ export interface XLComment { editComment(targetCell: any): void; /** This method is used to find the next comment from the active cell in Spreadsheet. - * @returns {boolean} + * @returns {Boolean} */ - findNextComment(): boolean; + findNextComment(): Boolean; /** This method is used to find the previous comment from the active cell in Spreadsheet. - * @returns {boolean} + * @returns {Boolean} */ - findPrevComment(): boolean; + findPrevComment(): Boolean; /** This method is used to get comment data for the specified cell. * @param {HTMLElement} Pass the DOM element to get comment data as object. @@ -33908,9 +35202,9 @@ export interface XLEdit { * @param {number} Pass the column index to get the property value. * @param {string} Optional. Pass the property name that you want("value", "value2", "type", "cFormatRule", "range", "thousandSeparator", "rule", "format", "border", "picture", "chart", "calcValue", "align", "hyperlink", "formats", "borders", "tformats", "tborders", "isFilterHeader", "filterState", "tableName", "comment", "formatStr", "decimalPlaces", "cellType"). * @param {number} Optional. Pass the index of the sheet. - * @returns {any|string|Array} + * @returns {any|String|Array} */ - getPropertyValue(rowIdx: number,colIdx: number,prop: string,sheetIdx: number): any|string|Array; + getPropertyValue(rowIdx: number,colIdx: number,prop: string,sheetIdx: number): any|String|Array; /** This method is used to get the property value in specified cell in Spreadsheet. * @param {HTMLElement} Pass the cell element to get property value. @@ -34071,10 +35365,10 @@ export interface XLPivot { createPivotTable(range: string,location: string,name: string,settings: any,pvt: any): void; /** This method is used to delete the pivot table which is selected. - * @param {string} Pass the name of the pivot table. + * @param {String} Pass the name of the pivot table. * @returns {void} */ - deletePivotTable(pivotName: string): void; + deletePivotTable(pivotName: String): void; /** This method is used to refresh data in pivot table. * @param {string} Optional. Pass the name of the pivot table. @@ -34101,15 +35395,15 @@ export interface XLResize { /** This method is used to get the column width of the specified column index in the Spreadsheet. * @param {number} Pass the column index. - * @returns {number} + * @returns {Number} */ - getColWidth(colIdx: number): number; + getColWidth(colIdx: number): Number; /** This method is used to get the row height of the specified row index in the Spreadsheet. * @param {number} Pass the row index which you want to find its height. - * @returns {number} + * @returns {Number} */ - getRowHeight(rowIdx: number): number; + getRowHeight(rowIdx: number): Number; /** This method is used to set the column width of the specified column index in the Spreadsheet. * @param {number} Pass the column index. @@ -34278,162 +35572,162 @@ export interface Model { /** Gets or sets an active sheet index in the Spreadsheet. By defining this value, you can specify which sheet should be active in workbook. * @Default {1} */ - activeSheetIndex?: number; + activeSheetIndex?: Number; /** Gets or sets a value that indicates whether to enable or disable auto rendering of cell type in the Spreadsheet. * @Default {false} */ - allowAutoCellType?: boolean; + allowAutoCellType?: Boolean; /** Gets or sets a value that indicates whether to enable or disable auto fill feature in the Spreadsheet. * @Default {true} */ - allowAutoFill?: boolean; + allowAutoFill?: Boolean; /** Gets or sets a value that indicates whether to enable or disable auto sum feature in the Spreadsheet. * @Default {true} */ - allowAutoSum?: boolean; + allowAutoSum?: Boolean; /** Gets or sets a value that indicates whether to enable or disable cell format feature in the Spreadsheet. By enabling this, you can customize styles and number formats. * @Default {true} */ - allowCellFormatting?: boolean; + allowCellFormatting?: Boolean; /** Gets or sets a value that indicates whether to enable or disable cell type feature in the Spreadsheet. * @Default {false} */ - allowCellType?: boolean; + allowCellType?: Boolean; /** Gets or sets a value that indicates whether to enable or disable chart feature in the Spreadsheet. By enabling this feature, you can create and customize charts in Spreadsheet. * @Default {true} */ - allowCharts?: boolean; + allowCharts?: Boolean; /** Gets or sets a value that indicates whether to enable or disable clipboard feature in the Spreadsheet. By enabling this feature, you can perform cut/copy and paste operations in Spreadsheet. * @Default {true} */ - allowClipboard?: boolean; + allowClipboard?: Boolean; /** Gets or sets a value that indicates whether to enable or disable comment feature in the Spreadsheet. By enabling this, you can add/delete/modify comments in Spreadsheet. * @Default {true} */ - allowComments?: boolean; + allowComments?: Boolean; /** Gets or sets a value that indicates whether to enable or disable Conditional Format feature in the Spreadsheet. By enabling this, you can apply formatting to the selected range of cells based on the provided conditions (Greater than, Less than, Equal, Between, Contains, etc.). * @Default {true} */ - allowConditionalFormats?: boolean; + allowConditionalFormats?: Boolean; /** Gets or sets a value that indicates whether to enable or disable data validation feature in the Spreadsheet. * @Default {true} */ - allowDataValidation?: boolean; + allowDataValidation?: Boolean; /** Gets or sets a value that indicates whether to enable or disable the delete action in the Spreadsheet. By enabling this feature, you can delete existing rows, columns, cells and sheet. * @Default {true} */ - allowDelete?: boolean; + allowDelete?: Boolean; /** Gets or sets a value that indicates whether to enable or disable drag and drop feature in the Spreadsheet. * @Default {true} */ - allowDragAndDrop?: boolean; + allowDragAndDrop?: Boolean; /** Gets or sets a value that indicates whether to enable or disable the edit action in the Spreadsheet. * @Default {true} */ - allowEditing?: boolean; + allowEditing?: Boolean; /** Gets or sets a value that indicates whether to enable or disable filtering feature in the Spreadsheet. Filtering can be used to limit the data displayed using required criteria. * @Default {true} */ - allowFiltering?: boolean; + allowFiltering?: Boolean; /** Gets or sets a value that indicates whether to enable or disable table feature in the Spreadsheet. By enabling this, you can render table in selected range. * @Default {true} */ - allowFormatAsTable?: boolean; + allowFormatAsTable?: Boolean; /** Get or sets a value that indicates whether to enable or disable format painter feature in the Spreadsheet. By enabling this feature, you can copy the format from the selected range and apply it to another range. * @Default {true} */ - allowFormatPainter?: boolean; + allowFormatPainter?: Boolean; /** Gets or sets a value that indicates whether to enable or disable formula bar in the Spreadsheet. * @Default {true} */ - allowFormulaBar?: boolean; + allowFormulaBar?: Boolean; /** Gets or sets a value that indicates whether to enable or disable freeze pane support in Spreadsheet. After enabling this feature, you can use freeze top row, freeze first column and freeze panes options. * @Default {true} */ - allowFreezing?: boolean; + allowFreezing?: Boolean; /** Gets or sets a value that indicates whether to enable or disable hyperlink feature in the Spreadsheet. By enabling this feature, you can add hyperlink which is used to easily navigate to the cell reference from one sheet to another or a web page. * @Default {true} */ - allowHyperlink?: boolean; + allowHyperlink?: Boolean; /** Gets or sets a value that indicates whether to enable or disable import feature in the Spreadsheet. By enabling this feature, you can open existing Spreadsheet documents. * @Default {true} */ - allowImport?: boolean; + allowImport?: Boolean; /** Gets or sets a value that indicates whether to enable or disable the insert action in the Spreadsheet. By enabling this feature, you can insert new rows, columns, cells and sheet. * @Default {true} */ - allowInsert?: boolean; + allowInsert?: Boolean; /** Gets or sets a value that indicates whether to enable or disable keyboard navigation feature in the Spreadsheet. * @Default {true} */ - allowKeyboardNavigation?: boolean; + allowKeyboardNavigation?: Boolean; /** Gets or sets a value that indicates whether to enable or disable lock cell feature in the Spreadsheet. * @Default {true} */ - allowLockCell?: boolean; + allowLockCell?: Boolean; /** Gets or sets a value that indicates whether to enable or disable merge feature in the Spreadsheet. * @Default {true} */ - allowMerging?: boolean; + allowMerging?: Boolean; /** Gets or sets a value that indicates whether to enable or disable resizing feature in the Spreadsheet. By enabling this feature, you can change the column width and row height by dragging its header boundaries. * @Default {true} */ - allowResizing?: boolean; + allowResizing?: Boolean; /** Gets or sets a value that indicates whether to enable or disable find and replace feature in the Spreadsheet. By enabling this, you can easily find and replace a specific value in the sheet or workbook. By using goto behavior, you can select and highlight all cells that contains specific data or data types. * @Default {true} */ - allowSearching?: boolean; + allowSearching?: Boolean; /** Gets or sets a value that indicates whether to enable or disable selection in the Spreadsheet. By enabling this feature, selected items will be highlighted. * @Default {true} */ - allowSelection?: boolean; + allowSelection?: Boolean; /** Gets or sets a value that indicates whether to enable the sorting feature in the Spreadsheet. * @Default {true} */ - allowSorting?: boolean; + allowSorting?: Boolean; /** Gets or sets a value that indicates whether to enable or disable undo and redo feature in the Spreadsheet. * @Default {true} */ - allowUndoRedo?: boolean; + allowUndoRedo?: Boolean; /** Gets or sets a value that indicates whether to enable or disable wrap text feature in the Spreadsheet. By enabling this, cell content can wrap to the next line, if the cell content exceeds the boundary of the cell. * @Default {true} */ - allowWrap?: boolean; + allowWrap?: Boolean; /** Gets or sets a value that indicates to define the width of the activation panel in Spreadsheet. * @Default {300} */ - apWidth?: number; + apWidth?: Number; /** Gets or sets an object that indicates to customize the auto fill behavior in the Spreadsheet. */ @@ -34446,16 +35740,16 @@ export interface Model { /** Gets or sets a value that defines the number of columns displayed in the sheet. * @Default {21} */ - columnCount?: number; + columnCount?: Number; /** Gets or sets a value that indicates to define the common width for each column in the Spreadsheet. * @Default {64} */ - columnWidth?: number; + columnWidth?: Number; - /** Gets or sets a value to add root css class for customizing Spreadsheet skins. + /** Gets or sets a value to add root CSS class for customizing Spreadsheet skins. */ - cssClass?: string; + cssClass?: String; /** Gets or sets a value that indicates custom formulas in Spreadsheet. * @Default {[]} @@ -34465,17 +35759,17 @@ export interface Model { /** Gets or sets a value that indicates whether to enable or disable context menu in the Spreadsheet. * @Default {true} */ - enableContextMenu?: boolean; + enableContextMenu?: Boolean; /** Gets or sets a value that indicates whether to enable or disable pivot table in the Spreadsheet. * @Default {false} */ - enablePivotTable?: boolean; + enablePivotTable?: Boolean; /** Gets or sets a value that indicates whether to enable or disable touch support in the Spreadsheet. * @Default {true} */ - enableTouch?: boolean; + enableTouch?: Boolean; /** Gets or sets an object that indicates to customize the exporting behavior in Spreadsheet. */ @@ -34492,7 +35786,7 @@ export interface Model { /** Gets or sets a value that indicates whether to customizing the user interface (UI) as locale-specific in order to display regional data (i.e.) in a language and culture specific to a particular country or region. * @Default {en-US} */ - locale?: string; + locale?: String; /** Gets or sets an object that indicates to customize the picture behavior in the Spreadsheet. */ @@ -34509,12 +35803,12 @@ export interface Model { /** Gets or sets a value that indicates whether to define the number of rows to be displayed in the sheet. * @Default {20} */ - rowCount?: number; + rowCount?: Number; /** Gets or sets a value that indicates to define the common height for each row in the sheet. * @Default {20} */ - rowHeight?: number; + rowHeight?: Number; /** Gets or sets an object that indicates to customize the scroll options in the Spreadsheet. */ @@ -34527,7 +35821,7 @@ export interface Model { /** Gets or sets a value that indicates to define the number of sheets to be created at the initial load. * @Default {1} */ - sheetCount?: number; + sheetCount?: Number; /** Gets or sets an object that indicates to customize the sheet behavior in Spreadsheet. */ @@ -34536,22 +35830,22 @@ export interface Model { /** Gets or sets a value that indicates whether to show or hide pager in the Spreadsheet. * @Default {true} */ - showPager?: boolean; + showPager?: Boolean; /** Gets or sets a value that indicates whether to show or hide ribbon in the Spreadsheet. * @Default {true} */ - showRibbon?: boolean; + showRibbon?: Boolean; /** This is used to set the number of undo-redo steps in the Spreadsheet. * @Default {20} */ - undoRedoStep?: number; + undoRedoStep?: Number; /** Define the username for the Spreadsheet which is displayed in comment. * @Default {User Name} */ - userName?: string; + userName?: String; /** Triggered for every action before its starts. */ actionBegin? (e: ActionBeginEventArgs): void; @@ -34794,7 +36088,7 @@ export interface BeforeBatchSaveEventArgs { /** Returns the sheet index. */ - sheetIdx?: number; + sheetIdx?: Number; /** Returns the query, primary key,batch changes for the data Source. */ @@ -35024,7 +36318,7 @@ export interface CellFormattingEventArgs { */ Cell?: number; - /** Returns the name of the css theme. + /** Returns the name of the CSS theme. */ cssClass?: string; @@ -35076,11 +36370,11 @@ export interface CellSaveEventArgs { /** Returns the index of the row. */ - rowIndex?: number; + rowIndex?: Number; /** Returns the index of the column. */ - colIndex?: number; + colIndex?: Number; /** Returns the Spreadsheet model. */ @@ -35111,7 +36405,7 @@ export interface CellSelectedEventArgs { /** Returns the active sheet index. */ - sheetIdx?: number; + sheetIdx?: Number; /** Returns the selected range. */ @@ -35596,7 +36890,7 @@ export interface AutoFillSettings { /** Gets or sets a value that indicates to enable or disable auto fill options in the Spreadsheet. * @Default {true} */ - showFillOptions?: boolean; + showFillOptions?: Boolean; } export interface ChartSettings { @@ -35604,12 +36898,12 @@ export interface ChartSettings { /** Gets or sets a value that defines the chart height in Spreadsheet. * @Default {220} */ - height?: number; + height?: Number; /** Gets or sets a value that defines the chart width in the Spreadsheet. * @Default {440} */ - width?: number; + width?: Number; } export interface ExportSettings { @@ -35617,27 +36911,27 @@ export interface ExportSettings { /** Gets or sets a value that indicates whether to enable or disable save feature in Spreadsheet. By enabling this feature, you can save existing Spreadsheet. * @Default {true} */ - allowExporting?: boolean; + allowExporting?: Boolean; /** Gets or sets a value that indicates to define csvUrl for export to CSV format. * @Default {null} */ - csvUrl?: string; + csvUrl?: String; /** Gets or sets a value that indicates to define excelUrl for export to excel format. * @Default {null} */ - excelUrl?: string; + excelUrl?: String; /** Gets or sets a value that indicates to define password while export to excel format. * @Default {null} */ - password?: string; + password?: String; - /** Gets or sets a value that indicates to define pdfUrl for export to pdf format. + /** Gets or sets a value that indicates to define pdfUrl for export to PDF format. * @Default {null} */ - pdfUrl?: string; + pdfUrl?: String; } export interface FormatSettings { @@ -35645,37 +36939,37 @@ export interface FormatSettings { /** Gets or sets a value that indicates whether to enable or disable cell border feature in the Spreadsheet. * @Default {true} */ - allowCellBorder?: boolean; + allowCellBorder?: Boolean; /** Gets or sets a value that indicates whether to enable or disable decimal places in the Spreadsheet. * @Default {true} */ - allowDecimalPlaces?: boolean; + allowDecimalPlaces?: Boolean; /** Gets or sets a value that indicates whether to enable or disable font family feature in Spreadsheet. * @Default {true} */ - allowFontFamily?: boolean; + allowFontFamily?: Boolean; } export interface ImportSettings { /** Sets import mapper to perform import feature in Spreadsheet. */ - importMapper?: string; + importMapper?: String; /** Gets or sets a value that indicates whether to enable or disable import while initial loading. * @Default {false} */ - importOnLoad?: boolean; + importOnLoad?: Boolean; /** Sets import URL to access the online files in the Spreadsheet. */ - importUrl?: string; + importUrl?: String; /** Gets or sets a value that indicates to define password while importing in the Spreadsheet. */ - password?: string; + password?: String; } export interface PictureSettings { @@ -35683,17 +36977,17 @@ export interface PictureSettings { /** Gets or sets a value that indicates whether to enable or disable picture feature in Spreadsheet. By enabling this, you can add pictures in Spreadsheet. * @Default {true} */ - allowPictures?: boolean; + allowPictures?: Boolean; /** Gets or sets a value that indicates to define height to picture in the Spreadsheet. * @Default {220} */ - height?: number; + height?: Number; /** Gets or sets a value that indicates to define width to picture in the Spreadsheet. * @Default {440} */ - width?: number; + width?: Number; } export interface PrintSettings { @@ -35701,17 +36995,17 @@ export interface PrintSettings { /** Gets or sets a value that indicates whether to enable or disable page setup support for printing in Spreadsheet. * @Default {true} */ - allowPageSetup?: boolean; + allowPageSetup?: Boolean; /** Gets or sets a value that indicates whether to enable or disable page size support for printing in Spreadsheet. * @Default {false} */ - allowPageSize?: boolean; + allowPageSize?: Boolean; /** Gets or sets a value that indicates whether to enable or disable print feature in the Spreadsheet. * @Default {true} */ - allowPrinting?: boolean; + allowPrinting?: Boolean; } export interface RibbonSettingsApplicationTabMenuSettings { @@ -35719,9 +37013,9 @@ export interface RibbonSettingsApplicationTabMenuSettings { /** Gets or sets a value that indicates whether to enable or disable isAppend property in ribbon settings. * @Default {false} */ - isAppend?: boolean; + isAppend?: Boolean; - /** Specifies the data source to append in applicationtab. + /** Specifies the data source to append in application tab. * @Default {[]} */ dataSource?: Array; @@ -35751,27 +37045,27 @@ export interface ScrollSettings { /** Gets or sets a value that indicates whether to enable or disable scrolling in Spreadsheet. * @Default {true} */ - allowScrolling?: boolean; + allowScrolling?: Boolean; /** Gets or sets a value that indicates whether to enable or disable sheet on demand. By enabling this, it render only the active sheet element while paging remaining sheets are created one by one. * @Default {false} */ - allowSheetOnDemand?: boolean; + allowSheetOnDemand?: Boolean; /** Gets or sets a value that indicates whether to enable or disable virtual scrolling feature in the Spreadsheet. * @Default {true} */ - allowVirtualScrolling?: boolean; + allowVirtualScrolling?: Boolean; /** Gets or sets the value that indicates to define the height of spreadsheet. * @Default {100%} */ - height?: number|string; + height?: Number|String; /** Gets or sets the value that indicates whether to enable or disable responsive mode in the Spreadsheet. * @Default {true} */ - isResponsive?: boolean; + isResponsive?: Boolean; /** Gets or sets a value that indicates to set scroll mode in Spreadsheet. It has two scroll modes, Normal and Infinite. * @Default {ej.Spreadsheet.scrollMode.Infinite} @@ -35781,24 +37075,24 @@ export interface ScrollSettings { /** Gets or sets the value that indicates to define the height of the spreadsheet. * @Default {100%} */ - width?: number|string; + width?: Number|String; } export interface SelectionSettings { /** Gets or sets a value that indicates to define active cell in spreadsheet. */ - activeCell?: string; + activeCell?: String; /** Gets or sets a value that indicates to define animation time while selection in the Spreadsheet. * @Default {0.001} */ - animationTime?: number; + animationTime?: Number; /** Gets or sets a value that indicates to enable or disable animation while selection. * @Default {false} */ - enableAnimation?: boolean; + enableAnimation?: Boolean; /** Gets or sets a value that indicates to set selection type in Spreadsheet. It has three types which are Column, Row and Default. * @Default {ej.Spreadsheet.SelectionType.Default} @@ -35819,11 +37113,11 @@ export interface SheetsBorder { /** Specifies border color for range of cells in Spreadsheet. */ - color?: string; + color?: String; /** To apply border for the specified range of cell. */ - range?: string; + range?: String; } export interface SheetsCFormatRule { @@ -35843,7 +37137,7 @@ export interface SheetsCFormatRule { /** Specifies the range for conditional formatting in Spreadsheet. */ - range?: string; + range?: String; } export interface SheetsRangeSetting { @@ -35860,7 +37154,7 @@ export interface SheetsRangeSetting { /** Specifies the primary key for the datasource in Spreadsheet. */ - primaryKey?: string; + primaryKey?: String; /** Specifies the query for the datasource in Spreadsheet. * @Default {null} @@ -35870,12 +37164,12 @@ export interface SheetsRangeSetting { /** Gets or sets a value that indicates whether to enable or disable the datasource header in Spreadsheet. * @Default {false} */ - showHeader?: boolean; + showHeader?: Boolean; /** Specifies the start cell for the datasource range in Spreadsheet. * @Default {A1} */ - startCell?: string; + startCell?: String; } export interface SheetsRowsCellsComment { @@ -35883,49 +37177,49 @@ export interface SheetsRowsCellsComment { /** Get or sets the value that indicates whether to show or hide comments in Spreadsheet. * @Default {false} */ - isVisible?: boolean; + isVisible?: Boolean; /** Specifies the value for the comment in Spreadsheet. */ - value?: string; + value?: String; } export interface SheetsRowsCellsFormat { /** Specifies the type of the format in Spreadsheet. */ - type?: string; + type?: String; } export interface SheetsRowsCellsHyperlink { /** Specifies the web address for the hyperlink of a cell. */ - webAddr?: string; + webAddr?: String; /** Specifies the cell address for the hyperlink of a cell. */ - cellAddr?: string; + cellAddr?: String; /** Specifies the sheet index to which the cell is referred. * @Default {1} */ - sheetIndex?: number; + sheetIndex?: Number; } export interface SheetsRowsCellsStyle { /** Specifies the background color of a cell in the Spreadsheet. */ - backgroundColor?: string; + backgroundColor?: String; /** Specifies the font color of a cell in the Spreadsheet. */ - color?: string; + color?: String; /** Specifies the font weight of a cell in the Spreadsheet. */ - fontWeight?: string; + fontWeight?: String; } export interface SheetsRowsCell { @@ -35948,7 +37242,7 @@ export interface SheetsRowsCell { /** Specifies the index of a cell in Spreadsheet. * @Default {0} */ - index?: number; + index?: Number; /** Specifies the styles of a cell in Spreadsheet. * @Default {null} @@ -35957,7 +37251,7 @@ export interface SheetsRowsCell { /** Specifies the value for a cell in Spreadsheet. */ - value?: string; + value?: String; } export interface SheetsRow { @@ -35965,7 +37259,7 @@ export interface SheetsRow { /** Gets or sets the height of a row in Spreadsheet. * @Default {20} */ - height?: number; + height?: Number; /** Specifies the cells of a row in Spreadsheet. * @Default {[]} @@ -35975,7 +37269,7 @@ export interface SheetsRow { /** Gets or sets the index of a row in Spreadsheet. * @Default {0} */ - index?: number; + index?: Number; } export interface Sheet { @@ -35993,12 +37287,12 @@ export interface Sheet { /** Gets or sets a value that indicates to define column count in the Spreadsheet. * @Default {21} */ - colCount?: number; + colCount?: Number; /** Gets or sets a value that indicates to define column width in the Spreadsheet. * @Default {64} */ - columnWidth?: number; + columnWidth?: Number; /** Gets or sets the data to render the Spreadsheet. * @Default {null} @@ -36008,7 +37302,7 @@ export interface Sheet { /** Gets or sets a value that indicates whether to enable or disable field as column header in the Spreadsheet. * @Default {false} */ - fieldAsColumnHeader?: boolean; + fieldAsColumnHeader?: Boolean; /** Specifies the header styles for the headers in datasource range. * @Default {null} @@ -36032,7 +37326,7 @@ export interface Sheet { /** Specifies the primary key for the datasource in Spreadsheet. */ - primaryKey?: string; + primaryKey?: String; /** Specifies the query for the dataSource in Spreadsheet. * @Default {null} @@ -36047,7 +37341,7 @@ export interface Sheet { /** Gets or sets a value that indicates to define row count in the Spreadsheet. * @Default {20} */ - rowCount?: number; + rowCount?: Number; /** Specifies the rows for a sheet in Spreadsheet. * @Default {[]} @@ -36057,22 +37351,22 @@ export interface Sheet { /** Gets or sets a value that indicates whether to show or hide grid lines in the Spreadsheet. * @Default {true} */ - showGridlines?: boolean; + showGridlines?: Boolean; /** Gets or sets a value that indicates whether to enable or disable the datasource header in Spreadsheet. * @Default {false} */ - showHeader?: boolean; + showHeader?: Boolean; /** Gets or sets a value that indicates whether to show or hide headings in the Spreadsheet. * @Default {true} */ - showHeadings?: boolean; + showHeadings?: Boolean; /** Specifies the start cell for the datasource range in Spreadsheet. * @Default {A1} */ - startCell?: string; + startCell?: String; } enum AutoFillOptions{ @@ -36210,6 +37504,7 @@ class PdfViewer extends ej.Widget { static fn: PdfViewer; constructor(element: JQuery, options?: PdfViewer.Model); constructor(element: Element, options?: PdfViewer.Model); + static Locale: any; model:PdfViewer.Model; defaults:PdfViewer.Model; @@ -36294,7 +37589,7 @@ export interface Model { /** Specifies the locale information of the PDF viewer. */ - locale?: string; + locale?: String; /** Specifies the toolbar settings. */ @@ -36306,19 +37601,19 @@ export interface Model { /** Sets the PDF Web API service URL */ - serviceUrl?: string; + serviceUrl?: String; /** Gets the total number of pages in PDF document. */ - pageCount?: number; + pageCount?: Number; /** Gets the number of the page being displayed in the PDF Viewer. */ - currentPageNumber?: number; + currentPageNumber?: Number; /** Gets the current zoom percentage of the PDF document in viewer. */ - zoomPercentage?: number; + zoomPercentage?: Number; /** Specifies the location of the supporting PDF service */ @@ -36330,7 +37625,7 @@ export interface Model { /** Enables or disables the responsive support for PDF Viewer control during the window resizing time. */ - isResponsive?: boolean; + isResponsive?: Boolean; /** Gets the name of the PDF document which loaded in the ejPdfViewer control for downloading. */ @@ -36483,7 +37778,7 @@ export interface ToolbarSettings { /** Shows or hides the tooltip of the toolbar items. */ - showToolTip?: boolean; + showToolTip?: Boolean; } enum ToolbarItems{ @@ -36529,6 +37824,490 @@ enum LinkTarget{ } +class SpellCheck extends ej.Widget { + static fn: SpellCheck; + constructor(element: JQuery, options?: SpellCheck.Model); + constructor(element: Element, options?: SpellCheck.Model); + static Locale: any; + model:SpellCheck.Model; + defaults:SpellCheck.Model; + + /** Open the dialog to correct the spelling of the target content. + * @returns {void} + */ + showInDialog(): void; + + /** Highlighting the error word in the target area itself and correct the spelling using the context menu. + * @returns {void} + */ + validate(): void; + + /** To get the error word highlighted string by passing the given input sentence. + * @param {string} Content to be spell check + * @param {string} Class name that contains style value to highlight the error word + * @returns {void} + */ + spellCheck(targetSentence: string, misspellWordCss: string): void; + + /** To ignore all the error word occurrences from the given input sentence. + * @param {string} Error word to ignore from the target content + * @param {string} Content to perform the ignore all operation + * @returns {void} + */ + ignoreAll(word: string, targetSentence: string): void; + + /** To ignore the error word once from the given input sentence. + * @param {string} Error word to ignore from the target content + * @param {string} Content to perform the ignore operation + * @param {number} Index of the error word present in the target content + * @returns {void} + */ + ignore(word: string, targetSentence: string, index: number): void; + + /** To change the error word once from the given input sentence. + * @param {string} Error word to change from the target content + * @param {string} Content to perform the change operation + * @param {string} Word to replace with the error word + * @param {number} Index of the error word present in the target content + * @returns {void} + */ + change(word: string, targetSentence: string, changeWord: string, index: number): void; + + /** To change all the error word occurrences from the given input sentence. + * @param {string} Error word to change from the target content + * @param {string} Content to perform the change all operation + * @param {string} Word to replace with the error word + * @returns {void} + */ + changeAll(word: string, targetSentence: string, changeWord: string): void; + + /** To add the words into the custom dictionary. + * @param {string} Word to add into the dictionary file + * @returns {void} + */ + addToDictionary(customWord: string): void; +} +export module SpellCheck{ + +export interface Model { + + /** It includes the service method path to find the error words and its suggestions also adding the custom word into the custom dictionary. + */ + dictionarySettings?: DictionarySettings; + + /** To display the error word in a customized style. + * @Default {e-errorword} + */ + misspellWordCss?: string; + + /** Sets the specific culture to the SpellCheck. + * @Default {en-US} + */ + locale?: string; + + /** To set the maximum suggestion display count. + * @Default {6} + */ + maxSuggestionCount?: number; + + /** To ignore the words from the error word consideration. + * @Default {[]} + */ + ignoreWords?: Array; + + /** Holds all options related to the context menu settings of SpellCheck. + */ + contextMenuSettings?: ContextMenuSettings; + + /** It helps to ignore the uppercase, mixed case words, alpha numeric words, file path and email addresses based on the property values. + */ + ignoreSettings?: IgnoreSettings; + + /** Triggers on the success of AJAX call request. */ + actionSuccess? (e: ActionSuccessEventArgs): void; + + /** Triggers on the AJAX call request beginning. */ + actionBegin? (e: ActionBeginEventArgs): void; + + /** Triggers when the AJAX call request failure. */ + actionFailure? (e: ActionFailureEventArgs): void; + + /** Triggers when the dialog mode spell check starting. */ + start? (e: StartEventArgs): void; + + /** Triggers when the spell check operations completed through dialog mode. */ + complete? (e: CompleteEventArgs): void; + + /** Triggers before context menu opening. */ + contextOpen? (e: ContextOpenEventArgs): void; + + /** Triggers when the context menu item clicked. */ + contextClick? (e: ContextClickEventArgs): void; + + /** Triggers before the spell check dialog opens. */ + dialogBeforeOpen? (e: DialogBeforeOpenEventArgs): void; + + /** Triggers after the spell check dialog opens. */ + dialogOpen? (e: DialogOpenEventArgs): void; + + /** Triggers when the spell check dialog closed. */ + dialogClose? (e: DialogCloseEventArgs): void; + + /** Triggers when the spell check control performing the spell check operations such as ignore, ignoreAll, change, changeAll and addToDictionary. */ + validating? (e: ValidatingEventArgs): void; +} + +export interface ActionSuccessEventArgs { + + /** Returns the error word highlighted string. + */ + resultHTML?: string; + + /** Returns the error word details of the given input. + */ + errorWordDetails?: any; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface ActionBeginEventArgs { + + /** Returns the input string. + */ + targetSentence?: string; + + /** Returns the misspellWordCss class name. + */ + misspellWordCss?: string; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface ActionFailureEventArgs { + + /** Returns AJAX request failure error message. + */ + errorMessage?: string; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface StartEventArgs { + + /** Returns the input string. + */ + targetSentence?: string; + + /** Returns the error words details. + */ + errorWords?: any; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface CompleteEventArgs { + + /** Returns the error word highlighted string. + */ + resultHTML?: string; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface ContextOpenEventArgs { + + /** Returns the selected error word. + */ + selectedErrorWord?: string; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface ContextClickEventArgs { + + /** Returns the selected error word. + */ + selectedValue?: string; + + /** Returns the selected option in the context menu. + */ + selectedOption?: string; + + /** Returns the input string. + */ + targetContent?: string; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface DialogBeforeOpenEventArgs { + + /** Returns the spell check window details. + */ + spellCheckDialog?: any; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface DialogOpenEventArgs { + + /** Returns the target input. + */ + targetText?: string; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface DialogCloseEventArgs { + + /** Returns the error corrected string. + */ + updatedText?: string; + + /** Returns the request type value. + */ + requestType?: string; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the name of the event. + */ + type?: string; +} + +export interface ValidatingEventArgs { + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the error word to ignore. + */ + ignoreWord?: string; + + /** Returns the target content. + */ + targetContent?: string; + + /** Returns the index of an error word. + */ + index?: number; + + /** Returns the SpellCheck model. + */ + model?: ej.SpellCheck.Model; + + /** Returns the validating request type. + */ + requestType?: string; + + /** Returns the name of the event. + */ + type?: string; + + /** Returns the error word to change. + */ + changeableWord?: string; + + /** Returns the change word to replace the error word. + */ + changeWord?: string; + + /** Returns the custom word to add into dictionary file. + */ + customWord?: string; +} + +export interface DictionarySettings { + + /** The dictionaryUrl option accepts string, which is the method path to find the error words and get the suggestions to correct the errors. + */ + dictionaryUrl?: string; + + /** The customDictionaryUrl option accepts string, which is the method path to add the error word into the custom dictionary. + */ + customDictionaryUrl?: string; +} + +export interface ContextMenuSettings { + + /** When set to true, enables the context menu options available for the SpellCheck. + * @Default {true} + */ + enable?: boolean; + + /** Contains all the default context menu options that are applicable for SpellCheck. It also supports adding custom menu items. All the SpellCheck related context menu items are grouped under this menu collection. + * @Default {{% highlight javascript %}[{ id: IgnoreAll, text: Ignore All },{ id: AddToDictionary, text: Add To Dictionary }]{% endhighlight %}} + */ + menuItems?: Array; +} + +export interface IgnoreSettings { + + /** When set to true, ignoring the alphanumeric words from the error word consideration. + * @Default {true} + */ + ignoreAlphaNumericWords?: string; + + /** When set to true, ignoring the Email address from the error word consideration. + * @Default {true} + */ + ignoreEmailAddress?: boolean; + + /** When set to true, ignoring the MixedCase words from the error word consideration. + * @Default {true} + */ + ignoreMixedCaseWords?: boolean; + + /** When set to true, ignoring the UpperCase words from the error word consideration. + * @Default {true} + */ + ignoreUpperCase?: boolean; + + /** When set to true, ignoring the Url from the error word consideration. + * @Default {true} + */ + ignoreUrl?: boolean; + + /** When set to true, ignoring the file address path from the error word consideration. + * @Default {true} + */ + ignoreFileNames?: boolean; +} +} + } declare module ej.datavisualization { @@ -36536,6 +38315,7 @@ class SymbolPalette extends ej.Widget { static fn: SymbolPalette; constructor(element: JQuery, options?: SymbolPalette.Model); constructor(element: Element, options?: SymbolPalette.Model); + static Locale: any; model:SymbolPalette.Model; defaults:SymbolPalette.Model; } @@ -36546,12 +38326,12 @@ export interface Model { /** Defines whether the symbols can be dragged from palette or not * @Default {true} */ - allowDrag?: boolean; + allowDrag?: Boolean; /** Customizes the style of the symbol palette * @Default {e-symbolpalette} */ - cssClass?: string; + cssClass?: String; /** Defines the default properties of nodes and connectors */ @@ -36560,27 +38340,27 @@ export interface Model { /** Sets the Id of the diagram, over which the symbols will be dropped * @Default {null} */ - diagramId?: string; + diagramId?: String; /** Sets the height of the palette headers * @Default {30} */ - headerHeight?: number; + headerHeight?: Number; /** Defines the height of the symbol palette * @Default {400} */ - height?: number; + height?: Number; /** Defines the height of the palette items * @Default {50} */ - paletteItemHeight?: number; + paletteItemHeight?: Number; /** Defines the width of the palette items * @Default {50} */ - paletteItemWidth?: number; + paletteItemWidth?: Number; /** An array of JSON objects, where each object represents a node/connector * @Default {[]} @@ -36590,7 +38370,7 @@ export interface Model { /** Defines the preview height of the symbols * @Default {100} */ - previewHeight?: number; + previewHeight?: Number; /** Defines the offset value to be left between the mouse cursor and symbol previews * @Default {(110, 110)} @@ -36600,17 +38380,17 @@ export interface Model { /** Defines the width of the symbol previews * @Default {100} */ - previewWidth?: number; + previewWidth?: Number; /** Enable or disable the palette item text * @Default {true} */ - showPaletteItemText?: boolean; + showPaletteItemText?: Boolean; /** The width of the palette * @Default {250} */ - width?: number; + width?: Number; /** Triggers when a palette item is selected or unselected */ selectionChange? (e: SelectionChangeEventArgs): void; @@ -36620,7 +38400,7 @@ export interface SelectionChangeEventArgs { /** returns whether an element is selected or unselected */ - changeType?: string; + changeType?: String; /** returns the node or connector that is selected or unselected */ @@ -36663,6 +38443,7 @@ class LinearGauge extends ej.Widget { static fn: LinearGauge; constructor(element: JQuery, options?: LinearGauge.Model); constructor(element: Element, options?: LinearGauge.Model); + static Locale: any; model:LinearGauge.Model; defaults:LinearGauge.Model; @@ -37168,7 +38949,7 @@ export interface Model { /** Specifies the scales * @Default {null} */ - scales?: Scales; + scales?: Array; /** Specifies the theme for Linear gauge. See LinearGauge.Themes * @Default {flatlight} @@ -38402,7 +40183,7 @@ export interface ScalesTick { width?: number; } -export interface Scales { +export interface Scale { /** Specifies the backgroundColor of the Scale. * @Default {null} @@ -38699,6 +40480,7 @@ class CircularGauge extends ej.Widget { static fn: CircularGauge; constructor(element: JQuery, options?: CircularGauge.Model); constructor(element: Element, options?: CircularGauge.Model); + static Locale: any; model:CircularGauge.Model; defaults:CircularGauge.Model; @@ -39204,7 +40986,7 @@ export interface Model { /** Specify the pointers, ticks, labels, indicators, ranges of circular gauge * @Default {null} */ - scales?: Scales; + scales?: Array; /** Specify the theme of circular gauge. * @Default {flatlight} @@ -40389,7 +42171,7 @@ export interface ScalesTick { width?: number; } -export interface Scales { +export interface Scale { /** Specify backgroundColor for the scale of circular gauge * @Default {null} @@ -40710,6 +42492,7 @@ class DigitalGauge extends ej.Widget { static fn: DigitalGauge; constructor(element: JQuery, options?: DigitalGauge.Model); constructor(element: Element, options?: DigitalGauge.Model); + static Locale: any; model:DigitalGauge.Model; defaults:DigitalGauge.Model; @@ -40778,7 +42561,7 @@ export interface Model { /** Specifies the items for the DigitalGauge. * @Default {null} */ - items?: Items; + items?: Array; /** Specifies the matrixSegmentData for the DigitalGauge. */ @@ -40840,7 +42623,7 @@ export interface InitEventArgs { /** returns the name of the event */ - type?: string; + type?: String; } export interface ItemRenderingEventArgs { @@ -40867,7 +42650,7 @@ export interface ItemRenderingEventArgs { /** returns the name of the event */ - type?: string; + type?: String; } export interface LoadEventArgs { @@ -40894,7 +42677,7 @@ export interface LoadEventArgs { /** returns the name of the event */ - type?: string; + type?: String; } export interface RenderCompleteEventArgs { @@ -40921,7 +42704,7 @@ export interface RenderCompleteEventArgs { /** returns the name of the event */ - type?: string; + type?: String; } export interface Frame { @@ -41029,7 +42812,7 @@ export interface ItemsSegmentSettings { width?: number; } -export interface Items { +export interface Item { /** Specifies the Character settings for the DigitalGauge. * @Default {null} @@ -41129,6 +42912,7 @@ class Chart extends ej.Widget { static fn: Chart; constructor(element: JQuery, options?: Chart.Model); constructor(element: Element, options?: Chart.Model); + static Locale: any; model:Chart.Model; defaults:Chart.Model; @@ -41429,11 +43213,11 @@ export interface AxesLabelRenderingEventArgs { /** Formatted text of the respective label. You can also add custom text to the label. */ - LabelText?: string; + LabelText?: String; /** Actual value of the label. */ - LabelValue?: string; + LabelValue?: String; /** Set this option to true to cancel the event. */ @@ -42735,6 +44519,11 @@ export interface CommonSeriesOptionsMarkerDataLabelFont { */ opacity?: number; + /** Font color of the data label text. + * @Default {null} + */ + color?: string; + /** Font size of the data label. * @Default {12px} */ @@ -42771,6 +44560,16 @@ export interface CommonSeriesOptionsMarkerDataLabel { */ angle?: number; + /** Maximum label width of the data label. + * @Default {null} + */ + maximumLabelWidth?: number; + + /** Enable the wrap option to the data label. + * @Default {false} + */ + enableWrap?: boolean; + /** Options for customizing the border of the data label. */ border?: CommonSeriesOptionsMarkerDataLabelBorder; @@ -42879,6 +44678,29 @@ export interface CommonSeriesOptionsMarker { visible?: boolean; } +export interface CommonSeriesOptionsCornerRadius { + + /** Specifies the radius for the top left corner. + * @Default {0} + */ + topLeft?: number; + + /** Specifies the radius for the top right corner. + * @Default {0} + */ + topRight?: number; + + /** Specifies the radius for the bottom left corner. + * @Default {0} + */ + bottomLeft?: number; + + /** Specifies the radius for the bottom right corner. + * @Default {0} + */ + bottomRight?: number; +} + export interface CommonSeriesOptionsTooltipBorder { /** Border color of the tooltip. @@ -43263,6 +45085,11 @@ export interface CommonSeriesOptions { */ border?: CommonSeriesOptionsBorder; + /** To render the column and bar type series in rectangle/cylinder shape. See ColumnFacet + * @Default {rectangle} + */ + columnFacet?: ej.datavisualization.Chart.ColumnFacet|string; + /** Relative width of the columns in column type series. Value ranges from 0 to 1. Width also depends upon columnSpacing property. * @Default {0.7} */ @@ -43424,6 +45251,10 @@ export interface CommonSeriesOptions { */ startAngle?: number; + /** Options for customizing the corner radius. cornerRadius property also takes the numeric input and applies it for all the four corners of the column. + */ + cornerRadius?: CommonSeriesOptionsCornerRadius; + /** Options for customizing the tooltip of chart. */ tooltip?: CommonSeriesOptionsTooltip; @@ -43473,7 +45304,7 @@ export interface CommonSeriesOptions { */ close?: string; - /** zOrder of the series. + /** Z-order of the series. * @Default {0} */ zOrder?: number; @@ -43513,6 +45344,51 @@ export interface CommonSeriesOptions { selectionSettings?: CommonSeriesOptionsSelectionSettings; } +export interface CrosshairTrackballTooltipSettingsBorder { + + /** Border width of the trackball tooltip. + * @Default {null} + */ + width?: number; + + /** Border color of the trackball tooltip. + * @Default {null} + */ + color?: string; +} + +export interface CrosshairTrackballTooltipSettings { + + /** Options for customizing the trackball tooltip border. + */ + border?: CrosshairTrackballTooltipSettingsBorder; + + /** Background color of the trackball tooltip. + * @Default {null} + */ + fill?: string; + + /** Rounded corner x value of the trackball tooltip. + * @Default {3} + */ + rx?: number; + + /** Rounded corner y value of the trackball tooltip. + * @Default {3} + */ + ry?: number; + + /** Opacity value of the trackball tooltip. + * @Default {1} + */ + opacity?: number; + + /** Specifies the mode of the trackball tooltip. + * @Default {float. See CrosshairMode} + */ + mode?: ej.datavisualization.Chart.CrosshairMode|string; +} + export interface CrosshairMarkerBorder { /** Border width of the marker. @@ -43570,6 +45446,10 @@ export interface CrosshairLine { export interface Crosshair { + /** Options for customizing the trackball tooltip. + */ + trackballTooltipSettings?: CrosshairTrackballTooltipSettings; + /** Options for customizing the marker in crosshair. */ marker?: CrosshairMarker; @@ -44243,6 +46123,107 @@ export interface PrimaryXAxisRange { interval?: number; } +export interface PrimaryXAxisMultiLevelLabelsFont { + + /** Font color of the multi level labels text. + * @Default {null} + */ + color?: string; + + /** Font family of the multi level labels text. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style of the multi level labels text. + * @Default {Normal} + */ + fontStyle?: ej.datavisualization.Chart.FontStyle|string; + + /** Font weight of the multi level label text. + * @Default {regular} + */ + fontWeight?: string; + + /** Opacity of the multi level label text. + * @Default {1} + */ + opacity?: number; + + /** Font size of the multi level label text. + * @Default {12px} + */ + size?: string; +} + +export interface PrimaryXAxisMultiLevelLabelsBorder { + + /** Border color of the multi level labels. + * @Default {null} + */ + color?: string; + + /** Border width of the multi level labels. + * @Default {1} + */ + width?: number; + + /** Border type of the multi level labels. + * @Default {rectangle. See Type} + */ + type?: ej.datavisualization.Chart.MultiLevelLabelsBorderType|string; +} + +export interface PrimaryXAxisMultiLevelLabel { + + /** Visibility of the multi level labels. + * @Default {false} + */ + visible?: boolean; + + /** Text of the multi level labels. + */ + text?: string; + + /** Starting value of the multi level labels. + * @Default {null} + */ + start?: number; + + /** Ending value of the multi level labels. + * @Default {null} + */ + end?: number; + + /** Specifies the level of multi level labels. + * @Default {0} + */ + level?: number; + + /** Specifies the maximum width of the text in multi level labels. + * @Default {null} + */ + maximumTextWidth?: number; + + /** Specifies the alignment of the text in multi level labels. + * @Default {center. See TextAlignment} + */ + textAlignment?: ej.datavisualization.Chart.TextAlignment|string; + + /** Specifies the handling of text over flow in multi level labels. + * @Default {center. See TextOverflow} + */ + textOverflow?: ej.datavisualization.Chart.TextOverflow|string; + + /** Options for customizing the font of the text. + */ + font?: PrimaryXAxisMultiLevelLabelsFont; + + /** Options for customizing the border of the series. + */ + border?: PrimaryXAxisMultiLevelLabelsBorder; +} + export interface PrimaryXAxisStripLineFont { /** Font color of the strip line text. @@ -44333,6 +46314,19 @@ export interface PrimaryXAxisStripLine { zIndex?: ej.datavisualization.Chart.ZIndex|string; } +export interface PrimaryXAxisLabelBorder { + + /** Specifies the color of the label border. + * @Default {null} + */ + color?: string; + + /** Specifies the width of the label border. + * @Default {1} + */ + width?: number; +} + export interface PrimaryXAxisTitleFont { /** Font family of the title text. @@ -44385,6 +46379,21 @@ export interface PrimaryXAxisTitle { * @Default {true} */ visible?: boolean; + + /** offset value for axis title. + * @Default {0} + */ + offset?: number; + + /** Specifies the position of the axis title. + * @Default {outside. See Position} + */ + position?: ej.datavisualization.Chart.LabelPosition|string; + + /** Specifies the position of the axis title. + * @Default {center. See Alignment} + */ + alignment?: ej.datavisualization.Chart.TextAlignment|string; } export interface PrimaryXAxis { @@ -44431,6 +46440,11 @@ export interface PrimaryXAxis { */ desiredIntervals?: number; + /** Specifies the placement of labels. + * @Default {ej.datavisualization.Chart.LabelPlacement.BetweenTicks. See LabelPlacement} + */ + labelPlacement?: ej.datavisualization.Chart.LabelPlacement|string; + /** Specifies the position of labels at the edge of the axis. * @Default {ej.datavisualization.Chart.EdgeLabelPlacement.None. See EdgeLabelPlacement} */ @@ -44470,6 +46484,11 @@ export interface PrimaryXAxis { */ labelPosition?: ej.datavisualization.Chart.LabelPosition|string; + /** Specifies the position of the axis labels. + * @Default {center. See Alignment} + */ + alignment?: ej.datavisualization.Chart.LabelAlignment|string; + /** Angle in degrees to rotate the axis labels. * @Default {null} */ @@ -44540,6 +46559,11 @@ export interface PrimaryXAxis { */ roundingPlaces?: number; + /** Options for customizing the multi level labels. + * @Default {[ ]} + */ + multiLevelLabels?: Array; + /** Options for customizing the strip lines. * @Default {[ ]} */ @@ -44550,6 +46574,10 @@ export interface PrimaryXAxis { */ tickLinesPosition?: ej.datavisualization.Chart.TickLinesPosition|string; + /** Options for customizing the border of the labels. + */ + labelBorder?: PrimaryXAxisLabelBorder; + /** Options for customizing the axis title. */ title?: PrimaryXAxisTitle; @@ -44771,6 +46799,107 @@ export interface PrimaryYAxisRange { interval?: number; } +export interface PrimaryYAxisMultiLevelLabelsFont { + + /** Font color of the multi level labels text. + * @Default {null} + */ + color?: string; + + /** Font family of the multi level labels text. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style of the multi level labels text. + * @Default {Normal} + */ + fontStyle?: ej.datavisualization.Chart.FontStyle|string; + + /** Font weight of the multi level label text. + * @Default {regular} + */ + fontWeight?: string; + + /** Opacity of the multi level label text. + * @Default {1} + */ + opacity?: number; + + /** Font size of the multi level label text. + * @Default {12px} + */ + size?: string; +} + +export interface PrimaryYAxisMultiLevelLabelsBorder { + + /** Border color of the multi level labels. + * @Default {null} + */ + color?: string; + + /** Border width of the multi level labels. + * @Default {1} + */ + width?: number; + + /** Border type of the multi level labels. + * @Default {rectangle. See Type} + */ + type?: ej.datavisualization.Chart.MultiLevelLabelsBorderType|string; +} + +export interface PrimaryYAxisMultiLevelLabel { + + /** Visibility of the multi level labels. + * @Default {false} + */ + visible?: boolean; + + /** Text of the multi level labels. + */ + text?: string; + + /** Starting value of the multi level labels. + * @Default {null} + */ + start?: number; + + /** Ending value of the multi level labels. + * @Default {null} + */ + end?: number; + + /** Specifies the level of multi level labels. + * @Default {0} + */ + level?: number; + + /** Specifies the maximum width of the text in multi level labels. + * @Default {null} + */ + maximumTextWidth?: number; + + /** Specifies the alignment of the text in multi level labels. + * @Default {center. See TextAlignment} + */ + textAlignment?: ej.datavisualization.Chart.TextAlignment|string; + + /** Specifies the handling of text over flow in multi level labels. + * @Default {center. See TextOverflow} + */ + textOverflow?: ej.datavisualization.Chart.TextOverflow|string; + + /** Options for customizing the font of the text. + */ + font?: PrimaryYAxisMultiLevelLabelsFont; + + /** Options for customizing the border of the series. + */ + border?: PrimaryYAxisMultiLevelLabelsBorder; +} + export interface PrimaryYAxisStripLineFont { /** Font color of the strip line text. @@ -44861,6 +46990,19 @@ export interface PrimaryYAxisStripLine { zIndex?: ej.datavisualization.Chart.ZIndex|string; } +export interface PrimaryYAxisLabelBorder { + + /** Specifies the color of the label border. + * @Default {null} + */ + color?: string; + + /** Specifies the width of the label border. + * @Default {1} + */ + width?: number; +} + export interface PrimaryYAxisTitleFont { /** Font family of the title text. @@ -44913,6 +47055,21 @@ export interface PrimaryYAxisTitle { * @Default {true} */ visible?: boolean; + + /** offset value for axis title. + * @Default {0} + */ + offset?: number; + + /** Specifies the position of the axis title. + * @Default {outside. See Position} + */ + position?: ej.datavisualization.Chart.LabelPosition|string; + + /** Specifies the position of the axis title. + * @Default {center. See Alignment} + */ + alignment?: ej.datavisualization.Chart.TextAlignment|string; } export interface PrimaryYAxis { @@ -44944,6 +47101,11 @@ export interface PrimaryYAxis { */ desiredIntervals?: number; + /** Specifies the placement of labels. + * @Default {ej.datavisualization.Chart.LabelPlacement.BetweenTicks. See LabelPlacement} + */ + labelPlacement?: ej.datavisualization.Chart.LabelPlacement|string; + /** Specifies the position of labels at the edge of the axis. * @Default {ej.datavisualization.Chart.EdgeLabelPlacement.None. See EdgeLabelPlacement} */ @@ -44983,6 +47145,11 @@ export interface PrimaryYAxis { */ labelPosition?: ej.datavisualization.Chart.LabelPosition|string; + /** Specifies the position of the axis labels. + * @Default {center. See Alignment} + */ + alignment?: ej.datavisualization.Chart.LabelAlignment|string; + /** Logarithmic base value. This is applicable only for logarithmic axis. * @Default {10} */ @@ -45058,6 +47225,11 @@ export interface PrimaryYAxis { */ rowSpan?: number; + /** Options for customizing the multi level labels. + * @Default {[ ]} + */ + multiLevelLabels?: Array; + /** Options for customizing the strip lines. * @Default {[ ]} */ @@ -45068,6 +47240,10 @@ export interface PrimaryYAxis { */ tickLinesPosition?: ej.datavisualization.Chart.TickLinesPosition|string; + /** Options for customizing the border of the labels. + */ + labelBorder?: PrimaryYAxisLabelBorder; + /** Options for customizing the axis title. */ title?: PrimaryYAxisTitle; @@ -45223,6 +47399,11 @@ export interface SeriesMarkerDataLabelFont { */ fontFamily?: string; + /** Font color of the data label text. + * @Default {null} + */ + color?: string; + /** Font style of the data label. * @Default {normal. See FontStyle} */ @@ -45274,6 +47455,16 @@ export interface SeriesMarkerDataLabel { */ angle?: number; + /** Maximum label width of the data label. + * @Default {null} + */ + maximumLabelWidth?: number; + + /** Enable the wrap option to the data label. + * @Default {false} + */ + enableWrap?: boolean; + /** Options for customizing the border of the data label. */ border?: SeriesMarkerDataLabelBorder; @@ -45838,6 +48029,29 @@ export interface SeriesPoint { y?: number; } +export interface SeriesCornerRadius { + + /** Specifies the radius for the top left corner. + * @Default {0} + */ + topLeft?: number; + + /** Specifies the radius for the top right corner. + * @Default {0} + */ + topRight?: number; + + /** Specifies the radius for the bottom left corner. + * @Default {0} + */ + bottomLeft?: number; + + /** Specifies the radius for the bottom right corner. + * @Default {0} + */ + bottomRight?: number; +} + export interface SeriesTooltipBorder { /** Border Color of the tooltip. @@ -46079,6 +48293,11 @@ export interface Series { */ bullFillColor?: string; + /** To render the column and bar type series in rectangle/cylinder shape. See ColumnFacet + * @Default {rectangle} + */ + columnFacet?: ej.datavisualization.Chart.ColumnFacet|string; + /** Relative width of the columns in column type series. Value ranges from 0 to 1. Width also depends upon columnSpacing property. * @Default {0.7} */ @@ -46111,7 +48330,7 @@ export interface Series { /** Type of series to be drawn in radar or polar series. * @Default {line. See DrawType} */ - drawType?: boolean; + drawType?: ej.datavisualization.Chart.DrawType|string; /** Enable/disable the animation of series. * @Default {false} @@ -46261,6 +48480,10 @@ export interface Series { */ startAngle?: number; + /** Options for customizing the corner radius. cornerRadius property also takes the numeric input and applies it for all the four corners of the column. + */ + cornerRadius?: SeriesCornerRadius; + /** Options for customizing the tooltip of chart. */ tooltip?: SeriesTooltip; @@ -46325,7 +48548,7 @@ export interface Series { */ pointColorMappingName?: string; - /** zOrder of the series. + /** Z-order of the series. * @Default {0} */ zOrder?: number; @@ -46646,6 +48869,16 @@ Pixel, } module Chart { +enum ColumnFacet +{ +//string +Rectangle, +//string +Cylinder, +} +} +module Chart +{ enum DrawType { //string @@ -46962,6 +49195,16 @@ Y, } module Chart { +enum CrosshairMode +{ +//string +Float, +//string +Grouping, +} +} +module Chart +{ enum CrosshairType { //string @@ -47012,6 +49255,16 @@ WrapAndTrim, } module Chart { +enum LabelPlacement +{ +//string +OnTicks, +//string +BetweenTicks, +} +} +module Chart +{ enum EdgeLabelPlacement { //string @@ -47066,6 +49319,18 @@ MultipleRows, } module Chart { +enum LabelAlignment +{ +//string +Near, +//string +Far, +//string +Center, +} +} +module Chart +{ enum RangePadding { //string @@ -47080,6 +49345,22 @@ Round, } module Chart { +enum MultiLevelLabelsBorderType +{ +//string +Rectangle, +//string +None, +//string +WithoutTopAndBottom, +//string +Brace, +//string +CurlyBrace, +} +} +module Chart +{ enum TextAlignment { //string @@ -47155,6 +49436,7 @@ class RangeNavigator extends ej.Widget { static fn: RangeNavigator; constructor(element: JQuery, options?: RangeNavigator.Model); constructor(element: Element, options?: RangeNavigator.Model); + static Locale: any; model:RangeNavigator.Model; defaults:RangeNavigator.Model; @@ -48269,6 +50551,7 @@ class BulletGraph extends ej.Widget { static fn: BulletGraph; constructor(element: JQuery, options?: BulletGraph.Model); constructor(element: Element, options?: BulletGraph.Model); + static Locale: any; model:BulletGraph.Model; defaults:BulletGraph.Model; @@ -49308,6 +51591,7 @@ class Barcode extends ej.Widget { static fn: Barcode; constructor(element: JQuery, options?: Barcode.Model); constructor(element: Element, options?: Barcode.Model); + static Locale: any; model:Barcode.Model; defaults:Barcode.Model; @@ -49462,6 +51746,7 @@ class Map extends ej.Widget { static fn: Map; constructor(element: JQuery, options?: Map.Model); constructor(element: Element, options?: Map.Model); + static Locale: any; model:Map.Model; defaults:Map.Model; @@ -49703,6 +51988,36 @@ export interface NavigationControl { orientation?: ej.datavisualization.Map.LabelOrientation|string; } +export interface LayersBubbleSettingsColorMappingsRangeColorMapping { + + /** Start range colorMappings in the bubble layer. + * @Default {null} + */ + from?: number; + + /** End range colorMappings in the bubble layer. + * @Default {null} + */ + to?: number; + + /** GradientColors in the bubble layer of map. + */ + gradientColors?: Array; + + /** Color of the bubble layer. + * @Default {null} + */ + color?: string; +} + +export interface LayersBubbleSettingsColorMappings { + + /** Specifies the range colorMappings in the bubble layer. + * @Default {null} + */ + rangeColorMapping?: Array; +} + export interface LayersBubbleSettings { /** Specifies the bubble Opacity value of bubbles for shape layer in map @@ -49718,7 +52033,7 @@ export interface LayersBubbleSettings { /** Specifies the colorMappings of the shape layer in map * @Default {null} */ - colorMappings?: any; + colorMappings?: LayersBubbleSettingsColorMappings; /** Specifies the bubble color valuePath of the shape layer in map * @Default {null} @@ -49761,7 +52076,7 @@ export interface LayersLabelSettings { /** enable or disable the enableSmartLabel property * @Default {false} */ - enableSmartLabel?: boolean; + enableSmartLabel?: Boolean; /** set the labelLength property * @Default {'2'} @@ -50245,6 +52560,7 @@ class TreeMap extends ej.Widget { static fn: TreeMap; constructor(element: JQuery, options?: TreeMap.Model); constructor(element: Element, options?: TreeMap.Model); + static Locale: any; model:TreeMap.Model; defaults:TreeMap.Model; @@ -50516,7 +52832,7 @@ export interface LegendSettings { */ template?: string; - /** Specifies the mode for legendSettings whether defaul or interactive mode + /** Specifies the mode for legendSettings whether default or interactive mode * @Default {default} */ mode?: string; @@ -50776,6 +53092,7 @@ class Diagram extends ej.Widget { static fn: Diagram; constructor(element: JQuery, options?: Diagram.Model); constructor(element: Element, options?: Diagram.Model); + static Locale: any; model:Diagram.Model; defaults:Diagram.Model; @@ -50841,6 +53158,11 @@ class Diagram extends ej.Widget { */ clear(): void; + /** Clears the actions which is recorded to perform undo/redo operation in the diagram. + * @returns {void} + */ + clearHistory(): void; + /** Remove the current selection in diagram * @returns {void} */ @@ -50857,10 +53179,10 @@ class Diagram extends ej.Widget { cut(): void; /** Export the diagram as downloadable files or as data - * @param {Diagram.Options} options to export the desired region of diagram to the desired formats.NameTypeDescriptionfileNamestringname of the file to be downloaded.formatstringformat of the exported file/data. See [File Formats](/js/api/global#fileformats).modestringto set whether to export diagram as a file or as raw data. See [Export Modes](/js/api/global#exportmodes).regionstringto set the region of the diagram to be exported. See [Region](/js/api/global#region).boundsobjectto export any custom region of diagram.marginobjectto set margin to the exported data. - * @returns {string} + * @param {Diagram.Options} options to export the desired region of diagram to the desired formats.NameTypeDescriptionfileNamestringname of the file to be downloaded.formatstringformat of the exported file/data. See [File Formats](/api/js/global#fileformats).modestringto set whether to export diagram as a file or as raw data. See [Export Modes](/api/js/global#exportmodes).regionstringto set the region of the diagram to be exported. See [Region](/api/js/global#region).boundsobjectto export any custom region of diagram.marginobjectto set margin to the exported data. + * @returns {String} */ - exportDiagram(options?: Diagram.Options): string; + exportDiagram(options?: Diagram.Options): String; /** Read a node/connector object by its name * @param {string} name of the node/connector that is to be identified @@ -50869,8 +53191,8 @@ class Diagram extends ej.Widget { findNode(name: string): any; /** Fit the diagram content into diagram viewport - * @param {string} to set the mode of fit to command. See [Fit Mode](/js/api/global#fitmode) - * @param {string} to set whether the region to be fit will be based on diagram elements or page settings [Region](/js/api/global#region) + * @param {string} to set the mode of fit to command. See [Fit Mode](/api/js/global#fitmode) + * @param {string} to set whether the region to be fit will be based on diagram elements or page settings [Region](/api/js/global#region) * @param {any} to set the required margin * @returns {void} */ @@ -51093,15 +53415,15 @@ export interface Options { */ fileName?: string; - /** format of the exported file/data. See [File Formats](/js/api/global#fileformats). + /** format of the exported file/data. See [File Formats](/api/js/global#fileformats). */ format?: string; - /** to set whether to export diagram as a file or as raw data. See [Export Modes](/js/api/global#exportmodes). + /** to set whether to export diagram as a file or as raw data. See [Export Modes](/api/js/global#exportmodes). */ mode?: string; - /** to set the region of the diagram to be exported. See [Region](/js/api/global#region). + /** to set the region of the diagram to be exported. See [Region](/api/js/global#region). */ region?: string; @@ -51119,11 +53441,11 @@ export interface Model { /** Defines the background color of diagram elements * @Default {transparent} */ - backgroundColor?: string; + backgroundColor?: String; /** Defines the path of the background image of diagram elements */ - backgroundImage?: string; + backgroundImage?: String; /** Sets the direction of line bridges. * @Default {ej.datavisualization.Diagram.BridgeDirection.Top} @@ -51170,17 +53492,17 @@ export interface Model { /** Enables or disables auto scroll in diagram * @Default {true} */ - enableAutoScroll?: boolean; + enableAutoScroll?: Boolean; /** Enables or disables diagram context menu * @Default {true} */ - enableContextMenu?: boolean; + enableContextMenu?: Boolean; /** Specifies the height of the diagram * @Default {null} */ - height?: string; + height?: String; /** Customizes the undo redo functionality */ @@ -51193,7 +53515,7 @@ export interface Model { /** Defines the current culture of diagram * @Default {en-US} */ - locale?: string; + locale?: String; /** Array of JSON objects where each object represents a node * @Default {[]} @@ -51220,7 +53542,7 @@ export interface Model { /** Enables or disables tooltip of diagram * @Default {true} */ - showTooltip?: boolean; + showTooltip?: Boolean; /** Defines the gridlines and defines how and when the objects have to be snapped */ @@ -51239,12 +53561,12 @@ export interface Model { /** Specifies the width of the diagram * @Default {null} */ - width?: string; + width?: String; /** Sets the factor by which we can zoom in or zoom out * @Default {0.2} */ - zoomFactor?: number; + zoomFactor?: Number; /** Triggers When auto scroll is changed */ autoScrollChange? (e: AutoScrollChangeEventArgs): void; @@ -51288,6 +53610,9 @@ export interface Model { /** Triggers when a symbol is dragged and dropped from symbol palette to drawing area */ drop? (e: DropEventArgs): void; + /** Triggers when editor got focus at the time of node's label or text node editing. */ + editorFocusChange? (e: EditorFocusChangeEventArgs): void; + /** Triggers when a child is added to or removed from a group */ groupChange? (e: GroupChangeEventArgs): void; @@ -51339,6 +53664,10 @@ export interface AutoScrollChangeEventArgs { /** Returns the delay between subsequent auto scrolls */ delay?: string; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ClickEventArgs { @@ -51366,6 +53695,10 @@ export interface ClickEventArgs { /** parameter returns the actual click event arguments that explains which button is clicked */ event?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ConnectionChangeEventArgs { @@ -51385,6 +53718,10 @@ export interface ConnectionChangeEventArgs { /** parameter defines whether to cancel the change or not */ cancel?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ConnectorCollectionChangeEventArgs { @@ -51400,6 +53737,14 @@ export interface ConnectorCollectionChangeEventArgs { /** parameter defines whether to cancel the collection change or not */ cancel?: boolean; + + /** triggers before and after adding the connector in the diagram which can be differentiated through `state` argument. We can cancel the event only before adding the connector. + */ + state?: string; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ConnectorSourceChangeEventArgs { @@ -51427,6 +53772,10 @@ export interface ConnectorSourceChangeEventArgs { /** parameter defines whether to cancel the change or not */ cancel?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ConnectorTargetChangeEventArgs { @@ -51454,6 +53803,10 @@ export interface ConnectorTargetChangeEventArgs { /** parameter defines whether to cancel the change or not */ cancel?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ContextMenuBeforeOpenEventArgs { @@ -51469,6 +53822,10 @@ export interface ContextMenuBeforeOpenEventArgs { /** parameter returns the object that was clicked */ target?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ContextMenuClickEventArgs { @@ -51496,6 +53853,10 @@ export interface ContextMenuClickEventArgs { /** parameter defines whether to execute the click event or not */ canExecute?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface DoubleClickEventArgs { @@ -51507,6 +53868,10 @@ export interface DoubleClickEventArgs { /** parameter returns the selected object */ element?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface DragEventArgs { @@ -51530,6 +53895,10 @@ export interface DragEventArgs { /** parameter returns whether or not to cancel the drag event */ cancel?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface DragEnterEventArgs { @@ -51541,6 +53910,10 @@ export interface DragEnterEventArgs { /** parameter returns whether to add or remove the symbol from diagram */ cancel?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface DragLeaveEventArgs { @@ -51548,6 +53921,10 @@ export interface DragLeaveEventArgs { /** parameter returns the node or connector that is dragged outside of the diagram */ element?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface DragOverEventArgs { @@ -51575,6 +53952,10 @@ export interface DragOverEventArgs { /** parameter returns whether or not to cancel the dragOver event */ cancel?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface DropEventArgs { @@ -51597,7 +53978,14 @@ export interface DropEventArgs { /** parameter returns the enum which defines the type of the source */ - sourceType?: string; + sourceType?: String; + + /** parameter returns the id of the diagram + */ + diagramId?: string; +} + +export interface EditorFocusChangeEventArgs { } export interface GroupChangeEventArgs { @@ -51617,6 +54005,10 @@ export interface GroupChangeEventArgs { /** parameter returns the cause of group change("group", unGroup") */ cause?: string; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface HistoryChangeEventArgs { @@ -51628,6 +54020,10 @@ export interface HistoryChangeEventArgs { /** A collection of objects that are changed in the last undo/redo */ Source?: Array; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ItemClickEventArgs { @@ -51647,6 +54043,10 @@ export interface ItemClickEventArgs { /** parameter returns the actual click event arguments that explains which button is clicked */ event?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface MouseEnterEventArgs { @@ -51662,6 +54062,10 @@ export interface MouseEnterEventArgs { /** parameter returns the target object over which the selected object is dragged */ target?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface MouseLeaveEventArgs { @@ -51677,6 +54081,10 @@ export interface MouseLeaveEventArgs { /** parameter returns the target object over which the selected object is dragged */ target?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface MouseOverEventArgs { @@ -51692,6 +54100,10 @@ export interface MouseOverEventArgs { /** parameter returns the object over which the element is being dragged. */ target?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface NodeCollectionChangeEventArgs { @@ -51707,6 +54119,14 @@ export interface NodeCollectionChangeEventArgs { /** parameter defines whether to cancel the collection change or not */ cancel?: boolean; + + /** triggers before and after adding the node in the diagram which can be differentiated through `state` argument. We can cancel the event only before adding the node + */ + state?: string; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface PropertyChangeEventArgs { @@ -51717,7 +54137,7 @@ export interface PropertyChangeEventArgs { /** parameter returns the action is nudge or not */ - cause?: string; + cause?: String; /** parameter returns the new value of the node property that is being changed */ @@ -51730,6 +54150,10 @@ export interface PropertyChangeEventArgs { /** parameter returns the name of the property that is changed */ propertyName?: string; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface RotationChangeEventArgs { @@ -51749,6 +54173,10 @@ export interface RotationChangeEventArgs { /** parameter to specify whether or not to cancel the event */ cancel?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface ScrollChangeEventArgs { @@ -51760,6 +54188,10 @@ export interface ScrollChangeEventArgs { /** parameter returns the previous zoom value, horizontal and vertical scroll offsets. */ oldValues?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface SegmentChangeEventArgs { @@ -51779,6 +54211,10 @@ export interface SegmentChangeEventArgs { /** parameter to specify whether or not to cancel the event */ cancel?: boolean; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface SelectionChangeEventArgs { @@ -51806,6 +54242,14 @@ export interface SelectionChangeEventArgs { /** parameter to specify whether or not to cancel the selection change event */ cancel?: boolean; + + /** triggers before and after adding the selection to the object in the diagram which can be differentiated through `state` argument. We can cancel the event only before the selection of the object. + */ + state?: string; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface SizeChangeEventArgs { @@ -51833,6 +54277,10 @@ export interface SizeChangeEventArgs { /** parameter returns the difference between new and old value */ offset?: any; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface TextChangeEventArgs { @@ -51848,6 +54296,10 @@ export interface TextChangeEventArgs { /** parameter returns the keyCode of the key entered */ keyCode?: string; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface CreateEventArgs { @@ -51859,6 +54311,10 @@ export interface CreateEventArgs { /** Returns the name of the event */ type?: string; + + /** parameter returns the id of the diagram + */ + diagramId?: string; } export interface BackgroundImage { @@ -51867,16 +54323,6 @@ export interface BackgroundImage { * @Default {ej.datavisualization.Diagram.ImageAlignment.XMidYMid} */ alignment?: ej.datavisualization.Diagram.ImageAlignment |string; - - /** Defines how the background image should be scaled/stretched - * @Default {ej.datavisualization.Diagram.ScaleConstraints.Meet} - */ - scale?: ej.datavisualization.Diagram.ScaleConstraints |string; - - /** Sets the source path of the background image - * @Default {null} - */ - source?: string; } export interface CommandManagerCommandsGesture { @@ -51953,42 +54399,42 @@ export interface ConnectorsLabel { /** Enables/disables the bold style * @Default {false} */ - bold?: boolean; + bold?: Boolean; /** Sets the border color of the label * @Default {transparent} */ - borderColor?: string; + borderColor?: String; /** Sets the border width of the label * @Default {0} */ - borderWidth?: number; + borderWidth?: Number; /** Defines whether the label should be aligned within the connector boundaries * @Default {true} */ - boundaryConstraints?: boolean; + boundaryConstraints?: Boolean; /** Sets the fill color of the text area * @Default {transparent} */ - fillColor?: string; + fillColor?: String; /** Sets the font color of the text * @Default {black} */ - fontColor?: string; + fontColor?: String; /** Sets the font family of the text * @Default {Arial} */ - fontFamily?: string; + fontFamily?: String; /** Defines the font size of the text * @Default {12} */ - fontSize?: number; + fontSize?: Number; /** Sets the horizontal alignment of the label. * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} @@ -51998,7 +54444,7 @@ export interface ConnectorsLabel { /** Enables/disables the italic style * @Default {false} */ - italic?: boolean; + italic?: Boolean; /** Gets whether the label is currently being edited or not. * @Default {ej.datavisualization.Diagram.LabelEditMode.Edit} @@ -52007,7 +54453,7 @@ export interface ConnectorsLabel { /** Sets the unique identifier of the label */ - name?: string; + name?: String; /** Sets the fraction/ratio(relative to connector) that defines the position of the label * @Default {ej.datavisualization.Diagram.Point(0.5, 0.5)} @@ -52022,12 +54468,12 @@ export interface ConnectorsLabel { /** Defines the transparency of labels * @Default {1} */ - opacity?: number; + opacity?: Number; /** Defines whether the label is editable or not * @Default {false} */ - readOnly?: boolean; + readOnly?: Boolean; /** Defines whether the label should be positioned whether relative to segments or connector boundaries * @Default {ej.datavisualization.Diagram.LabelRelativeMode.SegmentPath} @@ -52037,16 +54483,16 @@ export interface ConnectorsLabel { /** Defines the angle to which the label needs to be rotated * @Default {0} */ - rotateAngle?: number; + rotateAngle?: Number; /** Sets the position of the label with respect to the total segment length * @Default {0.5} */ - segmentOffset?: string; + segmentOffset?: String; /** Defines the label text */ - text?: string; + text?: String; /** Defines how to align the text inside the label. * @Default {ej.datavisualization.Diagram.TextAlign.Center} @@ -52066,12 +54512,12 @@ export interface ConnectorsLabel { /** Enables or disables the visibility of the label * @Default {true} */ - visible?: boolean; + visible?: Boolean; /** Sets the width of the label(the maximum value of label width and the connector width will be considered as label width) * @Default {50} */ - width?: number; + width?: Number; /** Defines how the label text needs to be wrapped. * @Default {ej.datavisualization.Diagram.TextWrapping.WrapWithOverflow} @@ -52083,12 +54529,12 @@ export interface ConnectorsSegment { /** Sets the direction of orthogonal segment */ - direction?: string; + direction?: String; /** Describes the length of orthogonal segment * @Default {undefined} */ - length?: number; + length?: Number; /** Describes the end point of bezier/straight segment * @Default {Diagram.Point()} @@ -52121,6 +54567,41 @@ export interface ConnectorsSegment { vector2?: any; } +export interface ConnectorsShapeMultiplicitySource { + + /** Defines the source label to connector. Applicable, if the connector is of type "UML" + * @Default {true} + */ + optional?: boolean; + + /** Defines the source label to connector. Applicable, if the connector is of type "UML" + * @Default {null} + */ + lowerBounds?: Number; + + /** Defines the source label to connector. Applicable, if the connector is of type "UML" + * @Default {null} + */ + upperBounds?: Number; +} + +export interface ConnectorsShapeMultiplicity { + + /** Sets the type of the multiplicity. Applicable, if the connector is of type "classifier" + * @Default {ej.datavisualization.Diagram.Multiplicity.OneToOne} + */ + type?: ej.datavisualization.Diagram.Multiplicity|string; + + /** Defines the source label to connector. Applicable, if the connector is of type "UML" + */ + source?: ConnectorsShapeMultiplicitySource; + + /** Defines the target label to connector. Applicable, if the connector is of type "UML" + * @Default {true} + */ + target?: ej.datavisualization.Diagram.ConnectorsShapeMultiplicitySource|string; +} + export interface ConnectorsShape { /** Sets the type of the connector @@ -52151,11 +54632,12 @@ export interface ConnectorsShape { /** Defines the role of the connector in a UML Class Diagram. Applicable, if the type of the connector is "classifier". * @Default {ej.datavisualization.Diagram.ClassifierShapes.Association} */ - relationship?: string; + relationship?: ej.datavisualization.Diagram.ClassifierShapes|string; - /** Defines the multiplicity of a relationship in UML class diagram + /** Defines the multiplicity option of the connector + * @Default {null} */ - multiplicity?: string; + multiplicity?: ConnectorsShapeMultiplicity; } export interface ConnectorsSourceDecorator { @@ -52163,26 +54645,26 @@ export interface ConnectorsSourceDecorator { /** Sets the border color of the source decorator * @Default {black} */ - borderColor?: string; + borderColor?: String; /** Sets the border width of the decorator * @Default {1} */ - borderWidth?: number; + borderWidth?: Number; /** Sets the fill color of the source decorator * @Default {black} */ - fillColor?: string; + fillColor?: String; /** Sets the height of the source decorator * @Default {8} */ - height?: number; + height?: Number; /** Defines the custom shape of the source decorator */ - pathData?: string; + pathData?: String; /** Defines the shape of the source decorator. * @Default {ej.datavisualization.Diagram.DecoratorShapes.Arrow} @@ -52192,7 +54674,7 @@ export interface ConnectorsSourceDecorator { /** Defines the width of the source decorator * @Default {8} */ - width?: number; + width?: Number; } export interface ConnectorsSourcePoint { @@ -52200,12 +54682,12 @@ export interface ConnectorsSourcePoint { /** Defines the x-coordinate of a position * @Default {0} */ - x?: number; + x?: Number; /** Defines the y-coordinate of a position * @Default {0} */ - y?: number; + y?: Number; } export interface ConnectorsTargetDecorator { @@ -52213,21 +54695,21 @@ export interface ConnectorsTargetDecorator { /** Sets the border color of the decorator * @Default {black} */ - borderColor?: string; + borderColor?: String; /** Sets the color with which the decorator will be filled * @Default {black} */ - fillColor?: string; + fillColor?: String; /** Defines the height of the target decorator * @Default {8} */ - height?: number; + height?: Number; /** Defines the custom shape of the target decorator */ - pathData?: string; + pathData?: String; /** Defines the shape of the target decorator. * @Default {ej.datavisualization.Diagram.DecoratorShapes.Arrow} @@ -52237,7 +54719,7 @@ export interface ConnectorsTargetDecorator { /** Defines the width of the target decorator * @Default {8} */ - width?: number; + width?: Number; } export interface Connector { @@ -52250,7 +54732,7 @@ export interface Connector { /** Defines the width of the line bridges * @Default {10} */ - bridgeSpace?: number; + bridgeSpace?: Number; /** Enables or disables the behaviors of connectors. * @Default {ej.datavisualization.Diagram.ConnectorConstraints.Default} @@ -52260,11 +54742,11 @@ export interface Connector { /** Defines the radius of the rounded corner * @Default {0} */ - cornerRadius?: number; + cornerRadius?: Number; /** Configures the styles of shapes */ - cssClass?: string; + cssClass?: String; /** Sets the horizontal alignment of the connector. Applicable, if the parent of the connector is a container. * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Left} @@ -52279,50 +54761,50 @@ export interface Connector { /** Sets the stroke color of the connector * @Default {black} */ - lineColor?: string; + lineColor?: String; /** Sets the pattern of dashes and gaps used to stroke the path of the connector */ - lineDashArray?: string; + lineDashArray?: String; /** Defines the padding value to ease the interaction with connectors * @Default {10} */ - lineHitPadding?: number; + lineHitPadding?: Number; /** Sets the width of the line * @Default {1} */ - lineWidth?: number; + lineWidth?: Number; /** Defines the minimum space to be left between the bottom of parent bounds and the connector. Applicable, if the parent is a container. * @Default {0} */ - marginBottom?: number; + marginBottom?: Number; /** Defines the minimum space to be left between the left of parent bounds and the connector. Applicable, if the parent is a container. * @Default {0} */ - marginLeft?: number; + marginLeft?: Number; /** Defines the minimum space to be left between the right of parent bounds and the connector. Applicable, if the parent is a container. * @Default {0} */ - marginRight?: number; + marginRight?: Number; /** Defines the minimum space to be left between the top of parent bounds and the connector. Applicable, if the parent is a container. * @Default {0} */ - marginTop?: number; + marginTop?: Number; /** Sets a unique name for the connector */ - name?: string; + name?: String; /** Defines the transparency of the connector * @Default {1} */ - opacity?: number; + opacity?: Number; /** Defines the size and preview size of the node to add that to symbol palette. To explore palette item, refer Palette Item * @Default {null} @@ -52331,7 +54813,7 @@ export interface Connector { /** Sets the parent name of the connector. */ - parent?: string; + parent?: String; /** An array of JSON objects where each object represents a segment * @Default {[ { type:straight } ]} @@ -52350,12 +54832,12 @@ export interface Connector { /** Sets the source node of the connector */ - sourceNode?: string; + sourceNode?: String; /** Defines the space to be left between the source node and the source point of a connector * @Default {0} */ - sourcePadding?: number; + sourcePadding?: Number; /** Describes the start point of the connector * @Default {ej.datavisualization.Diagram.Point()} @@ -52364,7 +54846,7 @@ export interface Connector { /** Sets the source port of the connector */ - sourcePort?: string; + sourcePort?: String; /** Defines the target decorator of the connector * @Default {{ shape:arrow, width: 8, height:8, borderColor:black, fillColor:black }} @@ -52373,12 +54855,12 @@ export interface Connector { /** Sets the target node of the connector */ - targetNode?: string; + targetNode?: String; /** Defines the space to be left between the target node and the target point of the connector * @Default {0} */ - targetPadding?: number; + targetPadding?: Number; /** Describes the end point of the connector * @Default {ej.datavisualization.Diagram.Point()} @@ -52387,7 +54869,7 @@ export interface Connector { /** Sets the targetPort of the connector */ - targetPort?: string; + targetPort?: String; /** Defines the tooltip that should be shown when the mouse hovers over connector. For tooltip properties, refer Tooltip * @Default {null} @@ -52402,12 +54884,12 @@ export interface Connector { /** Enables or disables the visibility of connector * @Default {true} */ - visible?: boolean; + visible?: Boolean; /** Sets the z-index of the connector * @Default {0} */ - zOrder?: number; + zOrder?: Number; } export interface ContextMenu { @@ -52420,7 +54902,7 @@ export interface ContextMenu { /** To set whether to display the default context menu items or not * @Default {false} */ - showCustomMenuItemsOnly?: boolean; + showCustomMenuItemsOnly?: Boolean; } export interface DataSourceSettings { @@ -52432,26 +54914,26 @@ export interface DataSourceSettings { /** Sets the unique id of the data source items */ - id?: string; + id?: String; /** Defines the parent id of the data source item * @Default {''} */ - parent?: string; + parent?: String; /** Describes query to retrieve a set of data from the specified datasource * @Default {null} */ - query?: string; + query?: String; /** Sets the unique id of the root data source item */ - root?: string; + root?: String; /** Describes the name of the table on which the specified query has to be executed * @Default {null} */ - tableName?: string; + tableName?: String; } export interface DefaultSettings { @@ -52495,6 +54977,16 @@ export interface HistoryManager { */ redo?: Function; + /** The redoStack property is used to get the number of redo actions to be stored on the history manager. Its an read-only property and the collection should not be modified. + * @Default {[]} + */ + redoStack?: Array; + + /** The stackLimit property used to restrict the undo and redo actions to a certain limit. + * @Default {null} + */ + stackLimit?: Number; + /** A method that starts to group the changes to revert/restore them in a single undo or redo */ startGroupAction?: Function; @@ -52502,6 +54994,11 @@ export interface HistoryManager { /** Defines what should be happened while trying to revert a custom change */ undo?: Function; + + /** The undoStack property is used to get the number of undo actions to be stored on the history manager. Its an read-only property and the collection should not be modified. + * @Default {[]} + */ + undoStack?: Array; } export interface Layout { @@ -52513,7 +55010,7 @@ export interface Layout { /** Defines the fixed node with reference to which, the layout will be arranged and fixed node will not be repositioned */ - fixedNode?: string; + fixedNode?: String; /** Customizes the orientation of trees/sub trees. For orientations, see Chart Orientations. For chart types, see Chart Types * @Default {null} @@ -52523,7 +55020,7 @@ export interface Layout { /** Sets the space to be horizontally left between nodes * @Default {30} */ - horizontalSpacing?: number; + horizontalSpacing?: Number; /** Defines the space to be left between layout bounds and layout. * @Default {ej.datavisualization.Diagram.Margin()} @@ -52553,7 +55050,7 @@ export interface Layout { /** Sets the space to be vertically left between nodes * @Default {30} */ - verticalSpacing?: number; + verticalSpacing?: Number; } export interface NodesAnnotation { @@ -52561,7 +55058,7 @@ export interface NodesAnnotation { /** Sets the angle between the BPMN shape and the annotation * @Default {0} */ - angle?: number; + angle?: Number; /** Sets the direction of the text annotation * @Default {ej.datavisualization.Diagram.BPMNAnnotationDirections.Left} @@ -52571,37 +55068,37 @@ export interface NodesAnnotation { /** Sets the height of the text annotation * @Default {20} */ - height?: number; + height?: Number; /** Sets the distance between the BPMN shape and the annotation * @Default {0} */ - length?: number; + length?: Number; /** Defines the additional information about the flow object in a BPMN Process */ - text?: string; + text?: String; /** Sets the width of the text annotation * @Default {20} */ - width?: number; + width?: Number; } export interface NodesClassAttribute { /** Sets the name of the attribute */ - name?: string; + name?: String; /** Sets the data type of attribute */ - type?: string; + type?: String; /** Defines the visibility of the attribute * @Default {ej.datavisualization.Diagram.ScopeValueDefaults.Public} */ - scope?: string; + scope?: String; } export interface NodesClassMethod { @@ -52609,14 +55106,14 @@ export interface NodesClassMethod { /** Sets the visibility of the method. * @Default {ej.datavisualization.Diagram.ScopeValueDefaults.Public} */ - scope?: string; + scope?: String; } export interface NodesClass { /** Sets the name of class. */ - name?: string; + name?: String; /** Defines the collection of attributes * @Default {[]} @@ -52629,12 +55126,60 @@ export interface NodesClass { methods?: Array; } +export interface NodesCollapseIcon { + + /** Sets the border color for collapse icon of node + * @Default {black} + */ + borderColor?: String; + + /** Sets the border width for collapse icon of node + * @Default {1} + */ + borderWidth?: Number; + + /** Sets the fill color for collapse icon of node + * @Default {white} + */ + fillColor?: String; + + /** Defines the height for collapse icon of node + * @Default {15} + */ + height?: Number; + + /** Sets the horizontal alignment of the icon. + * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} + */ + horizontalAlignment?: ej.datavisualization.Diagram.HorizontalAlignment|string; + + /** To set the margin for the collapse icon of node + * @Default {ej.datavisualization.Diagram.Margin()} + */ + margin?: any; + + /** Sets the fraction/ratio(relative to node) that defines the position of the icon + * @Default {ej.datavisualization.Diagram.Point(0.5, 1)} + */ + offset?: any; + + /** Defines the shape of the collapsed state of the node. + * @Default {ej.datavisualization.Diagram.IconShapes.None} + */ + shape?: ej.datavisualization.Diagram.IconShapes|string; + + /** Sets the vertical alignment of the icon. + * @Default {ej.datavisualization.Diagram.VerticalAlignment.Center} + */ + verticalAlignment?: ej.datavisualization.Diagram.VerticalAlignment|string; +} + export interface NodesContainer { /** Defines the orientation of the container. Applicable, if the group is a container. * @Default {vertical} */ - orientation?: string; + orientation?: String; /** Sets the type of the container. Applicable if the group is a container. * @Default {ej.datavisualization.Diagram.ContainerType.Canvas} @@ -52652,21 +55197,21 @@ export interface NodesData { /** Defines whether the BPMN data object is a collection or not * @Default {false} */ - collection?: boolean; + collection?: Boolean; } export interface NodesEnumerationMember { /** Sets the name of the enumeration member */ - name?: string; + name?: String; } export interface NodesEnumeration { /** Sets the name of the Enumeration */ - name?: string; + name?: String; /** Defines the collection of enumeration members * @Default {[]} @@ -52674,6 +55219,54 @@ export interface NodesEnumeration { members?: Array; } +export interface NodesExpandIcon { + + /** Sets the border color for expand icon of node + * @Default {black} + */ + borderColor?: String; + + /** Sets the border width for expand icon of node + * @Default {1} + */ + borderWidth?: Number; + + /** Sets the fill color for expand icon of node + * @Default {white} + */ + fillColor?: String; + + /** Defines the height for expand icon of node + * @Default {15} + */ + height?: Number; + + /** Sets the horizontal alignment of the icon. + * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} + */ + horizontalAlignment?: ej.datavisualization.Diagram.HorizontalAlignment|string; + + /** To set the margin for the expand icon of node + * @Default {ej.datavisualization.Diagram.Margin()} + */ + margin?: any; + + /** Sets the fraction/ratio(relative to node) that defines the position of the icon + * @Default {ej.datavisualization.Diagram.Point(0.5, 1)} + */ + offset?: any; + + /** Defines the shape of the expanded state of the node. + * @Default {ej.datavisualization.Diagram.IconShapes.None} + */ + shape?: ej.datavisualization.Diagram.IconShapes|string; + + /** Sets the vertical alignment of the icon. + * @Default {ej.datavisualization.Diagram.VerticalAlignment.Center} + */ + verticalAlignment?: ej.datavisualization.Diagram.VerticalAlignment|string; +} + export interface NodesGradientLinearGradient { /** Defines the different colors and the region of color transitions @@ -52684,22 +55277,22 @@ export interface NodesGradientLinearGradient { /** Defines the left most position(relative to node) of the rectangular region that needs to be painted * @Default {0} */ - x1?: number; + x1?: Number; /** Defines the right most position(relative to node) of the rectangular region that needs to be painted * @Default {0} */ - x2?: number; + x2?: Number; /** Defines the top most position(relative to node) of the rectangular region that needs to be painted * @Default {0} */ - y1?: number; + y1?: Number; /** Defines the bottom most position(relative to node) of the rectangular region that needs to be painted * @Default {0} */ - y2?: number; + y2?: Number; } export interface NodesGradientRadialGradient { @@ -52707,22 +55300,22 @@ export interface NodesGradientRadialGradient { /** Defines the position of the outermost circle * @Default {0} */ - cx?: number; + cx?: Number; /** Defines the outer most circle of the radial gradient * @Default {0} */ - cy?: number; + cy?: Number; /** Defines the innermost circle of the radial gradient * @Default {0} */ - fx?: number; + fx?: Number; /** Defines the innermost circle of the radial gradient * @Default {0} */ - fy?: number; + fy?: Number; /** Defines the different colors and the region of color transitions. * @Default {[]} @@ -52734,17 +55327,17 @@ export interface NodesGradientStop { /** Sets the color to be filled over the specified region */ - color?: string; + color?: String; /** Sets the position where the previous color transition ends and a new color transition starts * @Default {0} */ - offset?: number; + offset?: Number; /** Describes the transparency level of the region * @Default {1} */ - opacity?: number; + opacity?: Number; } export interface NodesGradient { @@ -52766,29 +55359,29 @@ export interface NodesInterfaceAttribute { /** Sets the name of the attribute */ - name?: string; + name?: String; /** Sets the type of the attribute */ - type?: string; + type?: String; /** Sets the visibility of the attribute */ - scope?: string; + scope?: String; } export interface NodesInterfaceMethod { /** Sets the visibility of the method */ - scope?: string; + scope?: String; } export interface NodesInterface { /** Sets the name of the interface */ - name?: string; + name?: String; /** Defines a collection of attributes of the interface * @Default {[]} @@ -52806,37 +55399,37 @@ export interface NodesLabel { /** Enables/disables the bold style * @Default {false} */ - bold?: boolean; + bold?: Boolean; /** Sets the border color of the label * @Default {transparent} */ - borderColor?: string; + borderColor?: String; /** Sets the border width of the label * @Default {0} */ - borderWidth?: number; + borderWidth?: Number; /** Sets the fill color of the text area * @Default {transparent} */ - fillColor?: string; + fillColor?: String; /** Sets the font color of the text * @Default {black} */ - fontColor?: string; + fontColor?: String; /** Sets the font family of the text * @Default {Arial} */ - fontFamily?: string; + fontFamily?: String; /** Defines the font size of the text * @Default {12} */ - fontSize?: number; + fontSize?: Number; /** Sets the horizontal alignment of the label. * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Center} @@ -52846,7 +55439,7 @@ export interface NodesLabel { /** Enables/disables the italic style * @Default {false} */ - italic?: boolean; + italic?: Boolean; /** To set the margin of the label * @Default {ej.datavisualization.Diagram.Margin()} @@ -52860,7 +55453,7 @@ export interface NodesLabel { /** Sets the unique identifier of the label */ - name?: string; + name?: String; /** Sets the fraction/ratio(relative to node) that defines the position of the label * @Default {ej.datavisualization.Diagram.Point(0.5, 0.5)} @@ -52870,21 +55463,21 @@ export interface NodesLabel { /** Defines the transparency of the labels * @Default {1} */ - opacity?: number; + opacity?: Number; /** Defines whether the label is editable or not * @Default {false} */ - readOnly?: boolean; + readOnly?: Boolean; /** Defines the angle to which the label needs to be rotated * @Default {0} */ - rotateAngle?: number; + rotateAngle?: Number; /** Defines the label text */ - text?: string; + text?: String; /** Defines how to align the text inside the label. * @Default {ej.datavisualization.Diagram.TextAlign.Center} @@ -52904,12 +55497,12 @@ export interface NodesLabel { /** Enables or disables the visibility of the label * @Default {true} */ - visible?: boolean; + visible?: Boolean; /** Sets the width of the label(the maximum value of label width and the node width will be considered as label width) * @Default {50} */ - width?: number; + width?: Number; /** Defines how the label text needs to be wrapped. * @Default {ej.datavisualization.Diagram.TextWrapping.WrapWithOverflow} @@ -52947,7 +55540,7 @@ export interface NodesLane { /** Defines the fill color of the lane * @Default {white} */ - fillColor?: string; + fillColor?: String; /** Defines the header of the lane * @Default {{ text: Function, fontSize: 11 }} @@ -52957,16 +55550,16 @@ export interface NodesLane { /** Defines the object as a lane * @Default {false} */ - isLane?: boolean; + isLane?: Boolean; /** Sets the unique identifier of the lane */ - name?: string; + name?: String; /** Sets the orientation of the lane. * @Default {vertical} */ - orientation?: string; + orientation?: String; } export interface NodesPaletteItem { @@ -52974,12 +55567,12 @@ export interface NodesPaletteItem { /** Defines whether the symbol should be drawn at its actual size regardless of precedence factors or not * @Default {true} */ - enableScale?: boolean; + enableScale?: Boolean; /** Defines the height of the symbol * @Default {0} */ - height?: number; + height?: Number; /** Defines the margin of the symbol item * @Default {{ left: 4, right: 4, top: 4, bottom: 4 }} @@ -52989,17 +55582,17 @@ export interface NodesPaletteItem { /** Defines the preview height of the symbol * @Default {undefined} */ - previewHeight?: number; + previewHeight?: Number; /** Defines the preview width of the symbol * @Default {undefined} */ - previewWidth?: number; + previewWidth?: Number; /** Defines the width of the symbol * @Default {0} */ - width?: number; + width?: Number; } export interface NodesPhase { @@ -53012,36 +55605,36 @@ export interface NodesPhase { /** Defines the line color of the splitter that splits adjacent phases. * @Default {#606060} */ - lineColor?: string; + lineColor?: String; /** Sets the dash array that used to stroke the phase splitter * @Default {3,3} */ - lineDashArray?: string; + lineDashArray?: String; /** Sets the lineWidth of the phase * @Default {1} */ - lineWidth?: number; + lineWidth?: Number; /** Sets the unique identifier of the phase */ - name?: string; + name?: String; /** Sets the length of the smaller region(phase) of a swimlane * @Default {100} */ - offset?: number; + offset?: Number; /** Sets the orientation of the phase * @Default {horizontal} */ - orientation?: string; + orientation?: String; /** Sets the type of the object as phase * @Default {phase} */ - type?: string; + type?: String; } export interface NodesPort { @@ -53049,17 +55642,17 @@ export interface NodesPort { /** Sets the border color of the port * @Default {#1a1a1a} */ - borderColor?: string; + borderColor?: String; /** Sets the stroke width of the port * @Default {1} */ - borderWidth?: number; + borderWidth?: Number; /** Defines the space to be left between the port bounds and its incoming and outgoing connections. * @Default {0} */ - connectorPadding?: number; + connectorPadding?: Number; /** Defines whether connections can be created with the port * @Default {ej.datavisualization.Diagram.PortConstraints.Connect} @@ -53069,11 +55662,11 @@ export interface NodesPort { /** Sets the fill color of the port * @Default {white} */ - fillColor?: string; + fillColor?: String; /** Sets the unique identifier of the port */ - name?: string; + name?: String; /** Defines the position of the port as fraction/ ratio relative to node * @Default {ej.datavisualization.Diagram.Point(0, 0)} @@ -53082,7 +55675,7 @@ export interface NodesPort { /** Defines the path data to draw the port. Applicable, if the port shape is path. */ - pathData?: string; + pathData?: String; /** Defines the shape of the port. * @Default {ej.datavisualization.Diagram.PortShapes.Square} @@ -53092,7 +55685,7 @@ export interface NodesPort { /** Defines the size of the port * @Default {8} */ - size?: number; + size?: Number; /** Defines when the port should be visible. * @Default {ej.datavisualization.Diagram.PortVisibility.Default} @@ -53105,17 +55698,17 @@ export interface NodesShadow { /** Defines the angle of the shadow relative to node * @Default {45} */ - angle?: number; + angle?: Number; /** Sets the distance to move the shadow relative to node * @Default {5} */ - distance?: number; + distance?: Number; /** Defines the opaque of the shadow * @Default {0.7} */ - opacity?: number; + opacity?: Number; } export interface NodesSubProcess { @@ -53123,7 +55716,7 @@ export interface NodesSubProcess { /** Defines whether the BPMN sub process is without any prescribed order or not * @Default {false} */ - adhoc?: boolean; + adhoc?: Boolean; /** Sets the boundary of the BPMN process * @Default {ej.datavisualization.Diagram.BPMNBoundary.Default} @@ -53133,12 +55726,12 @@ export interface NodesSubProcess { /** Sets whether the BPMN subprocess is triggered as a compensation of a specific activity * @Default {false} */ - compensation?: boolean; + compensation?: Boolean; /** Sets whether the BPMN subprocess is triggered as a collapsed of a specific activity * @Default {true} */ - collapsed?: boolean; + collapsed?: Boolean; /** Sets the type of the event by which the sub-process will be triggered * @Default {ej.datavisualization.Diagram.BPMNEvents.Start} @@ -53154,6 +55747,11 @@ export interface NodesSubProcess { */ loop?: ej.datavisualization.Diagram.BPMNLoops|string; + /** Defines the children for BPMN's SubProcess + * @Default {[]} + */ + Processes?: Array; + /** Defines the type of the event trigger * @Default {ej.datavisualization.Diagram.BPMNTriggers.Message} */ @@ -53170,12 +55768,12 @@ export interface NodesTask { /** To set whether the task is a global task or not * @Default {false} */ - call?: boolean; + call?: Boolean; /** Sets whether the task is triggered as a compensation of another specific activity * @Default {false} */ - compensation?: boolean; + compensation?: Boolean; /** Sets the loop type of a BPMN task. * @Default {ej.datavisualization.Diagram.BPMNLoops.None} @@ -53208,21 +55806,21 @@ export interface Node { /** Sets the border color of node * @Default {black} */ - borderColor?: string; + borderColor?: String; /** Sets the pattern of dashes and gaps to stroke the border */ - borderDashArray?: string; + borderDashArray?: String; /** Sets the border width of the node * @Default {1} */ - borderWidth?: number; + borderWidth?: Number; /** Defines whether the group can be ungrouped or not * @Default {true} */ - canUngroup?: boolean; + canUngroup?: Boolean; /** Array of JSON objects where each object represents a child node/connector * @Default {[]} @@ -53239,10 +55837,14 @@ export interface Node { */ class?: NodesClass; + /** Defines the state of the node is collapsed. + */ + collapseIcon?: NodesCollapseIcon; + /** Defines the distance to be left between a node and its connections(In coming and out going connections). * @Default {0} */ - connectorPadding?: number; + connectorPadding?: Number; /** Enables or disables the default behaviors of the node. * @Default {ej.datavisualization.Diagram.NodeConstraints.Default} @@ -53257,11 +55859,11 @@ export interface Node { /** Defines the corner radius of rectangular shapes. * @Default {0} */ - cornerRadius?: number; + cornerRadius?: Number; /** Configures the styles of shapes */ - cssClass?: string; + cssClass?: String; /** Defines the BPMN data object */ @@ -53280,12 +55882,16 @@ export interface Node { /** Defines whether the node can be automatically arranged using layout or not * @Default {false} */ - excludeFromLayout?: boolean; + excludeFromLayout?: Boolean; + + /** Defines the state of the node is expanded or collapsed. + */ + expandIcon?: NodesExpandIcon; /** Defines the fill color of the node * @Default {white} */ - fillColor?: string; + fillColor?: String; /** Sets the type of the BPMN Gateway. Applicable, if the node is a BPMN gateway. * @Default {ej.datavisualization.Diagram.BPMNGateways.None} @@ -53309,7 +55915,7 @@ export interface Node { /** Defines the height of the node * @Default {0} */ - height?: number; + height?: Number; /** Sets the horizontal alignment of the node. Applicable, if the parent of the node is a container. * @Default {ej.datavisualization.Diagram.HorizontalAlignment.Left} @@ -53329,12 +55935,12 @@ export interface Node { /** Defines whether the sub tree of the node is expanded or collapsed * @Default {true} */ - isExpanded?: boolean; + isExpanded?: Boolean; /** Sets the node as a swimlane * @Default {false} */ - isSwimlane?: boolean; + isSwimlane?: Boolean; /** A collection of objects where each object represents a label * @Default {[]} @@ -53349,66 +55955,66 @@ export interface Node { /** Defines the minimum space to be left between the bottom of parent bounds and the node. Applicable, if the parent is a container. * @Default {0} */ - marginBottom?: number; + marginBottom?: Number; /** Defines the minimum space to be left between the left of parent bounds and the node. Applicable, if the parent is a container. * @Default {0} */ - marginLeft?: number; + marginLeft?: Number; /** Defines the minimum space to be left between the right of the parent bounds and the node. Applicable, if the parent is a container. * @Default {0} */ - marginRight?: number; + marginRight?: Number; /** Defines the minimum space to be left between the top of parent bounds and the node. Applicable, if the parent is a container. * @Default {0} */ - marginTop?: number; + marginTop?: Number; /** Defines the maximum height limit of the node * @Default {0} */ - maxHeight?: number; + maxHeight?: Number; /** Defines the maximum width limit of the node * @Default {0} */ - maxWidth?: number; + maxWidth?: Number; /** Defines the minimum height limit of the node * @Default {0} */ - minHeight?: number; + minHeight?: Number; /** Defines the minimum width limit of the node * @Default {0} */ - minWidth?: number; + minWidth?: Number; /** Sets the unique identifier of the node */ - name?: string; + name?: String; /** Defines the position of the node on X-Axis * @Default {0} */ - offsetX?: number; + offsetX?: Number; /** Defines the position of the node on Y-Axis * @Default {0} */ - offsetY?: number; + offsetY?: Number; /** Defines the opaque of the node * @Default {1} */ - opacity?: number; + opacity?: Number; /** Defines the orientation of nodes. Applicable, if the node is a swimlane. * @Default {vertical} */ - orientation?: string; + orientation?: String; /** A read only collection of outgoing connectors/edges of the node * @Default {[]} @@ -53418,22 +56024,22 @@ export interface Node { /** Defines the minimum padding value to be left between the bottom most position of a group and its children. Applicable, if the group is a container. * @Default {0} */ - paddingBottom?: number; + paddingBottom?: Number; /** Defines the minimum padding value to be left between the left most position of a group and its children. Applicable, if the group is a container. * @Default {0} */ - paddingLeft?: number; + paddingLeft?: Number; /** Defines the minimum padding value to be left between the right most position of a group and its children. Applicable, if the group is a container. * @Default {0} */ - paddingRight?: number; + paddingRight?: Number; /** Defines the minimum padding value to be left between the top most position of a group and its children. Applicable, if the group is a container. * @Default {0} */ - paddingTop?: number; + paddingTop?: Number; /** Defines the size and preview size of the node to add that to symbol palette * @Default {null} @@ -53442,11 +56048,11 @@ export interface Node { /** Sets the name of the parent group */ - parent?: string; + parent?: String; /** Sets the path geometry that defines the shape of a path node */ - pathData?: string; + pathData?: String; /** An array of objects, where each object represents a smaller region(phase) of a swimlane. * @Default {[]} @@ -53456,7 +56062,7 @@ export interface Node { /** Sets the height of the phase headers * @Default {0} */ - phaseSize?: number; + phaseSize?: Number; /** Sets the ratio/ fractional value relative to node, based on which the node will be transformed(positioning, scaling and rotation) * @Default {ej.datavisualization.Diagram.Points(0.5,0.5)} @@ -53476,12 +56082,7 @@ export interface Node { /** Sets the angle to which the node should be rotated * @Default {0} */ - rotateAngle?: number; - - /** Defines how the node should be scaled/stretched - * @Default {ej.datavisualization.Diagram.ScaleConstraints.Meet} - */ - scale?: ej.datavisualization.Diagram.ScaleConstraints |string; + rotateAngle?: Number; /** Defines the opacity and the position of shadow * @Default {ej.datavisualization.Diagram.Shadow()} @@ -53495,7 +56096,7 @@ export interface Node { /** Sets the source path of the image. Applicable, if the type of the node is image. */ - source?: string; + source?: String; /** Defines the sub process of a BPMN Activity. Applicable, if the type of the BPMN activity is sub process. * @Default {ej.datavisualization.Diagram.BPMNSubProcess()} @@ -53509,7 +56110,7 @@ export interface Node { /** Sets the id of svg/html templates. Applicable, if the node is HTML or native. */ - templateId?: string; + templateId?: String; /** Defines the textBlock of a text node * @Default {null} @@ -53539,17 +56140,17 @@ export interface Node { /** Defines the visibility of the node * @Default {true} */ - visible?: boolean; + visible?: Boolean; /** Defines the width of the node * @Default {0} */ - width?: number; + width?: Number; /** Defines the z-index of the node * @Default {0} */ - zOrder?: number; + zOrder?: Number; } export interface PageSettings { @@ -53562,32 +56163,32 @@ export interface PageSettings { /** Sets whether multiple pages can be created to fit all nodes and connectors * @Default {false} */ - multiplePage?: boolean; + multiplePage?: Boolean; /** Defines the background color of diagram pages * @Default {#ffffff} */ - pageBackgroundColor?: string; + pageBackgroundColor?: String; /** Defines the page border color * @Default {#565656} */ - pageBorderColor?: string; + pageBorderColor?: String; /** Sets the border width of diagram pages * @Default {0} */ - pageBorderWidth?: number; + pageBorderWidth?: Number; /** Defines the height of a page * @Default {null} */ - pageHeight?: number; + pageHeight?: Number; /** Defines the page margin * @Default {24} */ - pageMargin?: number; + pageMargin?: Number; /** Sets the orientation of the page. * @Default {ej.datavisualization.Diagram.PageOrientations.Portrait} @@ -53597,7 +56198,7 @@ export interface PageSettings { /** Defines the height of a diagram page * @Default {null} */ - pageWidth?: number; + pageWidth?: Number; /** Defines the scrollable area of diagram. Applicable, if the scroll limit is "limited". * @Default {null} @@ -53617,7 +56218,7 @@ export interface PageSettings { /** Enables or disables the page breaks * @Default {false} */ - showPageBreak?: boolean; + showPageBreak?: Boolean; } export interface ScrollSettings { @@ -53625,12 +56226,12 @@ export interface ScrollSettings { /** Allows to read the zoom value of diagram * @Default {0} */ - currentZoom?: number; + currentZoom?: Number; /** Sets the horizontal scroll offset * @Default {0} */ - horizontalOffset?: number; + horizontalOffset?: Number; /** Allows to extend the scrollable region that is based on the scroll limit * @Default {{left: 0, right: 0, top:0, bottom: 0}} @@ -53640,17 +56241,17 @@ export interface ScrollSettings { /** Sets the vertical scroll offset * @Default {0} */ - verticalOffset?: number; + verticalOffset?: Number; /** Allows to read the view port height of the diagram * @Default {0} */ - viewPortHeight?: number; + viewPortHeight?: Number; /** Allows to read the view port width of the diagram * @Default {0} */ - viewPortWidth?: number; + viewPortWidth?: Number; } export interface SelectedItemsUserHandle { @@ -53658,26 +56259,26 @@ export interface SelectedItemsUserHandle { /** Defines the background color of the user handle * @Default {#2382c3} */ - backgroundColor?: string; + backgroundColor?: String; /** Sets the border color of the user handle * @Default {transparent} */ - borderColor?: string; + borderColor?: String; /** Defines whether the user handle should be added, when more than one element is selected * @Default {false} */ - enableMultiSelection?: boolean; + enableMultiSelection?: Boolean; /** Sets the stroke color of the user handle * @Default {transparent} */ - pathColor?: string; + pathColor?: String; /** Defines the custom shape of the user handle */ - pathData?: string; + pathData?: String; /** Defines the position of the user handle * @Default {ej.datavisualization.Diagram.UserHandlePositions.BottomCenter} @@ -53687,7 +56288,7 @@ export interface SelectedItemsUserHandle { /** Defines the size of the user handle * @Default {8} */ - size?: number; + size?: Number; /** Defines the interactive behaviors of the user handle */ @@ -53696,7 +56297,7 @@ export interface SelectedItemsUserHandle { /** Defines the visibility of the user handle * @Default {true} */ - visible?: boolean; + visible?: Boolean; } export interface SelectedItems { @@ -53719,22 +56320,22 @@ export interface SelectedItems { /** Sets the height of the selected items * @Default {0} */ - height?: number; + height?: Number; /** Sets the x position of the selector * @Default {0} */ - offsetX?: number; + offsetX?: Number; /** Sets the y position of the selector * @Default {0} */ - offsetY?: number; + offsetY?: Number; /** Sets the angle to rotate the selected items * @Default {0} */ - rotateAngle?: number; + rotateAngle?: Number; /** Sets the angle to rotate the selected items. For tooltip properties, refer Tooltip * @Default {ej.datavisualization.Diagram.Tooltip()} @@ -53749,7 +56350,7 @@ export interface SelectedItems { /** Sets the width of the selected items * @Default {0} */ - width?: number; + width?: Number; } export interface SnapSettingsHorizontalGridLines { @@ -53757,11 +56358,11 @@ export interface SnapSettingsHorizontalGridLines { /** Defines the line color of horizontal grid lines * @Default {lightgray} */ - lineColor?: string; + lineColor?: String; /** Specifies the pattern of dashes and gaps used to stroke horizontal grid lines */ - lineDashArray?: string; + lineDashArray?: String; /** A pattern of lines and gaps that defines a set of horizontal gridlines * @Default {[1.25, 18.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75]} @@ -53779,11 +56380,11 @@ export interface SnapSettingsVerticalGridLines { /** Defines the line color of horizontal grid lines * @Default {lightgray} */ - lineColor?: string; + lineColor?: String; /** Specifies the pattern of dashes and gaps used to stroke horizontal grid lines */ - lineDashArray?: string; + lineDashArray?: String; /** A pattern of lines and gaps that defines a set of horizontal gridlines * @Default {[1.25, 18.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75, 0.25, 19.75]} @@ -53801,7 +56402,7 @@ export interface SnapSettings { /** Enables or disables snapping nodes/connectors to objects * @Default {true} */ - enableSnapToObject?: boolean; + enableSnapToObject?: Boolean; /** Defines the appearance of horizontal gridlines */ @@ -53810,7 +56411,7 @@ export interface SnapSettings { /** Defines the angle by which the object needs to be snapped * @Default {5} */ - snapAngle?: number; + snapAngle?: Number; /** Defines and sets the snapConstraints */ @@ -53819,7 +56420,7 @@ export interface SnapSettings { /** Defines the minimum distance between the selected object and the nearest object * @Default {5} */ - snapObjectDistance?: number; + snapObjectDistance?: Number; /** Defines the appearance of horizontal gridlines */ @@ -53857,7 +56458,7 @@ export interface Tooltip { /** Sets the svg/html template to be bound with tooltip */ - templateId?: string; + templateId?: String; } } module Diagram @@ -53888,18 +56489,6 @@ XMaxYMax, } module Diagram { -enum ScaleConstraints -{ -//Used to scale the image non-uniformly to the given width/height -None, -//Used to scale the image uniformly so that it fits the viewport -Meet, -//Used to scale the image uniformly to the maximum -Slice, -} -} -module Diagram -{ enum BridgeDirection { //Used to set the direction of line bridges as left @@ -54048,6 +56637,8 @@ DragLabel, InheritBridging, //Enables user interaction to the connector PointerEvents, +//Enables the contrast between clean edges of connector over rendering speed and geometric precision +CrispEdges, //Enables all constraints Default, } @@ -54158,6 +56749,42 @@ Default, } module Diagram { +enum ClassifierShapes +{ +//Used to define a Class +Class, +//Used to define an Interface +Interface, +//Used to define an Enumeration +Enumeration, +//Used to notate association in UML Class Diagram +Association, +//Used to notate aggregation in a UML Class Diagram +Aggregation, +//Used to notate composition in a UML Class Diagram +Composition, +//Used to notate dependency in a UML Class Diagram +Dependency, +//Used to notate inheritance in a UML Class Diagram +Inheritance, +} +} +module Diagram +{ +enum Multiplicity +{ +//Each entity instance is related to a single instance of another entity +OneToOne, +//An entity instance can be related to multiple instances of the other entities +OneToMany, +//Multiple instances of an entity can be related to a single instance of the other entity +ManyToOne, +//The entity instances can be related to multiple instances of each other +ManyToMany, +} +} +module Diagram +{ enum DecoratorShapes { //Used to set decorator shape as none @@ -54206,6 +56833,8 @@ PannableY, Pannable, //Enables/Disables undo actions Undoable, +//Enables/Disables the sharp edges +CrispEdges, //Enables all Constraints Default, } @@ -54264,14 +56893,22 @@ Bottom, } module Diagram { -enum ClassifierShapes +enum IconShapes { -//Used to define a Class -Class, -//Used to define an Interface -Interface, -//Used to define an Enumeration -Enumeration, +//Used to set collapse icon shape as none +None, +//Used to set collapse icon shape as Arrow(Up/Down) +Arrow, +//Used to set collapse icon shape as Plus +Plus, +//Used to set collapse icon shape as Minus +Minus, +//Used to set collapse icon shape as path +Path, +//Used to set icon shape as template +Template, +//Used to set icon shape as image +Image, } } module Diagram @@ -54318,6 +56955,8 @@ AllowPan, AspectRatio, //Enables the user interaction with the node PointerEvents, +//Enables contrast between clean edges for the node over rendering speed and geometric precision +CrispEdges, //Enables all node constraints Default, } @@ -54440,6 +57079,8 @@ enum PortConstraints None, //Enables connections with connector Connect, +//Enables to create the connection when mouse hover on the port. +ConnectOnDrag, } } module Diagram @@ -54747,6 +57388,7 @@ class HeatMap extends ej.Widget { static fn: HeatMap; constructor(element: JQuery, options?: HeatMap.Model); constructor(element: Element, options?: HeatMap.Model); + static Locale: any; model:HeatMap.Model; defaults:HeatMap.Model; } @@ -54767,7 +57409,7 @@ export interface Model { /** Specifies the name of the heat map. * @Default {null} */ - id?: number; + id?: Number; /** Specifies the source data of the heat map. * @Default {[]} @@ -54782,12 +57424,12 @@ export interface Model { /** Specifies can enable responsive mode or not for heat map. * @Default {false} */ - isResponsive?: boolean; + isResponsive?: Boolean; /** Specifies whether the virtualization can be enable or not. * @Default {false} */ - enableVirtualization?: boolean; + enableVirtualization?: Boolean; /** Specifies the default column properties for all the column style not specified in column properties. * @Default {[]} @@ -54892,7 +57534,7 @@ export interface HeatMapCell { /** Specifies whether the cell color can be visible or not. * @Default {true} */ - showColor?: boolean; + showColor?: Boolean; } export interface DefaultColumnStyle { @@ -54904,11 +57546,11 @@ export interface DefaultColumnStyle { /** Specifies the template id of the heat map column header. */ - headerTemplateID?: string; + headerTemplateID?: String; /** Specifies the template id of all individual cell data of the heat map. */ - templateID?: string; + templateID?: String; } export interface ItemsMappingColumnStyle { @@ -54916,7 +57558,7 @@ export interface ItemsMappingColumnStyle { /** Specifies the width of the heat map column. * @Default {0} */ - width?: number; + width?: Number; /** Specifies the text align mode of the heat map column. * @Default {ej.HeatMap.TextAlign.Center} @@ -55019,16 +57661,16 @@ export interface ColorMappingCollectionLabel { /** Enables/disables the bold style of the heat map label. * @Default {false} */ - bold?: boolean; + bold?: Boolean; /** Enables/disables the italic style of the heat map label. * @Default {false} */ - italic?: boolean; + italic?: Boolean; /** specifies the text value of the heat map label. */ - text?: string; + text?: String; /** Specifies the text style of the heat map label. * @Default {ej.HeatMap.TextDecoration.None} @@ -55038,17 +57680,17 @@ export interface ColorMappingCollectionLabel { /** Specifies the font size of the heat map label. * @Default {10} */ - fontSize?: number; + fontSize?: Number; /** Specifies the font family of the heat map label. * @Default {Arial} */ - fontFamily?: string; + fontFamily?: String; /** Specifies the font color of the heat map label. * @Default {black} */ - fontColor?: string; + fontColor?: String; } export interface ColorMappingCollection { @@ -55056,12 +57698,12 @@ export interface ColorMappingCollection { /** Specifies the color of the heat map column data. * @Default {white} */ - color?: string; + color?: String; /** Specifies the color values of the heat map column data. * @Default {0} */ - value?: number; + value?: Number; /** Specifies the label properties of the heat map color. * @Default {null} @@ -55098,6 +57740,7 @@ class HeatMapLegend extends ej.Widget { static fn: HeatMapLegend; constructor(element: JQuery, options?: HeatMapLegend.Model); constructor(element: Element, options?: HeatMapLegend.Model); + static Locale: any; model:HeatMapLegend.Model; defaults:HeatMapLegend.Model; } @@ -55118,12 +57761,12 @@ export interface Model { /** Specifies can enable responsive mode or not for heatmap legend. * @Default {false} */ - isResponsive?: boolean; + isResponsive?: Boolean; /** Specifies whether the cell label can be shown or not. * @Default {false} */ - showLabel?: boolean; + showLabel?: Boolean; /** Specifies the color values of the column data. * @Default {[]} @@ -55146,16 +57789,16 @@ export interface ColorMappingCollectionLabel { /** Enables/disables the bold style of the heatmap legend label. * @Default {false} */ - bold?: boolean; + bold?: Boolean; /** Enables/disables the italic style of the heatmap legend label. * @Default {false} */ - italic?: boolean; + italic?: Boolean; /** specifies the text value of the heatmap legend label. */ - text?: string; + text?: String; /** Specifies the text style of the heatmap legend label. * @Default {ej.HeatMap.TextDecoration.None} @@ -55165,17 +57808,17 @@ export interface ColorMappingCollectionLabel { /** Specifies the font size of the heatmap legend label. * @Default {10} */ - fontSize?: number; + fontSize?: Number; /** Specifies the font family of the heatmap legend label. * @Default {Arial} */ - fontFamily?: string; + fontFamily?: String; /** Specifies the font color of the heatmap legend label. * @Default {black} */ - fontColor?: string; + fontColor?: String; } export interface ColorMappingCollection { @@ -55183,12 +57826,12 @@ export interface ColorMappingCollection { /** Specifies the color of the heatmap legend data. * @Default {white} */ - color?: string; + color?: String; /** Specifies the color values of the heatmap legend column data. * @Default {0} */ - value?: number; + value?: Number; /** Specifies the label properties of the heatmap legend color. * @Default {null} @@ -55221,6 +57864,7 @@ class Sparkline extends ej.Widget { static fn: Sparkline; constructor(element: JQuery, options?: Sparkline.Model); constructor(element: Element, options?: Sparkline.Model); + static Locale: any; model:Sparkline.Model; defaults:Sparkline.Model; @@ -55817,6 +58461,7 @@ class Overview extends ej.Widget { static fn: Overview; constructor(element: JQuery, options?: Overview.Model); constructor(element: Element, options?: Overview.Model); + static Locale: any; model:Overview.Model; defaults:Overview.Model; } @@ -55827,17 +58472,17 @@ export interface Model { /** The sourceId property of overview should be set with the corresponding Diagram ID for you need the overall view. * @Default {null} */ - sourceID?: string; + sourceID?: String; /** Defines the height of the overview * @Default {400} */ - height?: number; + height?: Number; /** Defines the width of the overview * @Default {250} */ - width?: number; + width?: Number; } } @@ -55934,6 +58579,11 @@ ejDigitalGauge(options?: ej.datavisualization.DigitalGauge.Model): JQuery; ejDigitalGauge(memberName: any, value?: any, param?: any): any; data(key: "ejDigitalGauge"): ej.datavisualization.DigitalGauge; +ejDocumentEditor(): JQuery; +ejDocumentEditor(options?: ej.DocumentEditor.Model): JQuery; +ejDocumentEditor(memberName: any, value?: any, param?: any): any; +data(key: "ejDocumentEditor"): ej.DocumentEditor; + ejDraggable(): JQuery; ejDraggable(options?: ej.Draggable.Model): JQuery; ejDraggable(memberName: any, value?: any, param?: any): any; @@ -56139,6 +58789,11 @@ ejScroller(options?: ej.Scroller.Model): JQuery; ejScroller(memberName: any, value?: any, param?: any): any; data(key: "ejScroller"): ej.Scroller; +ejSignature(): JQuery; +ejSignature(options?: ej.Signature.Model): JQuery; +ejSignature(memberName: any, value?: any, param?: any): any; +data(key: "ejSignature"): ej.Signature; + ejSlider(): JQuery; ejSlider(options?: ej.Slider.Model): JQuery; ejSlider(memberName: any, value?: any, param?: any): any; @@ -56149,6 +58804,11 @@ ejSparkline(options?: ej.datavisualization.Sparkline.Model): JQuery; ejSparkline(memberName: any, value?: any, param?: any): any; data(key: "ejSparkline"): ej.datavisualization.Sparkline; +ejSpellCheck(): JQuery; +ejSpellCheck(options?: ej.SpellCheck.Model): JQuery; +ejSpellCheck(memberName: any, value?: any, param?: any): any; +data(key: "ejSpellCheck"): ej.SpellCheck; + ejSplitButton(): JQuery; ejSplitButton(options?: ej.SplitButton.Model): JQuery; ejSplitButton(memberName: any, value?: any, param?: any): any; @@ -56234,3 +58894,4 @@ ejWaitingPopup(options?: ej.WaitingPopup.Model): JQuery; ejWaitingPopup(memberName: any, value?: any, param?: any): any; data(key: "ejWaitingPopup"): ej.WaitingPopup; } + diff --git a/ejs/index.d.ts b/ejs/index.d.ts index 8a5cd267f8..6bd3b397c9 100644 --- a/ejs/index.d.ts +++ b/ejs/index.d.ts @@ -11,7 +11,12 @@ declare namespace Ejs { function resolveInclude(name: string, filename: string): string; function compile(template: string, opts?: Options): (TemplateFunction); function render(template: string, data?: Data, opts?: Options): string; - function renderFile(path: string, data?: Data, opts?: Options, cb?: Function): any;// TODO RenderFileCallback return type + + type RenderFileCallback = (err: Error, str?: string) => T; + function renderFile(path: string, cb: RenderFileCallback): T; + function renderFile(path: string, data: Data, cb: RenderFileCallback): T; + function renderFile(path: string, data: Data, opts: Options, cb: RenderFileCallback): T; + function clearCache(): any; interface TemplateFunction { diff --git a/ejson/ejson-tests.ts b/ejson/ejson-tests.ts new file mode 100644 index 0000000000..1902849b3d --- /dev/null +++ b/ejson/ejson-tests.ts @@ -0,0 +1,55 @@ +import { + clone as importedClone, + parse as importedParse, + stringify as importedStringify, + toJSONValue as importedToJSONValue, + fromJSONValue as importedFromJSONValue, + isBinary as importedIsBinary, + newBinary as importedNewBinary, + equals as importedEquals +} from "ejson"; + +function testImportedClone() { + var obj: Object = { + a: "a" + }; + var retval: Object = importedClone(obj); + + var str: string = "as"; + var retval2: string = importedClone(str); +} + +function testParse() { + var str: string = '{a:"a"}'; + importedParse(str); +} + +function testStringify() { + var obj: any = {a:"a"}; + var retval: string = importedStringify(obj); +} + +function testToJSONValue() { + var obj: any = {a:"a"}; + var retval: string = importedToJSONValue(obj); +} + +function testFromJSONValue() { + var str: string = '{a:"a"}'; + importedFromJSONValue(str); +} + +function testIsBinary() { + var val: any = 'sasda'; + var retval: boolean = importedIsBinary(val); +} + +function testNewBinary() { + var retval: Uint8Array = importedNewBinary(3); +} + +function testEquals() { + var a: any; + var b: any; + var retval: boolean = importedEquals(a,b); +} \ No newline at end of file diff --git a/ejson/index.d.ts b/ejson/index.d.ts new file mode 100644 index 0000000000..d2882646eb --- /dev/null +++ b/ejson/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for ejson v2.1.2 +// Project: https://www.npmjs.com/package/ejson +// Definitions by: Shantanu Bhadoria +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface StringifyOptions { + canonical: boolean; + indent: boolean|number|string; +} + +interface CloneOptions { + keyOrderSensitive: boolean; +} + +export function clone(obj: T): T; +export function parse(str: string): any; +export function stringify(obj: any, options?: StringifyOptions): string; + +export function toJSONValue(obj: any): string; +export function fromJSONValue(obj: string): any; +export function isBinary(value: any): boolean; +export function newBinary(len: number): Uint8Array; +export function equals(a: any, b: any, options?: CloneOptions): boolean; diff --git a/ejson/tsconfig.json b/ejson/tsconfig.json new file mode 100644 index 0000000000..45ff41e26b --- /dev/null +++ b/ejson/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ejson-tests.ts" + ] +} \ No newline at end of file diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index f57ee926ce..62e45dfd58 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -1,4 +1,3 @@ - import elasticsearch = require("elasticsearch"); var client = new elasticsearch.Client({ @@ -15,8 +14,7 @@ client = new elasticsearch.Client({ }); client.ping({ - requestTimeout: 30000, - hello: "elasticsearch" + requestTimeout: 30000 }, function (error) { }); @@ -85,4 +83,140 @@ client.cluster.state({ client.cluster.stats({ ignore: 1 }, (err, response) => { -}); \ No newline at end of file +}); + +client.count({ + index: 'index_name' +}, function (error, response) { + // ... +}); + +client.count({ + index: 'index_name', + body: { + query: { + filtered: { + filter: { + terms: { + foo: ['bar'] + } + } + } + } + } +}, function (err, response) { + // ... +}); + +client.explain({ + // the document to test + index: 'myindex', + type: 'mytype', + id: '1', + + // the query to score it against + q: 'field:value' +}, function (error, response) { + // ... +}); + +client.explain({ + index: 'myindex', + type: 'mytype', + id: '1', + body: { + query: { + match: { title: 'test' } + } + } +}, function (error, response) { + // ... +}); + +client.index({ + index: 'myindex', + type: 'mytype', + id: '1', + body: { + title: 'Test 1', + tags: ['y', 'z'], + published: true, + } +}, function (error, response) { + +}); + +client.mget({ + body: { + docs: [ + { _index: 'indexA', _type: 'typeA', _id: '1' }, + { _index: 'indexB', _type: 'typeB', _id: '1' }, + { _index: 'indexC', _type: 'typeC', _id: '1' } + ] + } +}, function (error, response) { + // ... +}); + +client.mget({ + index: 'myindex', + type: 'mytype', + body: { + ids: [1, 2, 3] + } +}, function (error, response) { + // ... +}); + +client.search({ + index: 'myindex', + q: 'title:test' +}, function (error, response) { + // ... +}); + +client.search({ + index: 'myindex', + body: { + query: { + match: { + title: 'test' + } + }, + facets: { + tags: { + terms: { + field: 'tags' + } + } + } + } +}, function (error, response) { + // ... +}); + +client.suggest({ + index: 'myindex', + body: { + mysuggester: { + text: 'tset', + term: { + field: 'title' + } + } + } +}, function (error, response) { +}); + +client.indices.updateAliases({ + body: { + actions: [ + { remove: { index: 'logstash-2014.04', alias: 'logstash-current' } }, + { add: { index: 'logstash-2014.05', alias: 'logstash-current' } } + ] + } +}).then(function (response) { + // ... +}, function (error) { + // ... +}); diff --git a/elasticsearch/index.d.ts b/elasticsearch/index.d.ts index 26a9a1e880..d7df27565f 100644 --- a/elasticsearch/index.d.ts +++ b/elasticsearch/index.d.ts @@ -1,66 +1,91 @@ -// Type definitions for elasticsearch +// Type definitions for elasticsearch 5.0 // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin , Jeffery Grajkowski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { export class Client { constructor(params: ConfigOptions); - indices: Indices; - cluster: Cluster; cat: Cat; + cluster: Cluster; + indices: Indices; + ingest: Ingest; + nodes: Nodes; + snapshot: Snapshot; + tasks: Tasks; bulk(params: BulkIndexDocumentsParams): PromiseLike; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; - create(params: CreateDocumentParams): PromiseLike; - create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void; - delete(params: DeleteDocumentParams): PromiseLike; - delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void; + clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; + clearScroll(params: ClearScrollParams): PromiseLike; + count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; + count(params: CountParams): PromiseLike; + create(params: CreateDocumentParams): PromiseLike; + create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; + delete(params: DeleteDocumentParams): PromiseLike; + delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; + deleteByQuery(params: DeleteDocumentByQueryParams): PromiseLike; + deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; + deleteScript(params: DeleteScriptParams): PromiseLike; + deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; + deleteTemplate(params: DeleteTemplateParams): PromiseLike; + deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; exists(params: ExistsParams): PromiseLike; exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; + explain(params: ExplainParams): PromiseLike; + explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; + fieldStats(params: FieldStatsParams): PromiseLike; + fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): PromiseLike>; + getScript(params: GetScriptParams): PromiseLike; + getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; + getSource(params: GetSourceParams): PromiseLike; + getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; + getTemplate(params: GetTemplateParams): PromiseLike; + getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; index(params: IndexDocumentParams): PromiseLike; index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; + info(params: InfoParams): PromiseLike; + info(params: InfoParams, callback: (error: any, response: any) => void): void; mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; mget(params: MGetParams): PromiseLike>; msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; msearch(params: MSearchParams): PromiseLike>; + msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; + msearchTemplate(params: MSearchTemplateParams): PromiseLike>; + mtermvectors(params: MTermVectorsParams): PromiseLike; + mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; ping(params: PingParams): PromiseLike; ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; + putScript(params: PutScriptParams): PromiseLike; + putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; + putTemplate(params: PutTemplateParams): PromiseLike; + putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; + reindex(params: ReindexParams): PromiseLike; + reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; + reindexRethrottle(params: ReindexRethrottleParams): PromiseLike; + reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; + renderSearchTemplate(params: RenderSearchTemplateParams): PromiseLike; + renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; scroll(params: ScrollParams): PromiseLike; scroll(params: ScrollParams, callback: (error: any, response: any) => void): void; search(params: SearchParams): PromiseLike>; search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; + searchShards(params: SearchShardsParams): PromiseLike; + searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; + searchTemplate(params: SearchTemplateParams): PromiseLike; + searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; suggest(params: SuggestParams): PromiseLike; suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; + termvectors(params: TermvectorsParams): PromiseLike; + termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; update(params: UpdateDocumentParams): PromiseLike; update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; + updateByQuery(params: UpdateDocumentByQueryParams): PromiseLike; + updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: any) => void): void; } - export class Indices { - delete(params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void): void; - delete(params: IndicesDeleteParams): PromiseLike; - create(params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void): void; - create(params: IndicesCreateParams): PromiseLike; - exists(params: IndicesIndexExitsParams, callback: (error: any, response: any, status: any) => void): void; - exists(params: IndicesIndexExitsParams): PromiseLike; - existsType(params: IndicesIndexExitsParams & {type: string}, callback: (error: any, response: any, status: any) => void): void; - existsType(params: IndicesIndexExitsParams & {type: string}): PromiseLike; - get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; - get(params: IndicesGetParams): PromiseLike; - getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; - getAlias(params: IndicesGetAliasParams): PromiseLike; - putAlias(params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void): void; - putAlias(params: IndicesPutAliasParams): PromiseLike; - putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; - putTemplate(params: IndicesPutTemplateParams): PromiseLike; - putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any) => void): void; - putMapping(params: IndicesPutMappingParams): PromiseLike; - refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; - refresh(params: IndicesRefreshParams): PromiseLike; - } - - export interface ConfigOptions{ + export interface ConfigOptions { host?: any; hosts?: any; log?: any; @@ -100,103 +125,239 @@ declare module Elasticsearch { filterPath?: string | string[]; } + export interface ShardsResponse { + total: number; + successful: number; + failed: number; + } + + export type NameList = string | string[] | boolean; + export type DateLike = Date | number; + export type Refresh = boolean | "true" | "false" | "wait_for" | ""; + export type VersionType = "internal" | "external" | "external_gte" | "force"; + export type ExpandWildcards = "open" | "closed" | "none" | "all"; + export type DefaultOperator = "AND" | "OR"; + export interface BulkIndexDocumentsParams extends GenericParams { - refresh?: boolean; - routing? : string; - timeout?: number | Date; + waitForActiveShards?: string; + refresh?: Refresh; + routing?: string; + timeout?: DateLike; type?: string; - fields?: string | string[] | boolean; + fields?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + pipeline?: string; index?: string; } - export interface CreateDocumentParams extends GenericParams { - consistency?: "one" | "quorum" | "all"; - parent?: string; - refresh?: boolean; + export interface ClearScrollParams extends GenericParams { + scrollId: NameList; + } + + export interface CountParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + minScore?: number; + preference?: string; routing?: string; - timeout?: number | Date; - timestamp?: number | Date; - ttl?: number; + q?: string; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + index?: NameList; + type?: NameList; + } + + export interface CountResponse { + count: number; + _shards: ShardsResponse; + } + + export interface CreateDocumentParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + timeout?: DateLike; + timestamp?: DateLike; + ttl?: DateLike; version?: number; - versionType?: "internal" | "external" | "external_gte" | "force"; + versionType?: VersionType; + pipeline?: string; id: string; index: string; type: string; } - export interface IndicesGetParams extends GenericParams { - ignoreUnavailable?: boolean; - index: string | string[] | boolean; + export interface CreateDocumentResponse { + _shards: ShardsResponse; + _index: string; + _type: string; + _id: string; + _version: number; + created: boolean; + result: string; } - export interface IndicesRefreshParams extends GenericParams { - force?: boolean; - ignoreUnavailable?: boolean; - index: string | string[] | boolean; - } - - export interface IndicesDeleteParams extends GenericParams { - index: string | string[] | boolean; - timeout?: Date | number; - masterTimeout?: Date | number; - } - - export interface IndicesCreateParams extends GenericParams { - index: string | string[] | boolean; - timeout?: Date | number; - masterTimeout?: Date | number; - } - - export interface IndicesPutTemplateParams extends GenericParams { - order?: number; - create?: boolean; - timeout?: Date | number; - masterTimeout?: Date | number; - flatSettings?: boolean; - name: string; - body: string | any; - } - - export interface IndicesPutMappingParams extends GenericParams { - timeout?: Date | number; - masterTimeout?: Date | number; - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: "open" | "closed" | "none" | "all"; - updateAllTypes?: boolean; - index: string | string[] | boolean; - type: string; - } - - export interface IndicesGetAliasParams extends GenericParams { - ignoreUnavailable?: boolean; - allowNoIndices?: boolean; - expandWildcards?: "open" | "closed" | "none" | "all"; - local?: boolean; - index?: string | string[] | boolean; - name: string | string[] | boolean; - } - - export interface IndicesPutAliasParams extends GenericParams { - index?: string | string[] | boolean; - name: string | string[] | boolean; - } - - export interface GetParams extends GenericParams { + export interface DeleteDocumentParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + routing?: string; + timeout?: DateLike; + version?: number; + versionType?: VersionType; index: string; type: string; id: string; - fields?: string | string[] | boolean; + } + + export interface DeleteDocumentResponse { + _shards: ShardsResponse; + found: boolean; + _index: string; + _type: string; + _id: string; + _version: number; + result: string; + } + + export interface DeleteDocumentByQueryParams extends GenericParams { + waitForActiveShards?: string; + parent?: string; + refresh?: Refresh; + routing?: string; + timeout?: DateLike; + version?: number; + versionType?: VersionType; + index: string; + type: string; + id: string; + } + + export interface DeleteDocumentByQueryResponse { + took: number; + timed_out: boolean; + deleted: number; + batches: number; + version_conflicts: number; + noops: number; + retries: { + bulk: number; + search: number; + }; + throttled_millis: number; + requests_per_second: number; + throttled_until_millis: number; + total: number; + failures: any[]; + } + + export interface DeleteScriptParams extends GenericParams { + id: string; + lang: string; + } + + export interface DeleteTemplateParams extends GenericParams { + id: string; + } + + export interface ExistsParams extends GenericParams { parent?: string; preference?: string; realtime?: boolean; refresh?: boolean; routing?: string; - _source?: string | string[] | boolean; - _sourceExclude?: string | string[] | boolean; - _sourceInclude?: string | string[] | boolean; + id: string; + index: string; + type: string; + } + + export interface ExplainParams extends GenericParams { + analyzeWildcard?: boolean; + analyzer?: string; + defaultOperator?: DefaultOperator; + df?: string; + storedFields?: NameList; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + parent?: string; + preference?: string; + q?: string; + routing?: string; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + id?: string; + index?: string; + type?: string; + } + + export interface ExplainResponse { + _index: string; + _type: string; + _id: string; + matched: boolean; + explanation: ExplainResponseDetails; + } + + export interface ExplainResponseDetails { + value: number; + description: string; + details: ExplainResponseDetails[]; + } + + export interface FieldStatsParams extends GenericParams { + fields?: NameList; + level?: "indices" | "cluster"; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + } + + export interface FieldStatsResponse { + _shards: ShardsResponse; + indices: { [indexName: string]: FieldStatsResponseIndex }; + conflicts?: { [fieldName: string]: string }; + } + + export interface FieldStatsResponseIndex { + fields: { [fieldName: string]: FieldStatsResponseField }; + } + + export interface FieldStatsResponseField { + max_doc: number; + doc_count: number; + density: number; + sum_doc_freq: number; + sum_total_term_freq: number; + min_value: any; + max_value: any; + is_searchable: string; + is_aggregatable: string; + } + + export interface GetParams extends GenericParams { + storedFields?: NameList; + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; version?: number; - versionType?: string; + versionType?: VersionType; + id: string; + index: string; + type: string; } export interface GetResponse { @@ -208,103 +369,59 @@ declare module Elasticsearch { _source: T; } - export interface ExistsParams extends GenericParams { + export interface GetScriptParams extends GenericParams { id: string; - index: string; - parent?: string; + lang: string; + } + + export interface GetSourceParams extends GenericParams { preference?: string; realtime?: boolean; refresh?: boolean; routing?: string; + _source: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + version?: number; + versionType?: VersionType; + id: string; + index: string; type: string; } + export interface GetTemplateParams extends GenericParams { + id: string; + } + export interface IndexDocumentParams extends GenericParams { + waitForActiveShards?: string; + opType?: "index" | "create"; + parent?: string; + refresh?: string; + routing?: string; + timeout?: DateLike; + timestamp?: DateLike; + ttl?: DateLike; + version?: number; + versionType?: VersionType; + pipeline?: string; + id?: string; index: string; type: string; - id: string; body: T; - consistensy?: string; - parent?: string; - replication?: string; - routing?: string; - timeout?: Date | number; - timestamp?: Date | number; - version?: number; - versionType?: string; } - export interface ScrollParams extends GenericParams { - scroll: string; - scrollId: string; - } - - export interface SearchParams extends GenericParams { - index?: string; - type?: string | string[] | number; - body?: any; - q?: string; - scroll?: string; - search_type?: string; - fields?: string[]; - from?: number; - size?: number; - sort?: string | string[] | boolean; - _source?: string | string[] | boolean; - _sourceExclude?: string | string[] | boolean; - _sourceInclude?: string | string[] | boolean; - stats?: string | string[] | boolean; - suggestField?: string; - suggestSize?: number; - suggestText?: string; - timeout?: Date | number; - } - - export interface SearchResponse { - took: number, - timed_out: boolean, - _scroll_id?: string, - _shards: { - total: number, - successful: number, - failed: number - }, - hits: { - total: number, - max_score: number, - hits: { - _index: string, - _type: string, - _id: string, - _score: number, - _source: T, - _version: number, - _explanation?: Explanation, - fields?: any, - highlight?: any, - inner_hits?: any - }[] - }, - aggregations?: any - } - - export interface MSearchParams extends GenericParams { - index?: string | string[] | Boolean; - type?: string | string[] | Boolean; - search_type?: string; - } - - export interface MSearchResponse { - responses?: SearchResponse[]; + export interface InfoParams extends GenericParams { } export interface MGetParams extends GenericParams { - fields?: string | string[] | Boolean; + storedFields?: NameList; preference?: string; realtime?: Boolean; refresh?: Boolean; - _sourceExclude?: string | string[] | boolean; - _sourceInclude?: string | string[] | boolean; + source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; index?: string; type?: string; } @@ -313,137 +430,1143 @@ declare module Elasticsearch { docs?: GetResponse[]; } - export interface IndicesIndexExitsParams extends GenericParams { - index: string | string[] | boolean; - ignoreUnavailable?: boolean; + export interface MSearchParams extends GenericParams { + search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + maxConcurrentSearches?: number; + index?: NameList; + type?: NameList; + } + + export interface MSearchResponse { + responses?: SearchResponse[]; + } + + export interface MSearchTemplateParams extends GenericParams { + search_type?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + index?: NameList; + type?: NameList; + } + + export interface MTermVectorsParams extends GenericParams { + ids?: NameList; + termStatistics?: boolean; + fieldStatistics?: boolean; + fields?: NameList; + offsets?: boolean; + positions?: boolean; + payloads?: boolean; + preference?: string; + routing?: string; + parent?: string; + realtime?: boolean; + version?: number; + versionType?: VersionType; + index: string; + type: string; } export interface PingParams extends GenericParams { - requestTimeout?: number; - hello?: string; } - export interface DeleteDocumentParams extends GenericParams { - index: string; - type: string; + export interface PutScriptParams extends GenericParams { id: string; - parent?: string; + lang: string; + body: any; + } + + export interface PutTemplateParams extends GenericParams { + id: string; + body: any; + } + + export interface ReindexParams extends GenericParams { refresh?: boolean; + timeout?: DateLike; + waitForActiveShards?: string; + waitForCompletion?: boolean; + requestsPerSecond?: number; + body: { + conflicts?: string; + source: { + index: string | string[]; + type?: string | string[]; + query?: any; + sort?: any; + size?: number; + remote?: { + host: string; + username?: string; + password?: string; + } + }; + dest: { + index: string; + version_type?: string; + op_type?: string; + routing?: string; + pipeline?: string; + }; + script?: { + inline: string; + lang: string; + } + } } - export interface UpdateDocumentParams extends GenericParams { - index: string; - type: string; + export interface ReindexResponse { + took: number; + updated: number; + created: number; + batches: number; + version_conflicts: number; + retries: { + bulk: number; + search: number; + } + throttled_millis: number; + failures: any[]; + } + + export interface ReindexRethrottleParams extends GenericParams { + requestsPerSecond: number; + taskId: string; + } + + export interface RenderSearchTemplateParams extends GenericParams { id: string; - body?: string | any; - version?: Number; - timesstamp?: Date | Number; - scriptedUpsert?: Boolean; - scriptId?: any; - script?: any; + } + + export interface ScrollParams extends GenericParams { + scroll: DateLike; + scrollId: string; + } + + export interface SearchParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + explain?: boolean; + storedFields?: NameList; + docvalueFields?: NameList; + fielddataFields?: NameList; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + preference?: string; + q?: string; + routing?: NameList; + scroll?: DateLike; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: NameList; + suggestField?: string; + suggestMode?: "missing" | "popular" | "always"; + suggestSize?: number; + suggestText?: string; + timeout?: DateLike; + trackScores?: boolean; + version?: boolean; + requestCache?: boolean; + index?: NameList; + type?: NameList; + } + + export interface SearchResponse { + took: number; + timed_out: boolean; + _scroll_id?: string; + _shards: ShardsResponse; + hits: { + total: number; + max_score: number; + hits: { + _index: string; + _type: string; + _id: string; + _score: number; + _source: T; + _version: number; + _explanation?: Explanation; + fields?: any; + highlight?: any; + inner_hits?: any; + }[]; + }; + aggregations?: any; + } + + export interface SearchShardsParams extends GenericParams { + preference?: string; routing?: string; - retryOnConflict?: Number; - refresh?: Boolean; - parent?: string; - lang?:string; - fields?: string | string[] | Boolean; - consistensy?: string; + local?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; + type: NameList; + } + + export interface SearchShardsResponse { + nodes: any; + shards: SearchShardsResponseShard[][]; + } + + export interface SearchShardsResponseShard { + index: string; + node: string; + primary: boolean; + share: number; + state: string; + allocation_id: { + id: string; + }; + relocating_node: any; + } + + export interface SearchTemplateParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + preference?: string; + routing?: NameList; + scroll?: DateLike; + searchType?: "query_then_fetch" | "query_and_fetch" | "dfs_query_then_fetch" | "dfs_query_and_fetch"; + index: NameList; + type: NameList; } export interface SuggestParams extends GenericParams { ignoreUnavailable?: boolean; allowNoIndices?: boolean; - expandWildcards?: "open" | "closed" | "none" | "all"; + expandWildcards?: ExpandWildcards; preference?: string; routing?: string; - source?: string; - body: string | any; - index: string | string[] | boolean; + index: NameList; + } + + export interface TermvectorsParams extends GenericParams { + termStatistics?: boolean; + fieldStatistics?: boolean; + fields?: NameList; + offsets?: boolean; + positions?: boolean; + payloads?: boolean; + preference?: string; + routing?: string; + parent?: string; + realtime?: boolean; + version?: number; + versionType?: VersionType; + index: string; + type: string; + id?: string; + } + + export interface UpdateDocumentParams extends GenericParams { + waitForActiveShards?: string; + fields?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + lang?: string; + parent?: string; + refresh?: Refresh; + retryOnConflict?: number; + routing?: string; + timeout?: DateLike; + timestamp?: DateLike; + ttl?: DateLike; + version?: number; + versionType?: "internal" | "force"; + id: string; + index: string; + type: string; + } + + export interface UpdateDocumentByQueryParams extends GenericParams { + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + explain?: boolean; + storedFields?: NameList; + docvalueFields?: NameList; + fielddataFields?: NameList; + from?: number; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + conflicts?: "abort" | "proceed"; + expandWildcards?: ExpandWildcards; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + pipeline?: string; + preference?: string; + q?: string; + routing?: NameList; + scroll?: DateLike; + searchType?: "query_then_fetch" | "dfs_query_then_fetch"; + searchTimeout?: DateLike; + size?: number; + sort?: NameList; + _source?: NameList; + _sourceExclude?: NameList; + _sourceInclude?: NameList; + terminateAfter?: number; + stats?: NameList; + suggestField?: string; + suggestMode?: "missing" | "popular" | "always"; + suggestSize?: number; + suggestText?: string; + timeout?: DateLike; + trackScores?: boolean; + version?: boolean; + versionType?: boolean; + requestCache?: boolean; + refresh?: boolean; + waitForActiveShards?: string; + scrollSize?: number; + waitForCompletion?: boolean; + requestsPerSecond?: number; + index: NameList; + type: NameList; } export interface Cat { - health(params: CatHealthOptions, callback: (error: any, response: any) => void): void; - health(params: CatHealthOptions): PromiseLike + aliases(params: CatAliasesParams, callback: (error: any, response: any) => void): void; + aliases(params: CatAliasesParams): PromiseLike; + allocation(params: CatAllocationParams, callback: (error: any, response: any) => void): void; + allocation(params: CatAllocationParams): PromiseLike; + count(params: CatCountParams, callback: (error: any, response: any) => void): void; + count(params: CatAllocationParams): PromiseLike; + fielddata(params: CatFielddataParams, callback: (error: any, response: any) => void): void; + fielddata(params: CatFielddataParams): PromiseLike; + health(params: CatHealthParams, callback: (error: any, response: any) => void): void; + health(params: CatHealthParams): PromiseLike; + help(params: CatHelpParams, callback: (error: any, response: any) => void): void; + help(params: CatHelpParams): PromiseLike; + indices(params: CatIndicesParams, callback: (error: any, response: any) => void): void; + indices(params: CatIndicesParams): PromiseLike; + master(params: CatCommonParams, callback: (error: any, response: any) => void): void; + master(params: CatCommonParams): PromiseLike; + nodeattrs(params: CatCommonParams, callback: (error: any, response: any) => void): void; + nodeattrs(params: CatCommonParams): PromiseLike; + nodes(params: CatCommonParams, callback: (error: any, response: any) => void): void; + nodes(params: CatCommonParams): PromiseLike; + pendingTasks(params: CatCommonParams, callback: (error: any, response: any) => void): void; + pendingTasks(params: CatCommonParams): PromiseLike; + plugins(params: CatCommonParams, callback: (error: any, response: any) => void): void; + plugins(params: CatCommonParams): PromiseLike; + recovery(params: CatRecoveryParams, callback: (error: any, response: any) => void): void; + recovery(params: CatRecoveryParams): PromiseLike; + repositories(params: CatCommonParams, callback: (error: any, response: any) => void): void; + repositories(params: CatCommonParams): PromiseLike; + segments(params: CatSegmentsParams, callback: (error: any, response: any) => void): void; + segments(params: CatSegmentsParams): PromiseLike; + shards(params: CatShardsParams, callback: (error: any, response: any) => void): void; + shards(params: CatShardsParams): PromiseLike; + snapshots(params: CatSnapshotsParams, callback: (error: any, response: any) => void): void; + snapshots(params: CatSnapshotsParams): PromiseLike; + tasks(params: CatTasksParams, callback: (error: any, response: any) => void): void; + tasks(params: CatTasksParams): PromiseLike; + threadPool(params: CatThreadPoolParams, callback: (error: any, response: any) => void): void; + threadPool(params: CatThreadPoolParams): PromiseLike; } - export interface CatHealthOptions extends GenericParams { + export type CatBytes = "b" | "k" | "kb" | "m" | "mb" | "g" | "gb" | "t" | "tb" | "p" | "pb"; + + export interface CatCommonParams extends GenericParams { + format: string; local?: boolean; - masterTimeout?: number | Date; - h?: string | string[] | boolean; + masterTimeout?: DateLike; + h?: NameList; help?: boolean; - ts?: boolean; v?: boolean; } + export interface CatAliasesParams extends CatCommonParams { + name?: NameList; + } + + export interface CatAllocationParams extends CatCommonParams { + bytes?: CatBytes; + nodeId?: NameList; + } + + export interface CatCountParams extends CatCommonParams { + index?: NameList; + } + + export interface CatFielddataParams extends CatCommonParams { + bytes?: CatBytes; + fields?: NameList; + } + + export interface CatHealthParams extends CatCommonParams { + ts?: boolean; + } + + export interface CatHelpParams extends GenericParams { + help?: boolean; + } + + export interface CatIndicesParams extends CatCommonParams { + bytes?: CatBytes; + health?: "green" | "yellow" | "red"; + pri?: boolean; + index?: NameList; + } + + export interface CatRecoveryParams extends GenericParams { + format: string; + bytes?: CatBytes; + masterTimeout?: DateLike; + h?: NameList; + help?: boolean; + v?: boolean; + } + + export interface CatSegmentsParams extends GenericParams { + format: string; + h?: NameList; + help?: boolean; + v?: boolean; + index?: NameList; + } + + export interface CatShardsParams extends CatCommonParams { + index?: NameList; + } + + export interface CatSnapshotsParams extends GenericParams { + format: string; + ignoreUnavailable?: boolean; + masterTimeout?: DateLike; + h?: NameList; + help?: boolean; + v?: boolean; + repository?: NameList; + } + + export interface CatTasksParams extends GenericParams { + format: string; + nodeId?: NameList; + actions?: NameList; + detailed?: boolean; + parentNode?: string; + parentTask?: number; + h?: NameList; + help?: boolean; + v?: boolean; + } + + export interface CatThreadPoolParams extends CatCommonParams { + size?: "" | "k" | "m" | "g" | "t" | "p"; + threadPoolPatterns?: NameList; + } + export interface Cluster { - getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void; - getSettings(params: ClusterGetSettingsOptions): PromiseLike; - health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void; - health(params: ClusterHealthOptions): PromiseLike; - pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void; - pendingTasks(params: ClusterPendingTasksOptions): PromiseLike; - putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void; - putSettings(params: ClusterPutSettingsOptions): PromiseLike; - reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void; - reroute(params: ClusterRerouteOptions): PromiseLike; - state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void; - state(params: ClusterStateOptions): PromiseLike; - stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void; - stats(params: ClusterStatsOptions): PromiseLike; + allocationExplain(params: ClusterAllocationExplainParams, callback: (error: any, response: any) => void): void; + allocationExplain(params: ClusterAllocationExplainParams): PromiseLike; + getSettings(params: ClusterGetSettingsParams, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsParams): PromiseLike; + health(params: ClusterHealthParams, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthParams): PromiseLike; + pendingTasks(params: ClusterPendingTasksParams, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksParams): PromiseLike; + putSettings(params: ClusterPutSettingsParams, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsParams): PromiseLike; + reroute(params: ClusterRerouteParams, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteParams): PromiseLike; + state(params: ClusterStateParams, callback: (error: any, response: any) => void): void; + state(params: ClusterStateParams): PromiseLike; + stats(params: ClusterStatsParams, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsParams): PromiseLike; } - export interface ClusterGetSettingsOptions extends GenericParams { + export interface ClusterAllocationExplainParams extends GenericParams { + includeYesDecisions?: boolean; + includeDiskInfo?: boolean; + } + + export interface ClusterGetSettingsParams extends GenericParams { flatSettings?: boolean; - masterTimeout?: number | Date; - timeout?: number | Date; + masterTimeout?: DateLike; + timeout?: DateLike; + includeDefaults?: boolean; } - export interface ClusterHealthOptions extends GenericParams { - level?: string; // cluster, indices, shards + export interface ClusterHealthParams extends GenericParams { + level?: "cluster" | "indices" | "shards"; local?: boolean; - masterTimeout?: number | Date; - waitForActiveShards?: number; + masterTimeout?: DateLike; + waitForActiveShards?: string; waitForNodes?: string; - waitForRelocatingShards?: number; - waitForStatus?: string; // green, yellow, red - index?: string | string[] | boolean; + waitForEvents?: "immediate" | "urgent" | "high" | "normal" | "low" | "languid"; + waitForRelocatingShards?: boolean; + waitForStatus?: "green" | "yellow" | "red"; + index?: NameList; } - export interface ClusterPendingTasksOptions extends GenericParams { + export interface ClusterPendingTasksParams extends GenericParams { local?: boolean; - masterTimeout?: number | Date; + masterTimeout?: DateLike; } - export interface ClusterPutSettingsOptions extends GenericParams { + export interface ClusterPutSettingsParams extends GenericParams { flatSettings?: boolean; - masterTimeout?: number | Date; - timeout?: number | Date; + masterTimeout?: DateLike; + timeout?: DateLike; } - export interface ClusterRerouteOptions extends GenericParams { + export interface ClusterRerouteParams extends GenericParams { dryRun?: boolean; explain?: boolean; - metric?: string | string[] | boolean; - masterTimeout?: number | Date; - timeout?: number | Date; + retryFailed?: boolean; + metric?: NameList; + masterTimeout?: DateLike; + timeout?: DateLike; } - export interface ClusterStateOptions extends GenericParams { + export interface ClusterStateParams extends GenericParams { local?: boolean; - masterTimeout?: number | Date; + masterTimeout?: DateLike; flatSettings?: boolean; ignoreUnavailable?: boolean; allowNoIndices?: boolean; - expandWildcards?: string; // open, closed, none, all (default open) - index?: string | string[] | boolean; - metric?: string | string[] | boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + metric?: NameList; } - export interface ClusterStatsOptions extends GenericParams { + export interface ClusterStatsParams extends GenericParams { flatSettings?: boolean; human?: boolean; - timeout?: number | Date; - nodeId?: string | string[] | boolean; + timeout?: DateLike; + nodeId?: NameList; + } + + export class Indices { + analyze(params: IndicesAnalyzeParams, callback: (error: any, response: any, status: any) => void): void; + analyze(params: IndicesAnalyzeParams): PromiseLike; + clearCache(params: IndicesClearCacheParams, callback: (error: any, response: any, status: any) => void): void; + clearCache(params: IndicesClearCacheParams): PromiseLike; + close(params: IndicesCloseParams, callback: (error: any, response: any, status: any) => void): void; + close(params: IndicesCloseParams): PromiseLike; + create(params: IndicesCreateParams, callback: (error: any, response: any, status: any) => void): void; + create(params: IndicesCreateParams): PromiseLike; + delete(params: IndicesDeleteParams, callback: (error: any, response: any, status: any) => void): void; + delete(params: IndicesDeleteParams): PromiseLike; + deleteAlias(params: IndicesDeleteAliasParams, callback: (error: any, response: any, status: any) => void): void; + deleteAlias(params: IndicesDeleteAliasParams): PromiseLike; + deleteTemplate(params: IndicesDeleteTemplateParams, callback: (error: any, response: any, status: any) => void): void; + deleteTemplate(params: IndicesDeleteTemplateParams): PromiseLike; + exists(params: IndicesExistsParams, callback: (error: any, response: any, status: any) => void): void; + exists(params: IndicesExistsParams): PromiseLike; + existsAlias(params: IndicesExistsAliasParams, callback: (error: any, response: any, status: any) => void): void; + existsAlias(params: IndicesExistsAliasParams): PromiseLike; + existsTemplate(params: IndicesExistsTemplateParams, callback: (error: any, response: any, status: any) => void): void; + existsTemplate(params: IndicesExistsTemplateParams): PromiseLike; + existsType(params: IndicesExistsTypeParams, callback: (error: any, response: any, status: any) => void): void; + existsType(params: IndicesExistsTypeParams): PromiseLike; + flush(params: IndicesFlushParams, callback: (error: any, response: any, status: any) => void): void; + flush(params: IndicesFlushParams): PromiseLike; + flushSynced(params: IndicesFlushSyncedParams, callback: (error: any, response: any, status: any) => void): void; + flushSynced(params: IndicesFlushSyncedParams): PromiseLike; + forcemerge(params: IndicesForcemergeParams, callback: (error: any, response: any, status: any) => void): void; + forcemerge(params: IndicesForcemergeParams): PromiseLike; + get(params: IndicesGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: IndicesGetParams): PromiseLike; + getAlias(params: IndicesGetAliasParams, callback: (error: any, response: any, status: any) => void): void; + getAlias(params: IndicesGetAliasParams): PromiseLike; + getFieldMapping(params: IndicesGetFieldMappingParams, callback: (error: any, response: any, status: any) => void): void; + getFieldMapping(params: IndicesGetFieldMappingParams): PromiseLike; + getMapping(params: IndicesGetMappingParams, callback: (error: any, response: any, status: any) => void): void; + getMapping(params: IndicesGetMappingParams): PromiseLike; + getSettings(params: IndicesGetSettingsParams, callback: (error: any, response: any, status: any) => void): void; + getSettings(params: IndicesGetSettingsParams): PromiseLike; + getTemplate(params: IndicesGetTemplateParams, callback: (error: any, response: any, status: any) => void): void; + getTemplate(params: IndicesGetTemplateParams): PromiseLike; + getUpgrade(params: IndicesGetUpgradeParams, callback: (error: any, response: any, status: any) => void): void; + getUpgrade(params: IndicesGetUpgradeParams): PromiseLike; + open(params: IndicesOpenParams, callback: (error: any, response: any, status: any) => void): void; + open(params: IndicesOpenParams): PromiseLike; + putAlias(params: IndicesPutAliasParams, callback: (error: any, response: any, status: any) => void): void; + putAlias(params: IndicesPutAliasParams): PromiseLike; + putMapping(params: IndicesPutMappingParams, callback: (error: any, response: any, status: any) => void): void; + putMapping(params: IndicesPutMappingParams): PromiseLike; + putSettings(params: IndicesPutSettingsParams, callback: (error: any, response: any, status: any) => void): void; + putSettings(params: IndicesPutSettingsParams): PromiseLike; + putTemplate(params: IndicesPutTemplateParams, callback: (error: any, response: any) => void): void; + putTemplate(params: IndicesPutTemplateParams): PromiseLike; + recovery(params: IndicesRecoveryParams, callback: (error: any, response: any) => void): void; + recovery(params: IndicesRecoveryParams): PromiseLike; + refresh(params: IndicesRefreshParams, callback: (error: any, response: any) => void): void; + refresh(params: IndicesRefreshParams): PromiseLike; + rollover(params: IndicesRolloverParams, callback: (error: any, response: IndicesRolloverResponse) => void): void; + rollover(params: IndicesRolloverParams): PromiseLike; + segments(params: IndicesSegmentsParams, callback: (error: any, response: any) => void): void; + segments(params: IndicesSegmentsParams): PromiseLike; + shardStores(params: IndicesShardStoresParams, callback: (error: any, response: any) => void): void; + shardStores(params: IndicesShardStoresParams): PromiseLike; + shrink(params: IndicesShrinkParams, callback: (error: any, response: any) => void): void; + shrink(params: IndicesShrinkParams): PromiseLike; + stats(params: IndicesStatsParams, callback: (error: any, response: any) => void): void; + stats(params: IndicesStatsParams): PromiseLike; + updateAliases(params: IndicesUpdateAliasesParams, callback: (error: any, response: any) => void): void; + updateAliases(params: IndicesUpdateAliasesParams): PromiseLike; + upgrade(params: IndicesUpgradeParams, callback: (error: any, response: any) => void): void; + upgrade(params: IndicesUpgradeParams): PromiseLike; + validateQuery(params: IndicesValidateQueryParams, callback: (error: any, response: any) => void): void; + validateQuery(params: IndicesValidateQueryParams): PromiseLike; + } + + export interface IndicesAnalyzeParams extends GenericParams { + analyzer?: string; + charFilter?: NameList; + field?: string; + filter?: NameList; + index?: string; + perferLocal?: boolean; + text?: NameList; + tokenizer?: string; + explain?: boolean; + attributes?: NameList; + format?: "" + } + + export interface IndicesClearCacheParams extends GenericParams { + fieldData?: boolean; + fielddata?: boolean; // yes the docs really have both + fields?: NameList; + query?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + recycler?: boolean; + request?: boolean; + } + + export interface IndicesCloseParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; + } + + export interface IndicesCreateParams extends GenericParams { + waitForActiveShards?: string; + timeout?: DateLike; + masterTimeout?: DateLike; + updateAllTypes?: boolean; + index: string; + } + + export interface IndicesDeleteParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + index: NameList; + } + + export interface IndicesDeleteAliasParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + index: NameList; + name: NameList; + } + + export interface IndicesDeleteTemplateParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + name: string; + } + + export interface IndicesExistsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index: NameList; + } + + export interface IndicesExistsAliasParams extends IndicesExistsParams { + name: NameList; + } + + export interface IndicesExistsTemplateParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + name: NameList; + } + + export interface IndicesExistsTypeParams extends IndicesExistsParams { + type: NameList; + } + + export interface IndicesFlushParams extends GenericParams { + force?: boolean; + waitIfOngoing?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; + } + + export interface IndicesFlushSyncedParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index: NameList; + } + + export interface IndicesForcemergeParams extends GenericParams { + flush?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + maxNumSegments?: number; + onlyExpungeDeletes?: boolean; + operationThreading?: any; // even the docs don't know what this does + waitForMerge?: boolean; + index: NameList; + } + + export interface IndicesGetParams extends GenericParams { + local?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + human?: boolean; + includeDefaults?: boolean; + index?: NameList; + feature?: NameList; + } + + export interface IndicesGetAliasParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + name?: NameList; + } + + export interface IndicesGetFieldMappingParams extends GenericParams { + includeDefaults?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + type?: NameList; + fields?: NameList; + } + + export interface IndicesGetMappingParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + local?: boolean; + index?: NameList; + type?: NameList; + } + + export interface IndicesGetSettingsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + local?: boolean; + human?: boolean; + includeDefaults?: boolean; + index?: NameList; + name?: NameList; + } + + export interface IndicesGetTemplateParams extends GenericParams { + flatSettings?: boolean; + masterTimeout?: DateLike; + local?: boolean; + name?: NameList; + } + + export interface IndicesGetUpgradeParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + human?: boolean; + index?: NameList; + } + + export interface IndicesOpenParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + index?: NameList; + } + + export interface IndicesPutAliasParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + index?: NameList; + name: NameList; + } + + export interface IndicesPutMappingParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + updateAllTypes?: boolean; + index: NameList; + type: string; + body: any; + } + + export interface IndicesPutSettingsParams extends GenericParams { + masterTimeout?: DateLike; + preserveExisting?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + flatSettings?: boolean; + index: NameList; + body: any; + } + + export interface IndicesPutTemplateParams extends GenericParams { + order?: number; + create?: boolean; + timeout?: DateLike; + masterTimeout?: DateLike; + flatSettings?: boolean; + name: string; + body: any; + } + + export interface IndicesRecoveryParams extends GenericParams { + detailed?: boolean; + activeOnly?: boolean; + human?: boolean; + index: NameList; + } + + export interface IndicesRefreshParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + force?: boolean; + operationThreading?: any; // even the docs don't know what this does + index: NameList; + } + + export interface IndicesRolloverParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + waitForActiveShards?: number | string; + alias?: string; + newIndex?: string; + } + + export interface IndicesRolloverResponse { + acknowledged: boolean; + shards_acknowledged: boolean; + old_index: string; + new_index: string; + rolled_over: boolean; + dry_run: boolean; + conditions: { [condition: string]: boolean }; + } + + export interface IndicesSegmentsParams extends GenericParams { + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + human?: boolean; + operationThreading?: any; // even the docs don't know what this does + verbose?: boolean; + index: NameList; + } + + export interface IndicesShardStoresParams extends GenericParams { + status?: NameList; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + operationThreading?: any; // even the docs don't know what this does + index: NameList; + } + + export interface IndicesShrinkParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + waitForActiveShards?: string | number; + index: string; + target: string; + } + + export interface IndicesStatsParams extends GenericParams { + completionFields?: NameList; + fielddataFields?: NameList; + fields?: NameList; + groups?: NameList; + human?: boolean; + level?: "cluster" | "indices" | "shards"; + types?: NameList; + index: NameList; + metric?: NameList; + } + + export interface IndicesUpdateAliasesParams extends GenericParams { + timeout?: DateLike; + masterTimeout?: DateLike; + body: { + actions: IndicesUpdateAliasesParamsAction[]; + } + } + + export interface IndicesUpdateAliasesParamsAction { + add?: { + index?: string; + indices?: string[]; + alias: string; + }; + remove?: { + index?: string; + indices?: string[]; + alias: string; + }; + remove_index?: { + index: string; + } + } + + export interface IndicesUpgradeParams extends GenericParams { + expandWildcards?: ExpandWildcards; + ignoreUnavailable?: boolean; + waitForCompletion?: boolean; + onlyAncientSegments?: boolean; + index: NameList; + } + + export interface IndicesValidateQueryParams extends GenericParams { + explain?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: ExpandWildcards; + operationThreading?: any; // even the docs don't know what this does + q?: string; + analyzer?: string; + analyzeWildcard?: boolean; + defaultOperator?: DefaultOperator; + df?: string; + lenient?: boolean; + lowercaseExpandedTerms?: boolean; + rewrite?: boolean; + index: NameList; + type?: NameList; + } + + export class Ingest { + deletePipeline(params: IngestDeletePipelineParams, callback: (error: any, response: any, status: any) => void): void; + deletePipeline(params: IngestDeletePipelineParams): PromiseLike; + getPipeline(params: IngestGetPipelineParams, callback: (error: any, response: any, status: any) => void): void; + getPipeline(params: IngestGetPipelineParams): PromiseLike; + putPipeline(params: IngestPutPipelineParams, callback: (error: any, response: any, status: any) => void): void; + putPipeline(params: IngestPutPipelineParams): PromiseLike; + simulate(params: IngestSimulateParams, callback: (error: any, response: any, status: any) => void): void; + simulate(params: IngestSimulateParams): PromiseLike; + } + + export interface IngestDeletePipelineParams extends GenericParams { + masterTimeout?: number; + timeout?: number; + id: string; + } + + export interface IngestGetPipelineParams extends GenericParams { + masterTimeout?: number; + id: string; + } + + export interface IngestPutPipelineParams extends GenericParams { + masterTimeout?: number; + timeout?: number; + id: string; + body: any; + } + + export interface IngestSimulateParams extends GenericParams { + verbose?: boolean; + id: string; + } + + export class Nodes { + hotThreads(params: NodesHotThreadsParams, callback: (error: any, response: any, status: any) => void): void; + hotThreads(params: NodesHotThreadsParams): PromiseLike; + info(params: NodesInfoParams, callback: (error: any, response: any, status: any) => void): void; + info(params: NodesInfoParams): PromiseLike; + stats(params: NodesStatsParams, callback: (error: any, response: any, status: any) => void): void; + stats(params: NodesStatsParams): PromiseLike; + } + + export interface NodesHotThreadsParams extends GenericParams { + interval?: DateLike; + snapshots?: number; + threads?: number; + ignoreIdleThreads?: boolean; + type?: "cpu" | "wait" | "blocked"; + timeout?: DateLike; + nodeId: NameList; + } + + export interface NodesInfoParams extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: DateLike; + nodeId: NameList; + metric?: NameList; + } + + export interface NodesStatsParams extends GenericParams { + completionFields?: NameList; + fielddataFields?: NameList; + fields?: NameList; + groups?: boolean; + human?: boolean; + level?: "indices" | "node" | "shards"; + types?: NameList; + timeout?: DateLike; + metric?: NameList; + indexMetric?: NameList; + nodeId?: NameList; + } + + export class Snapshot { + create(params: SnapshotCreateParams, callback: (error: any, response: any, status: any) => void): void; + create(params: SnapshotCreateParams): PromiseLike; + createRepository(params: SnapshotCreateRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + createRepository(params: SnapshotCreateRepositoryParams): PromiseLike; + delete(params: SnapshotDeleteParams, callback: (error: any, response: any, status: any) => void): void; + delete(params: SnapshotDeleteParams): PromiseLike; + deleteRepository(params: SnapshotDeleteRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + deleteRepository(params: SnapshotDeleteRepositoryParams): PromiseLike; + get(params: SnapshotGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: SnapshotGetParams): PromiseLike; + getRepository(params: SnapshotGetRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + getRepository(params: SnapshotGetRepositoryParams): PromiseLike; + restore(params: SnapshotRestoreParams, callback: (error: any, response: any, status: any) => void): void; + restore(params: SnapshotRestoreParams): PromiseLike; + status(params: SnapshotStatusParams, callback: (error: any, response: any, status: any) => void): void; + status(params: SnapshotStatusParams): PromiseLike; + verifyRepository(params: SnapshotVerifyRepositoryParams, callback: (error: any, response: any, status: any) => void): void; + verifyRepository(params: SnapshotVerifyRepositoryParams): PromiseLike; + } + + export interface SnapshotCreateParams extends GenericParams { + masterTimeout?: DateLike; + waitForCompletion?: boolean; + repository: string; + snapshot: string; + } + + export interface SnapshotCreateRepositoryParams extends GenericParams { + masterTimeout?: DateLike; + timeout?: DateLike; + verify?: boolean; + repository: string; + } + + export interface SnapshotDeleteParams extends GenericParams { + masterTimeout?: DateLike; + repository: string; + snapshot: string; + } + + export interface SnapshotDeleteRepositoryParams extends GenericParams { + masterTimeout?: DateLike; + timeout?: DateLike; + repository: string; + } + + export interface SnapshotGetParams extends GenericParams { + masterTimeout?: DateLike; + ignoreUnavailable?: boolean; + repository: string; + snapshot: NameList; + } + + export interface SnapshotGetRepositoryParams extends GenericParams { + masterTimeout?: DateLike; + local?: boolean; + repository: NameList; + } + + export interface SnapshotRestoreParams extends GenericParams { + masterTimeout?: DateLike; + waitForCompletion?: boolean; + repository: string; + snapshot: string; + } + + export interface SnapshotStatusParams extends GenericParams { + masterTimeout?: DateLike; + ignoreUnavailable?: boolean; + repository: string; + snapshot: NameList; + } + + export interface SnapshotVerifyRepositoryParams extends GenericParams { + masterTimeout?: DateLike; + timeout?: DateLike; + repository: string; + } + + export class Tasks { + cancel(params: TasksCancelParams, callback: (error: any, response: any, status: any) => void): void; + cancel(params: TasksCancelParams): PromiseLike; + get(params: TasksGetParams, callback: (error: any, response: any, status: any) => void): void; + get(params: TasksGetParams): PromiseLike; + list(params: TasksListParams, callback: (error: any, response: any, status: any) => void): void; + list(params: TasksListParams): PromiseLike; + } + + export interface TasksCancelParams extends GenericParams { + nodeId?: NameList; + actions?: NameList; + parentNode?: string; + parentTask?: string; + taskId?: string; + } + + export interface TasksGetParams extends GenericParams { + waitForCompletion?: boolean; + taskId?: string; + } + + export interface TasksListParams extends GenericParams { + nodeId?: NameList; + actions?: NameList; + detailed?: boolean; + parentNode?: string; + parentTask?: string; + waitForCompletion?: boolean; + groupBy?: "nodes" | "parents"; } } diff --git a/electron/electron-prebuilt-tests.ts b/electron/electron-prebuilt-tests.ts deleted file mode 100644 index 2f503fa5b6..0000000000 --- a/electron/electron-prebuilt-tests.ts +++ /dev/null @@ -1,7 +0,0 @@ - -/// - -import electron = require('electron-prebuilt'); -import child_process = require('child_process'); - -child_process.spawn(electron); diff --git a/electron/electron-prebuilt.d.ts b/electron/electron-prebuilt.d.ts deleted file mode 100644 index d6b6dffc0e..0000000000 --- a/electron/electron-prebuilt.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for electron-prebuilt 0.30.1 -// Project: https://github.com/mafintosh/electron-prebuilt -// Definitions by: rhysd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'electron-prebuilt' { - var electron: string; - export = electron; -} - diff --git a/electron/github-electron-main-tests.ts b/electron/github-electron-main-tests.ts index 546f6235d4..f333e86ec7 100644 --- a/electron/github-electron-main-tests.ts +++ b/electron/github-electron-main-tests.ts @@ -9,6 +9,7 @@ import { ipcMain, Menu, MenuItem, + net, powerMonitor, powerSaveBlocker, protocol, @@ -303,6 +304,10 @@ if (app.isAccessibilitySupportEnabled()) { } app.setLoginItemSettings({openAtLogin: true, openAsHidden: false}); console.log(app.getLoginItemSettings().wasOpenedAtLogin); +app.setAboutPanelOptions({ + applicationName: 'Test', + version: '1.2.3' +}); var window = new BrowserWindow(); window.setProgressBar(0.5); @@ -359,6 +364,12 @@ if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { browserOptions.frame = false; } +if (process.platform === 'win32') { + systemPreferences.on('color-changed', () => { console.log('color changed'); }); + systemPreferences.on('inverted-color-scheme-changed', (_, inverted) => console.log(inverted ? 'inverted' : 'not inverted')); + console.log('Color for menu is', systemPreferences.getColor('menu')); +} + // Create the window. var win = new BrowserWindow(browserOptions); @@ -722,6 +733,51 @@ Menu.buildFromTemplate([ { label: '3', position: 'endof=numbers' } ]); +// net +// https://github.com/electron/electron/blob/master/docs/api/net.md + +app.on('ready', () => { + const request = net.request('https://github.com') + request.setHeader('Some-Custom-Header-Name', 'Some-Custom-Header-Value'); + let header = request.getHeader('Some-Custom-Header-Name'); + request.removeHeader('Some-Custom-Header-Name'); + request.on('response', (response) => { + console.log(`Status code: ${response.statusCode}`); + console.log(`Status message: ${response.statusMessage}`); + console.log(`Headers: ${JSON.stringify(response.headers)}`); + console.log(`Http version: ${response.httpVersion}`); + console.log(`Major Http version: ${response.httpVersionMajor}`); + console.log(`Minor Http version: ${response.httpVersionMinor}`); + response.on('data', (chunk) => { + console.log(`BODY: ${chunk}`); + }) + response.on('end', () => { + console.log('No more data in response.'); + }) + response.on('error', () => { + console.log('"error" event emitted'); + }); + response.on('aborted', () => { + console.log('"aborted" event emitted'); + }); + }) + request.on('login', (authInfo, callback) => { + callback('username', 'password'); + }); + request.on('finish', () => { + console.log('"finish" event emitted'); + }); + request.on('abort', () => { + console.log('"abort" event emitted'); + }); + request.on('error', () => { + console.log('"error" event emitted'); + }); + request.write('Hello World!', 'utf-8', () => { }); + request.end('Hello World!', 'utf-8', () => { }); + request.abort(); +}) + // power-monitor // https://github.com/atom/electron/blob/master/docs/api/power-monitor.md diff --git a/electron/github-electron-renderer-tests.ts b/electron/github-electron-renderer-tests.ts index e70b660073..87d9a4abf7 100644 --- a/electron/github-electron-renderer-tests.ts +++ b/electron/github-electron-renderer-tests.ts @@ -26,7 +26,7 @@ ipcRenderer.send('asynchronous-message', 'ping'); // remote // https://github.com/atom/electron/blob/master/docs/api/remote.md -var BrowserWindow: typeof Electron.BrowserWindow = remote.require('browser-window'); +var BrowserWindow = remote.BrowserWindow; var win = new BrowserWindow({ width: 800, height: 600 }); win.loadURL('https://github.com'); @@ -167,7 +167,7 @@ holder.ondrop = function (e) { // nativeImage // https://github.com/atom/electron/blob/master/docs/api/native-image.md -var Tray: Electron.Tray = remote.require('Tray'); +var Tray = remote.Tray; var appIcon2 = new Tray('/Users/somebody/images/icon.png'); var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); var image = clipboard.readImage(); @@ -187,7 +187,7 @@ process.once('loaded', function() { // screen // https://github.com/atom/electron/blob/master/docs/api/screen.md -var app: Electron.App = remote.require('app'); +var app = remote.app; var mainWindow: Electron.BrowserWindow = null; diff --git a/electron/index.d.ts b/electron/index.d.ts index 612e9e4ab0..d55b47df4c 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -1,28 +1,15 @@ -// Type definitions for Electron v1.4.1 +// Type definitions for Electron v1.4.5 // Project: http://electron.atom.io/ -// Definitions by: jedmao , rhysd , Milan Burda +// Definitions by: jedmao , rhysd , Milan Burda , aliib // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// declare namespace Electron { - class EventEmitter extends NodeJS.EventEmitter { - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; - } - interface Event { preventDefault: Function; - sender: EventEmitter; + sender: NodeJS.EventEmitter; } type Point = { @@ -42,6 +29,17 @@ declare namespace Electron { height: number; } + interface Destroyable { + /** + * Destroys the object. + */ + destroy(): void; + /** + * @returns Whether the object is destroyed. + */ + isDestroyed(): boolean; + } + // https://github.com/electron/electron/blob/master/docs/api/app.md /** @@ -425,6 +423,13 @@ declare namespace Electron { * Note: This API is only available on macOS and Windows. */ setLoginItemSettings(settings: LoginItemSettings): void; + /** + * Set the about panel options. This will override the values defined in the app's .plist file. + * See the Apple docs for more details. + * + * Note: This API is only available on macOS. + */ + setAboutPanelOptions(options: AboutPanelOptions): void; commandLine: CommandLine; /** * Note: This API is only available on macOS. @@ -686,6 +691,29 @@ declare namespace Electron { restoreState?: boolean; } + interface AboutPanelOptions { + /** + * The app's name. + */ + applicationName?: string; + /** + * The app's version. + */ + applicationVersion?: string; + /** + * Copyright information. + */ + copyright?: string; + /** + * Credit information. + */ + credits?: string; + /** + * The app's build version number. + */ + version?: string; + } + // https://github.com/electron/electron/blob/master/docs/api/auto-updater.md /** @@ -740,7 +768,7 @@ declare namespace Electron { * The BrowserWindow class gives you ability to create a browser window. * You can also create a window without chrome by using Frameless Window API. */ - class BrowserWindow extends EventEmitter { + class BrowserWindow extends NodeJS.EventEmitter implements Destroyable { /** * Emitted when the document changed its title, * calling event.preventDefault() would prevent the native window’s title to change. @@ -1104,7 +1132,7 @@ declare namespace Electron { * setting this, the window is still a normal window, not a toolbox window * which can not be focused on. */ - setAlwaysOnTop(flag: boolean): void; + setAlwaysOnTop(flag: boolean, level?: WindowLevel): void; /** * @returns Whether the window is always on top of other windows. */ @@ -1357,8 +1385,8 @@ declare namespace Electron { getChildWindows(): BrowserWindow[]; } + type WindowLevel = 'normal' | 'floating' | 'torn-off-menu' | 'modal-panel' | 'main-menu' | 'status' | 'pop-up-menu' | 'screen-saver' | 'dock'; type SwipeDirection = 'up' | 'right' | 'down' | 'left'; - type ThumbarButtonFlags = 'enabled' | 'disabled' | 'dismissonclick' | 'nobackground' | 'hidden' | 'noninteractive'; interface ThumbarButton { @@ -1538,6 +1566,11 @@ declare namespace Electron { * Default: false. */ offscreen?: boolean; + /** + * Whether to enable Chromium OS-level sandbox. + * Default: false. + */ + sandbox?: boolean; } interface BrowserWindowOptions { @@ -2532,7 +2565,7 @@ declare namespace Electron { * * Each menu consists of multiple menu items, and each menu item can have a submenu. */ - class Menu extends EventEmitter { + class Menu extends NodeJS.EventEmitter { /** * Creates a new menu. */ @@ -2627,7 +2660,7 @@ declare namespace Electron { */ getBitmap(): Buffer; /** - * @returns string The data URL of the image. + * @returns The data URL of the image. */ toDataURL(): string; /** @@ -2637,11 +2670,11 @@ declare namespace Electron { */ getNativeHandle(): Buffer; /** - * @returns boolean Whether the image is empty. + * @returns Whether the image is empty. */ isEmpty(): boolean; /** - * @returns {} The size of the image. + * @returns The size of the image. */ getSize(): Size; /** @@ -2654,6 +2687,247 @@ declare namespace Electron { isTemplateImage(): boolean; } + // https://github.com/electron/electron/blob/master/docs/api/net.md + + /** + * The net module is a client-side API for issuing HTTP(S) requests. + * It is similar to the HTTP and HTTPS modules of Node.js but uses Chromium’s native + * networking library instead of the Node.js implementation, offering better support + * for web proxies. + * The following is a non-exhaustive list of why you may consider using the net module + * instead of the native Node.js modules: + * - Automatic management of system proxy configuration, support of the wpad protocol + * and proxy pac configuration files. + * - Automatic tunneling of HTTPS requests. + * - Support for authenticating proxies using basic, digest, NTLM, Kerberos or negotiate + * authentication schemes. + * - Support for traffic monitoring proxies: Fiddler-like proxies used for access control + * and monitoring. + * + * The net module API has been specifically designed to mimic, as closely as possible, + * the familiar Node.js API. The API components including classes, methods, + * properties and event names are similar to those commonly used in Node.js. + * + * The net API can be used only after the application emits the ready event. + * Trying to use the module before the ready event will throw an error. + */ + interface Net extends NodeJS.EventEmitter { + /** + * @param options The ClientRequest constructor options. + * @param callback A one time listener for the response event. + * + * @returns a ClientRequest instance using the provided options which are directly + * forwarded to the ClientRequest constructor. + */ + request(options: string | RequestOptions, callback?: (response: IncomingMessage) => void): ClientRequest; + } + + /** + * The RequestOptions interface allows to define various options for an HTTP request. + */ + interface RequestOptions { + /** + * The HTTP request method. Defaults to the GET method. + */ + method?: string; + /** + * The request URL. Must be provided in the absolute form with the protocol + * scheme specified as http or https. + */ + url?: string; + /** + * The Session instance with which the request is associated. + */ + session?: Session; + /** + * The name of the partition with which the request is associated. + * Defaults to the empty string. The session option prevails on partition. + * Thus if a session is explicitly specified, partition is ignored. + */ + partition?: string; + /** + * The protocol scheme in the form ‘scheme:’. Currently supported values are ‘http:’ or ‘https:’. + * Defaults to ‘http:’. + */ + Protocol?: 'http:' | 'https:'; + /** + * The server host provided as a concatenation of the hostname and the port number ‘hostname:port’. + */ + host?: string; + /** + * The server host name. + */ + hostname?: string; + /** + * The server’s listening port number. + */ + port?: number; + /** + * The path part of the request URL. + */ + path?: string; + /** + * A map specifying extra HTTP header name/value. + */ + headers?: { [key: string]: any }; + } + + /** + * The ClientRequest class represents an HTTP request. + */ + class ClientRequest extends NodeJS.EventEmitter { + /** + * Emitted when an HTTP response is received for the request. + */ + on(event: 'response', listener: (response: IncomingMessage) => void): this; + /** + * Emitted when an authenticating proxy is asking for user credentials. + * The callback function is expected to be called back with user credentials. + * Providing empty credentials will cancel the request and report an authentication + * error on the response object. + */ + on(event: 'login', listener: (authInfo: LoginAuthInfo, callback: (username?: string, password?: string) => void) => void): this; + /** + * Emitted just after the last chunk of the request’s data has been written into + * the request object. + */ + on(event: 'finish', listener: () => void): this; + /** + * Emitted when the request is aborted. The abort event will not be fired if the + * request is already closed. + */ + on(event: 'abort', listener: () => void): this; + /** + * Emitted when the net module fails to issue a network request. + * Typically when the request object emits an error event, a close event will + * subsequently follow and no response object will be provided. + */ + on(event: 'error', listener: (error: Error) => void): this; + /** + * Emitted as the last event in the HTTP request-response transaction. + * The close event indicates that no more events will be emitted on either the + * request or response objects. + */ + on(event: 'close', listener: () => void): this; + on(event: string, listener: Function): this; + /** + * A Boolean specifying whether the request will use HTTP chunked transfer encoding or not. + * Defaults to false. The property is readable and writable, however it can be set only before + * the first write operation as the HTTP headers are not yet put on the wire. + * Trying to set the chunkedEncoding property after the first write will throw an error. + * + * Using chunked encoding is strongly recommended if you need to send a large request + * body as data will be streamed in small chunks instead of being internally buffered + * inside Electron process memory. + */ + chunkedEncoding: boolean; + /** + * @param options If options is a String, it is interpreted as the request URL. + * If it is an object, it is expected to be a RequestOptions. + * @param callback A one time listener for the response event. + */ + constructor(options: string | RequestOptions, callback?: (response: IncomingMessage) => void); + /** + * Adds an extra HTTP header. The header name will issued as it is without lowercasing. + * It can be called only before first write. Calling this method after the first write + * will throw an error. + * @param name An extra HTTP header name. + * @param value An extra HTTP header value. + */ + setHeader(name: string, value: string): void; + /** + * @param name Specify an extra header name. + * @returns The value of a previously set extra header name. + */ + getHeader(name: string): string; + /** + * Removes a previously set extra header name. This method can be called only before first write. + * Trying to call it after the first write will throw an error. + * @param name Specify an extra header name. + */ + removeHeader(name: string): void; + /** + * Adds a chunk of data to the request body. The first write operation may cause the + * request headers to be issued on the wire. + * After the first write operation, it is not allowed to add or remove a custom header. + * @param chunk A chunk of the request body’s data. If it is a string, it is converted + * into a Buffer using the specified encoding. + * @param encoding Used to convert string chunks into Buffer objects. Defaults to ‘utf-8’. + * @param callback Called after the write operation ends. + */ + write(chunk: string | Buffer, encoding?: string, callback?: Function): boolean; + /** + * Sends the last chunk of the request data. Subsequent write or end operations will not be allowed. + * The finish event is emitted just after the end operation. + * @param chunk A chunk of the request body’s data. If it is a string, it is converted into + * a Buffer using the specified encoding. + * @param encoding Used to convert string chunks into Buffer objects. Defaults to ‘utf-8’. + * @param callback Called after the write operation ends. + * + */ + end(chunk?: string | Buffer, encoding?: string, callback?: Function): boolean; + /** + * Cancels an ongoing HTTP transaction. If the request has already emitted the close event, + * the abort operation will have no effect. + * Otherwise an ongoing event will emit abort and close events. + * Additionally, if there is an ongoing response object,it will emit the aborted event. + */ + abort(): void + } + + /** + * An IncomingMessage represents an HTTP response. + */ + interface IncomingMessage extends NodeJS.ReadableStream { + /** + * The data event is the usual method of transferring response data into applicative code. + */ + on(event: 'data', listener: (chunk: Buffer) => void): this; + /** + * Indicates that response body has ended. + */ + on(event: 'end', listener: () => void): this; + /** + * Emitted when a request has been canceled during an ongoing HTTP transaction. + */ + on(event: 'aborted', listener: () => void): this; + /** + * Emitted when an error was encountered while streaming response data events. + * For instance, if the server closes the underlying while the response is still + * streaming, an error event will be emitted on the response object and a close + * event will subsequently follow on the request object. + */ + on(event: 'error', listener: (error: Error) => void): this; + on(event: string, listener: Function): this; + /** + * An Integer indicating the HTTP response status code. + */ + statusCode: number; + /** + * A String representing the HTTP status message. + */ + statusMessage: string; + /** + * An object representing the response HTTP headers. The headers object is formatted as follows: + * - All header names are lowercased. + * - Each header name produces an array-valued property on the headers object. + * - Each header value is pushed into the array associated with its header name. + */ + headers: Headers; + /** + * A string indicating the HTTP protocol version number. Typical values are ‘1.0’ or ‘1.1’. + */ + httpVersion: string; + /** + * An integer-valued read-only property that returns the HTTP major version number. + */ + httpVersionMajor: number; + /** + * An integer-valued read-only property that returns the HTTP minor version number. + */ + httpVersionMinor: number; + } + // https://github.com/electron/electron/blob/master/docs/api/power-monitor.md /** @@ -2689,7 +2963,7 @@ declare namespace Electron { interface PowerSaveBlocker { /** * Starts preventing the system from entering lower-power mode. - * @returns an integer identifying the power save blocker. + * @returns The blocker ID that is assigned to this power blocker. * Note: prevent-display-sleep has higher has precedence over prevent-app-suspension. */ start(type: 'prevent-app-suspension' | 'prevent-display-sleep'): number; @@ -2700,7 +2974,7 @@ declare namespace Electron { stop(id: number): void; /** * @param id The power save blocker id returned by powerSaveBlocker.start. - * @returns a boolean whether the corresponding powerSaveBlocker has started. + * @returns Whether the corresponding powerSaveBlocker has started. */ isStarted(id: number): boolean; } @@ -2817,7 +3091,7 @@ declare namespace Electron { interface StringProtocolCallback extends ProtocolCallback { (str: string): void; (obj: { - data: Buffer, + data: string, mimeType: string, charset?: string }): void; @@ -2940,7 +3214,7 @@ declare namespace Electron { * You can also access the session of existing pages by using * the session property of webContents which is a property of BrowserWindow. */ - class Session extends EventEmitter { + class Session extends NodeJS.EventEmitter { /** * @returns a new Session instance from partition string. */ @@ -3136,6 +3410,11 @@ declare namespace Electron { } interface Cookie { + /** + * Emitted when a cookie is changed because it was added, edited, removed, or expired. + */ + on(event: 'changed', listener: (event: Event, cookie: Cookie, cause: CookieChangedCause) => void): this; + on(event: string, listener: Function): this; /** * The name of the cookie. */ @@ -3175,6 +3454,8 @@ declare namespace Electron { expirationDate?: number; } + type CookieChangedCause = 'explicit' | 'overwrite' | 'expired' | 'evicted' | 'expired-overwrite'; + interface CookieDetails { /** * The URL associated with the cookie. @@ -3515,6 +3796,38 @@ declare namespace Electron { // https://github.com/electron/electron/blob/master/docs/api/system-preferences.md + type SystemColor = + '3d-dark-shadow' | // Dark shadow for three-dimensional display elements. + '3d-face' | // Face color for three-dimensional display elements and for dialog box backgrounds. + '3d-highlight' | // Highlight color for three-dimensional display elements. + '3d-light' | // Light color for three-dimensional display elements. + '3d-shadow' | // Shadow color for three-dimensional display elements. + 'active-border' | // Active window border. + 'active-caption' | // Active window title bar. Specifies the left side color in the color gradient of an active window's title bar if the gradient effect is enabled. + 'active-caption-gradient' | // Right side color in the color gradient of an active window's title bar. + 'app-workspace' | // Background color of multiple document interface (MDI) applications. + 'button-text' | // Text on push buttons. + 'caption-text' | // Text in caption, size box, and scroll bar arrow box. + 'desktop' | // Desktop background color. + 'disabled-text' | // Grayed (disabled) text. + 'highlight' | // Item(s) selected in a control. + 'highlight-text' | // Text of item(s) selected in a control. + 'hotlight' | // Color for a hyperlink or hot-tracked item. + 'inactive-border' | // Inactive window border. + 'inactive-caption' | // Inactive window caption. Specifies the left side color in the color gradient of an inactive window's title bar if the gradient effect is enabled. + 'inactive-caption-gradient' | // Right side color in the color gradient of an inactive window's title bar. + 'inactive-caption-text' | // Color of text in an inactive caption. + 'info-background' | // Background color for tooltip controls. + 'info-text' | // Text color for tooltip controls. + 'menu' | // Menu background. + 'menu-highlight' | // The color used to highlight menu items when the menu appears as a flat menu. + 'menubar' | // The background color for the menu bar when menus appear as flat menus. + 'menu-text' | // Text in menus. + 'scrollbar' | // Scroll bar gray area. + 'window' | // Window background. + 'window-frame' | // Window frame. + 'window-text'; // Text in windows. + /** * Get system preferences. */ @@ -3523,15 +3836,29 @@ declare namespace Electron { * Note: This is only implemented on Windows. */ on(event: 'accent-color-changed', listener: (event: Event, newColor: string) => void): this; + /** + * Note: This is only implemented on Windows. + */ + on(event: 'color-changed', listener: (event: Event) => void): this; + /** + * Note: This is only implemented on Windows. + */ + on(event: 'inverted-color-scheme-changed', listener: ( + event: Event, + /** + * @param invertedColorScheme true if an inverted color scheme, such as a high contrast theme, is being used, false otherwise. + */ + invertedColorScheme: boolean + ) => void): this; on(event: string, listener: Function): this; /** - * @returns If the system is in Dark Mode. + * @returns Whether the system is in Dark Mode. * * Note: This is only implemented on macOS. */ isDarkMode(): boolean; /** - * @returns If the Swipe between pages setting is on. + * @returns Whether the Swipe between pages setting is on. * * Note: This is only implemented on macOS. */ @@ -3589,6 +3916,18 @@ declare namespace Electron { * Note: This is only implemented on Windows. */ getAccentColor(): string; + /** + * @returns true if an inverted color scheme, such as a high contrast theme, is active, false otherwise. + * + * Note: This is only implemented on Windows. + */ + isInvertedColorScheme(): boolean; + /** + * @returns The system color setting in RGB hexadecimal form (#ABCDEF). See the Windows docs for more details. + * + * Note: This is only implemented on Windows. + */ + getColor(color: SystemColor): string; } // https://github.com/electron/electron/blob/master/docs/api/tray.md @@ -3596,7 +3935,7 @@ declare namespace Electron { /** * A Tray represents an icon in an operating system's notification area. */ - interface Tray extends NodeJS.EventEmitter { + class Tray extends NodeJS.EventEmitter implements Destroyable { /** * Emitted when the tray icon is clicked. * Note: The bounds payload is only implemented on macOS and Windows. @@ -3661,7 +4000,7 @@ declare namespace Electron { /** * Creates a new tray icon associated with the image. */ - new(image: NativeImage|string): Tray; + constructor(image: NativeImage|string); /** * Destroys the tray icon immediately. */ @@ -3712,6 +4051,10 @@ declare namespace Electron { * @returns The bounds of this tray icon. */ getBounds(): Rectangle; + /** + * @returns Whether the tray icon is destroyed. + */ + isDestroyed(): boolean; } interface Modifiers { @@ -5463,13 +5806,14 @@ declare namespace Electron { globalShortcut: Electron.GlobalShortcut; Menu: typeof Electron.Menu; MenuItem: typeof Electron.MenuItem; + net: Electron.Net; powerMonitor: Electron.PowerMonitor; powerSaveBlocker: Electron.PowerSaveBlocker; protocol: Electron.Protocol; screen: Electron.Screen; session: typeof Electron.Session; systemPreferences: Electron.SystemPreferences; - Tray: Electron.Tray; + Tray: typeof Electron.Tray; webContents: Electron.WebContentsStatic; } diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 59e759d6aa..77bd63e3e6 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -93,6 +93,18 @@ namespace ShallowWrapperTest { boolVal = shallowWrapper.containsAnyMatchingElements([

]); } + function test_dive() { + interface TmpProps { + foo: any + } + + interface TmpState { + bar: any + } + + const diveWrapper: ShallowWrapper = shallowWrapper.dive({ context: { foobar: 'barfoo' }}); + } + function test_equals() { boolVal = shallowWrapper.equals(
); } @@ -189,7 +201,7 @@ namespace ShallowWrapperTest { } function test_state() { - shallowWrapper.state(); + const state: MyComponentState = shallowWrapper.state(); shallowWrapper.state('key'); const tmp: String = shallowWrapper.state('key'); } @@ -219,11 +231,11 @@ namespace ShallowWrapperTest { } function test_setState() { - shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' }); + shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' }, () => console.log('state updated')); } function test_setProps() { - shallowWrapper = shallowWrapper.setProps({ propsProperty: 'foo' }); + shallowWrapper = shallowWrapper.setProps({ propsProperty: 'foo' }, () => console.log('props updated')); } function test_setContext() { diff --git a/enzyme/index.d.ts b/enzyme/index.d.ts index 02b0db7ef0..d531d12f03 100644 --- a/enzyme/index.d.ts +++ b/enzyme/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Enzyme v2.4.1 +// Type definitions for Enzyme v2.5.1 // Project: https://github.com/airbnb/enzyme -// Definitions by: Marian Palkus , Cap3 +// Definitions by: Marian Palkus , Cap3 , Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes as ReactHTMLAttributes } from "react"; @@ -101,11 +101,11 @@ interface CommonWrapper { is(selector: EnzymeSelector): boolean; /** - * Returns whether or not the current node is empty. - */ - isEmpty(): boolean; + * Returns whether or not the current node is empty. + */ + isEmpty(): boolean; - /** + /** * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. * This method is effectively the negation or inverse of filter. * @param selector @@ -202,8 +202,9 @@ interface CommonWrapper { * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. * @param [key] */ - state(key?: string): any; - state(key?: string): T; + state(): S; + state(key: string): any; + state(key: string): T; /** * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. @@ -251,8 +252,9 @@ interface CommonWrapper { * * NOTE: can only be called on a wrapper instance that is also the root instance. * @param state + * @param [callback] */ - setState(state: S): this; + setState(state: S, callback?: () => void): this; /** * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test @@ -263,9 +265,10 @@ interface CommonWrapper { * Returns itself. * * NOTE: can only be called on a wrapper instance that is also the root instance. - * @param state + * @param props + * @param [callback] */ - setProps(props: P): this; + setProps(props: P, callback?: () => void): this; /** * A method that sets the context of the root component, and re-renders. Useful for when you are wanting to @@ -423,6 +426,13 @@ export interface ShallowWrapper extends CommonWrapper { childAt(index: number): ShallowWrapper; /** + * Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result. + * NOTE: can only be called on wrapper of a single non-DOM component element node. + * @param [options] + */ + dive(options?: ShallowRendererProps): ShallowWrapper; + + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. * diff --git a/es6-error/es6-error-tests.ts b/es6-error/es6-error-tests.ts new file mode 100644 index 0000000000..26ed7b6677 --- /dev/null +++ b/es6-error/es6-error-tests.ts @@ -0,0 +1,9 @@ +import * as ExtendableError from "es6-error" + +class TestError extends ExtendableError { + constructor (message: string = "TestError") { + super(message) + } +} + +throw new TestError("Test Message") diff --git a/es6-error/index.d.ts b/es6-error/index.d.ts new file mode 100644 index 0000000000..c1d3d5ce21 --- /dev/null +++ b/es6-error/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for es6-error v4.0.0 +// Project: https://github.com/bjyoungblood/es6-error +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Error; diff --git a/es6-error/tsconfig.json b/es6-error/tsconfig.json new file mode 100644 index 0000000000..a36756343e --- /dev/null +++ b/es6-error/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "es6-error-tests.ts" + ] +} \ No newline at end of file diff --git a/event-kit/event-kit-tests.ts b/event-kit/event-kit-tests.ts index 8c5969f756..4b4a0d4e7c 100644 --- a/event-kit/event-kit-tests.ts +++ b/event-kit/event-kit-tests.ts @@ -24,6 +24,7 @@ class User { } destroy(): void { + this.emitter.clear(); this.emitter.dispose(); } } @@ -39,6 +40,7 @@ var user = new User(); var subscription = user.onDidChangeName((name: string) => { console.log('User name change to: ' + name); }); +if(Disposable.isDisposable(subscription)) {} subscription.dispose(); // CompositeDisposable diff --git a/event-kit/index.d.ts b/event-kit/index.d.ts index de4e7a485c..0e2efc1e65 100644 --- a/event-kit/index.d.ts +++ b/event-kit/index.d.ts @@ -14,6 +14,10 @@ declare namespace AtomEventKit { interface DisposableStatic { prototype: Disposable; new (disposalAction: Function): Disposable; + /** + * Ensure that Object correctly implements the Disposable. + */ + isDisposable(object: Object): boolean; } /** Instance side of the Disposable class. */ @@ -59,6 +63,13 @@ declare namespace AtomEventKit { isDisposed: boolean; constructor: EmitterStatic; + /** + * Clear out any existing subscribers. + */ + clear(): void; + /** + * Unsubscribe all handlers. + */ dispose(): void; /** * Registers a handler to be invoked whenever the given event is emitted. diff --git a/event-to-promise/event-to-promise-tests.ts b/event-to-promise/event-to-promise-tests.ts new file mode 100644 index 0000000000..2b99ddc62f --- /dev/null +++ b/event-to-promise/event-to-promise-tests.ts @@ -0,0 +1,21 @@ +import { EventEmitter } from 'events' + +import * as eventToPromise from 'event-to-promise' + + +{ + const ee = new EventEmitter() + const ep = eventToPromise(ee, 'custom') + + ep.then(console.log) + ee.emit('custom') +} + + +{ + const et = new EventTarget() + const tp = eventToPromise.multi(et, ['custom']) + + tp.then(console.log) + et.dispatchEvent(new Event('custom')) +} diff --git a/event-to-promise/index.d.ts b/event-to-promise/index.d.ts new file mode 100644 index 0000000000..aa491f0b0e --- /dev/null +++ b/event-to-promise/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for event-to-promise v0.7.0 +// Project: https://github.com/JsCommunity/event-to-promise +// Definitions by: flying-sheep +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { EventEmitter } from 'events' + +type EventSource = EventEmitter | EventTarget + +interface EventToPromiseOptions { + /** If true, all parameters of the emitted events are put in an array which is used to resolve/reject the promise. (default: `false`) */ + array?: boolean, + /** The name of the event which rejects the promise. (default: `'error'`) */ + error?: string, + /** Whether the error event should be ignored and not reject the promise. (default: `false`) */ + ignoreErrors?: boolean, +} + +/** + * Wait for one event. The first parameter of the emitted event is used to resolve/reject the promise. + * + * @param emitter The event emitter you want to watch an event on. + * @param event The name of the event you want to watch. + * @param options An `Object` controlling advanced options. + * @return The returned promise has a `cancel()` method which can be used to remove the event listeners. Note that the promise will never settled if canceled. + */ +declare function eventToPromise(emitter: EventSource, event: string, options?: EventToPromiseOptions): Promise; + +declare namespace eventToPromise { + /** + * Wait for one of multiple events. The array of all the parameters of the emitted event is used to resolve/reject the promise. + * + * The array also has an event property indicating which event has been emitted. + * + * @param emitter The event emitter you want to watch an event on. + * @param successEvents The names of the events which resolve the promise. + * @param errorEvents The names of the events which reject the promise. (default: `['error']`) + * @return The returned promise has a `cancel()` method which can be used to remove the event listeners. Note that the promise will never settled if canceled. + */ + export function multi(emitter: EventSource, successEvents: string[], errorEvents?: string[]): Promise; +} + +export = eventToPromise diff --git a/event-to-promise/tsconfig.json b/event-to-promise/tsconfig.json new file mode 100644 index 0000000000..d5fd4f1e8e --- /dev/null +++ b/event-to-promise/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "event-to-promise-tests.ts" + ] +} diff --git a/eventemitter2/eventemitter2-tests.ts b/eventemitter2/eventemitter2-tests.ts index 936366c0b9..8a7849abfa 100644 --- a/eventemitter2/eventemitter2-tests.ts +++ b/eventemitter2/eventemitter2-tests.ts @@ -18,7 +18,8 @@ function testConfiguration() { wildcard: true, delimiter: '::', newListener: false, - maxListeners: 20 + maxListeners: 20, + verboseMemoryLeak: true }); var bar = new EventEmitter2({}); var bazz = new EventEmitter2(); diff --git a/eventemitter2/index.d.ts b/eventemitter2/index.d.ts index de1be0d064..0372b675dc 100644 --- a/eventemitter2/index.d.ts +++ b/eventemitter2/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for EventEmitter2 v0.14.4 +// Type definitions for EventEmitter2 v2.2.0 // Project: https://github.com/asyncly/EventEmitter2 // Definitions by: ryiwamoto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -23,6 +23,11 @@ interface EventEmitter2Configuration { * max listeners that can be assigned to an event, default 10. */ maxListeners?: number; + + /** + * show event name in memory leak message when more than maximum amount of listeners is assigned, default false + */ + verboseMemoryLeak?: boolean; } declare class EventEmitter2 { diff --git a/eventemitter3/eventemitter3-tests.ts b/eventemitter3/eventemitter3-tests.ts index c0a532fc87..9c8e379ec9 100644 --- a/eventemitter3/eventemitter3-tests.ts +++ b/eventemitter3/eventemitter3-tests.ts @@ -1,585 +1,116 @@ -/// -/// 'use strict'; -import EventEmitter = require('eventemitter3'); -import util = require('util'); -import * as EventEmitter3ImportedAsES6Module from 'eventemitter3'; +import * as EventEmitter from 'eventemitter3'; -declare namespace Assume { - interface Class { - new(...args: any[]): T; - } - - interface Assume { - equals(compare: T): Assume; - equal(compare: T): Assume; - eqls(compare: T): Assume; - is: Assume; - deep: Assume; - to: Assume; - either(arr: T[]): Assume; - instanceOf(clazz: Class): Assume; - a(typeofString: string): Assume; - } - - export function assume(input: T): Assume; -} - -let assume = Assume.assume; - -class EventEmitterTest { - v: any; +const eventName = 'test'; +const eventSymbol: symbol = Symbol('test'); +const fn = () => console.log(1); +// Extending EventEmitter +class TestEmitter extends EventEmitter { constructor() { - this.v = new EventEmitter(); - this.v = new EventEmitter3ImportedAsES6Module(); - - // Some methods are missing or incompatible with current implementation (v4.2.x) of NodeJS.EventEmitter - // (e.g. getMaxListenters or listeners) - // var n: NodeJS.EventEmitter = this.v; + super(); } - listeners() { - var v1: Function[] = this.v.listeners('click'); - } - - emit() { - var v1: boolean = this.v.emit('click'); - var v2: boolean = this.v.emit('click', 1); - var v3: boolean = this.v.emit('click', 1, '1'); - var v4: boolean = this.v.emit('click', 1, '1', true); - var v5: boolean = this.v.emit('click', 1, '1', true, new Date()); - } - - on() { - var fn = () => console.log(1); - var v1 = this.v.on('click', fn); - var v2 = this.v.on('click', fn, this); - } - - once() { - var fn = () => console.log(1); - var v1 = this.v.once('click', fn); - var v2 = this.v.once('click', fn, this); - } - - removeListener() { - var fn = () => console.log(1); - var v1 = this.v.removeListener('click', fn); - var v2 = this.v.removeListener('click', fn, true); - } - - removeAllListeners() { - var v1 = this.v.removeAllListeners('click'); - } - - off() { - var fn = () => console.log(1); - var v1 = this.v.off('click', fn); - var v2 = this.v.off('click', fn, true); - } - - addListener() { - var fn = () => console.log(1); - var v1 = this.v.addListener('click', fn); - var v2 = this.v.addListener('click', fn, this); - } - - setMaxListeners() { - var v1 = this.v.setMaxListeners(); + test() { + return this; } } +const ee: TestEmitter = new TestEmitter(); -describe('EventEmitter', function tests() { - 'use strict'; +// EventEmitter.prefixed +// should be boolean or string static property +const prefix = EventEmitter.prefixed; +if (typeof prefix === 'boolean') { + console.log(prefix.valueOf()); +} else { + console.log(prefix.length); +} - it('exposes a `prefixed` property', function () { - assume(EventEmitter.prefixed).is.either([false, '~']); - }); - - it('inherits when used with require(util).inherits', function () { - class Beast extends EventEmitter { - /* rawr, i'm a beast */ +// EventEmitter.eventNames() +// should return array of strings or symbols +ee.eventNames().every((event) => { + if (typeof event === 'symbol') { + return false; + } else { + return event.length > 0; } - - class BeastES6 extends EventEmitter3ImportedAsES6Module { - /* rawr, i'm a beast */ - } - - util.inherits(Beast, EventEmitter); - - var moop = new Beast() - , meap = new Beast(); - - assume(moop).is.instanceOf(Beast); - assume(moop).is.instanceOf(EventEmitter); - - moop.listeners(); - meap.listeners(); - - moop.on('data', function () { - throw new Error('I should not emit'); - }); - - meap.emit('data', 'rawr'); - meap.removeListener('foo'); - meap.removeAllListeners(); - }); - - describe('EventEmitter#emit', function () { - it('should return false when there are not events to emit', function () { - var e = new EventEmitter(); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - }); - - it('emits with context', function (done) { - var context = { bar: 'baz' } - , e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(bar).equals('bar'); - assume(this).equals(context); - - done(); - }, context).emit('foo', 'bar'); - }); - - it('emits with context, multiple arguments (force apply)', function (done) { - var context = { bar: 'baz' } - , e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(bar).equals('bar'); - assume(this).equals(context); - - done(); - }, context).emit('foo', 'bar', 1,2,3,4,5,6,7,8,9,0); - }); - - it('can emit the function with multiple arguments', function () { - var e = new EventEmitter(); - - for(var i = 0; i < 100; i++) { - (function (j: number) { - for (var i = 0, args: number[] = []; i < j; i++) { - args.push(j); - } - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.emit.apply(e, (['args'] as any[]).concat(args)); - })(i); - } - }); - - it('can emit the function with multiple arguments, multiple listeners', function () { - var e = new EventEmitter(); - - for(var i = 0; i < 100; i++) { - (function (j: number) { - for (var i = 0, args: number[] = []; i < j; i++) { - args.push(j); - } - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.once('args', function () { - assume(arguments.length).equals(args.length); - }); - - e.emit.apply(e, (['args'] as any[]).concat(args)); - })(i); - } - }); - - it('emits with context, multiple listeners (force loop)', function () { - var e = new EventEmitter(); - - e.on('foo', function (bar: string) { - assume(this).eqls({ foo: 'bar' }); - assume(bar).equals('bar'); - }, { foo: 'bar' }); - - e.on('foo', function (bar: string) { - assume(this).eqls({ bar: 'baz' }); - assume(bar).equals('bar'); - }, { bar: 'baz' }); - - e.emit('foo', 'bar'); - }); - - it('emits with different contexts', function () { - var e = new EventEmitter() - , pattern = ''; - - function writer() { - pattern += this; - } - - e.on('write', writer, 'foo'); - e.on('write', writer, 'baz'); - e.once('write', writer, 'bar'); - e.once('write', writer, 'banana'); - - e.emit('write'); - assume(pattern).equals('foobazbarbanana'); - }); - - it('should return true when there are events to emit', function (done) { - var e = new EventEmitter(); - - e.on('foo', function () { - process.nextTick(done); - }); - - assume(e.emit('foo')).equals(true); - assume(e.emit('foob')).equals(false); - }); - - it('receives the emitted events', function (done) { - var e = new EventEmitter(); - - e.on('data', function (a: string, b: any, c: Date, d: void, undef: void) { - assume(a).equals('foo'); - assume(b).equals(e); - assume(c).is.instanceOf(Date); - assume(undef).equals(undefined); - assume(arguments.length).equals(3); - - done(); - }); - - e.emit('data', 'foo', e, new Date()); - }); - - it('emits to all event listeners', function () { - var e = new EventEmitter() - , pattern: string[] = []; - - e.on('foo', function () { - pattern.push('foo1'); - }); - - e.on('foo', function () { - pattern.push('foo2'); - }); - - e.emit('foo'); - - assume(pattern.join(';')).equals('foo1;foo2'); - }); - - (function each(keys: string[]) { - var key = keys.shift(); - - if (!key) return; - - it('can store event which is a known property: '+ key, function (next) { - var e = new EventEmitter(); - - e.on(key, function (key: string) { - assume(key).equals(key); - next(); - }).emit(key, key); - }); - - each(keys); - })([ - 'hasOwnProperty', - 'constructor', - '__proto__', - 'toString', - 'toValue', - 'unwatch', - 'watch' - ]); - }); - - describe('EventEmitter#listeners', function () { - it('returns an empty array if no listeners are specified', function () { - var e = new EventEmitter(); - - assume(e.listeners('foo')).is.a('array'); - assume(e.listeners('foo').length).equals(0); - }); - - it('returns an array of function', function () { - var e = new EventEmitter(); - - function foo() {} - - e.on('foo', foo); - assume(e.listeners('foo')).is.a('array'); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('foo')).deep.equals([foo]); - }); - - it('is not vulnerable to modifications', function () { - var e = new EventEmitter(); - - function foo() {} - - e.on('foo', foo); - - assume(e.listeners('foo')).deep.equals([foo]); - - e.listeners('foo').length = 0; - assume(e.listeners('foo')).deep.equals([foo]); - }); - - it('can return a boolean as indication if listeners exist', function () { - var e = new EventEmitter(); - - function foo() {} - - e.once('once', foo); - e.once('multiple', foo); - e.once('multiple', foo); - e.on('on', foo); - e.on('multi', foo); - e.on('multi', foo); - - assume(e.listeners('foo', true)).equals(false); - assume(e.listeners('multiple', true)).equals(true); - assume(e.listeners('on', true)).equals(true); - assume(e.listeners('multi', true)).equals(true); - - e.removeAllListeners(); - - assume(e.listeners('multiple', true)).equals(false); - assume(e.listeners('on', true)).equals(false); - assume(e.listeners('multi', true)).equals(false); - }); - }); - - describe('EventEmitter#once', function () { - it('only emits it once', function () { - var e = new EventEmitter() - , calls = 0; - - e.once('foo', function () { - calls++; - }); - - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - - assume(e.listeners('foo').length).equals(0); - assume(calls).equals(1); - }); - - it('only emits once if emits are nested inside the listener', function () { - var e = new EventEmitter() - , calls = 0; - - e.once('foo', function () { - calls++; - e.emit('foo'); - }); - - e.emit('foo'); - assume(e.listeners('foo').length).equals(0); - assume(calls).equals(1); - }); - - it('only emits once for multiple events', function () { - var e = new EventEmitter() - , multi = 0 - , foo = 0 - , bar = 0; - - e.once('foo', function () { - foo++; - }); - - e.once('foo', function () { - bar++; - }); - - e.on('foo', function () { - multi++; - }); - - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - e.emit('foo'); - - assume(e.listeners('foo').length).equals(1); - assume(multi).equals(5); - assume(foo).equals(1); - assume(bar).equals(1); - }); - - it('only emits once with context', function (done) { - var context = { foo: 'bar' } - , e = new EventEmitter(); - - e.once('foo', function (bar: string) { - assume(this).equals(context); - assume(bar).equals('bar'); - - done(); - }, context).emit('foo', 'bar'); - }); - }); - - describe('EventEmitter#removeListener', function () { - it('should only remove the event with the specified function', function () { - var e = new EventEmitter(); - - function bar() {} - e.on('foo', function () {}); - e.on('bar', function () {}); - e.on('bar', bar); - - assume(e.removeListener('foo', bar)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('bar').length).equals(2); - - assume(e.removeListener('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(2); - - assume(e.removeListener('bar', bar)).equals(e); - assume(e.listeners('bar').length).equals(1); - assume(e.removeListener('bar')).equals(e); - assume(e.listeners('bar').length).equals(0); - }); - - it('should only remove once events when using the once flag', function () { - var e = new EventEmitter(); - - function foo() {} - e.on('foo', foo); - - assume(e.removeListener('foo', function () {}, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo)).equals(e); - assume(e.listeners('foo').length).equals(0); - - e.on('foo', foo); - e.once('foo', foo); - - assume(e.removeListener('foo', function () {}, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, undefined, true)).equals(e); - assume(e.listeners('foo').length).equals(1); - - e.once('foo', foo); - - assume(e.removeListener('foo', foo)).equals(e); - assume(e.listeners('foo').length).equals(0); - }); - - it('should only remove listeners matching the correct context', function () { - var e = new EventEmitter() - , context = { foo: 'bar' }; - - function foo() {} - function bar() {} - e.on('foo', foo, context); - - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', function () {}, context)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, { baz: 'quux' })).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.removeListener('foo', foo, context)).equals(e); - assume(e.listeners('foo').length).equals(0); - - e.on('foo', foo, context); - e.on('foo', bar); - - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, { baz: 'quux' })).equals(e); - assume(e.listeners('foo').length).equals(2); - assume(e.removeListener('foo', foo, context)).equals(e); - assume(e.listeners('foo').length).equals(1); - assume(e.listeners('foo')[0]).equals(bar); - - e.on('foo', foo, context); - - assume(e.listeners('foo').length).equals(2); - assume(e.removeAllListeners('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - }); - }); - - describe('EventEmitter#removeAllListeners', function () { - it('removes all events for the specified events', function () { - var e = new EventEmitter(); - - e.on('foo', function () { throw new Error('oops'); }); - e.on('foo', function () { throw new Error('oops'); }); - e.on('bar', function () { throw new Error('oops'); }); - e.on('aaa', function () { throw new Error('oops'); }); - - assume(e.removeAllListeners('foo')).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(1); - assume(e.listeners('aaa').length).equals(1); - - assume(e.removeAllListeners('bar')).equals(e); - assume(e.removeAllListeners('aaa')).equals(e); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - assume(e.emit('aaa')).equals(false); - }); - - it('just nukes the fuck out of everything', function () { - var e = new EventEmitter(); - - e.on('foo', function () { throw new Error('oops'); }); - e.on('foo', function () { throw new Error('oops'); }); - e.on('bar', function () { throw new Error('oops'); }); - e.on('aaa', function () { throw new Error('oops'); }); - - assume(e.removeAllListeners()).equals(e); - assume(e.listeners('foo').length).equals(0); - assume(e.listeners('bar').length).equals(0); - assume(e.listeners('aaa').length).equals(0); - - assume(e.emit('foo')).equals(false); - assume(e.emit('bar')).equals(false); - assume(e.emit('aaa')).equals(false); - }); - }); - - describe('#setMaxListeners', function () { - it('is a function', function () { - var e = new EventEmitter(); - - assume(e.setMaxListeners).is.a('function'); - }); - - it('returns self when called', function () { - var e = new EventEmitter(); - - assume(e.setMaxListeners()).to.equal(e); - }); - }); }); + +// EventEmitter.listeners() +// should return array of functions +ee.listeners(eventName).map((listener) => { + return listener.bind(this); +}); +// should accept symbol as event name +ee.listeners(eventSymbol).map((listener) => { + return listener.bind(this); +}); +// should return boolean with 'exists' flag +const hasListeners: boolean = ee.listeners(eventName, true); + +// EventEmitter.emit() +// should support any number of arguments +ee.emit(eventName, 1, true, {}, [], 'test', Symbol(), null); +// should accept symbol as event name +ee.emit(eventSymbol); + +// EventEmitter.addListener() and EventEmitter.on() +// should accept function +ee.on(eventName, fn); +ee.addListener(eventName, fn); +// should accept optional context argument +ee.on(eventName, fn, this); +ee.addListener(eventName, fn, this); +// should accept symbol as event name +ee.on(eventSymbol, fn); +ee.addListener(eventSymbol, fn); +// should support fluent interface +ee.on(eventSymbol, fn).test(); +ee.addListener(eventSymbol, fn).test(); + +// EventEmitter.once() +// should accept event name and function +ee.once(eventName, fn); +// should accept optional context argument +ee.once(eventName, fn, this); +ee.once(eventName, fn, {}); +// should accept symbol as event name +ee.once(eventSymbol, fn); +// should support fluent interface +ee.once(eventSymbol, fn).test(); + +// EventEmitter.removeListener() and EventEmitter.off() +// should accept event name +ee.removeListener(eventName); +ee.off(eventName); +// should accept optional function +ee.removeListener(eventName, fn); +ee.off(eventName, fn); +// should accept optional context argument +ee.removeListener(eventName, fn, {}); +ee.off(eventName, fn, {}); +// should accept optional boolean flag for removing listeners added with `EventEmitter.once()` +ee.removeListener(eventName, fn, null, true); +ee.off(eventName, fn, null, true); +// should accept symbol as event name +ee.removeListener(eventSymbol); +ee.off(eventSymbol); +// should support fluent interface +ee.removeListener(eventName).test(); +ee.off(eventName).test(); + +// EventEmitter.removeAllListeners() +// should not require any arguments +ee.removeAllListeners(); +// should accept optional event name +ee.removeAllListeners(eventName); +// should accept symbol as event name +ee.removeAllListeners(eventSymbol); +// should support fluent interface +ee.removeAllListeners(eventName).test(); + +// EventEmitter.setMaxListeners() +// should support fluent interface +ee.setMaxListeners().test(); \ No newline at end of file diff --git a/eventemitter3/eventemitter3-tests.ts.tscparams b/eventemitter3/eventemitter3-tests.ts.tscparams new file mode 100644 index 0000000000..30c9419a57 --- /dev/null +++ b/eventemitter3/eventemitter3-tests.ts.tscparams @@ -0,0 +1 @@ +-m commonjs diff --git a/eventemitter3/index.d.ts b/eventemitter3/index.d.ts index 31ede80c21..9c1fe2397e 100644 --- a/eventemitter3/index.d.ts +++ b/eventemitter3/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for EventEmitter3 1.1.1 +// Type definitions for EventEmitter3 1.2.0 // Project: https://github.com/primus/eventemitter3 -// Definitions by: Yuichi Murata , Leon Yu +// Definitions by: Yuichi Murata , Leon Yu , Boriss Nazarovs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = EventEmitter; @@ -10,6 +10,10 @@ declare namespace EventEmitter { } type self = EventEmitter; +/** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + */ declare class EventEmitter { static prefixed: string | boolean; @@ -28,96 +32,91 @@ declare class EventEmitter { constructor(); /** - * Return a list of assigned event listeners. + * Return an array listing the events for which the emitter has registered listeners. * - * @param {String} event The events that should be listed. - * @returns {Array} - * @api public + * @returns {(string | symbol)[]} */ - listeners(event?: string): Function[]; + eventNames(): (string | symbol)[]; /** - * Return a list of assigned event listeners. + * Return the listeners registered for a given event. * - * @param {String} event The events that should be listed. - * @param {Boolean} exists We only need to know if there are listeners. - * @returns {Boolean} - * @api public + * @param {(string | symbol)} event The event name. + * @returns {Function[]} */ - listeners(event: string, param: boolean): boolean; + listeners(event: string | symbol): Function[]; /** - * Emit an event to all registered event listeners. + * Check if there listeners for a given event. + * If `exists` argument is not `true` lists listeners. * - * @param {String} event The name of the event. - * @returns {Boolean} Indication if we've emitted an event. - * @api public + * @param {(string | symbol)} event The event name. + * @param {boolean} exists Only check if there are listeners. + * @returns {boolean} */ - emit(event: string, ...args: any[]): boolean; + listeners(event: string | symbol, exists: boolean): boolean; /** - * Register a new EventListener for the given event. + * Calls each of the listeners registered for a given event. * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * @param {(string | symbol)} event The event name. + * @param {...*} args Arguments that are passed to registered listeners + * @returns {boolean} `true` if the event had listeners, else `false`. */ - on(event: string, fn: Function, context?: any): EventEmitter; + emit(event: string | symbol, ...args: any[]): boolean; /** - * Add an EventListener that's only called once. + * Add a listener for a given event. * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * @param {(string | symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. */ - once(event: string, fn: Function, context?: any): EventEmitter; + on(event: string | symbol, fn: Function, context?: any): this; /** - * Remove event listeners. + * Add a one-time listener for a given event. * - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Mixed} context Only remove listeners matching this context. - * @param {Boolean} once Only remove once listeners. - * @api public + * @param {(string | symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. */ - removeListener(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + once(event: string | symbol, fn: Function, context?: any): this; /** - * Remove all listeners or only the listeners for the specified event. + * Remove the listeners of a given event. * - * @param {String} event The event want to remove all listeners for. - * @api public + * @param {(string | symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. */ - removeAllListeners(event?: string): EventEmitter; + removeListener(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; /** - * Remove event listeners. + * Remove all listeners, or those of the specified event. * - * @param {String} event The event we want to remove. - * @param {Function} fn The listener that we need to find. - * @param {Mixed} context Only remove listeners matching this context. - * @param {Boolean} once Only remove once listeners. - * @api public + * @param {(string | symbol)} event The event name. + * @returns {EventEmitter} `this`. */ - off(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + removeAllListeners(event?: string | symbol): this; /** - * Register a new EventListener for the given event. - * - * @param {String} event Name of the event. - * @param {Function} fn Callback function. - * @param {Mixed} [context=this] The context of the function. - * @api public + * Alias method for `removeListener` */ - addListener(event: string, fn: Function, context?: any): EventEmitter; + off(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; + + /** + * Alias method for `on` + */ + addListener(event: string | symbol, fn: Function, context?: any): this; /** * This function doesn't apply anymore. * @deprecated */ - setMaxListeners(): EventEmitter; + setMaxListeners(): this; } diff --git a/express-brute/index.d.ts b/express-brute/index.d.ts index 3f0c3927b9..b6a60d4247 100644 --- a/express-brute/index.d.ts +++ b/express-brute/index.d.ts @@ -7,58 +7,6 @@ import express = require("express"); -/** - * @summary Options for {@link MemoryStore} class. - * @interface - */ -interface MemoryStoreOptions { - /** - * @summary Key prefix. - * @type {string} - */ - prefix: string; -} - -/** - * @summary Options for {@link ExpressBrute#getMiddleware} class. - * @interface - */ -interface ExpressBruteMiddleware { - /** - * @summary Allows you to override the value of failCallback for this middleware. - * @type {Function} - */ - failCallback: Function; - - /** - * @summary Disregard IP address when matching requests if set to true. Defaults to false. - * @type {boolean} - */ - ignoreIP: boolean; - - /** - * @summary Key. - * @type {any} - */ - key: any; -} - -/** - * @summary Options for {@link ExpressBrute} class. - * @interface - */ -interface ExpressBruteOptions { - freeRetries?: number; - proxyDepth?: number; - attachResetToRequest?: boolean; - refreshTimeoutOnRequest?: boolean; - minWait?: number; - maxWait?: number; - lifetime?: number; - failCallback?: (req: express.Request, res: express.Response, next: Function, nextValidRequestDate: any) => void; - handleStoreError?: any; -} - /** * @summary Middleware. * @class @@ -69,20 +17,13 @@ declare class ExpressBrute { * @constructor * @param {any} store The store. */ - constructor(store: any, options?: ExpressBruteOptions); + constructor(store: any, options?: ExpressBrute.Options); /** * @summary Generates middleware that will bounce requests with the same key and IP address that happen faster than the current wait time by calling failCallback. * @param {Object} options The options. */ - getMiddleware(options: ExpressBruteMiddleware): express.RequestHandler; - - /** - * @summary Uses the current proxy trust settings to get the current IP from a request object. - * @param {Request} request The HTTP request. - * @return {RequestHandler} The Request handler. - */ - getIPFromRequest(request: express.Request): express.RequestHandler; + getMiddleware(options: ExpressBrute.Middleware): express.RequestHandler; /** * @summary Middleware that will bounce requests that happen faster than the current wait time by calling failCallback. @@ -104,6 +45,81 @@ declare class ExpressBrute { } declare namespace ExpressBrute { + /** + * @summary Options for {@link MemoryStore} class. + * @interface + */ + export interface MemoryStoreOptions { + /** + * @summary Key prefix. + * @type {string} + */ + prefix: string; + } + + /** + * @summary Options for {@link ExpressBrute#getMiddleware} class. + * @interface + */ + export interface Middleware { + /** + * @summary Allows you to override the value of failCallback for this middleware. + * @type {Function} + */ + failCallback: Function; + + /** + * @summary Disregard IP address when matching requests if set to true. Defaults to false. + * @type {boolean} + */ + ignoreIP: boolean; + + /** + * @summary Key. + * @type {any} + */ + key: any; + } + + /** + * @summary Options for {@link ExpressBrute} class. + * @interface + */ + export interface Options { + /** + * @summary The number of retires the user has before they need to start waiting (default: 2) + */ + freeRetries?: number; + /** + * @summary Specify whether or not a simplified reset method should be attached at req.brute.reset. The simplified method takes only a callback, and resets all ExpressBrute middleware that was called on the current request. If multiple instances of ExpressBrute have middleware on the same request, only those with attachResetToRequest set to true will be reset (default: true) + */ + attachResetToRequest?: boolean; + /** + * @summary Defines whether the lifetime counts from the time of the last request that ExpressBrute didn't prevent for a given IP (true) or from of that IP's first request (false). Useful for allowing limits over fixed periods of time, for example: a limited number of requests per day. (Default: true). + */ + refreshTimeoutOnRequest?: boolean; + /** + * @summary The initial wait time (in milliseconds) after the user runs out of retries (default: 500 milliseconds) + */ + minWait?: number; + /** + * @summary The maximum amount of time (in milliseconds) between requests the user needs to wait (default: 15 minutes). The wait for a given request is determined by adding the time the user needed to wait for the previous two requests. + */ + maxWait?: number; + /** + * @summary The length of time (in seconds since the last request) to remember the number of requests that have been made by an IP. By default it will be set to maxWait * the number of attempts before you hit maxWait to discourage simply waiting for the lifetime to expire before resuming an attack. With default values this is about 6 hours. + */ + lifetime?: number; + /** + * @summary Gets called with (req, res, next, nextValidRequestDate) when a request is rejected (default: ExpressBrute.FailForbidden) + */ + failCallback?: (req: express.Request, res: express.Response, next: Function, nextValidRequestDate: any) => void; + /** + * @summary Gets called whenever an error occurs with the persistent store from which ExpressBrute cannot recover. It is passed an object containing the properties message (a description of the message), parent (the error raised by the session store), and [key, ip] or [req, res, next] depending on whether or the error occurs during reset or in the middleware itself. + */ + handleStoreError?: any; + } + /** * @summary In-memory store. * @class diff --git a/express-formidable/express-formidable-tests.ts b/express-formidable/express-formidable-tests.ts new file mode 100644 index 0000000000..91f9e34519 --- /dev/null +++ b/express-formidable/express-formidable-tests.ts @@ -0,0 +1,16 @@ +import express = require("express"); +import expform = require("express-formidable"); + +const app = express(); + +app.use("/form1", expform()); +app.use("/form2", expform({ + encoding: "utf-8", + uploadDir: "./uploads", + keepExtensions: true, + type: "multipart", + maxFieldsSize: 3 * 1024 * 1024, + maxFields: 50, + hash: "sha1", + multiples: true +})); diff --git a/express-formidable/index.d.ts b/express-formidable/index.d.ts new file mode 100644 index 0000000000..57342521c2 --- /dev/null +++ b/express-formidable/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for express-formidable 1.0.0 +// Project: https://github.com/noraesae/express-formidable +// Definitions by: Torkild Dyvik Olsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { RequestHandler } from "express"; + +interface ExpressFormidableOptions { + encoding?: string; + uploadDir?: string; + keepExtensions?: boolean; + type?: "multipart" | "urlencoded"; + maxFieldsSize?: number; + maxFields?: number; + hash?: boolean | "sha1" | "md5"; + multiples?: boolean; +} + +declare function ExpressFormidable(options?: ExpressFormidableOptions): RequestHandler; + +export = ExpressFormidable; diff --git a/express-formidable/tsconfig.json b/express-formidable/tsconfig.json new file mode 100644 index 0000000000..bac18433b1 --- /dev/null +++ b/express-formidable/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "express-formidable-tests.ts" + ] +} diff --git a/express-serve-static-core/index.d.ts b/express-serve-static-core/index.d.ts index d36964a1da..932b8075b1 100644 --- a/express-serve-static-core/index.d.ts +++ b/express-serve-static-core/index.d.ts @@ -5,1088 +5,1101 @@ // This extracts the core definitions from express to prevent a circular dependency between express and serve-static /// -declare namespace Express { +declare global { + namespace Express { - // These open interfaces may be extended in an application-specific manner via declaration merging. - // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/method-override/method-override.d.ts) - export interface Request { } - export interface Response { } - export interface Application { } + // These open interfaces may be extended in an application-specific manner via declaration merging. + // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/method-override/method-override.d.ts) + export interface Request { } + export interface Response { } + export interface Application { } + } } -declare module "express-serve-static-core" { - import * as http from "http"; - - interface NextFunction { - (err?: any): void; - } - - interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; - } - - type PathParams = string | RegExp | (string | RegExp)[]; - - type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; - - interface IRouterMatcher { - (path: PathParams, ...handlers: RequestHandler[]): T; - (path: PathParams, ...handlers: RequestHandlerParams[]): T; - } - - interface IRouterHandler { - (...handlers: RequestHandler[]): T; - (...handlers: RequestHandlerParams[]): T; - } - - interface IRouter extends RequestHandler { - /** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the samesignature as middleware, the only differencing - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param name - * @param fn - */ - param(name: string, handler: RequestParamHandler): this; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - // deprecated since express 4.11.0 - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; - - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param path - * @param fn - */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - head: IRouterMatcher; - - use: IRouterHandler & IRouterMatcher; - - route(prefix: PathParams): IRoute; - /** - * Stack of configured routes - */ - stack: any[]; - } - - interface IRoute { - path: string; - stack: any; - all: IRouterHandler; - get: IRouterHandler; - post: IRouterHandler; - put: IRouterHandler; - delete: IRouterHandler; - patch: IRouterHandler; - options: IRouterHandler; - head: IRouterHandler; - } - - export interface Router extends IRouter { } - - interface CookieOptions { - maxAge?: number; - signed?: boolean; - expires?: Date | boolean; - httpOnly?: boolean; - path?: string; - domain?: string; - secure?: boolean | 'auto'; - } - - interface Errback { (err: Error): void; } - - interface Request extends http.IncomingMessage, Express.Request { - - /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param name - */ - get(name: string): string; - - header(name: string): string; - - headers: { [key: string]: string; }; - - /** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html, json'); - * // => "json" - */ - accepts(): string[]; - accepts(type: string): string | boolean; - accepts(type: string[]): string | boolean; - accepts(...type: string[]): string | boolean; - - /** - * Returns the first accepted charset of the specified character sets, - * based on the request's Accept-Charset HTTP header field. - * If none of the specified charsets is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param charset - */ - acceptsCharsets(): string[]; - acceptsCharsets(charset: string): string | boolean; - acceptsCharsets(charset: string[]): string | boolean; - acceptsCharsets(...charset: string[]): string | boolean; - - /** - * Returns the first accepted encoding of the specified encodings, - * based on the request's Accept-Encoding HTTP header field. - * If none of the specified encodings is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * @param encoding - */ - acceptsEncodings(): string[]; - acceptsEncodings(encoding: string): string | boolean; - acceptsEncodings(encoding: string[]): string | boolean; - acceptsEncodings(...encoding: string[]): string | boolean; - - /** - * Returns the first accepted language of the specified languages, - * based on the request's Accept-Language HTTP header field. - * If none of the specified languages is accepted, returns false. - * - * For more information, or if you have issues or concerns, see accepts. - * - * @param lang - */ - acceptsLanguages(): string[]; - acceptsLanguages(lang: string): string | boolean; - acceptsLanguages(lang: string[]): string | boolean; - acceptsLanguages(...lang: string[]): string | boolean; - - /** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param size - */ - range(size: number): any[]; - - /** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - */ - accepted: MediaType[]; - - /** - * @deprecated Use either req.params, req.body or req.query, as applicable. - * - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param name - * @param defaultValue - */ - param(name: string, defaultValue?: any): string; - - /** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param type - */ - is(type: string): boolean; - - /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - */ - protocol: string; - - /** - * Short-hand for: - * - * req.protocol == 'https' - */ - secure: boolean; - - /** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - */ - ip: string; - - /** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - */ - ips: string[]; - - /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - */ - subdomains: string[]; - - /** - * Short-hand for `url.parse(req.url).pathname`. - */ - path: string; - - /** - * Parse the "Host" header field hostname. - */ - hostname: string; - - /** - * @deprecated Use hostname instead. - */ - host: string; - - /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - */ - fresh: boolean; - - /** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - */ - stale: boolean; - - /** - * Check if the request was an _XMLHttpRequest_. - */ - xhr: boolean; - - //body: { username: string; password: string; remember: boolean; title: string; }; - body: any; - - //cookies: { string; remember: boolean; }; - cookies: any; - - method: string; - - params: any; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - query: any; - - route: any; - - signedCookies: any; - - originalUrl: string; - - url: string; - - baseUrl: string; - - app: Application; - } - - interface MediaType { - value: string; - quality: number; - type: string; - subtype: string; - } - - interface Send { - (status: number, body?: any): Response; - (body?: any): Response; - } - - interface Response extends http.ServerResponse, Express.Response { - /** - * Set status `code`. - * - * @param code - */ - status(code: number): Response; - - /** - * Set the response HTTP status code to `statusCode` and send its string representation as the response body. - * @link http://expressjs.com/4x/api.html#res.sendStatus - * - * Examples: - * - * res.sendStatus(200); // equivalent to res.status(200).send('OK') - * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') - * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') - * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') - * - * @param code - */ - sendStatus(code: number): Response; - - /** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param links - */ - links(links: any): Response; - - /** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - */ - send: Send; - - /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - */ - json: Send; - - /** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - */ - jsonp: Send; - - /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @api public - */ - sendFile(path: string): void; - sendFile(path: string, options: any): void; - sendFile(path: string, fn: Errback): void; - sendFile(path: string, options: any, fn: Errback): void; - - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, fn: Errback): void; - /** - * @deprecated Use sendFile instead. - */ - sendfile(path: string, options: any, fn: Errback): void; - - /** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - */ - download(path: string): void; - download(path: string, filename: string): void; - download(path: string, fn: Errback): void; - download(path: string, filename: string, fn: Errback): void; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - contentType(type: string): Response; - - /** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param type - */ - type(type: string): Response; - - /** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param obj - */ - format(obj: any): Response; - - /** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param filename - */ - attachment(filename?: string): Response; - - /** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - */ - set(field: any): Response; - set(field: string, value?: string): Response; - - header(field: any): Response; - header(field: string, value?: string): Response; - - // Property indicating if HTTP headers has been sent for the response. - headersSent: boolean; - - /** - * Get value for header `field`. - * - * @param field - */ - get(field: string): string; - - /** - * Clear cookie `name`. - * - * @param name - * @param options - */ - clearCookie(name: string, options?: any): Response; - - /** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - */ - cookie(name: string, val: string, options: CookieOptions): Response; - cookie(name: string, val: any, options: CookieOptions): Response; - cookie(name: string, val: any): Response; - - /** - * Set the location header to `url`. - * - * The given `url` can also be the name of a mapped url, for - * example by default express supports "back" which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param url - */ - location(url: string): Response; - - /** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - */ - redirect(url: string): void; - redirect(status: number, url: string): void; - redirect(url: string, status: number): void; - - /** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - */ - render(view: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(view: string, callback?: (err: Error, html: string) => void): void; - - locals: any; - - charset: string; - - /** - * Adds the field to the Vary response header, if it is not there already. - * Examples: - * - * res.vary('User-Agent').render('docs'); - * - */ - vary(field: string): Response; - } - - interface Handler extends RequestHandler { } - - interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, value: any, name: string): any; - } - - interface Application extends IRouter, Express.Application { - /** - * Express instance itself is a request handler, which could be invoked without - * third argument. - */ - (req: Request, res: Response): any; - - /** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - */ - init(): void; - - /** - * Initialize application configuration. - */ - defaultConfiguration(): void; - - /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - */ - engine(ext: string, fn: Function): Application; - - /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * app.set('foo', ['bar', 'baz']); - * app.get('foo'); - * // => ["bar", "baz"] - * - * Mounted servers inherit their parent server's settings. - * - * @param setting - * @param val - */ - set(setting: string, val: any): Application; - get: {(name: string): any;} & IRouterMatcher; - - param(name: string | string[], handler: RequestParamHandler): this; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; - - /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - */ - path(): string; - - /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - */ - enabled(setting: string): boolean; - - /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param setting - */ - disabled(setting: string): boolean; - - /** - * Enable `setting`. - * - * @param setting - */ - enable(setting: string): Application; - - /** - * Disable `setting`. - * - * @param setting - */ - disable(setting: string): Application; - - /** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param env - * @param fn - */ - configure(fn: Function): Application; - configure(env0: string, fn: Function): Application; - configure(env0: string, env1: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; - configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; - - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param name - * @param options or fn - * @param fn - */ - render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; - render(name: string, callback: (err: Error, html: string) => void): void; - - - /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - */ - listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; - listen(port: number, hostname: string, callback?: Function): http.Server; - listen(port: number, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - - router: string; - - settings: any; - - resource: any; - - map: any; - - locals: any; - - /** - * The app.routes object houses all of the routes defined mapped by the - * associated HTTP verb. This object may be used for introspection - * capabilities, for example Express uses this internally not only for - * routing but to provide default OPTIONS behaviour unless app.options() - * is used. Your application or framework may also remove routes by - * simply by removing them from this object. - */ - routes: any; - - /** - * Used to get all registered routes in Express Application - */ - _router: any; - } - - interface Express extends Application { - /** - * Framework version. - */ - version: string; - - /** - * Expose mime. - */ - mime: string; - - (): Application; - - /** - * Create an express application. +import * as http from "http"; + +interface NextFunction { + (err?: any): void; +} + +interface RequestHandler { + (req: Request, res: Response, next: NextFunction): any; +} + +interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; +} + +type PathParams = string | RegExp | (string | RegExp)[]; + +type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; + +interface IRouterMatcher { + (path: PathParams, ...handlers: RequestHandler[]): T; + (path: PathParams, ...handlers: RequestHandlerParams[]): T; +} + +interface IRouterHandler { + (...handlers: RequestHandler[]): T; + (...handlers: RequestHandlerParams[]): T; +} + +interface IRouter extends RequestHandler { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the samesignature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + * + * @param name + * @param fn */ - createApplication(): Application; + param(name: string, handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + // deprecated since express 4.11.0 + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; - createServer(): Application; + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param path + * @param fn + */ + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; - application: any; + checkout: IRouterMatcher; + copy: IRouterMatcher; + lock: IRouterMatcher; + merge: IRouterMatcher; + mkactivity: IRouterMatcher; + mkcol: IRouterMatcher; + move: IRouterMatcher; + "m-search": IRouterMatcher; + notify: IRouterMatcher; + purge: IRouterMatcher; + report: IRouterMatcher; + search: IRouterMatcher; + subscribe: IRouterMatcher; + trace: IRouterMatcher; + unlock: IRouterMatcher; + unsubscribe: IRouterMatcher; - request: Request; + use: IRouterHandler & IRouterMatcher; - response: Response; - } + route(prefix: PathParams): IRoute; + /** + * Stack of configured routes + */ + stack: any[]; } + +interface IRoute { + path: string; + stack: any; + all: IRouterHandler; + get: IRouterHandler; + post: IRouterHandler; + put: IRouterHandler; + delete: IRouterHandler; + patch: IRouterHandler; + options: IRouterHandler; + head: IRouterHandler; + + checkout: IRouterHandler; + copy: IRouterHandler; + lock: IRouterHandler; + merge: IRouterHandler; + mkactivity: IRouterHandler; + mkcol: IRouterHandler; + move: IRouterHandler; + "m-search": IRouterHandler; + notify: IRouterHandler; + purge: IRouterHandler; + report: IRouterHandler; + search: IRouterHandler; + subscribe: IRouterHandler; + trace: IRouterHandler; + unlock: IRouterHandler; + unsubscribe: IRouterHandler +} + +export interface Router extends IRouter { } + +interface CookieOptions { + maxAge?: number; + signed?: boolean; + expires?: Date | boolean; + httpOnly?: boolean; + path?: string; + domain?: string; + secure?: boolean | 'auto'; +} + +interface Errback { (err: Error): void; } + +interface Request extends http.IncomingMessage, Express.Request { + + /** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param name + */ + get(name: string): string; + + header(name: string): string; + + headers: { [key: string]: string; }; + + /** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json", a comma-delimted list such as "json, html, text/plain", + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html, json'); + * // => "json" + */ + accepts(): string[]; + accepts(type: string): string | boolean; + accepts(type: string[]): string | boolean; + accepts(...type: string[]): string | boolean; + + /** + * Returns the first accepted charset of the specified character sets, + * based on the request's Accept-Charset HTTP header field. + * If none of the specified charsets is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * @param charset + */ + acceptsCharsets(): string[]; + acceptsCharsets(charset: string): string | boolean; + acceptsCharsets(charset: string[]): string | boolean; + acceptsCharsets(...charset: string[]): string | boolean; + + /** + * Returns the first accepted encoding of the specified encodings, + * based on the request's Accept-Encoding HTTP header field. + * If none of the specified encodings is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * @param encoding + */ + acceptsEncodings(): string[]; + acceptsEncodings(encoding: string): string | boolean; + acceptsEncodings(encoding: string[]): string | boolean; + acceptsEncodings(...encoding: string[]): string | boolean; + + /** + * Returns the first accepted language of the specified languages, + * based on the request's Accept-Language HTTP header field. + * If none of the specified languages is accepted, returns false. + * + * For more information, or if you have issues or concerns, see accepts. + * + * @param lang + */ + acceptsLanguages(): string[]; + acceptsLanguages(lang: string): string | boolean; + acceptsLanguages(lang: string[]): string | boolean; + acceptsLanguages(...lang: string[]): string | boolean; + + /** + * Parse Range header field, + * capping to the given `size`. + * + * Unspecified ranges such as "0-" require + * knowledge of your resource length. In + * the case of a byte range this is of course + * the total number of bytes. If the Range + * header field is not given `null` is returned, + * `-1` when unsatisfiable, `-2` when syntactically invalid. + * + * NOTE: remember that ranges are inclusive, so + * for example "Range: users=0-3" should respond + * with 4 users when available, not 3. + * + * @param size + */ + range(size: number): any[]; + + /** + * Return an array of Accepted media types + * ordered from highest quality to lowest. + */ + accepted: MediaType[]; + + /** + * @deprecated Use either req.params, req.body or req.query, as applicable. + * + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `connect.bodyParser()` middleware. + * + * @param name + * @param defaultValue + */ + param(name: string, defaultValue?: any): string; + + /** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param type + */ + is(type: string): boolean; + + /** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting is enabled the "X-Forwarded-Proto" header + * field will be trusted. If you're running behind + * a reverse proxy that supplies https for you this + * may be enabled. + */ + protocol: string; + + /** + * Short-hand for: + * + * req.protocol == 'https' + */ + secure: boolean; + + /** + * Return the remote address, or when + * "trust proxy" is `true` return + * the upstream addr. + */ + ip: string; + + /** + * When "trust proxy" is `true`, parse + * the "X-Forwarded-For" ip address list. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream. + */ + ips: string[]; + + /** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + */ + subdomains: string[]; + + /** + * Short-hand for `url.parse(req.url).pathname`. + */ + path: string; + + /** + * Parse the "Host" header field hostname. + */ + hostname: string; + + /** + * @deprecated Use hostname instead. + */ + host: string; + + /** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + */ + fresh: boolean; + + /** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + */ + stale: boolean; + + /** + * Check if the request was an _XMLHttpRequest_. + */ + xhr: boolean; + + //body: { username: string; password: string; remember: boolean; title: string; }; + body: any; + + //cookies: { string; remember: boolean; }; + cookies: any; + + method: string; + + params: any; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + query: any; + + route: any; + + signedCookies: any; + + originalUrl: string; + + url: string; + + baseUrl: string; + + app: Application; +} + +interface MediaType { + value: string; + quality: number; + type: string; + subtype: string; +} + +interface Send { + (status: number, body?: any): Response; + (body?: any): Response; +} + +interface Response extends http.ServerResponse, Express.Response { + /** + * Set status `code`. + * + * @param code + */ + status(code: number): Response; + + /** + * Set the response HTTP status code to `statusCode` and send its string representation as the response body. + * @link http://expressjs.com/4x/api.html#res.sendStatus + * + * Examples: + * + * res.sendStatus(200); // equivalent to res.status(200).send('OK') + * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') + * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') + * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') + * + * @param code + */ + sendStatus(code: number): Response; + + /** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param links + */ + links(links: any): Response; + + /** + * Send a response. + * + * Examples: + * + * res.send(new Buffer('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * res.send(404, 'Sorry, cant find that'); + * res.send(404); + */ + send: Send; + + /** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * res.json(500, 'oh noes!'); + * res.json(404, 'I dont have that'); + */ + json: Send; + + /** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * res.jsonp(500, 'oh noes!'); + * res.jsonp(404, 'I dont have that'); + */ + jsonp: Send; + + /** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `fn(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @api public + */ + sendFile(path: string): void; + sendFile(path: string, options: any): void; + sendFile(path: string, fn: Errback): void; + sendFile(path: string, options: any, fn: Errback): void; + + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: any): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, fn: Errback): void; + /** + * @deprecated Use sendFile instead. + */ + sendfile(path: string, options: any, fn: Errback): void; + + /** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `fn(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headerSent` if you plan to respond. + * + * This method uses `res.sendfile()`. + */ + download(path: string): void; + download(path: string, filename: string): void; + download(path: string, fn: Errback): void; + download(path: string, filename: string, fn: Errback): void; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + contentType(type: string): Response; + + /** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param type + */ + type(type: string): Response; + + /** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param obj + */ + format(obj: any): Response; + + /** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param filename + */ + attachment(filename?: string): Response; + + /** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + */ + set(field: any): Response; + set(field: string, value?: string): Response; + + header(field: any): Response; + header(field: string, value?: string): Response; + + // Property indicating if HTTP headers has been sent for the response. + headersSent: boolean; + + /** + * Get value for header `field`. + * + * @param field + */ + get(field: string): string; + + /** + * Clear cookie `name`. + * + * @param name + * @param options + */ + clearCookie(name: string, options?: any): Response; + + /** + * Set cookie `name` to `val`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + */ + cookie(name: string, val: string, options: CookieOptions): Response; + cookie(name: string, val: any, options: CookieOptions): Response; + cookie(name: string, val: any): Response; + + /** + * Set the location header to `url`. + * + * The given `url` can also be the name of a mapped url, for + * example by default express supports "back" which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); // /blog/post/1 -> /blog/login + * + * Mounting: + * + * When an application is mounted and `res.location()` + * is given a path that does _not_ lead with "/" it becomes + * relative to the mount-point. For example if the application + * is mounted at "/blog", the following would become "/blog/login". + * + * res.location('login'); + * + * While the leading slash would result in a location of "/login": + * + * res.location('/login'); + * + * @param url + */ + location(url: string): Response; + + /** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('http://example.com', 301); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + */ + redirect(url: string): void; + redirect(status: number, url: string): void; + redirect(url: string, status: number): void; + + /** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + */ + render(view: string, options?: Object, callback?: (err: Error, html: string) => void): void; + render(view: string, callback?: (err: Error, html: string) => void): void; + + locals: any; + + charset: string; + + /** + * Adds the field to the Vary response header, if it is not there already. + * Examples: + * + * res.vary('User-Agent').render('docs'); + * + */ + vary(field: string): Response; +} + +interface Handler extends RequestHandler { } + +interface RequestParamHandler { + (req: Request, res: Response, next: NextFunction, value: any, name: string): any; +} + +interface Application extends IRouter, Express.Application { + /** + * Express instance itself is a request handler, which could be invoked without + * third argument. + */ + (req: Request, res: Response): any; + + /** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + */ + init(): void; + + /** + * Initialize application configuration. + */ + defaultConfiguration(): void; + + /** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.jade" file Express will invoke the following internally: + * + * app.engine('jade', require('jade').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/visionmedia/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + */ + engine(ext: string, fn: Function): Application; + + /** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.get('foo'); + * // => "bar" + * app.set('foo', ['bar', 'baz']); + * app.get('foo'); + * // => ["bar", "baz"] + * + * Mounted servers inherit their parent server's settings. + * + * @param setting + * @param val + */ + set(setting: string, val: any): Application; + get: { (name: string): any; } & IRouterMatcher; + + param(name: string | string[], handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + + /** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + */ + path(): string; + + /** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + */ + enabled(setting: string): boolean; + + /** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param setting + */ + disabled(setting: string): boolean; + + /** + * Enable `setting`. + * + * @param setting + */ + enable(setting: string): Application; + + /** + * Disable `setting`. + * + * @param setting + */ + disable(setting: string): Application; + + /** + * Configure callback for zero or more envs, + * when no `env` is specified that callback will + * be invoked for all environments. Any combination + * can be used multiple times, in any order desired. + * + * Examples: + * + * app.configure(function(){ + * // executed for all envs + * }); + * + * app.configure('stage', function(){ + * // executed staging env + * }); + * + * app.configure('stage', 'production', function(){ + * // executed for stage and production + * }); + * + * Note: + * + * These callbacks are invoked immediately, and + * are effectively sugar for the following: + * + * var env = process.env.NODE_ENV || 'development'; + * + * switch (env) { + * case 'development': + * ... + * break; + * case 'stage': + * ... + * break; + * case 'production': + * ... + * break; + * } + * + * @param env + * @param fn + */ + configure(fn: Function): Application; + configure(env0: string, fn: Function): Application; + configure(env0: string, env1: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, fn: Function): Application; + configure(env0: string, env1: string, env2: string, env3: string, env4: string, fn: Function): Application; + + /** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param name + * @param options or fn + * @param fn + */ + render(name: string, options?: Object, callback?: (err: Error, html: string) => void): void; + render(name: string, callback: (err: Error, html: string) => void): void; + + + /** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + */ + listen(port: number, hostname: string, backlog: number, callback?: Function): http.Server; + listen(port: number, hostname: string, callback?: Function): http.Server; + listen(port: number, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + + router: string; + + settings: any; + + resource: any; + + map: any; + + locals: any; + + /** + * The app.routes object houses all of the routes defined mapped by the + * associated HTTP verb. This object may be used for introspection + * capabilities, for example Express uses this internally not only for + * routing but to provide default OPTIONS behaviour unless app.options() + * is used. Your application or framework may also remove routes by + * simply by removing them from this object. + */ + routes: any; + + /** + * Used to get all registered routes in Express Application + */ + _router: any; +} + +interface Express extends Application { + request: Request; + + response: Response; +} \ No newline at end of file diff --git a/express/express-tests.ts b/express/express-tests.ts index fdcd85801f..e643ba208b 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -29,8 +29,7 @@ namespace express_tests { res.send('hello world'); }); - const router = express.Router(); - + const router = express.Router({ caseSensitive: true, mergeParams: true, strict: true }); const pathStr: string = 'test'; const pathRE: RegExp = /test/; diff --git a/express/index.d.ts b/express/index.d.ts index b1a618b79e..7222c8d3d9 100644 --- a/express/index.d.ts +++ b/express/index.d.ts @@ -28,7 +28,28 @@ declare namespace e { */ var static: typeof serveStatic; - export function Router(options?: any): core.Router; + export function Router(options?: RouterOptions): core.Router; + + interface RouterOptions { + /** + * Enable case sensitivity. + */ + caseSensitive?: boolean; + + /** + * Preserve the req.params values from the parent router. + * If the parent and the child have conflicting param names, the child’s value take precedence. + * + * @default false + * @since 4.5.0 + */ + mergeParams?: boolean; + + /** + * Enable strict routing. + */ + strict?: boolean; + } interface Application extends core.Application { } interface CookieOptions extends core.CookieOptions { } diff --git a/extjs/ExtJS-tests.ts b/extjs/extjs-tests.ts similarity index 100% rename from extjs/ExtJS-tests.ts rename to extjs/extjs-tests.ts diff --git a/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts new file mode 100644 index 0000000000..62e522a348 --- /dev/null +++ b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts @@ -0,0 +1,97 @@ +import { optimize, Configuration, Plugin } from 'webpack' + +import * as ExtractTextPlugin from 'extract-text-webpack-plugin' + + +let configuration: Configuration + + +configuration = { + // The standard entry point and output config + entry: { + posts: "./posts", + post: "./post", + about: "./about" + }, + output: { + filename: "[name].js", + chunkFilename: "[id].js" + }, + module: { + rules: [ + // Extract css files + { + test: /\.css$/, + loader: ExtractTextPlugin.extract({ + fallbackLoader: "style-loader", + loader: "css-loader", + }) + }, + // Optionally extract less files + // or any other compile-to-css language + { + test: /\.less$/, + loader: ExtractTextPlugin.extract({ + fallbackLoader: "style-loader", + loader: ["css-loader", "less-loader"], + }) + } + // You could also use other loaders the same way. I. e. the autoprefixer-loader + ] + }, + // Use the plugin to specify the resulting filename (and add needed behavior to the compiler) + plugins: [ + new ExtractTextPlugin("[name].css") + ] +}; + +configuration = { + // ... + plugins: [ + new ExtractTextPlugin({ + filename: "style.css", + allChunks: true, + }) + ] +}; + +configuration = { + // ... + plugins: [ + new optimize.CommonsChunkPlugin("commons", "commons.js"), + new ExtractTextPlugin("[name].css") + ] +}; + +configuration = { + // ... + module: { + rules: [ + { test: /\.css$/, loader: ExtractTextPlugin.extract({ + fallbackLoader: "style-loader", + loader: "css-loader" + }) } + ] + }, + plugins: [ + new ExtractTextPlugin("styles.css") + ], +}; + +// multiple extract instances +let extractCSS = new ExtractTextPlugin('stylesheets/[name].css'); +let extractLESS = new ExtractTextPlugin('stylesheets/[name].less'); + +configuration = { + // ... + module: { + rules: [ + { test: /\.scss$/i, loader: extractCSS.extract(['css','sass']) }, + { test: /\.less$/i, loader: extractLESS.extract(['css','less']) }, + ] + }, + plugins: [ + extractCSS, + extractLESS, + ], +}; diff --git a/extract-text-webpack-plugin/index.d.ts b/extract-text-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..21052b08c1 --- /dev/null +++ b/extract-text-webpack-plugin/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for extract-text-webpack-plugin 2.0.0 +// Project: https://github.com/webpack/extract-text-webpack-plugin +// Definitions by: flying-sheep +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Plugin, OldLoader } from 'webpack' + +/** + * extract-text-webpack-plugin has no support for .options instead of .query yet. + * See https://github.com/webpack/extract-text-webpack-plugin/issues/281 + */ +type Loader = string | OldLoader + +interface ExtractPluginOptions { + /** the filename of the result file. May contain `[name]`, `[id]` and `[contenthash]` */ + filename: string + /** extract from all additional chunks too (by default it extracts only from the initial chunk(s)) */ + allChunks?: boolean + /** disables the plugin */ + disable?: boolean + /** Unique ident for this plugin instance. (For advanced usage only, by default automatically generated) */ + id?: string +} + +interface ExtractOptions { + /** the loader(s) that should be used for converting the resource to a css exporting module */ + loader: Loader | Loader[] + /** the loader(s) that should be used when the css is not extracted (i.e. in an additional chunk when `allChunks: false`) */ + fallbackLoader?: Loader | Loader[] + /** override the `publicPath` setting for this loader */ + publicPath?: string +} + +/** + * Use an `ExtractTextPlugin` instance and a loader returned by `extract` in concert to write files to disk instead of loading them into others. + * Usage example at https://github.com/webpack/extract-text-webpack-plugin#usage-example-with-css + */ +interface ExtractTextPlugin extends Plugin { + /** Create a plugin instance defining the extraction target file(s) for the files loaded by `extract` */ + new (options: string | ExtractPluginOptions): ExtractTextPlugin + /** + * Creates an extracting loader from an existing loader. + * Use the resulting loader in `module.rules`/`module.loaders`. + */ + extract: (loader: Loader | Loader[] | ExtractOptions) => Loader +} + +declare const extractTextPlugin: ExtractTextPlugin +export = extractTextPlugin diff --git a/extract-text-webpack-plugin/tsconfig.json b/extract-text-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..77520c362d --- /dev/null +++ b/extract-text-webpack-plugin/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "extract-text-webpack-plugin-tests.ts" + ] +} \ No newline at end of file diff --git a/filesaver/FileSaver-tests.ts b/file-saver/FileSaver-tests.ts similarity index 100% rename from filesaver/FileSaver-tests.ts rename to file-saver/FileSaver-tests.ts diff --git a/filesaver/index.d.ts b/file-saver/index.d.ts similarity index 79% rename from filesaver/index.d.ts rename to file-saver/index.d.ts index 534ce4fe1c..31188a0c7a 100644 --- a/filesaver/index.d.ts +++ b/file-saver/index.d.ts @@ -20,13 +20,13 @@ interface FileSaver { * @summary File name. * @type {DOMString} */ - filename: string, + filename: string, - /** - * @summary Disable Unicode text encoding hints or not. - * @type {boolean} - */ - disableAutoBOM?: boolean + /** + * @summary Disable Unicode text encoding hints or not. + * @type {boolean} + */ + disableAutoBOM?: boolean ): void } diff --git a/filesaver/tsconfig.json b/file-saver/tsconfig.json similarity index 100% rename from filesaver/tsconfig.json rename to file-saver/tsconfig.json diff --git a/finalhandler/finalhandler-tests.ts b/finalhandler/finalhandler-tests.ts index 0b419544fe..af3550a4f4 100644 --- a/finalhandler/finalhandler-tests.ts +++ b/finalhandler/finalhandler-tests.ts @@ -1,6 +1,6 @@ import {ServerRequest, ServerResponse} from "http"; -import finalHandler from "finalhandler"; +import * as finalHandler from "finalhandler"; let req: ServerRequest; let res: ServerResponse; diff --git a/finalhandler/index.d.ts b/finalhandler/index.d.ts index 99245e91f1..07bbe63c91 100644 --- a/finalhandler/index.d.ts +++ b/finalhandler/index.d.ts @@ -8,12 +8,14 @@ import {ServerRequest, ServerResponse} from "http"; -export interface Options { - message?: boolean | ((err: any, status: number) => string); - onerror?: (err: any, req: ServerRequest, res: ServerResponse) => void; - stacktrace?: boolean; +declare function finalHandler(req: ServerRequest, res: ServerResponse, options?: finalHandler.Options): (err: any) => void; + +declare namespace finalHandler { + export interface Options { + message?: boolean|((err: any, status: number) => string); + onerror?: (err: any, req: ServerRequest, res: ServerResponse) => void; + stacktrace?: boolean; + } } -declare function finalHandler(req: ServerRequest, res: ServerResponse, options?: Options): (err: any) => void; - -export default finalHandler; +export = finalHandler; diff --git a/flickity/index.d.ts b/flickity/index.d.ts index febb09b525..16b5b7c96f 100644 --- a/flickity/index.d.ts +++ b/flickity/index.d.ts @@ -161,13 +161,7 @@ declare class Flickity { * @param eventName name of event (@see FlickityEvents class for filckity supported events) * @param callback callback funtion to execute when event fires */ - on(eventname: string, callback: (eventt?: Event, cellElement?: Element) => any) : void; - /** - * bind event listener - * @param eventName name of event (@see FlickityEvents class for filckity supported events) - * @param callback callback funtion to execute when event fires - */ - on(eventname: string, callback: (event?: Event, pointer?: Element | Touch) => any): void; + on(eventname: string, callback: (event?: Event, pointer?: Element | Touch, cellElement?: Element, cellIndex?: number) => any): void; /** * bind event listener * @param eventName name of event (@see FlickityEvents class for filckity supported events) @@ -179,7 +173,27 @@ declare class Flickity { * @param eventName name of event (@see FlickityEvents class for filckity supported events) * @param callback callback funtion to execute when event fires */ - on(eventname: string, callback: (event?: Event, pointer?: Element | Touch, cellElement?: Element, cellIndex?: number) => any): void; + on(eventname: string, callback: (eventt?: Event, cellElement?: Element) => any) : void; + /** + * bind event listener + * @param eventName name of event (@see FlickityEvents class for filckity supported events) + * @param callback callback funtion to execute when event fires + */ + on(eventname: string, callback: (event?: Event, pointer?: Element | Touch) => any): void; + + /** + * Remove event listener + * @param eventName name of event (@see FlickityEvents class for filckity supported events) + * @param callback callback funtion to execute when event fires + */ + off(eventname: string, callback: (event?: Event, pointer?: Element | Touch, cellElement?: Element, cellIndex?: number) => any): void; + + /** + * Remove event listener + * @param eventName name of event (@see FlickityEvents class for filckity supported events) + * @param callback callback funtion to execute when event fires + */ + off(eventname: string, callback: (event?: Event, pointer?: Element | Touch, moveVector?: Object) => any): void; /** * Remove event listener @@ -195,20 +209,20 @@ declare class Flickity { */ off(eventname: string, callback: (event?: Event, pointer?: Element | Touch) => any): void; + /** - * Remove event listener + * one time event handler * @param eventName name of event (@see FlickityEvents class for filckity supported events) * @param callback callback funtion to execute when event fires */ - off(eventname: string, callback: (event?: Event, pointer?: Element | Touch, moveVector?: Object) => any): void; + once(eventname: string, callback: (event?: Event, pointer?: Element | Touch, cellElement?: Element, cellIndex?: number) => any): void; /** - * Remove event listener + * one time event handler * @param eventName name of event (@see FlickityEvents class for filckity supported events) * @param callback callback funtion to execute when event fires */ - off(eventname: string, callback: (event?: Event, pointer?: Element | Touch, cellElement?: Element, cellIndex?: number) => any): void; - + once(eventname: string, callback: (event?: Event, pointer?: Element | Touch, moveVector?: Object) => any): void; /** * one time event handler @@ -223,22 +237,6 @@ declare class Flickity { * @param callback callback funtion to execute when event fires */ once(eventname: string, callback: (event?: Event, pointer?: Element | Touch) => any): void; - - /** - * one time event handler - * @param eventName name of event (@see FlickityEvents class for filckity supported events) - * @param callback callback funtion to execute when event fires - */ - once(eventname: string, callback: (event?: Event, pointer?: Element | Touch, moveVector?: Object) => any): void; - - /** - * one time event handler - * @param eventName name of event (@see FlickityEvents class for filckity supported events) - * @param callback callback funtion to execute when event fires - */ - once(eventname: string, callback: (event?: Event, pointer?: Element | Touch, cellElement?: Element, cellIndex?: number) => any): void; - - } interface FlickityOptions { diff --git a/form-data/form-data-tests.ts b/form-data/form-data-tests.ts index 3a9db203da..2df21510c0 100644 --- a/form-data/form-data-tests.ts +++ b/form-data/form-data-tests.ts @@ -4,7 +4,7 @@ import FormData = require('form-data'); import fs = require('fs'); import http = require('http'); import request = require('request'); -import fetch = require('node-fetch'); +import fetch from 'node-fetch'; import * as ImportUsingES6Syntax from 'form-data'; diff --git a/fossil-delta/fossil-delta-tests.ts b/fossil-delta/fossil-delta-tests.ts new file mode 100644 index 0000000000..f3a7635a7c --- /dev/null +++ b/fossil-delta/fossil-delta-tests.ts @@ -0,0 +1,9 @@ +import * as fossilDelta from "fossil-delta"; + +var origin = new Array(1,2,3); +var target = new Array(1,2,3,4,5); + +var delta = fossilDelta.create(origin, target); +var targetApplied = fossilDelta.apply(origin, delta); + +var outputSize: number = fossilDelta.outputSize(delta); diff --git a/fossil-delta/index.d.ts b/fossil-delta/index.d.ts new file mode 100644 index 0000000000..c72e914df6 --- /dev/null +++ b/fossil-delta/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for fossil-delta 0.2.5 +// Project: https://github.com/dchest/fossil-delta-js +// Definitions by: Endel Dreyer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +type ByteArray = Array | Uint8Array | Buffer; + +export function create(origin: ByteArray, target: ByteArray): Array; +export function apply(origin: ByteArray, delta: Array): Array; +export function outputSize(delta: Array): number; diff --git a/fossil-delta/tsconfig.json b/fossil-delta/tsconfig.json new file mode 100644 index 0000000000..434d0761b7 --- /dev/null +++ b/fossil-delta/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fossil-delta-tests.ts" + ] +} \ No newline at end of file diff --git a/fromjs/index.d.ts b/fromjs/index.d.ts index b023e24bea..937baa7cd2 100644 --- a/fromjs/index.d.ts +++ b/fromjs/index.d.ts @@ -32,9 +32,8 @@ declare namespace FromJS { contains(item: T): boolean; first(predicate: (item: T) => boolean): T; firstOrDefault(): T; - each(action: (item: T) => void): void; each(action: (value: T, key: TKey) => void): void; - each(action: (item: T) => void, a: boolean): void; + each(action: (item: T) => void, a?: boolean): void; toArray(): Array; concat(second: Array): IQueryable; sum(): T; diff --git a/fs-extra/index.d.ts b/fs-extra/index.d.ts index 334bc4b9ea..5d53a4d28f 100644 --- a/fs-extra/index.d.ts +++ b/fs-extra/index.d.ts @@ -8,7 +8,6 @@ /// import * as stream from 'stream'; - export * from "fs"; export declare function copy(src: string, dest: string, callback?: (err: Error) => void): void; @@ -19,9 +18,6 @@ export declare function copySync(src: string, dest: string): void; export declare function copySync(src: string, dest: string, filter: CopyFilter): void; export declare function copySync(src: string, dest: string, options: CopyOptions): void; -export declare function move(src: string, dest: string, callback?: (err: Error) => void): void; -export declare function move(src: string, dest: string, options: MoveOptions, callback?: (err: Error) => void): void; - export declare function createFile(file: string, callback?: (err: Error) => void): void; export declare function createFileSync(file: string): void; @@ -73,8 +69,8 @@ export declare function ensureSymlinkSync(path: string): void; export declare function emptyDir(path: string, callback?: (err: Error) => void): void; export declare function emptyDirSync(path: string): boolean; - -export interface CopyFilterFunction { + + export interface CopyFilterFunction { (src: string): boolean } @@ -87,10 +83,11 @@ export interface CopyOptions { filter?: CopyFilter recursive?: boolean } -export interface MoveOptions { - clobber?: boolean; - limit?: number; -} + + export interface MoveOptions { + clobber? : boolean; + limit?: number; + } export interface OpenOptions { encoding?: string; diff --git a/fullcalendar/index.d.ts b/fullcalendar/index.d.ts index c62b02d654..fc687696f1 100644 --- a/fullcalendar/index.d.ts +++ b/fullcalendar/index.d.ts @@ -136,13 +136,7 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr eventAfterAllRender?: (view: ViewObject) => void; eventDestroy?: (event: EventObject, element: JQuery, view: ViewObject) => void; - //scheduler options - resourceAreaWidth?: number; - schedulerLicenseKey?: string; - customButtons?: any; - resourceLabelText?: any; - resourceColumns?: any; - displayEventTime?: any; + //scheduler options } /** diff --git a/fusioncharts/fusioncharts-tests.ts b/fusioncharts/fusioncharts-tests.ts new file mode 100644 index 0000000000..9bbf640225 --- /dev/null +++ b/fusioncharts/fusioncharts-tests.ts @@ -0,0 +1,49 @@ +FusionCharts.addEventListener('ready',(eventObject)=>{ + eventObject.stopPropagation(); +}); + +FusionCharts.ready((fusioncharts)=>{ + +}); + +FusionCharts.version; + +FusionCharts('chartId').render();; + +FusionCharts["debugger"].enable(true); + +let chartData ={ + type: 'column2d', + renderAt: 'chart-container', + width: '450', + height: '200', + dataFormat: 'json', + dataSource: { + "chart": { + "caption": "Monthly revenue for last year", + "subCaption": "Harry's SuperMart", + }, + "data": [{ + "label": "Jan", + "value": "420000" + }, { + "label": "Feb", + "value": "810000" + } + ] + } +}; + +let chart = new FusionCharts(chartData); +chart.render(); +chart.isActive(); +chart.addEventListener('ready',function(eventObject){ + eventObject.type; +}); +chart.chartType(); +chart.addVariable(); +chart.clone(); +chart.zoomTo(0,3); +chart.zoomOut(); +chart.setJSONData(chartData); +chart.ref; \ No newline at end of file diff --git a/fusioncharts/index.d.ts b/fusioncharts/index.d.ts new file mode 100644 index 0000000000..dc053859b9 --- /dev/null +++ b/fusioncharts/index.d.ts @@ -0,0 +1,297 @@ +// Type definitions for FusionCharts 3.11.2 +// Project: http://www.fusioncharts.com +// Definitions by: Shivaraj KV +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare namespace FusionCharts { + + type ChartDataFormats = 'json' | 'jsonurl' | 'csv' | 'xml' | 'xmlurl'; + + type ImageHAlign = 'left' | 'right' | 'middle'; + + type ImageVAlign = 'top' | 'bottom' | 'middle'; + + interface EventObject { + type: string; + + eventId: number; + + sender: FusionCharts; + + cancelled: boolean; + + stopPropagation: () => void; + + prevented: boolean; + + preventDefault: () => void; + + detached: boolean; + + detachHandler: () => void; + } + + interface ChartObject { + + type?: string; + + id?: string; + + width?: number | string; + + height?: number | string; + + renderAt?: string; + + dataFormat?: ChartDataFormats; + + dataSource?: string | {}; + + events?: {}; + + link?: {}; + + showDataLoadingMessage?: boolean; + + showChartLoadingMessage?: boolean; + + baseChartMessageFont?: string; + + baseChartMessageFontSize?: string; + + baseChartMessageColor?: string; + + dataLoadStartMessage?: string; + + dataLoadErrorMessage?: string; + + dataInvalidMessage?: string; + + dataEmptyMessage?: string; + + typeNotSupportedMessage?: string; + + loadMessage?: string; + + renderErrorMessage?: string; + + containerBackgroundColor?: string; + + containerBackgroundOpacity?: number; + + containerClassName?: string; + + baseChartMessageImageHAlign?: ImageHAlign; + + dataLoadErrorMessageImageVAlign?: ImageVAlign; + + dataLoadErrorMessageImageAlpha?: number; + + dataLoadErrorMessageImageScale?: number; + + dataLoadStartMessageImageHAlign?: ImageHAlign; + + dataLoadStartMessageImageVAlign?: ImageVAlign; + + dataLoadStartMessageImageAlpha?: number; + + dataLoadStartMessageImageScale?: number; + + dataInvalidMessageImageHAlign?: ImageHAlign; + + dataInvalidMessageImageVAlign?: ImageVAlign; + + dataInvalidMessageImageAlpha?: number; + + dataInvalidMessageImageScale?: number; + + dataEmptyMessageImageHAlign?: ImageHAlign; + + dataEmptyMessageImageVAlign?: ImageVAlign; + + dataEmptyMessageImageAlpha?: number; + + dataEmptyMessageImageScale?: number; + + renderErrorMessageImageHAlign?: ImageHAlign; + + renderErrorMessageImageVAlign?: ImageVAlign; + + renderErrorMessageImageAlpha?: number; + + renderErrorMessageImageScale?: number; + + loadMessageImageHAlign?: ImageHAlign; + + loadMessageImageVAlign?: ImageVAlign; + + loadMessageImageAlpha?: number; + + loadMessageImageScale?: number; + } + + interface Debugger { + outputFormat(format: any): void; + + outputTo(callback: (message: any) => any): void; + + enable(state:any,outputTo?:(message: any) =>any,outputFormat?:any):void + + enableFirebugLite():any; + } + + interface FusionCharts { + clone(overrides?: {}, argsOnly?: boolean): any; + + isActive(): boolean; + + chartType(value?: string, options?: any): string; + + addEventListener(type: string | string[], listener: (eventObject?: EventObject, eventArgs?: {}) => void): void; + + removeEventListener(type: string | string[], listener: (eventObject?: EventObject, eventArgs?: {}) => void): void; + + configureLink(param: {} | any[], level?: number): void; + + setChartAttribute(attributes: ChartObject | String, value?: string): void; + + getChartAttribute(attribute?: string | string[]): ChartObject; + + getXMLData(): any; + + setXMLData(data: string | {}): void; + + setXMLUrl(url: string): void; + + setChartDataUrl(url: string, format: ChartDataFormats): void; + + setChartData(data: string | {}, format: ChartDataFormats): void; + + getChartData(format: ChartDataFormats): any; + + dataReady(available?: boolean): boolean; + + feedData(stream: string): void; + + getData(): any; + + getDataWithId(): any; + + setData(value: number, label: string): void; + + stopUpdate(): void; + + restartUpdate(): void; + + isUpdateActive(): boolean; + + clearChart(): void; + + getSWFHTML(): any; + + addVariable(): void; + + getXML(): any; + + setDataXML(data: string | {}): void; + + setDataURL(url: string): void; + + hasRendered(): boolean; + + setTransparent(transparency?: boolean): void; + + isPlotItemSliced(index: number): boolean; + + slicePlotItem(index: number, slice: boolean): void; + + centerLabel(labelText: string, options?: {}): void; + + startingAngle(angle?: number, relative?: boolean): void; + + zoomOut(): void; + + zoomTo(startIndex: number, endIndex: number): void; + + resetChart(): void; + + setZoomMode(yes: boolean): void; + + getViewStartIndex(): number; + + getViewEndIndex(): number; + + print(options?: {}): void; + + exportChart(options?: {}): void; + + getSVGString(): string; + + lockResize(state: boolean): boolean; + + showChartMessage(text: string, modal?: boolean, cancelable?: boolean): void; + + getJSONData(): JSON; + + setJSONData(data: string | {}): void; + + setJSONUrl(url: string): void; + + getCSVData(): any; + + getDataAsCSV(): any; + + render(containerElement?: string | Element, insertMode?: string, callback?: () => any): FusionCharts; + + resizeTo(width: number | string, height: number | string): any; + + dispose(): void; + + configure(options: {}): void; + + ref: {}; + + } + + interface FusionChartStatic { + new (chartObject: ChartObject|{}): FusionCharts; + + (chartId: string): FusionCharts; + + getObjectReference(elementId: string): Element; + + addEventListener(type: string | string[], listener: (eventObject?: EventObject, eventArgs?: {}) => void): void; + + removeEventListener(type: string | string[], listener: (eventObject?: EventObject, eventArgs?: {}) => void): void; + + ready(callback: (fusionChartStatic?: FusionChartStatic) => any, context?: any): FusionChartStatic; + + transcodeData(data: string | {}, source: ChartDataFormats, target: ChartDataFormats, advanced: boolean): any; + + batchExport(options: {}): void; + + formatNumber(num: number, type?: string, config?: {}): Element; + + setCurrentRenderer(name: string): void + + getCurrentRenderer(): string; + + render(options?: ChartObject, callback?: () => any): FusionCharts; + + version: string[]; + + items: {}; + + options: {}; + + debugger:Debugger; + + + } + +} + +declare var FusionCharts: FusionCharts.FusionChartStatic; +export = FusionCharts; +export as namespace FusionCharts; diff --git a/fusioncharts/tsconfig.json b/fusioncharts/tsconfig.json new file mode 100644 index 0000000000..8abb296bab --- /dev/null +++ b/fusioncharts/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fusioncharts-tests.ts" + ] +} \ No newline at end of file diff --git a/gapi.analytics/gapi.analytics-tests.ts b/gapi.analytics/gapi.analytics-tests.ts new file mode 100644 index 0000000000..2c35403d10 --- /dev/null +++ b/gapi.analytics/gapi.analytics-tests.ts @@ -0,0 +1,63 @@ +// Type definitions for Google Analytics API + +function test_namespace() { + var analytics : boolean = gapi.client.analytics instanceof Object; + + var provisioning : boolean = gapi.client.analytics.provisioning.createAccountTicket instanceof Function; + analytics = analytics && provisioning; + + var data : boolean = gapi.client.analytics.data.ga.get instanceof Function; + data = data && gapi.client.analytics.data.mcf.get instanceof Function; + data = data && gapi.client.analytics.data.realtime.get instanceof Function; + analytics = analytics && data; + + interface AnalyticsParameter { + "type" ?: string; + "description" ?: string; + "default" ?: string; + "enum" ?: string[]; + "enumDescriptions" ?: string[]; + "location" ?: string; + } + var kBI : AnalyticsParameter = gapi.client.analytics.kB.parameters.alt; + var kB = !!kBI; + kBI = gapi.client.analytics.kB.parameters.fields; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.key; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.oauth_token; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.prettyPrint; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.quotaUser; + kB = kB && !!kBI; + kBI = gapi.client.analytics.kB.parameters.userIP; + kB = kB && !!kBI; + analytics = analytics && kB; + + var management : boolean = gapi.client.analytics.management.accountSummaries.list instanceof Function; + management = management && gapi.client.analytics.management.accountUserLinks.list instanceof Function; + management = management && gapi.client.analytics.management.accounts.list instanceof Function; + management = management && gapi.client.analytics.management.customDataSources.list instanceof Function; + management = management && gapi.client.analytics.management.customDimensions.list instanceof Function; + management = management && gapi.client.analytics.management.customMetrics.list instanceof Function; + management = management && gapi.client.analytics.management.experiments.list instanceof Function; + management = management && gapi.client.analytics.management.filters.list instanceof Function; + management = management && gapi.client.analytics.management.goals.list instanceof Function; + management = management && gapi.client.analytics.management.profileFilterLinks.list instanceof Function; + management = management && gapi.client.analytics.management.profileUserLinks.list instanceof Function; + management = management && gapi.client.analytics.management.profiles.list instanceof Function; + management = management && gapi.client.analytics.management.remarketingAudience.list instanceof Function; + management = management && gapi.client.analytics.management.segments.list instanceof Function; + management = management && gapi.client.analytics.management.unsampledReports.list instanceof Function; + management = management && gapi.client.analytics.management.uploads.list instanceof Function; + management = management && gapi.client.analytics.management.webPropertyAdWordsLinks.list instanceof Function; + management = management && gapi.client.analytics.management.webproperties.list instanceof Function; + management = management && gapi.client.analytics.management.webpropertyUserLinks.list instanceof Function; + analytics = analytics && management; + + var metadata : boolean = gapi.client.analytics.metadata.column.list instanceof Function; + analytics = analytics && metadata; + + return analytics; +} diff --git a/gapi.analytics/index.d.ts b/gapi.analytics/index.d.ts new file mode 100644 index 0000000000..31bbd1a83b --- /dev/null +++ b/gapi.analytics/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for Google Analytics API +// Project: https://developers.google.com/analytics/devguides/reporting/core/v4/ +// Definitions by: César Costas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace gapi.client.analytics {} +declare namespace gapi.client.analytics.provisioning { + export function createAccountTicket() : Promise; +} + +interface DataQuery { + "ids" ?: string; + "start-date" ?: string; + "30daysAgo" ?: string; + "end-date" ?: string; + "yesterday" ?: string; + "metrics" ?: string; + "dimensions" ?: string; + "sort" ?: string; + "filters" ?: string; + "segment" ?: string; + "samplingLevel" ?: string; + "include-empty-rows" ?: string; + "start-index" ?: string; + "max-results" ?: string; +} +declare namespace gapi.client.analytics.data {} +declare namespace gapi.client.analytics.data.ga { + export function get(data ?: DataQuery) : Promise; +} +declare namespace gapi.client.analytics.data.mcf { + export function get(data ?: DataQuery) : Promise; +} +declare namespace gapi.client.analytics.data.realtime { + export function get(data ?: DataQuery) : Promise; +} + +declare namespace gapi.client.analytics.kB {} +declare namespace gapi.client.analytics.kB.parameters { + export interface AnalyticsParameter { + "type" ?: string; + "description" ?: string; + "default" ?: string; + "enum" ?: string[]; + "enumDescriptions" ?: string[]; + "location" ?: string; + } + export class alt implements AnalyticsParameter {} + export class fields implements AnalyticsParameter {} + export class key implements AnalyticsParameter {} + export class oauth_token implements AnalyticsParameter {} + export class prettyPrint implements AnalyticsParameter {} + export class quotaUser implements AnalyticsParameter {} + export class userIP implements AnalyticsParameter {} +} + +interface View { + accountId ?: string; + webPropertyId ?: string; + webViewId ?: string; +} +declare namespace gapi.client.analytics.management {} +declare namespace gapi.client.analytics.management.accountSummaries { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.accountUserLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.accounts { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customDataSources { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customDimensions { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.customMetrics { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.experiments { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.filters { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.goals { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profileFilterLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profileUserLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.profiles { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.remarketingAudience { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.segments { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.unsampledReports { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.uploads { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webPropertyAdWordsLinks { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webproperties { + export function list(view ?: View) : Promise; +} +declare namespace gapi.client.analytics.management.webpropertyUserLinks { + export function list(view ?: View) : Promise; +} + +declare namespace gapi.client.analytics.metadata {} +declare namespace gapi.client.analytics.metadata.column { + export function list() : Promise; +} diff --git a/gapi.analytics/tsconfig.json b/gapi.analytics/tsconfig.json new file mode 100644 index 0000000000..73c4caf42d --- /dev/null +++ b/gapi.analytics/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gapi.analytics-tests.ts" + ] +} \ No newline at end of file diff --git a/gl-matrix/gl-matrix-tests.ts b/gl-matrix/gl-matrix-tests.ts index a7ea76f353..5df2220f72 100644 --- a/gl-matrix/gl-matrix-tests.ts +++ b/gl-matrix/gl-matrix-tests.ts @@ -1,5 +1,3 @@ - - // common import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "gl-matrix"; @@ -345,3 +343,352 @@ outQuat = quat.fromMat3(outQuat, mat3A); outQuat = quat.calculateW(outQuat, quatA); outBool = quat.exactEquals(quatA, quatB); outBool = quat.equals(quatA, quatB); + +// common +import _vec2 = require('gl-matrix/src/gl-matrix/vec2'); +import _vec3 = require('gl-matrix/src/gl-matrix/vec3'); +import _vec4 = require('gl-matrix/src/gl-matrix/vec4'); +import _mat2 = require('gl-matrix/src/gl-matrix/mat2'); +import _mat2d = require('gl-matrix/src/gl-matrix/mat2d'); +import _mat3 = require('gl-matrix/src/gl-matrix/mat3'); +import _mat4 = require('gl-matrix/src/gl-matrix/mat4'); +import _quat = require('gl-matrix/src/gl-matrix/quat'); + +vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + +vec2A = _vec2.fromValues(1, 2); +vec2B = _vec2.fromValues(3, 4); +vec3A = _vec3.fromValues(1, 2, 3); +vec3B = _vec3.fromValues(3, 4, 5); +vec4A = _vec4.fromValues(1, 2, 3, 4); +vec4B = _vec4.fromValues(3, 4, 5, 6); +mat2A = _mat2.fromValues(1, 2, 3, 4); +mat2B = _mat2.fromValues(1, 2, 3, 4); +mat2dA = _mat2d.fromValues(1, 2, 3, 4, 5, 6); +mat2dB = _mat2d.fromValues(1, 2, 3, 4, 5, 6); +mat3A = _mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +mat3B = _mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +mat4A = _mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +mat4B = _mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +quatA = _quat.fromValues(1, 2, 3, 4); +quatB = _quat.fromValues(5, 6, 7, 8); + +outVec2 = _vec2.create(); +outVec3 = _vec3.create(); +outVec4 = _vec4.create(); +outMat2 = _mat2.create(); +outMat2d = _mat2d.create(); +outMat3 = _mat3.create(); +outMat4 = _mat4.create(); +outQuat = _quat.create(); + +// _vec2 +outVec2 = _vec2.create(); +outVec2 = _vec2.clone(vec2A); +outVec2 = _vec2.fromValues(1, 2); +outVec2 = _vec2.copy(outVec2, vec2A); +outVec2 = _vec2.set(outVec2, 1, 2); +outVec2 = _vec2.add(outVec2, vec2A, vec2B); +outVec2 = _vec2.subtract(outVec2, vec2A, vec2B); +outVec2 = _vec2.sub(outVec2, vec2A, vec2B); +outVec2 = _vec2.multiply(outVec2, vec2A, vec2B); +outVec2 = _vec2.mul(outVec2, vec2A, vec2B); +outVec2 = _vec2.divide(outVec2, vec2A, vec2B); +outVec2 = _vec2.div(outVec2, vec2A, vec2B); +outVec2 = _vec2.ceil(outVec2, vec2A); +outVec2 = _vec2.floor(outVec2, vec2A); +outVec2 = _vec2.min(outVec2, vec2A, vec2B); +outVec2 = _vec2.max(outVec2, vec2A, vec2B); +outVec2 = _vec2.round(outVec2, vec2A); +outVec2 = _vec2.scale(outVec2, vec2A, 2); +outVec2 = _vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); +outVal = _vec2.distance(vec2A, vec2B); +outVal = _vec2.dist(vec2A, vec2B); +outVal = _vec2.squaredDistance(vec2A, vec2B); +outVal = _vec2.sqrDist(vec2A, vec2B); +outVal = _vec2.length(vec2A); +outVal = _vec2.len(vec2A); +outVal = _vec2.squaredLength(vec2A); +outVal = _vec2.sqrLen(vec2A); +outVec2 = _vec2.negate(outVec2, vec2A); +outVec2 = _vec2.inverse(outVec2, vec2A); +outVec2 = _vec2.normalize(outVec2, vec2A); +outVal = _vec2.dot(vec2A, vec2B); +outVec2 = _vec2.cross(outVec2, vec2A, vec2B); +outVec2 = _vec2.lerp(outVec2, vec2A, vec2B, 0.5); +outVec2 = _vec2.random(outVec2); +outVec2 = _vec2.random(outVec2, 5.0); +outVec2 = _vec2.transformMat2(outVec2, vec2A, mat2A); +outVec2 = _vec2.transformMat2d(outVec2, vec2A, mat2dA); +outVec2 = _vec2.transformMat3(outVec2, vec2A, mat3A); +outVec2 = _vec2.transformMat4(outVec2, vec2A, mat4A); +vecArray = _vec2.forEach(vecArray, 0, 0, 0, _vec2.normalize); +outStr = _vec2.str(vec2A); +outBool = _vec2.exactEquals(vec2A, vec2B); +outBool = _vec2.equals(vec2A, vec2B); +outVec2 = _vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input + +// _vec3 +outVec3 = _vec3.create(); +outVec3 = _vec3.clone(vec3A); +outVec3 = _vec3.fromValues(1, 2, 3); +outVec3 = _vec3.copy(outVec3, vec3A); +outVec3 = _vec3.set(outVec3, 1, 2, 3); +outVec3 = _vec3.add(outVec3, vec3A, vec3B); +outVec3 = _vec3.subtract(outVec3, vec3A, vec3B); +outVec3 = _vec3.sub(outVec3, vec3A, vec3B); +outVec3 = _vec3.multiply(outVec3, vec3A, vec3B); +outVec3 = _vec3.mul(outVec3, vec3A, vec3B); +outVec3 = _vec3.divide(outVec3, vec3A, vec3B); +outVec3 = _vec3.div(outVec3, vec3A, vec3B); +outVec3 = _vec3.ceil(outVec3, vec3A); +outVec3 = _vec3.floor(outVec3, vec3A); +outVec3 = _vec3.min(outVec3, vec3A, vec3B); +outVec3 = _vec3.max(outVec3, vec3A, vec3B); +outVec3 = _vec3.round(outVec3, vec3A); +outVec3 = _vec3.scale(outVec3, vec3A, 2); +outVec3 = _vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); +outVal = _vec3.distance(vec3A, vec3B); +outVal = _vec3.dist(vec3A, vec3B); +outVal = _vec3.squaredDistance(vec3A, vec3B); +outVal = _vec3.sqrDist(vec3A, vec3B); +outVal = _vec3.length(vec3A); +outVal = _vec3.len(vec3A); +outVal = _vec3.squaredLength(vec3A); +outVal = _vec3.sqrLen(vec3A); +outVec3 = _vec3.negate(outVec3, vec3A); +outVec3 = _vec3.inverse(outVec3, vec3A); +outVec3 = _vec3.normalize(outVec3, vec3A); +outVal = _vec3.dot(vec3A, vec3B); +outVec3 = _vec3.cross(outVec3, vec3A, vec3B); +outVec3 = _vec3.lerp(outVec3, vec3A, vec3B, 0.5); +outVec3 = _vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = _vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = _vec3.random(outVec3); +outVec3 = _vec3.random(outVec3, 5.0); +outVec3 = _vec3.transformMat3(outVec3, vec3A, mat3A); +outVec3 = _vec3.transformMat4(outVec3, vec3A, mat4A); +outVec3 = _vec3.transformQuat(outVec3, vec3A, quatA); +outVec3 = _vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); +outVec3 = _vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); +outVec3 = _vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); +vecArray = _vec3.forEach(vecArray, 0, 0, 0, _vec3.normalize); +outVal = _vec3.angle(vec3A, vec3B); +outStr = _vec3.str(vec3A); +outBool = _vec3.exactEquals(vec3A, vec3B); +outBool = _vec3.equals(vec3A, vec3B); +outVec3 = _vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input + +// _vec4 +outVec4 = _vec4.create(); +outVec4 = _vec4.clone(vec4A); +outVec4 = _vec4.fromValues(1, 2, 3, 4); +outVec4 = _vec4.copy(outVec4, vec4A); +outVec4 = _vec4.set(outVec4, 1, 2, 3, 4); +outVec4 = _vec4.add(outVec4, vec4A, vec4B); +outVec4 = _vec4.subtract(outVec4, vec4A, vec4B); +outVec4 = _vec4.sub(outVec4, vec4A, vec4B); +outVec4 = _vec4.multiply(outVec4, vec4A, vec4B); +outVec4 = _vec4.mul(outVec4, vec4A, vec4B); +outVec4 = _vec4.divide(outVec4, vec4A, vec4B); +outVec4 = _vec4.div(outVec4, vec4A, vec4B); +outVec4 = _vec4.ceil(outVec4, vec4A); +outVec4 = _vec4.floor(outVec4, vec4A); +outVec4 = _vec4.min(outVec4, vec4A, vec4B); +outVec4 = _vec4.max(outVec4, vec4A, vec4B); +outVec4 = _vec4.scale(outVec4, vec4A, 2); +outVec4 = _vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); +outVal = _vec4.distance(vec4A, vec4B); +outVal = _vec4.dist(vec4A, vec4B); +outVal = _vec4.squaredDistance(vec4A, vec4B); +outVal = _vec4.sqrDist(vec4A, vec4B); +outVal = _vec4.length(vec4A); +outVal = _vec4.len(vec4A); +outVal = _vec4.squaredLength(vec4A); +outVal = _vec4.sqrLen(vec4A); +outVec4 = _vec4.negate(outVec4, vec4A); +outVec4 = _vec4.inverse(outVec4, vec4A); +outVec4 = _vec4.normalize(outVec4, vec4A); +outVal = _vec4.dot(vec4A, vec4B); +outVec4 = _vec4.lerp(outVec4, vec4A, vec4B, 0.5); +outVec4 = _vec4.random(outVec4); +outVec4 = _vec4.random(outVec4, 5.0); +outVec4 = _vec4.transformMat4(outVec4, vec4A, mat4A); +outVec4 = _vec4.transformQuat(outVec4, vec4A, quatA); +vecArray = _vec4.forEach(vecArray, 0, 0, 0, _vec4.normalize); +outStr = _vec4.str(vec4A); +outBool = _vec4.exactEquals(vec4A, vec4B); +outBool = _vec4.equals(vec4A, vec4B); +outVec4 = _vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input + +// _mat2 +outMat2 = _mat2.create(); +outMat2 = _mat2.clone(mat2A); +outMat2 = _mat2.copy(outMat2, mat2A); +outMat2 = _mat2.identity(outMat2); +outMat2 = _mat2.fromValues(1, 2, 3, 4); +outMat2 = _mat2.set(outMat2, 1, 2, 3, 4); +outMat2 = _mat2.transpose(outMat2, mat2A); +outMat2 = _mat2.invert(outMat2, mat2A); +outMat2 = _mat2.adjoint(outMat2, mat2A); +outVal = _mat2.determinant(mat2A); +outMat2 = _mat2.multiply(outMat2, mat2A, mat2B); +outMat2 = _mat2.mul(outMat2, mat2A, mat2B); +outMat2 = _mat2.rotate(outMat2, mat2A, Math.PI * 0.5); +outMat2 = _mat2.scale(outMat2, mat2A, vec2A); +outMat2 = _mat2.fromRotation(outMat2, 0.5); +outMat2 = _mat2.fromScaling(outMat2, vec2A); +outStr = _mat2.str(mat2A); +outVal = _mat2.frob(mat2A); +var L = _mat2.create(); +var D = _mat2.create(); +var U = _mat2.create(); +outMat2 = _mat2.LDU(L, D, U, mat2A); +outMat2 = _mat2.add(outMat2, mat2A, mat2B); +outMat2 = _mat2.subtract(outMat2, mat2A, mat2B); +outMat2 = _mat2.sub(outMat2, mat2A, mat2B); +outBool = _mat2.exactEquals(mat2A, mat2B); +outBool = _mat2.equals(mat2A, mat2B); +outMat2 = _mat2.multiplyScalar (outMat2, mat2A, 2); +outMat2 = _mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); + +// _mat2d +outMat2d = _mat2d.create(); +outMat2d = _mat2d.clone(mat2dA); +outMat2d = _mat2d.copy(outMat2d, mat2dA); +outMat2d = _mat2d.identity(outMat2d); +outMat2d = _mat2d.fromValues(1, 2, 3, 4, 5, 6); +outMat2d = _mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); +outMat2d = _mat2d.invert(outMat2d, mat2dA); +outVal = _mat2d.determinant(mat2dA); +outMat2d = _mat2d.multiply(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.mul(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); +outMat2d = _mat2d.scale(outMat2d, mat2dA, vec2A); +outMat2d = _mat2d.translate(outMat2d, mat2dA, vec2A); +outMat2d = _mat2d.fromRotation(outMat2d, 0.5); +outMat2d = _mat2d.fromScaling(outMat2d, vec2A); +outMat2d = _mat2d.fromTranslation(outMat2d, vec2A); +outStr = _mat2d.str(mat2dA); +outVal = _mat2d.frob(mat2dA); +outMat2d = _mat2d.add(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.subtract(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.sub(outMat2d, mat2dA, mat2dB); +outMat2d = _mat2d.multiplyScalar (outMat2d, mat2dA, 2); +outMat2d = _mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); +outBool = _mat2d.exactEquals(mat2dA, mat2dB); +outBool = _mat2d.equals(mat2dA, mat2dB); + +// _mat3 +outMat3 = _mat3.create(); +outMat3 = _mat3.fromMat4(outMat3, mat4A); +outMat3 = _mat3.clone(mat3A); +outMat3 = _mat3.copy(outMat3, mat3A); +outMat3 = _mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = _mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = _mat3.identity(outMat3); +outMat3 = _mat3.transpose(outMat3, mat3A); +outMat3 = _mat3.invert(outMat3, mat3A); +outMat3 = _mat3.adjoint(outMat3, mat3A); +outVal = _mat3.determinant(mat3A); +outMat3 = _mat3.multiply(outMat3, mat3A, mat3B); +outMat3 = _mat3.mul(outMat3, mat3A, mat3B); +outMat3 = _mat3.translate(outMat3, mat3A, vec3A); +outMat3 = _mat3.rotate(outMat3, mat3A, Math.PI/2); +outMat3 = _mat3.scale(outMat3, mat3A, vec2A); +outMat3 = _mat3.fromTranslation(outMat3, vec2A); +outMat3 = _mat3.fromRotation(outMat3, Math.PI); +outMat3 = _mat3.fromScaling(outMat3, vec2A); +outMat3 = _mat3.fromMat2d(outMat3, mat2dA); +outMat3 = _mat3.fromQuat(outMat3, quatA); +outMat3 = _mat3.normalFromMat4(outMat3, mat4A); +outStr = _mat3.str(mat3A); +outVal = _mat3.frob(mat3A); +outMat3 = _mat3.add(outMat3, mat3A, mat3B); +outMat3 = _mat3.subtract(outMat3, mat3A, mat3B); +outMat3 = _mat3.sub(outMat3, mat3A, mat3B); +outMat3 = _mat3.multiplyScalar (outMat3, mat3A, 2); +outMat3 = _mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); +outBool = _mat3.exactEquals(mat3A, mat3B); +outBool = _mat3.equals(mat3A, mat3B); + +//_mat4 +outMat4 = _mat4.create(); +outMat4 = _mat4.clone(mat4A); +outMat4 = _mat4.copy(outMat4, mat4A); +outMat4 = _mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = _mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = _mat4.identity(outMat4); +outMat4 = _mat4.transpose(outMat4, mat4A); +outMat4 = _mat4.invert(outMat4, mat4A); +outMat4 = _mat4.adjoint(outMat4, mat4A); +outVal = _mat4.determinant(mat4A); +outMat4 = _mat4.multiply(outMat4, mat4A, mat4B); +outMat4 = _mat4.mul(outMat4, mat4A, mat4B); +outMat4 = _mat4.translate(outMat4, mat4A, vec3A); +outMat4 = _mat4.scale(outMat4, mat4A, vec3A); +outMat4 = _mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4 = _mat4.rotateX(outMat4, mat4A, Math.PI); +outMat4 = _mat4.rotateY(outMat4, mat4A, Math.PI); +outMat4 = _mat4.rotateZ(outMat4, mat4A, Math.PI); +outMat4 = _mat4.fromTranslation(outMat4, vec3A); +outMat4 = _mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4 = _mat4.fromScaling(outMat4, vec3A); +outMat4 = _mat4.fromXRotation(outMat4, Math.PI); +outMat4 = _mat4.fromYRotation(outMat4, Math.PI); +outMat4 = _mat4.fromZRotation(outMat4, Math.PI); +outMat4 = _mat4.fromRotationTranslation(outMat4, quatA, vec3A); +outVec3 = _mat4.getTranslation(outVec3, mat4A) +outQuat = _mat4.getRotation(outQuat, mat4A) +outMat4 = _mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); +outMat4 = _mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); +outMat4 = _mat4.fromQuat(outMat4, quatB); +outMat4 = _mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = _mat4.perspective(outMat4, Math.PI, 1, 0, 1); +outMat4 = _mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); +outMat4 = _mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = _mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outStr = _mat4.str(mat4A); +outVal = _mat4.frob(mat4A); +outMat4 = _mat4.add(outMat4, mat4A, mat4B); +outMat4 = _mat4.subtract(outMat4, mat4A, mat4B); +outMat4 = _mat4.sub(outMat4, mat4A, mat4B); +outMat4 = _mat4.multiplyScalar (outMat4, mat4A, 2); +outMat4 = _mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); +outBool = _mat4.exactEquals(mat4A, mat4B); +outBool = _mat4.equals(mat4A, mat4B); + +// _quat +var deg90 = Math.PI / 2; +outQuat = _quat.create(); +outQuat = _quat.clone(quatA); +outQuat = _quat.fromValues(1, 2, 3, 4); +outQuat = _quat.copy(outQuat, quatA); +outQuat = _quat.set(outQuat, 1, 2, 3, 4); +outQuat = _quat.identity(outQuat); +outQuat = _quat.rotationTo(outQuat, vec3A, vec3B); +outQuat = _quat.setAxes(outQuat, vec3A, vec3B, vec3A); +outQuat = _quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); +outVal = _quat.getAxisAngle (outVec3, quatA); +outQuat = _quat.add(outQuat, quatA, quatB); +outQuat = _quat.multiply(outQuat, quatA, quatB); +outQuat = _quat.mul(outQuat, quatA, quatB); +outQuat = _quat.scale(outQuat, quatA, 2); +outVal = _quat.length(quatA); +outVal = _quat.len(quatA); +outVal = _quat.squaredLength(quatA); +outVal = _quat.sqrLen(quatA); +outQuat = _quat.normalize(outQuat, quatA); +outVal = _quat.dot(quatA, quatB); +outQuat = _quat.lerp(outQuat, quatA, quatB, 0.5); +outQuat = _quat.slerp(outQuat, quatA, quatB, 0.5); +outQuat = _quat.invert(outQuat, quatA); +outQuat = _quat.conjugate(outQuat, quatA); +outStr = _quat.str(quatA); +outQuat = _quat.rotateX(outQuat, quatA, deg90); +outQuat = _quat.rotateY(outQuat, quatA, deg90); +outQuat = _quat.rotateZ(outQuat, quatA, deg90); +outQuat = _quat.fromMat3(outQuat, mat3A); +outQuat = _quat.calculateW(outQuat, quatA); +outBool = _quat.exactEquals(quatA, quatB); +outBool = _quat.equals(quatA, quatB); diff --git a/gl-matrix/index.d.ts b/gl-matrix/index.d.ts index 2edbbd8bb5..b8a6694e40 100644 --- a/gl-matrix/index.d.ts +++ b/gl-matrix/index.d.ts @@ -3,3042 +3,3084 @@ // Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// vec2 -export class vec2 extends Float32Array { - private typeVec2: number; +declare module 'gl-matrix' { + // vec2 + export class vec2 extends Float32Array { + private typeVec2: number; - /** - * Creates a new, empty vec2 - * - * @returns a new 2D vector - */ - public static create(): vec2; + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + public static create(): vec2; - /** - * Creates a new vec2 initialized with values from an existing vector - * - * @param a a vector to clone - * @returns a new 2D vector - */ - public static clone(a: vec2 | number[]): vec2; + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + public static clone(a: vec2 | number[]): vec2; - /** - * Creates a new vec2 initialized with the given values - * - * @param x X component - * @param y Y component - * @returns a new 2D vector - */ - public static fromValues(x: number, y: number): vec2; + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + public static fromValues(x: number, y: number): vec2; - /** - * Copy the values from one vec2 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec2, a: vec2 | number[]): vec2; + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec2, a: vec2 | number[]): vec2; - /** - * Set the components of a vec2 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @returns out - */ - public static set(out: vec2, x: number, y: number): vec2; + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + public static set(out: vec2, x: number, y: number): vec2; - /** - * Adds two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Multiplies two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Multiplies two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Divides two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Divides two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Math.ceil the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to ceil - * @returns {vec2} out - */ - public static ceil(out: vec2, a: vec2 | number[]): vec2; + /** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ + public static ceil(out: vec2, a: vec2 | number[]): vec2; - /** - * Math.floor the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to floor - * @returns {vec2} out - */ - public static floor (out: vec2, a: vec2 | number[]): vec2; + /** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ + public static floor (out: vec2, a: vec2 | number[]): vec2; - /** - * Returns the minimum of two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Returns the maximum of two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Math.round the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to round - * @returns {vec2} out - */ - public static round(out: vec2, a: vec2 | number[]): vec2; + /** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ + public static round(out: vec2, a: vec2 | number[]): vec2; - /** - * Scales a vec2 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec2, a: vec2 | number[], b: number): vec2; + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; - /** - * Adds two vec2's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; - /** - * Calculates the euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Calculates the euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec2 | number[]): number; + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec2 | number[]): number; - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec2 | number[]): number; + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec2 | number[]): number; - /** - * Calculates the squared length of a vec2 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec2 | number[]): number; + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec2 | number[]): number; - /** - * Calculates the squared length of a vec2 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec2 | number[]): number; + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec2 | number[]): number; - /** - * Negates the components of a vec2 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec2, a: vec2 | number[]): vec2; + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec2, a: vec2 | number[]): vec2; - /** - * Returns the inverse of the components of a vec2 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec2, a: vec2 | number[]): vec2; + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec2, a: vec2 | number[]): vec2; - /** - * Normalize a vec2 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec2, a: vec2 | number[]): vec2; + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec2, a: vec2 | number[]): vec2; - /** - * Calculates the dot product of two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec2 | number[], b: vec2 | number[]): number; + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec2 | number[], b: vec2 | number[]): number; - /** - * Computes the cross product of two vec2's - * Note that the cross product must by definition produce a 3D vector - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - /** - * Performs a linear interpolation between two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec2): vec2; + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec2): vec2; - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec2, scale: number): vec2; + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec2, scale: number): vec2; - /** - * Transforms the vec2 with a mat2 - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; - /** - * Transforms the vec2 with a mat2d - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; - /** - * Transforms the vec2 with a mat3 - * 3rd vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; - /** - * Transforms the vec2 with a mat4 - * 3rd vector component is implicitly '0' - * 4th vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; - /** - * Perform some operation over an array of vec2s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec2s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; - /** - * Perform some operation over an array of vec2s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec2s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec2 | number[]): string; + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec2 | number[]): string; - /** - * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; + /** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; + } + + // vec3 + export class vec3 extends Float32Array { + private typeVec3: number; + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + public static create(): vec3; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + public static clone(a: vec3 | number[]): vec3; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + public static fromValues(x: number, y: number, z: number): vec3; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec3, a: vec3 | number[]): vec3; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + public static set(out: vec3, x: number, y: number, z: number): vec3; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ + public static ceil (out: vec3, a: vec3 | number[]): vec3; + + /** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ + public static floor (out: vec3, a: vec3 | number[]): vec3; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ + public static round (out: vec3, a: vec3 | number[]): vec3 + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec3 | number[]): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec3 | number[]): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec3 | number[]): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec3 | number[]): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec3, a: vec3 | number[]): vec3; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec3, a: vec3 | number[]): vec3; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec3, a: vec3 | number[]): vec3; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; + + /** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; + + /** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec3): vec3; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec3, scale: number): vec3; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; + + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + public static angle(a: vec3 | number[], b: vec3 | number[]): number; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec3 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec3 | number[], b: vec3 | number[]): boolean + } + + // vec4 + export class vec4 extends Float32Array { + private typeVec3: number; + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + public static create(): vec4; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + public static clone(a: vec4 | number[]): vec4; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + public static fromValues(x: number, y: number, z: number, w: number): vec4; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec4, a: vec4 | number[]): vec4; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ + public static ceil (out: vec4, a: vec4 | number[]): vec4; + + /** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ + public static floor (out: vec4, a: vec4 | number[]): vec4; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ + public static round (out: vec4, a: vec4 | number[]): vec4; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec4 | number[]): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec4 | number[]): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec4 | number[]): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec4 | number[]): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec4, a: vec4 | number[]): vec4; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec4, a: vec4 | number[]): vec4; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec4, a: vec4 | number[]): vec4; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec4 | number[], b: vec4 | number[]): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec4): vec4; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec4, scale: number): vec4; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec4 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; + } + + // mat2 + export class mat2 extends Float32Array { + private typeMat2: number; + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + public static create(): mat2; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + public static clone(a: mat2): mat2; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat2, a: mat2): mat2; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat2): mat2; + + /** + * Create a new mat2 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; + + /** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out: mat2, a: mat2): mat2; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat2, a: mat2): mat2; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out: mat2, a: mat2): mat2; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat2): number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out: mat2, a: mat2, rad: number): mat2; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + public static fromRotation(out: mat2, rad: number): mat2; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ + public static fromScaling(out: mat2, v: vec2 | number[]): mat2; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(a: mat2): string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat2): number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; + + /** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static add(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static subtract (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static sub (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2, b: mat2): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2, b: mat2): boolean; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 + + /** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 + + + + } + + // mat2d + export class mat2d extends Float32Array { + private typeMat2d: number; + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + public static create(): mat2d; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + public static clone(a: mat2d): mat2d; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat2d, a: mat2d): mat2d; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat2d): mat2d; + + /** + * Create a new mat2d with the given values + * + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d + + + /** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} out + */ + public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat2d, a: mat2d): mat2d; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat2d): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + **/ + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + public static fromRotation (out: mat2d, rad: number): mat2d; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2d} out + */ + public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Translation vector + * @returns {mat2d} out + */ + public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(a: mat2d): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat2d): number; + + /** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static add (out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; + + /** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2d, b: mat2d): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2d, b: mat2d): boolean + } + + // mat3 + export class mat3 extends Float32Array { + private typeMat3: number; + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + public static create(): mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ + public static fromMat4(out: mat3, a: mat4): mat3 + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + public static clone(a: mat3): mat3; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat3, a: mat3): mat3; + + /** + * Create a new mat3 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; + + + /** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat3): mat3; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out: mat3, a: mat3): mat3; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat3, a: mat3): mat3; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out: mat3, a: mat3): mat3; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat3): number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat3, a: mat3, b: mat3): mat3; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat3, a: mat3, b: mat3): mat3; + + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out: mat3, a: mat3, rad: number): mat3; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ + public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + public static fromRotation(out: mat3, rad: number): mat3 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ + public static fromScaling(out: mat3, v: vec2 | number[]): mat3 + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + public static fromMat2d(out: mat3, a: mat2d): mat3; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + public static fromQuat(out: mat3, q: quat): mat3; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + public static normalFromMat4(out: mat3, a: mat4): mat3; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat3): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat3): number; + + /** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static add(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static subtract(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static sub(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 + + /** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals(a: mat3, b: mat3): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals(a: mat3, b: mat3): boolean + } + + // mat4 + export class mat4 extends Float32Array { + private typeMat4: number; + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + public static create(): mat4; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + public static clone(a: mat4): mat4; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat4, a: mat4): mat4; + + + /** + * Create a new mat4 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; + + /** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat4): mat4; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out: mat4, a: mat4): mat4; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat4, a: mat4): mat4; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out: mat4, a: mat4): mat4; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat4): number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat4, a: mat4, b: mat4): mat4; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat4, a: mat4, b: mat4): mat4; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + **/ + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateX(out: mat4, a: mat4, rad: number): mat4; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateY(out: mat4, a: mat4, rad: number): mat4; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out + */ + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out + */ + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 + + /** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 + + /** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromXRotation(out: mat4, rad: number): mat4 + + /** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromYRotation(out: mat4, rad: number): mat4 + + + /** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromZRotation(out: mat4, rad: number): mat4 + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; + + /** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + public static getTranslation(out: vec3, mat: mat4): vec3; + + /** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + public static getRotation(out: quat, mat: mat4): quat; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector + * @returns out + */ + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 + + /** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + public static fromQuat(out: mat4, q: quat): mat4 + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static frustum(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static perspective(out: mat4, fovy: number, aspect: number, + near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experimental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + public static perspectiveFromFieldOfView(out: mat4, + fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, + near: number, far: number): mat4 + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static ortho(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat4): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat4): number; + + /** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static add(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static subtract(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static sub(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 + + /** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat4, b: mat4): boolean + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat4, b: mat4): boolean + + } + + // quat + export class quat extends Float32Array { + private typeQuat: number; + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + public static create(): quat; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + public static clone(a: quat): quat; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + public static fromValues(x: number, y: number, z: number, w: number): quat; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + public static copy(out: quat, a: quat): quat; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + public static set(out: quat, x: number, y: number, z: number, w: number): quat; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + public static identity(out: quat): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ + public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat + + + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + **/ + public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; + + /** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {number} Angle, in radians, of the rotation + */ + public static getAxisAngle (out_axis: vec3 | number[], q: quat): number + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + public static add(out: quat, a: quat, b: quat): quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: quat, a: quat, b: quat): quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: quat, a: quat, b: quat): quat; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + public static scale(out: quat, a: quat, b: number): quat; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + public static length(a: quat): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + public static len(a: quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + public static squaredLength(a: quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + public static sqrLen(a: quat): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + public static normalize(out: quat, a: quat): quat; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + public static dot(a: quat, b: quat): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + public static lerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static slerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {number} t interpolation amount + * @returns {quat} out + */ + public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + public static invert(out: quat, a: quat): quat; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + public static conjugate(out: quat, a: quat): quat; + + /** + * Returns a string representation of a quaternion + * + * @param a quat to represent as a string + * @returns string representation of the quat + */ + public static str(a: quat): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateX(out: quat, a: quat, rad: number): quat; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateY(out: quat, a: quat, rad: number): quat; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateZ(out: quat, a: quat, rad: number): quat; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + public static fromMat3(out: quat, m: mat3): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param out the receiving quat + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + public static calculateW(out: quat, a: quat): quat; + + /** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static exactEquals (a: quat, b: quat): boolean; + + /** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static equals (a: quat, b: quat): boolean; + } } -// vec3 -export class vec3 extends Float32Array { - private typeVec3: number; - - /** - * Creates a new, empty vec3 - * - * @returns a new 3D vector - */ - public static create(): vec3; - - /** - * Creates a new vec3 initialized with values from an existing vector - * - * @param a vector to clone - * @returns a new 3D vector - */ - public static clone(a: vec3 | number[]): vec3; - - /** - * Creates a new vec3 initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @returns a new 3D vector - */ - public static fromValues(x: number, y: number, z: number): vec3; - - /** - * Copy the values from one vec3 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec3, a: vec3 | number[]): vec3; - - /** - * Set the components of a vec3 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @param z Z component - * @returns out - */ - public static set(out: vec3, x: number, y: number, z: number): vec3; - - /** - * Adds two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 - - /** - * Multiplies two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Multiplies two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Divides two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Divides two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Math.ceil the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to ceil - * @returns {vec3} out - */ - public static ceil (out: vec3, a: vec3 | number[]): vec3; - - /** - * Math.floor the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to floor - * @returns {vec3} out - */ - public static floor (out: vec3, a: vec3 | number[]): vec3; - - /** - * Returns the minimum of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Returns the maximum of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Math.round the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to round - * @returns {vec3} out - */ - public static round (out: vec3, a: vec3 | number[]): vec3 - - /** - * Scales a vec3 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec3, a: vec3 | number[], b: number): vec3; - - /** - * Adds two vec3's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec3 | number[]): number; - - /** - * Calculates the squared length of a vec3 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec3 | number[]): number; - - /** - * Calculates the squared length of a vec3 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec3 | number[]): number; - - /** - * Negates the components of a vec3 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec3, a: vec3 | number[]): vec3; - - /** - * Returns the inverse of the components of a vec3 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec3, a: vec3 | number[]): vec3; - - /** - * Normalize a vec3 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec3, a: vec3 | number[]): vec3; - - /** - * Calculates the dot product of two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Computes the cross product of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Performs a linear interpolation between two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; - - /** - * Performs a hermite interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; - - /** - * Performs a bezier interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec3): vec3; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec3, scale: number): vec3; - - /** - * Transforms the vec3 with a mat3. - * - * @param out the receiving vector - * @param a the vector to transform - * @param m the 3x3 matrix to transform with - * @returns out - */ - public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; - - /** - * Transforms the vec3 with a mat4. - * 4th vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; - - /** - * Transforms the vec3 with a quat - * - * @param out the receiving vector - * @param a the vector to transform - * @param q quaternion to transform with - * @returns out - */ - public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; - - - /** - * Rotate a 3D vector around the x-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Rotate a 3D vector around the y-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Rotate a 3D vector around the z-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Perform some operation over an array of vec3s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec3s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec3s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec3s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; - - /** - * Get the angle between two 3D vectors - * @param a The first operand - * @param b The second operand - * @returns The angle in radians - */ - public static angle(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec3 | number[]): string; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec3 | number[], b: vec3 | number[]): boolean +declare module 'gl-matrix/src/gl-matrix/vec2' { + import { vec2 } from 'gl-matrix'; + export = vec2; } -// vec4 -export class vec4 extends Float32Array { - private typeVec3: number; - - /** - * Creates a new, empty vec4 - * - * @returns a new 4D vector - */ - public static create(): vec4; - - /** - * Creates a new vec4 initialized with values from an existing vector - * - * @param a vector to clone - * @returns a new 4D vector - */ - public static clone(a: vec4 | number[]): vec4; - - /** - * Creates a new vec4 initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns a new 4D vector - */ - public static fromValues(x: number, y: number, z: number, w: number): vec4; - - /** - * Copy the values from one vec4 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec4, a: vec4 | number[]): vec4; - - /** - * Set the components of a vec4 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns out - */ - public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; - - /** - * Adds two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Multiplies two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Multiplies two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Divides two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Divides two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Math.ceil the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to ceil - * @returns {vec4} out - */ - public static ceil (out: vec4, a: vec4 | number[]): vec4; - - /** - * Math.floor the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to floor - * @returns {vec4} out - */ - public static floor (out: vec4, a: vec4 | number[]): vec4; - - /** - * Returns the minimum of two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Returns the maximum of two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Math.round the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to round - * @returns {vec4} out - */ - public static round (out: vec4, a: vec4 | number[]): vec4; - - /** - * Scales a vec4 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec4, a: vec4 | number[], b: number): vec4; - - /** - * Adds two vec4's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec4 | number[]): number; - - /** - * Calculates the squared length of a vec4 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec4 | number[]): number; - - /** - * Calculates the squared length of a vec4 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec4 | number[]): number; - - /** - * Negates the components of a vec4 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec4, a: vec4 | number[]): vec4; - - /** - * Returns the inverse of the components of a vec4 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec4, a: vec4 | number[]): vec4; - - /** - * Normalize a vec4 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec4, a: vec4 | number[]): vec4; - - /** - * Calculates the dot product of two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Performs a linear interpolation between two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec4): vec4; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param scale length of the resulting vector. If ommitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec4, scale: number): vec4; - - /** - * Transforms the vec4 with a mat4. - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; - - /** - * Transforms the vec4 with a quat - * - * @param out the receiving vector - * @param a the vector to transform - * @param q quaternion to transform with - * @returns out - */ - - public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; - - /** - * Perform some operation over an array of vec4s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec4s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec4s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec4s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec4 | number[]): string; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; +declare module 'gl-matrix/src/gl-matrix/vec3' { + import { vec3 } from 'gl-matrix'; + export = vec3; } -// mat2 -export class mat2 extends Float32Array { - private typeMat2: number; - - /** - * Creates a new identity mat2 - * - * @returns a new 2x2 matrix - */ - public static create(): mat2; - - /** - * Creates a new mat2 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 2x2 matrix - */ - public static clone(a: mat2): mat2; - - /** - * Copy the values from one mat2 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat2, a: mat2): mat2; - - /** - * Set a mat2 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat2): mat2; - - /** - * Create a new mat2 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m10 Component in column 1, row 0 position (index 2) - * @param {number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out A new 2x2 matrix - */ - public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; - - /** - * Set the components of a mat2 to the given values - * - * @param {mat2} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m10 Component in column 1, row 0 position (index 2) - * @param {number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out - */ - public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; - - /** - * Transpose the values of a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat2, a: mat2): mat2; - - /** - * Inverts a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat2, a: mat2): mat2; - - /** - * Calculates the adjugate of a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat2, a: mat2): mat2; - - /** - * Calculates the determinant of a mat2 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat2): number; - - /** - * Multiplies two mat2's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Multiplies two mat2's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Rotates a mat2 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat2, a: mat2, rad: number): mat2; - - /** - * Scales the mat2 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.rotate(dest, dest, rad); - * - * @param {mat2} out mat2 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat2} out - */ - public static fromRotation(out: mat2, rad: number): mat2; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.scale(dest, dest, vec); - * - * @param {mat2} out mat2 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2} out - */ - public static fromScaling(out: mat2, v: vec2 | number[]): mat2; - - /** - * Returns a string representation of a mat2 - * - * @param a matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(a: mat2): string; - - /** - * Returns Frobenius norm of a mat2 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat2): number; - - /** - * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix - * @param L the lower triangular matrix - * @param D the diagonal matrix - * @param U the upper triangular matrix - * @param a the input matrix to factorize - */ - public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; - - /** - * Adds two mat2's - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static add(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static subtract (out: mat2, a: mat2, b: mat2): mat2; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static sub (out: mat2, a: mat2, b: mat2): mat2; - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat2, b: mat2): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat2, b: mat2): boolean; - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat2} out - */ - public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 - - /** - * Adds two mat2's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2} out the receiving vector - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat2} out - */ - public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 - - - +declare module 'gl-matrix/src/gl-matrix/vec4' { + import { vec4 } from 'gl-matrix'; + export = vec4; } -// mat2d -export class mat2d extends Float32Array { - private typeMat2d: number; - - /** - * Creates a new identity mat2d - * - * @returns a new 2x3 matrix - */ - public static create(): mat2d; - - /** - * Creates a new mat2d initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 2x3 matrix - */ - public static clone(a: mat2d): mat2d; - - /** - * Copy the values from one mat2d to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat2d, a: mat2d): mat2d; - - /** - * Set a mat2d to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat2d): mat2d; - - /** - * Create a new mat2d with the given values - * - * @param {number} a Component A (index 0) - * @param {number} b Component B (index 1) - * @param {number} c Component C (index 2) - * @param {number} d Component D (index 3) - * @param {number} tx Component TX (index 4) - * @param {number} ty Component TY (index 5) - * @returns {mat2d} A new mat2d - */ - public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d - - - /** - * Set the components of a mat2d to the given values - * - * @param {mat2d} out the receiving matrix - * @param {number} a Component A (index 0) - * @param {number} b Component B (index 1) - * @param {number} c Component C (index 2) - * @param {number} d Component D (index 3) - * @param {number} tx Component TX (index 4) - * @param {number} ty Component TY (index 5) - * @returns {mat2d} out - */ - public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d - - /** - * Inverts a mat2d - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat2d, a: mat2d): mat2d; - - /** - * Calculates the determinant of a mat2d - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat2d): number; - - /** - * Multiplies two mat2d's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; - - /** - * Multiplies two mat2d's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; - - /** - * Rotates a mat2d by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; - - /** - * Scales the mat2d by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; - - /** - * Translates the mat2d by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v the vec2 to translate the matrix by - * @returns out - **/ - public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.rotate(dest, dest, rad); - * - * @param {mat2d} out mat2d receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat2d} out - */ - public static fromRotation (out: mat2d, rad: number): mat2d; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.scale(dest, dest, vec); - * - * @param {mat2d} out mat2d receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2d} out - */ - public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.translate(dest, dest, vec); - * - * @param {mat2d} out mat2d receiving operation result - * @param {vec2} v Translation vector - * @returns {mat2d} out - */ - public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d - - /** - * Returns a string representation of a mat2d - * - * @param a matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(a: mat2d): string; - - /** - * Returns Frobenius norm of a mat2d - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat2d): number; - - /** - * Adds two mat2d's - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static add (out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat2d} out - */ - public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; - - /** - * Adds two mat2d's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2d} out the receiving vector - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat2d} out - */ - public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2d} a The first matrix. - * @param {mat2d} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat2d, b: mat2d): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2d} a The first matrix. - * @param {mat2d} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat2d, b: mat2d): boolean +declare module 'gl-matrix/src/gl-matrix/mat2' { + import { mat2 } from 'gl-matrix'; + export = mat2; } -// mat3 -export class mat3 extends Float32Array { - private typeMat3: number; - - /** - * Creates a new identity mat3 - * - * @returns a new 3x3 matrix - */ - public static create(): mat3; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param {mat3} out the receiving 3x3 matrix - * @param {mat4} a the source 4x4 matrix - * @returns {mat3} out - */ - public static fromMat4(out: mat3, a: mat4): mat3 - - /** - * Creates a new mat3 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 3x3 matrix - */ - public static clone(a: mat3): mat3; - - /** - * Copy the values from one mat3 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat3, a: mat3): mat3; - - /** - * Create a new mat3 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m10 Component in column 1, row 0 position (index 3) - * @param {number} m11 Component in column 1, row 1 position (index 4) - * @param {number} m12 Component in column 1, row 2 position (index 5) - * @param {number} m20 Component in column 2, row 0 position (index 6) - * @param {number} m21 Component in column 2, row 1 position (index 7) - * @param {number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} A new mat3 - */ - public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; - - - /** - * Set the components of a mat3 to the given values - * - * @param {mat3} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m10 Component in column 1, row 0 position (index 3) - * @param {number} m11 Component in column 1, row 1 position (index 4) - * @param {number} m12 Component in column 1, row 2 position (index 5) - * @param {number} m20 Component in column 2, row 0 position (index 6) - * @param {number} m21 Component in column 2, row 1 position (index 7) - * @param {number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} out - */ - public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 - - /** - * Set a mat3 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat3): mat3; - - /** - * Transpose the values of a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat3, a: mat3): mat3; - - /** - * Inverts a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat3, a: mat3): mat3; - - /** - * Calculates the adjugate of a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat3, a: mat3): mat3; - - /** - * Calculates the determinant of a mat3 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat3): number; - - /** - * Multiplies two mat3's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat3, a: mat3, b: mat3): mat3; - - /** - * Multiplies two mat3's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat3, a: mat3, b: mat3): mat3; - - - /** - * Translate a mat3 by the given vector - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v vector to translate by - * @returns out - */ - public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; - - /** - * Rotates a mat3 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat3, a: mat3, rad: number): mat3; - - /** - * Scales the mat3 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.translate(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Translation vector - * @returns {mat3} out - */ - public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.rotate(dest, dest, rad); - * - * @param {mat3} out mat3 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat3} out - */ - public static fromRotation(out: mat3, rad: number): mat3 - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.scale(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat3} out - */ - public static fromScaling(out: mat3, v: vec2 | number[]): mat3 - - /** - * Copies the values from a mat2d into a mat3 - * - * @param out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns out - **/ - public static fromMat2d(out: mat3, a: mat2d): mat3; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param out mat3 receiving operation result - * @param q Quaternion to create matrix from - * - * @returns out - */ - public static fromQuat(out: mat3, q: quat): mat3; - - /** - * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix - * - * @param out mat3 receiving operation result - * @param a Mat4 to derive the normal matrix from - * - * @returns out - */ - public static normalFromMat4(out: mat3, a: mat4): mat3; - - /** - * Returns a string representation of a mat3 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(mat: mat3): string; - - /** - * Returns Frobenius norm of a mat3 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat3): number; - - /** - * Adds two mat3's - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static add(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static subtract(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static sub(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat3} out - */ - public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 - - /** - * Adds two mat3's after multiplying each element of the second operand by a scalar value. - * - * @param {mat3} out the receiving vector - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat3} out - */ - public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals(a: mat3, b: mat3): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals(a: mat3, b: mat3): boolean +declare module 'gl-matrix/src/gl-matrix/mat2d' { + import { mat2d } from 'gl-matrix'; + export = mat2d; } -// mat4 -export class mat4 extends Float32Array { - private typeMat4: number; - - /** - * Creates a new identity mat4 - * - * @returns a new 4x4 matrix - */ - public static create(): mat4; - - /** - * Creates a new mat4 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 4x4 matrix - */ - public static clone(a: mat4): mat4; - - /** - * Copy the values from one mat4 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat4, a: mat4): mat4; - - - /** - * Create a new mat4 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m03 Component in column 0, row 3 position (index 3) - * @param {number} m10 Component in column 1, row 0 position (index 4) - * @param {number} m11 Component in column 1, row 1 position (index 5) - * @param {number} m12 Component in column 1, row 2 position (index 6) - * @param {number} m13 Component in column 1, row 3 position (index 7) - * @param {number} m20 Component in column 2, row 0 position (index 8) - * @param {number} m21 Component in column 2, row 1 position (index 9) - * @param {number} m22 Component in column 2, row 2 position (index 10) - * @param {number} m23 Component in column 2, row 3 position (index 11) - * @param {number} m30 Component in column 3, row 0 position (index 12) - * @param {number} m31 Component in column 3, row 1 position (index 13) - * @param {number} m32 Component in column 3, row 2 position (index 14) - * @param {number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} A new mat4 - */ - public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; - - /** - * Set the components of a mat4 to the given values - * - * @param {mat4} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m03 Component in column 0, row 3 position (index 3) - * @param {number} m10 Component in column 1, row 0 position (index 4) - * @param {number} m11 Component in column 1, row 1 position (index 5) - * @param {number} m12 Component in column 1, row 2 position (index 6) - * @param {number} m13 Component in column 1, row 3 position (index 7) - * @param {number} m20 Component in column 2, row 0 position (index 8) - * @param {number} m21 Component in column 2, row 1 position (index 9) - * @param {number} m22 Component in column 2, row 2 position (index 10) - * @param {number} m23 Component in column 2, row 3 position (index 11) - * @param {number} m30 Component in column 3, row 0 position (index 12) - * @param {number} m31 Component in column 3, row 1 position (index 13) - * @param {number} m32 Component in column 3, row 2 position (index 14) - * @param {number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} out - */ - public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; - - /** - * Set a mat4 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat4): mat4; - - /** - * Transpose the values of a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat4, a: mat4): mat4; - - /** - * Inverts a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat4, a: mat4): mat4; - - /** - * Calculates the adjugate of a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat4, a: mat4): mat4; - - /** - * Calculates the determinant of a mat4 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat4): number; - - /** - * Multiplies two mat4's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat4, a: mat4, b: mat4): mat4; - - /** - * Multiplies two mat4's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat4, a: mat4, b: mat4): mat4; - - /** - * Translate a mat4 by the given vector - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v vector to translate by - * @returns out - */ - public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; - - /** - * Scales the mat4 by the dimensions in the given vec3 - * - * @param out the receiving matrix - * @param a the matrix to scale - * @param v the vec3 to scale the matrix by - * @returns out - **/ - public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; - - /** - * Rotates a mat4 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @param axis the axis to rotate around - * @returns out - */ - public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; - - /** - * Rotates a matrix by the given angle around the X axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateX(out: mat4, a: mat4, rad: number): mat4; - - /** - * Rotates a matrix by the given angle around the Y axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateY(out: mat4, a: mat4, rad: number): mat4; - - /** - * Rotates a matrix by the given angle around the Z axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateZ(out: mat4, a: mat4, rad: number): mat4; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Translation vector - * @returns {mat4} out - */ - public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.scale(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Scaling vector - * @returns {mat4} out - */ - public static fromScaling(out: mat4, v: vec3 | number[]): mat4 - - /** - * Creates a matrix from a given angle around a given axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotate(dest, dest, rad, axis); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ - public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 - - /** - * Creates a matrix from the given angle around the X axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateX(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromXRotation(out: mat4, rad: number): mat4 - - /** - * Creates a matrix from the given angle around the Y axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateY(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromYRotation(out: mat4, rad: number): mat4 - - - /** - * Creates a matrix from the given angle around the Z axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateZ(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromZRotation(out: mat4, rad: number): mat4 - - /** - * Creates a matrix from a quaternion rotation and vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @returns out - */ - public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; - - /** - * Returns the translation vector component of a transformation - * matrix. If a matrix is built with fromRotationTranslation, - * the returned vector will be the same as the translation vector - * originally supplied. - * @param {vec3} out Vector to receive translation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {vec3} out - */ - public static getTranslation(out: vec3, mat: mat4): vec3; - - /** - * Returns a quaternion representing the rotational component - * of a transformation matrix. If a matrix is built with - * fromRotationTranslation, the returned quaternion will be the - * same as the quaternion originally supplied. - * @param {quat} out Quaternion to receive the rotation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {quat} out - */ - public static getRotation(out: quat, mat: mat4): quat; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @param s Scaling vector - * @returns out - */ - public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * mat4.translate(dest, origin); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * mat4.translate(dest, negativeOrigin); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Rotation quaternion - * @param {vec3} v Translation vector - * @param {vec3} s Scaling vector - * @param {vec3} o The origin vector around which to scale and rotate - * @returns {mat4} out - */ - public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 - - /** - * Calculates a 4x4 matrix from the given quaternion - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Quaternion to create matrix from - * - * @returns {mat4} out - */ - public static fromQuat(out: mat4, q: quat): mat4 - - /** - * Generates a frustum matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static frustum(out: mat4, left: number, right: number, - bottom: number, top: number, near: number, far: number): mat4; - - /** - * Generates a perspective projection matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param fovy Vertical field of view in radians - * @param aspect Aspect ratio. typically viewport width/height - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static perspective(out: mat4, fovy: number, aspect: number, - near: number, far: number): mat4; - - /** - * Generates a perspective projection matrix with the given field of view. - * This is primarily useful for generating projection matrices to be used - * with the still experimental WebVR API. - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ - public static perspectiveFromFieldOfView(out: mat4, - fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, - near: number, far: number): mat4 - - /** - * Generates a orthogonal projection matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static ortho(out: mat4, left: number, right: number, - bottom: number, top: number, near: number, far: number): mat4; - - /** - * Generates a look-at matrix with the given eye position, focal point, and up axis - * - * @param out mat4 frustum matrix will be written into - * @param eye Position of the viewer - * @param center Point the viewer is looking at - * @param up vec3 pointing up - * @returns out - */ - public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; - - /** - * Returns a string representation of a mat4 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(mat: mat4): string; - - /** - * Returns Frobenius norm of a mat4 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat4): number; - - /** - * Adds two mat4's - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static add(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static subtract(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static sub(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat4} out - */ - public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 - - /** - * Adds two mat4's after multiplying each element of the second operand by a scalar value. - * - * @param {mat4} out the receiving vector - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat4} out - */ - public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat4, b: mat4): boolean - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat4, b: mat4): boolean - +declare module 'gl-matrix/src/gl-matrix/mat3' { + import { mat3 } from 'gl-matrix'; + export = mat3; } -// quat -export class quat extends Float32Array { - private typeQuat: number; - - /** - * Creates a new identity quat - * - * @returns a new quaternion - */ - public static create(): quat; - - /** - * Creates a new quat initialized with values from an existing quaternion - * - * @param a quaternion to clone - * @returns a new quaternion - * @function - */ - public static clone(a: quat): quat; - - /** - * Creates a new quat initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns a new quaternion - * @function - */ - public static fromValues(x: number, y: number, z: number, w: number): quat; - - /** - * Copy the values from one quat to another - * - * @param out the receiving quaternion - * @param a the source quaternion - * @returns out - * @function - */ - public static copy(out: quat, a: quat): quat; - - /** - * Set the components of a quat to the given values - * - * @param out the receiving quaternion - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns out - * @function - */ - public static set(out: quat, x: number, y: number, z: number, w: number): quat; - - /** - * Set a quat to the identity quaternion - * - * @param out the receiving quaternion - * @returns out - */ - public static identity(out: quat): quat; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param {quat} out the receiving quaternion. - * @param {vec3} a the initial vector - * @param {vec3} b the destination vector - * @returns {quat} out - */ - public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} view the vector representing the viewing direction - * @param {vec3} right the vector representing the local "right" direction - * @param {vec3} up the vector representing the local "up" direction - * @returns {quat} out - */ - public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat - - - - /** - * Sets a quat from the given angle and rotation axis, - * then returns it. - * - * @param out the receiving quaternion - * @param axis the axis around which to rotate - * @param rad the angle in radians - * @returns out - **/ - public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; - - /** - * Gets the rotation axis and angle for a given - * quaternion. If a quaternion is created with - * setAxisAngle, this method will return the same - * values as providied in the original parameter list - * OR functionally equivalent values. - * Example: The quaternion formed by axis [0, 0, 1] and - * angle -90 is the same as the quaternion formed by - * [0, 0, 1] and 270. This method favors the latter. - * @param {vec3} out_axis Vector receiving the axis of rotation - * @param {quat} q Quaternion to be decomposed - * @return {number} Angle, in radians, of the rotation - */ - public static getAxisAngle (out_axis: vec3 | number[], q: quat): number - - /** - * Adds two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - * @function - */ - public static add(out: quat, a: quat, b: quat): quat; - - /** - * Multiplies two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: quat, a: quat, b: quat): quat; - - /** - * Multiplies two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: quat, a: quat, b: quat): quat; - - /** - * Scales a quat by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - * @function - */ - public static scale(out: quat, a: quat, b: number): quat; - - /** - * Calculates the length of a quat - * - * @param a vector to calculate length of - * @returns length of a - * @function - */ - public static length(a: quat): number; - - /** - * Calculates the length of a quat - * - * @param a vector to calculate length of - * @returns length of a - * @function - */ - public static len(a: quat): number; - - /** - * Calculates the squared length of a quat - * - * @param a vector to calculate squared length of - * @returns squared length of a - * @function - */ - public static squaredLength(a: quat): number; - - /** - * Calculates the squared length of a quat - * - * @param a vector to calculate squared length of - * @returns squared length of a - * @function - */ - public static sqrLen(a: quat): number; - - /** - * Normalize a quat - * - * @param out the receiving quaternion - * @param a quaternion to normalize - * @returns out - * @function - */ - public static normalize(out: quat, a: quat): quat; - - /** - * Calculates the dot product of two quat's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - * @function - */ - public static dot(a: quat, b: quat): number; - - /** - * Performs a linear interpolation between two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - * @function - */ - public static lerp(out: quat, a: quat, b: quat, t: number): quat; - - /** - * Performs a spherical linear interpolation between two quat - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static slerp(out: quat, a: quat, b: quat, t: number): quat; - - /** - * Performs a spherical linear interpolation with two control points - * - * @param {quat} out the receiving quaternion - * @param {quat} a the first operand - * @param {quat} b the second operand - * @param {quat} c the third operand - * @param {quat} d the fourth operand - * @param {number} t interpolation amount - * @returns {quat} out - */ - public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; - - /** - * Calculates the inverse of a quat - * - * @param out the receiving quaternion - * @param a quat to calculate inverse of - * @returns out - */ - public static invert(out: quat, a: quat): quat; - - /** - * Calculates the conjugate of a quat - * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. - * - * @param out the receiving quaternion - * @param a quat to calculate conjugate of - * @returns out - */ - public static conjugate(out: quat, a: quat): quat; - - /** - * Returns a string representation of a quaternion - * - * @param a quat to represent as a string - * @returns string representation of the quat - */ - public static str(a: quat): string; - - /** - * Rotates a quaternion by the given angle about the X axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateX(out: quat, a: quat, rad: number): quat; - - /** - * Rotates a quaternion by the given angle about the Y axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateY(out: quat, a: quat, rad: number): quat; - - /** - * Rotates a quaternion by the given angle about the Z axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateZ(out: quat, a: quat, rad: number): quat; - - /** - * Creates a quaternion from the given 3x3 rotation matrix. - * - * NOTE: The resultant quaternion is not normalized, so you should be sure - * to renormalize the quaternion yourself where necessary. - * - * @param out the receiving quaternion - * @param m rotation matrix - * @returns out - * @function - */ - public static fromMat3(out: quat, m: mat3): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param out the receiving quat - * @param view the vector representing the viewing direction - * @param right the vector representing the local "right" direction - * @param up the vector representing the local "up" direction - * @returns out - */ - public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param out the receiving quaternion. - * @param a the initial vector - * @param b the destination vector - * @returns out - */ - public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; - - /** - * Calculates the W component of a quat from the X, Y, and Z components. - * Assumes that quaternion is 1 unit in length. - * Any existing W component will be ignored. - * - * @param out the receiving quaternion - * @param a quat to calculate W component of - * @returns out - */ - public static calculateW(out: quat, a: quat): quat; - - /** - * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {boolean} True if the quaternions are equal, false otherwise. - */ - public static exactEquals (a: quat, b: quat): boolean; - - /** - * Returns whether or not the quaternions have approximately the same elements in the same position. - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {boolean} True if the quaternions are equal, false otherwise. - */ - public static equals (a: quat, b: quat): boolean; +declare module 'gl-matrix/src/gl-matrix/mat4' { + import { mat4 } from 'gl-matrix'; + export = mat4; +} + +declare module 'gl-matrix/src/gl-matrix/quat' { + import { quat } from 'gl-matrix'; + export = quat; } diff --git a/google-drive-realtime-api/index.d.ts b/google-drive-realtime-api/index.d.ts index b263b30bb9..025ce08a86 100644 --- a/google-drive-realtime-api/index.d.ts +++ b/google-drive-realtime-api/index.d.ts @@ -516,9 +516,91 @@ declare namespace gapi.drive.realtime { } - // INCOMPLETE + // Complete + // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime#.ErrorType + export type ErrorType = + "concurrent_creation" | "invalid_compound_operation" | "invalid_json_syntax" | + "missing_property" | "not_found" | "forbidden" | "server_error" | "client_error" | + "token_refresh_required" | "invalid_element_type" | "no_write_permission" | + "fatal_network_error" | "unexpected_element"; + export var ErrorType : { + // Another user created the document's initial state after + // gapi.drive.realtime.load was called but before the local + // creation was saved. + CONCURRENT_CREATION: ErrorType, + + // A compound operation was still open at the end of a + // synchronous block. Compound operations must always + // be ended in the same synchronous block that they + // are started. + INVALID_COMPOUND_OPERATION: ErrorType, + + // The user tried to decode a brix model that + // contained invalid json. + INVALID_JSON_SYNTAX: ErrorType, + + // The user tried to decode a brix model that was + // missing a neccessary property. + MISSING_PROPERTY: ErrorType, + + // The provided document ID could not be found. + NOT_FOUND: ErrorType, + + // The user associated with the provided OAuth token + // is not authorized to access the provided document + // ID. + FORBIDDEN: ErrorType, + + // An internal error occurred in the Drive Realtime + // API server. + SERVER_ERROR: ErrorType, + + // An internal error occurred in the Drive Realtime API client. + CLIENT_ERROR: ErrorType, + + // The provided OAuth token is no longer valid and + // must be refreshed. + TOKEN_REFRESH_REQUIRED: ErrorType, + + // The provided JSON element does not have the + // expected type. + INVALID_ELEMENT_TYPE: ErrorType, + + // The user does not have permission to edit the + // document. + NO_WRITE_PERMISSION: ErrorType, + + // A network error occurred on a request to the + // Realtime API server for a request which can not be + // retried. The document may no longer be used after + // this error has occurred. This error can only be + // corrected by reloading the document. + FATAL_NETWORK_ERROR: ErrorType, + + // The provided JSON element has the correct JSON type + // but does not have the correct expected Realtime + // type. + UNEXPECTED_ELEMENT: ErrorType, + }; + + // Complete // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.Error - export class Error { } + export class Error { + constructor (type: string, message: string, isFatal: boolean); + + // The type of the error that occurred. + type: ErrorType; + + // A message describing the error. + message: string; + + // Whether the error is fatal. Fatal errors cannot be recovered + // from and require the document to be reloaded. + isFatal: boolean; + + // Returns a string representation of the error object. + toString(): string; + } // Complete // Opens the debugger application on the current page. The debugger shows all realtime documents that the diff --git a/google-libphonenumber/index.d.ts b/google-libphonenumber/index.d.ts index fea36d9675..28f72f67a3 100644 --- a/google-libphonenumber/index.d.ts +++ b/google-libphonenumber/index.d.ts @@ -15,14 +15,26 @@ declare namespace libphonenumber { interface PhoneNumber { } + export module PhoneNumberUtil { + export enum ValidationResult { + IS_POSSIBLE, + INVALID_COUNTRY_CODE, + TOO_SHORT, + TOO_LONG + } + } + export class PhoneNumberUtil { static getInstance(): PhoneNumberUtil parse(number: string, region: string): PhoneNumber; isValidNumber(phoneNumber: PhoneNumber): boolean; - isValidNumberForRegion(phoneNumber: PhoneNumber): boolean; + isPossibleNumber(phoneNumber: PhoneNumber): boolean; + isPossibleNumberWithReason(phoneNumber: PhoneNumber): PhoneNumberUtil.ValidationResult; + isValidNumberForRegion(phoneNumber: PhoneNumber, region: string): boolean; getRegionCodeForNumber(phoneNumber: PhoneNumber): string; isNANPACountry(regionCode: string): boolean; format(phoneNumber: PhoneNumber, format: PhoneNumberFormat): string; + parseAndKeepRawInput(number: string, regionCode: string): PhoneNumber; } export class AsYouTypeFormatter { diff --git a/google.visualization/google.visualization-tests.ts b/google.visualization/google.visualization-tests.ts index 2cbd8220f2..a51657a592 100644 --- a/google.visualization/google.visualization-tests.ts +++ b/google.visualization/google.visualization-tests.ts @@ -156,10 +156,17 @@ function test_areaChart() { ['2016', 1030, 540] ]); - var options = { + var options:google.visualization.AreaChartOptions = { title: 'Company Performance', hAxis: {title: 'Year', titleTextStyle: {color: '#333'}}, - vAxis: {minValue: 0} + vAxis: {minValue: 0}, + annotations: { + textStyle: { + bold: true, + italic: true, + color: "black" + } + } }; var chart = new google.visualization.AreaChart(document.getElementById('chart_div')); @@ -510,3 +517,107 @@ function test_ChartsLoad() { google.charts.setOnLoadCallback(drawChart); } + + +function test_ChartAnnotations() { + var annotations:google.visualization.ChartAnnotations = { + boxStyle: { + // Color of the box outline. + stroke: '#888', + // Thickness of the box outline. + strokeWidth: 1, + // x-radius of the corner curvature. + rx: 10, + // y-radius of the corner curvature. + ry: 10, + // Attributes for linear gradient fill. + gradient: { + // Start color for gradient. + color1: '#fbf6a7', + // Finish color for gradient. + color2: '#33b679', + // Where on the boundary to start and + // end the color1/color2 gradient, + // relative to the upper left corner + // of the boundary. + x1: '0%', y1: '0%', + x2: '100%', y2: '100%', + // If true, the boundary for x1, + // y1, x2, and y2 is the box. If + // false, it's the entire chart. + useObjectBoundingBoxUnits: true + } + }, + datum: { + stem: { + color: 'black', + length: 12 + }, + style: 'point' + }, + domain: { + stem: { + color: 'black', + length: 5 + }, + style: 'point' + }, + highContrast: true, + stem: { + color: 'black', + length: 5 + }, + style: 'line', + textStyle: { + fontName: 'Times-Roman', + fontSize: 18, + bold: true, + italic: true, + // The color of the text. + color: '#871b47', + // The color of the text outline. + auraColor: '#d799ae', + // The transparency of the text. + opacity: 0.8 + } + }; + + var barAnnotations:google.visualization.ChartBarColumnAnnotations = { + alwaysOutside: true, + textStyle: { + fontName: 'Times-Roman', + fontSize: 18, + bold: true + } + }; +} + + +function test_OrgChart() { + var data = new google.visualization.DataTable(); + data.addColumn('string', 'Name'); + data.addColumn('string', 'Manager'); + data.addColumn('string', 'ToolTip'); + + // For each orgchart box, provide the name, manager, and tooltip to show. + data.addRows([ + [{v:'Mike', f:'Mike
President
'}, '', 'The President'], + [{v:'Jim', f:'Jim
Vice President
'}, 'Mike', 'VP'], + ['Alice', 'Mike', ''], + ['Bob', 'Jim', 'Bob Sponge'], + ['Carol', 'Bob', ''] + ]); + + var chart = new google.visualization.OrgChart(document.getElementById('chart_div')); + chart.draw(data, { + allowCollapse: true, + allowHtml: true, + nodeClass: 'node', + selectedNodeClass: 'selected', + size: 'small' + }); + chart.collapse(1, true); + var children = chart.getChildrenIndexes(0); + var collapsed = chart.getCollapsedNodes(); + +} diff --git a/google.visualization/index.d.ts b/google.visualization/index.d.ts index a4dc1b7b1a..83b08296f8 100644 --- a/google.visualization/index.d.ts +++ b/google.visualization/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Visualisation Apis // Project: https://developers.google.com/chart/ -// Definitions by: Dan Ludwig , Gregory Moore +// Definitions by: Dan Ludwig , Gregory Moore , Dan Manastireanu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace google { @@ -331,6 +331,25 @@ declare namespace google { export interface ChartAnnotations { boxStyle?: ChartBoxStyle; textStyle?: ChartTextStyle; + datum?: ChartStemAndStyle; + domain?: ChartStemAndStyle; + highContrast?: boolean; + stem?: ChartStem; + style?: string; // 'line' or 'point' + } + + export interface ChartBarColumnAnnotations extends ChartAnnotations { + alwaysOutside?: boolean; + } + + export interface ChartStemAndStyle { + stem?: ChartStem; + style?: string; + } + + export interface ChartStem { + color?: string; + length?: number; } export interface ChartBoxStyle { @@ -565,7 +584,7 @@ declare namespace google { export interface ColumnChartOptions { aggregationTarget?: string; animation?: TransitionAnimation; - annotations?: ChartAnnotations; + annotations?: ChartBarColumnAnnotations; axisTitlesPosition?: string; // in, out, none backgroundColor?: any; bar?: GroupWidth; @@ -645,7 +664,7 @@ declare namespace google { export interface BarChartOptions { aggregationTarget?: string; animation?: TransitionAnimation; - annotations?: ChartAnnotations; + annotations?: ChartBarColumnAnnotations; axisTitlesPosition?: string; // in, out, none backgroundColor?: any; bar?: GroupWidth; @@ -739,6 +758,7 @@ declare namespace google { export interface AreaChartOptions { aggregationTarget?: string; animation?: TransitionAnimation; + annotations?: ChartAnnotations; areaOpacity?: number; axisTitlesPosition?: string; backgroundColor?: any; @@ -1357,6 +1377,34 @@ declare namespace google { format(dataTable: DataTable, srcColumnIndices: number[], opt_dstColumnIndex?: number): void; } + //#endregion + //#region OrgChart + + // https://google-developers.appspot.com/chart/interactive/docs/gallery/orgchart + export class OrgChart extends CoreChartBase { + draw(data: DataTable, options: OrgChartOptions): void; + draw(data: DataView, options: OrgChartOptions): void; + collapse(row: number, collapsed: boolean): void; + getChildrenIndexes(row: number): number[]; + getCollapsedNodes(): number[]; + } + + // https://google-developers.appspot.com/chart/interactive/docs/gallery/orgchart#Configuration_Options + export interface OrgChartOptions { + allowCollapse?: boolean; + allowHtml?: boolean; + color?: string; + nodeClass?: string; + selectedNodeClass?: string; + selectionColor?: string; + /** + * Chart size + * @type {('small'|'medium'|'large')} + * @default 'medium' + */ + size?: string; + } + //#endregion } } diff --git a/googlemaps/index.d.ts b/googlemaps/index.d.ts index 2b56c2e836..c4168645a6 100644 --- a/googlemaps/index.d.ts +++ b/googlemaps/index.d.ts @@ -1797,6 +1797,8 @@ declare namespace google.maps { toString(): string; /** Returns a string of the form "lat,lng". We round the lat/lng values to 6 decimal places by default. */ toUrlValue(precision?: number): string; + /** Converts to JSON representation. This function is intended to be used via JSON.stringify. */ + toJSON(): LatLngLiteral; } export type LatLngLiteral = { lat: number; lng: number } diff --git a/graphql/index.d.ts b/graphql/index.d.ts index b441fbc204..43ca0fdc36 100644 --- a/graphql/index.d.ts +++ b/graphql/index.d.ts @@ -1,11 +1,11 @@ -// Type definitions for graphql v0.7.0 +// Type definitions for graphql v0.8.2 // Project: https://www.npmjs.com/package/graphql -// Definitions by: TonyYang +// Definitions by: TonyYang , Caleb Meredith , Dominic Watson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************* - * * - * MODULES * + * * + * MODULES * * * *************************************/ /////////////////////////// @@ -19,103 +19,26 @@ declare module "graphql" { // Create and operate on GraphQL type definitions and schema. - export { - GraphQLSchema, - - // Definitions - GraphQLScalarType, - GraphQLObjectType, - GraphQLInterfaceType, - GraphQLUnionType, - GraphQLEnumType, - GraphQLInputObjectType, - GraphQLList, - GraphQLNonNull, - GraphQLDirective, - - // "Enum" of Type Kinds - TypeKind, - - // "Enum" of Directive Locations - DirectiveLocation, - - // Scalars - GraphQLInt, - GraphQLFloat, - GraphQLString, - GraphQLBoolean, - GraphQLID, - - // Built-in Directives defined by the Spec - specifiedDirectives, - GraphQLIncludeDirective, - GraphQLSkipDirective, - GraphQLDeprecatedDirective, - - // Constant Deprecation Reason - DEFAULT_DEPRECATION_REASON, - - // Meta-field definitions. - SchemaMetaFieldDef, - TypeMetaFieldDef, - TypeNameMetaFieldDef, - - // GraphQL Types for introspection. - __Schema, - __Directive, - __DirectiveLocation, - __Type, - __Field, - __InputValue, - __EnumValue, - __TypeKind, - - // Predicates - isType, - isInputType, - isOutputType, - isLeafType, - isCompositeType, - isAbstractType, - - // Un-modifiers - getNullableType, - getNamedType, - } from 'graphql/type'; + export * from 'graphql/type'; // Parse and operate on GraphQL language source files. - export { - Source, - getLocation, - - // Parse - parse, - parseValue, - parseType, - - // Print - print, - - // Visit - visit, - visitInParallel, - visitWithTypeInfo, - Kind, - TokenKind, - BREAK, - } from 'graphql/language'; + export * from 'graphql/language'; // Execute GraphQL queries. export { execute, + defaultFieldResolver, + responsePathAsArray, + ExecutionResult, } from 'graphql/execution'; // Validate GraphQL queries. export { validate, + ValidationContext, specifiedRules, } from 'graphql/validation'; @@ -124,11 +47,12 @@ declare module "graphql" { export { GraphQLError, formatError, + GraphQLFormattedError, + GraphQLErrorLocation, } from 'graphql/error'; // Utilities for operating on GraphQL type schema and parsed sources. - /* export { // The GraphQL query recommended for a full schema introspection. introspectionQuery, @@ -152,6 +76,9 @@ declare module "graphql" { // Print a GraphQLSchema to GraphQL Schema language. printSchema, + // Print a GraphQLType to GraphQL Schema language. + printType, + // Create a GraphQLType from a GraphQL language AST. typeFromAST, @@ -184,13 +111,32 @@ declare module "graphql" { // Asserts a string is a valid GraphQL name. assertValidName, + + BreakingChange, + + IntrospectionDirective, + IntrospectionEnumType, + IntrospectionEnumValue, + IntrospectionField, + IntrospectionInputObjectType, + IntrospectionInputValue, + IntrospectionInterfaceType, + IntrospectionListTypeRef, + IntrospectionNamedTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionObjectType, + IntrospectionQuery, + IntrospectionScalarType, + IntrospectionSchema, + IntrospectionType, + IntrospectionTypeRef, + IntrospectionUnionType, } from 'graphql/utilities'; - */ } declare module "graphql/graphql" { - import { GraphQLError } from 'graphql/error/GraphQLError'; import { GraphQLSchema } from 'graphql/type/schema'; + import { ExecutionResult } from 'graphql/execution/execute'; /** * This is the primary entry point function for fulfilling GraphQL operations @@ -225,18 +171,7 @@ declare module "graphql/graphql" { [key: string]: any }, operationName?: string - ): Promise; - - /** - * The result of a GraphQL parse, validation and execution. - * - * `data` is the result of a successful execution of the query. - * `errors` is included when any errors occurred as a non-empty array. - */ - type GraphQLResult = { - data?: Object; - errors?: Array; - } + ): Promise; } /////////////////////////// @@ -256,11 +191,12 @@ declare module "graphql/language" { } declare module "graphql/language/index" { + export * from 'graphql/language/ast'; export { getLocation } from 'graphql/language/location'; import * as Kind from 'graphql/language/kinds'; export { Kind }; - export { createLexer, TokenKind } from 'graphql/language/lexer'; - export { parse, parseValue, parseType } from 'graphql/language/parser'; + export { createLexer, TokenKind, Lexer } from 'graphql/language/lexer'; + export { parse, parseValue, parseType, ParseOptions } from 'graphql/language/parser'; export { print } from 'graphql/language/printer'; export { Source } from 'graphql/language/source'; export { visit, visitInParallel, visitWithTypeInfo, BREAK } from 'graphql/language/visitor'; @@ -273,7 +209,7 @@ declare module "graphql/language/ast" { * Contains a range of UTF-8 character offsets and token references that * identify the region of the source from which the AST derived. */ - type Location = { + export type Location = { /** * The character offset at which this Node begins. @@ -305,7 +241,7 @@ declare module "graphql/language/ast" { * Represents a range of characters represented by a lexical token * within a Source. */ - type Token = { + export type Token = { /** * The kind of Token. @@ -368,46 +304,46 @@ declare module "graphql/language/ast" { /** * The list of all possible AST node types. */ - type Node = Name - | Document - | OperationDefinition - | VariableDefinition - | Variable - | SelectionSet - | Field - | Argument - | FragmentSpread - | InlineFragment - | FragmentDefinition - | IntValue - | FloatValue - | StringValue - | BooleanValue - | EnumValue - | ListValue - | ObjectValue - | ObjectField - | Directive - | NamedType - | ListType - | NonNullType - | SchemaDefinition - | OperationTypeDefinition - | ScalarTypeDefinition - | ObjectTypeDefinition - | FieldDefinition - | InputValueDefinition - | InterfaceTypeDefinition - | UnionTypeDefinition - | EnumTypeDefinition - | EnumValueDefinition - | InputObjectTypeDefinition - | TypeExtensionDefinition - | DirectiveDefinition + export type ASTNode = NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | TypeExtensionDefinitionNode + | DirectiveDefinitionNode; // Name - type Name = { + export type NameNode = { kind: 'Name'; loc?: Location; value: string; @@ -415,306 +351,306 @@ declare module "graphql/language/ast" { // Document - type Document = { + export type DocumentNode = { kind: 'Document'; loc?: Location; - definitions: Array; + definitions: Array; } - type Definition = OperationDefinition - | FragmentDefinition - | TypeSystemDefinition // experimental non-spec addition. + export type DefinitionNode = OperationDefinitionNode + | FragmentDefinitionNode + | TypeSystemDefinitionNode // experimental non-spec addition. - type OperationDefinition = { + export type OperationDefinitionNode = { kind: 'OperationDefinition'; loc?: Location; - operation: OperationType; - name?: Name; - variableDefinitions?: Array; - directives?: Array; - selectionSet: SelectionSet; + operation: OperationTypeNode; + name?: NameNode; + variableDefinitions?: Array; + directives?: Array; + selectionSet: SelectionSetNode; } // Note: subscription is an experimental non-spec addition. - type OperationType = 'query' | 'mutation' | 'subscription'; + export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; - type VariableDefinition = { + export type VariableDefinitionNode = { kind: 'VariableDefinition'; loc?: Location; - variable: Variable; - type: Type; - defaultValue?: Value; + variable: VariableNode; + type: TypeNode; + defaultValue?: ValueNode; } - type Variable = { + export type VariableNode = { kind: 'Variable'; loc?: Location; - name: Name; + name: NameNode; } - type SelectionSet = { + export type SelectionSetNode = { kind: 'SelectionSet'; loc?: Location; - selections: Array; + selections: Array; } - type Selection = Field - | FragmentSpread - | InlineFragment + export type SelectionNode = FieldNode + | FragmentSpreadNode + | InlineFragmentNode - type Field = { + export type FieldNode = { kind: 'Field'; loc?: Location; - alias?: Name; - name: Name; - arguments?: Array; - directives?: Array; - selectionSet?: SelectionSet; + alias?: NameNode; + name: NameNode; + arguments?: Array; + directives?: Array; + selectionSet?: SelectionSetNode; } - type Argument = { + export type ArgumentNode = { kind: 'Argument'; loc?: Location; - name: Name; - value: Value; + name: NameNode; + value: ValueNode; } // Fragments - type FragmentSpread = { + export type FragmentSpreadNode = { kind: 'FragmentSpread'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - type InlineFragment = { + export type InlineFragmentNode = { kind: 'InlineFragment'; loc?: Location; - typeCondition?: NamedType; - directives?: Array; - selectionSet: SelectionSet; + typeCondition?: NamedTypeNode; + directives?: Array; + selectionSet: SelectionSetNode; } - type FragmentDefinition = { + export type FragmentDefinitionNode = { kind: 'FragmentDefinition'; loc?: Location; - name: Name; - typeCondition: NamedType; - directives?: Array; - selectionSet: SelectionSet; + name: NameNode; + typeCondition: NamedTypeNode; + directives?: Array; + selectionSet: SelectionSetNode; } // Values - type Value = Variable - | IntValue - | FloatValue - | StringValue - | BooleanValue - | EnumValue - | ListValue - | ObjectValue + export type ValueNode = VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode - type IntValue = { + export type IntValueNode = { kind: 'IntValue'; loc?: Location; value: string; } - type FloatValue = { + export type FloatValueNode = { kind: 'FloatValue'; loc?: Location; value: string; } - type StringValue = { + export type StringValueNode = { kind: 'StringValue'; loc?: Location; value: string; } - type BooleanValue = { + export type BooleanValueNode = { kind: 'BooleanValue'; loc?: Location; value: boolean; } - type EnumValue = { + export type EnumValueNode = { kind: 'EnumValue'; loc?: Location; value: string; } - type ListValue = { + export type ListValueNode = { kind: 'ListValue'; loc?: Location; - values: Array; + values: Array; } - type ObjectValue = { + export type ObjectValueNode = { kind: 'ObjectValue'; loc?: Location; - fields: Array; + fields: Array; } - type ObjectField = { + export type ObjectFieldNode = { kind: 'ObjectField'; loc?: Location; - name: Name; - value: Value; + name: NameNode; + value: ValueNode; } // Directives - type Directive = { + export type DirectiveNode = { kind: 'Directive'; loc?: Location; - name: Name; - arguments?: Array; + name: NameNode; + arguments?: Array; } // Type Reference - type Type = NamedType - | ListType - | NonNullType + export type TypeNode = NamedTypeNode + | ListTypeNode + | NonNullTypeNode - type NamedType = { + export type NamedTypeNode = { kind: 'NamedType'; loc?: Location; - name: Name; + name: NameNode; }; - type ListType = { + export type ListTypeNode = { kind: 'ListType'; loc?: Location; - type: Type; + type: TypeNode; } - type NonNullType = { + export type NonNullTypeNode = { kind: 'NonNullType'; loc?: Location; - type: NamedType | ListType; + type: NamedTypeNode | ListTypeNode; } // Type System Definition - type TypeSystemDefinition = SchemaDefinition - | TypeDefinition - | TypeExtensionDefinition - | DirectiveDefinition + export type TypeSystemDefinitionNode = SchemaDefinitionNode + | TypeDefinitionNode + | TypeExtensionDefinitionNode + | DirectiveDefinitionNode - type SchemaDefinition = { + export type SchemaDefinitionNode = { kind: 'SchemaDefinition'; loc?: Location; - directives: Array; - operationTypes: Array; + directives: Array; + operationTypes: Array; } - type OperationTypeDefinition = { + export type OperationTypeDefinitionNode = { kind: 'OperationTypeDefinition'; loc?: Location; - operation: OperationType; - type: NamedType; + operation: OperationTypeNode; + type: NamedTypeNode; } - type TypeDefinition = ScalarTypeDefinition - | ObjectTypeDefinition - | InterfaceTypeDefinition - | UnionTypeDefinition - | EnumTypeDefinition - | InputObjectTypeDefinition + export type TypeDefinitionNode = ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode - type ScalarTypeDefinition = { + export type ScalarTypeDefinitionNode = { kind: 'ScalarTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - type ObjectTypeDefinition = { + export type ObjectTypeDefinitionNode = { kind: 'ObjectTypeDefinition'; loc?: Location; - name: Name; - interfaces?: Array; - directives?: Array; - fields: Array; + name: NameNode; + interfaces?: Array; + directives?: Array; + fields: Array; } - type FieldDefinition = { + export type FieldDefinitionNode = { kind: 'FieldDefinition'; loc?: Location; - name: Name; - arguments: Array; - type: Type; - directives?: Array; + name: NameNode; + arguments: Array; + type: TypeNode; + directives?: Array; } - type InputValueDefinition = { + export type InputValueDefinitionNode = { kind: 'InputValueDefinition'; loc?: Location; - name: Name; - type: Type; - defaultValue?: Value; - directives?: Array; + name: NameNode; + type: TypeNode; + defaultValue?: ValueNode; + directives?: Array; } - type InterfaceTypeDefinition = { + export type InterfaceTypeDefinitionNode = { kind: 'InterfaceTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - fields: Array; + name: NameNode; + directives?: Array; + fields: Array; } - type UnionTypeDefinition = { + export type UnionTypeDefinitionNode = { kind: 'UnionTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - types: Array; + name: NameNode; + directives?: Array; + types: Array; } - type EnumTypeDefinition = { + export type EnumTypeDefinitionNode = { kind: 'EnumTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - values: Array; + name: NameNode; + directives?: Array; + values: Array; } - type EnumValueDefinition = { + export type EnumValueDefinitionNode = { kind: 'EnumValueDefinition'; loc?: Location; - name: Name; - directives?: Array; + name: NameNode; + directives?: Array; } - type InputObjectTypeDefinition = { + export type InputObjectTypeDefinitionNode = { kind: 'InputObjectTypeDefinition'; loc?: Location; - name: Name; - directives?: Array; - fields: Array; + name: NameNode; + directives?: Array; + fields: Array; } - type TypeExtensionDefinition = { + export type TypeExtensionDefinitionNode = { kind: 'TypeExtensionDefinition'; loc?: Location; - definition: ObjectTypeDefinition; + definition: ObjectTypeDefinitionNode; } - type DirectiveDefinition = { + export type DirectiveDefinitionNode = { kind: 'DirectiveDefinition'; loc?: Location; - name: Name; - arguments?: Array; - locations: Array; + name: NameNode; + arguments?: Array; + locations: Array; } } @@ -746,6 +682,7 @@ declare module "graphql/language/kinds" { const FLOAT: 'FloatValue'; const STRING: 'StringValue'; const BOOLEAN: 'BooleanValue'; + const NULL: 'NullValue'; const ENUM: 'EnumValue'; const LIST: 'ListValue'; const OBJECT: 'ObjectValue'; @@ -883,7 +820,7 @@ declare module "graphql/language/location" { } declare module "graphql/language/parser" { - import { NamedType, Type, Value, Document } from "graphql/language/ast"; + import { NamedTypeNode, TypeNode, ValueNode, DocumentNode } from "graphql/language/ast"; import { Source } from "graphql/language/source"; import { Lexer } from "graphql/language/lexer"; @@ -906,7 +843,7 @@ declare module "graphql/language/parser" { function parse( source: string | Source, options?: ParseOptions - ): Document; + ): DocumentNode; /** * Given a string containing a GraphQL value, parse the AST for that value. @@ -918,9 +855,9 @@ declare module "graphql/language/parser" { function parseValue( source: Source | string, options?: ParseOptions - ): Value; + ): ValueNode; - function parseConstValue(lexer: Lexer): Value; + function parseConstValue(lexer: Lexer): ValueNode; /** * Type : @@ -928,12 +865,20 @@ declare module "graphql/language/parser" { * - ListType * - NonNullType */ - function parseType(lexer: Lexer): Type; + function parseType(lexer: Lexer): TypeNode; + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + function parseTypeReference(lexer: Lexer): TypeNode; /** * NamedType : Name */ - function parseNamedType(lexer: Lexer): NamedType; + function parseNamedType(lexer: Lexer): NamedTypeNode; } declare module "graphql/language/printer" { @@ -971,6 +916,7 @@ declare module "graphql/language/visitor" { FloatValue: number[]; StringValue: string[]; BooleanValue: boolean[]; + NullValue: null[], EnumValue: any[]; ListValue: string[]; ObjectValue: string[]; @@ -1014,29 +960,7 @@ declare module "graphql/type/index" { // GraphQL Schema definition export { GraphQLSchema } from 'graphql/type/schema'; - export { - // Predicates - isType, - isInputType, - isOutputType, - isLeafType, - isCompositeType, - isAbstractType, - - // Un-modifiers - getNullableType, - getNamedType, - - // Definitions - GraphQLScalarType, - GraphQLObjectType, - GraphQLInterfaceType, - GraphQLUnionType, - GraphQLEnumType, - GraphQLInputObjectType, - GraphQLList, - GraphQLNonNull, - } from 'graphql/type/definition'; + export * from 'graphql/type/definition'; export { // "Enum" of Directive Locations @@ -1084,21 +1008,22 @@ declare module "graphql/type/index" { TypeNameMetaFieldDef, } from 'graphql/type/introspection'; + export { DirectiveLocationEnum } from 'graphql/type/directives'; } declare module "graphql/type/definition" { import { - OperationDefinition, - Field, - FragmentDefinition, - Value, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, } from 'graphql/language/ast'; import { GraphQLSchema } from 'graphql/type/schema'; /** * These are all of the possible kinds of types. */ - type GraphQLType = + export type GraphQLType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | @@ -1108,12 +1033,14 @@ declare module "graphql/type/definition" { GraphQLList | GraphQLNonNull; - function isType(type: any): boolean; + export function isType(type: any): type is GraphQLType; + + export function assertType(type: any): GraphQLType; /** * These types may be used as input types for arguments and directives. */ - type GraphQLInputType = + export type GraphQLInputType = GraphQLScalarType | GraphQLEnumType | GraphQLInputObjectType | @@ -1125,12 +1052,14 @@ declare module "graphql/type/definition" { GraphQLList >; - function isInputType(type: GraphQLType): boolean; + export function isInputType(type: GraphQLType): type is GraphQLInputType; + + export function assertInputType(type: GraphQLType): GraphQLInputType; /** * These types may be used as output types as the result of fields. */ - type GraphQLOutputType = + export type GraphQLOutputType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | @@ -1146,40 +1075,48 @@ declare module "graphql/type/definition" { GraphQLList >; - function isOutputType(type: GraphQLType): boolean; + export function isOutputType(type: GraphQLType): type is GraphQLOutputType; + + export function assertOutputType(type: GraphQLType): GraphQLOutputType; /** * These types may describe types which may be leaf values. */ - type GraphQLLeafType = + export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; - function isLeafType(type: GraphQLType): boolean; + export function isLeafType(type: GraphQLType): type is GraphQLLeafType; + + export function assertLeafType(type: GraphQLType): GraphQLLeafType; /** * These types may describe the parent context of a selection set. */ - type GraphQLCompositeType = + export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType; - function isCompositeType(type: GraphQLType): boolean; + export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; + + export function assertCompositeType(type: GraphQLType): GraphQLCompositeType; /** * These types may describe the parent context of a selection set. */ - type GraphQLAbstractType = + export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; - function isAbstractType(type: GraphQLType): boolean; + export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; + + export function assertAbstractType(type: GraphQLType): GraphQLAbstractType; /** * These types can all accept null as a value. */ - type GraphQLNullableType = + export type GraphQLNullableType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | @@ -1188,14 +1125,14 @@ declare module "graphql/type/definition" { GraphQLInputObjectType | GraphQLList; - function getNullableType( + export function getNullableType( type: T ): (T & GraphQLNullableType); /** * These named types do not include modifiers like List or NonNull. */ - type GraphQLNamedType = + export type GraphQLNamedType = GraphQLScalarType | GraphQLObjectType | GraphQLInterfaceType | @@ -1203,7 +1140,7 @@ declare module "graphql/type/definition" { GraphQLEnumType | GraphQLInputObjectType; - function getNamedType(type: GraphQLType): GraphQLNamedType + export function getNamedType(type: GraphQLType): GraphQLNamedType /** * Used while defining GraphQL types to allow for circular references in @@ -1240,17 +1177,17 @@ declare module "graphql/type/definition" { parseValue(value: any): any; // Parses an externally provided literal value to use as an input. - parseLiteral(valueAST: Value): any; + parseLiteral(valueNode: ValueNode): any; toString(): string; } - interface GraphQLScalarTypeConfig { + export interface GraphQLScalarTypeConfig { name: string; description?: string; serialize: (value: any) => TInternal; parseValue?: (value: any) => TExternal; - parseLiteral?: (valueAST: Value) => TInternal; + parseLiteral?: (valueNode: ValueNode) => TInternal; } /** @@ -1293,97 +1230,99 @@ declare module "graphql/type/definition" { class GraphQLObjectType { name: string; description: string; - isTypeOf: GraphQLIsTypeOfFn; + isTypeOf: GraphQLIsTypeOfFn; - constructor(config: GraphQLObjectTypeConfig); - getFields(): GraphQLFieldDefinitionMap; + constructor(config: GraphQLObjectTypeConfig); + getFields(): GraphQLFieldMap; getInterfaces(): Array; toString(): string; } // - interface GraphQLObjectTypeConfig { + export interface GraphQLObjectTypeConfig { name: string; interfaces?: Thunk>; - fields: Thunk>; - isTypeOf?: GraphQLIsTypeOfFn; + fields: Thunk>; + isTypeOf?: GraphQLIsTypeOfFn; description?: string } - type GraphQLTypeResolveFn = ( - value: any, - context: any, + export type GraphQLTypeResolver = ( + value: TSource, + context: TContext, info: GraphQLResolveInfo ) => GraphQLObjectType; - type GraphQLIsTypeOfFn = ( - source: any, - context: any, + export type GraphQLIsTypeOfFn = ( + source: TSource, + context: TContext, info: GraphQLResolveInfo ) => boolean; - type GraphQLFieldResolveFn = ( + export type GraphQLFieldResolver = ( source: TSource, args: { [argName: string]: any }, - context: any, + context: TContext, info: GraphQLResolveInfo ) => any; - interface GraphQLResolveInfo { + export interface GraphQLResolveInfo { fieldName: string; - fieldASTs: Array; + fieldNodes: Array; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; - path: Array; + path: ResponsePath; schema: GraphQLSchema; - fragments: { [fragmentName: string]: FragmentDefinition }; + fragments: { [fragmentName: string]: FragmentDefinitionNode }; rootValue: any; - operation: OperationDefinition; + operation: OperationDefinitionNode; variableValues: { [variableName: string]: any }; } - interface GraphQLFieldConfig { + export type ResponsePath = { prev: ResponsePath, key: string | number } | void; + + export interface GraphQLFieldConfig { type: GraphQLOutputType; args?: GraphQLFieldConfigArgumentMap; - resolve?: GraphQLFieldResolveFn; + resolve?: GraphQLFieldResolver; deprecationReason?: string; description?: string; } - interface GraphQLFieldConfigArgumentMap { + export interface GraphQLFieldConfigArgumentMap { [argName: string]: GraphQLArgumentConfig; } - interface GraphQLArgumentConfig { + export interface GraphQLArgumentConfig { type: GraphQLInputType; defaultValue?: any; description?: string; } - interface GraphQLFieldConfigMap { - [fieldName: string]: GraphQLFieldConfig; + export interface GraphQLFieldConfigMap { + [fieldName: string]: GraphQLFieldConfig; } - interface GraphQLFieldDefinition { + export interface GraphQLField { name: string; description: string; type: GraphQLOutputType; args: Array; - resolve: GraphQLFieldResolveFn; - isDeprecated: boolean; - deprecationReason: string; + resolve?: GraphQLFieldResolver; + isDeprecated?: boolean; + deprecationReason?: string; } - interface GraphQLArgument { + export interface GraphQLArgument { name: string; type: GraphQLInputType; defaultValue?: any; description?: string; } - interface GraphQLFieldDefinitionMap { - [fieldName: string]: GraphQLFieldDefinition; + export interface GraphQLFieldMap { + [fieldName: string]: GraphQLField; } /** @@ -1407,24 +1346,24 @@ declare module "graphql/type/definition" { class GraphQLInterfaceType { name: string; description: string; - resolveType: GraphQLTypeResolveFn; + resolveType: GraphQLTypeResolver; - constructor(config: GraphQLInterfaceTypeConfig); + constructor(config: GraphQLInterfaceTypeConfig); - getFields(): GraphQLFieldDefinitionMap; + getFields(): GraphQLFieldMap; toString(): string; } - interface GraphQLInterfaceTypeConfig { + export interface GraphQLInterfaceTypeConfig { name: string, - fields: Thunk>, + fields: Thunk>, /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolveFn, + resolveType?: GraphQLTypeResolver, description?: string } @@ -1454,16 +1393,16 @@ declare module "graphql/type/definition" { class GraphQLUnionType { name: string; description: string; - resolveType: GraphQLTypeResolveFn; + resolveType: GraphQLTypeResolver; - constructor(config: GraphQLUnionTypeConfig); + constructor(config: GraphQLUnionTypeConfig); getTypes(): Array; toString(): string; } - interface GraphQLUnionTypeConfig { + export interface GraphQLUnionTypeConfig { name: string, types: Thunk>, /** @@ -1471,7 +1410,7 @@ declare module "graphql/type/definition" { * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolveFn; + resolveType?: GraphQLTypeResolver; description?: string; } @@ -1501,30 +1440,30 @@ declare module "graphql/type/definition" { description: string; constructor(config: GraphQLEnumTypeConfig); - getValues(): Array; + getValues(): Array; serialize(value: any): string; parseValue(value: any): any; - parseLiteral(valueAST: Value): any; + parseLiteral(valueNode: ValueNode): any; toString(): string; } - interface GraphQLEnumTypeConfig { + export interface GraphQLEnumTypeConfig { name: string; values: GraphQLEnumValueConfigMap; description?: string; } - interface GraphQLEnumValueConfigMap { + export interface GraphQLEnumValueConfigMap { [valueName: string]: GraphQLEnumValueConfig; } - interface GraphQLEnumValueConfig { + export interface GraphQLEnumValueConfig { value?: any; deprecationReason?: string; description?: string; } - interface GraphQLEnumValueDefinition { + export interface GraphQLEnumValue { name: string; description: string; deprecationReason: string; @@ -1554,36 +1493,36 @@ declare module "graphql/type/definition" { class GraphQLInputObjectType { name: string; description: string; - constructor(config: InputObjectConfig); - getFields(): InputObjectFieldMap; + constructor(config: GraphQLInputObjectTypeConfig); + getFields(): GraphQLInputFieldMap; toString(): string; } - interface InputObjectConfig { + export interface GraphQLInputObjectTypeConfig { name: string; - fields: Thunk; + fields: Thunk; description?: string; } - interface InputObjectFieldConfig { + export interface GraphQLInputFieldConfig { type: GraphQLInputType; defaultValue?: any; description?: string; } - interface InputObjectConfigFieldMap { - [fieldName: string]: InputObjectFieldConfig; + export interface GraphQLInputFieldConfigMap { + [fieldName: string]: GraphQLInputFieldConfig; } - interface InputObjectField { + export interface GraphQLInputField { name: string; type: GraphQLInputType; defaultValue?: any; description?: string; } - interface InputObjectFieldMap { - [fieldName: string]: InputObjectField; + export interface GraphQLInputFieldMap { + [fieldName: string]: GraphQLInputField; } /** @@ -1727,7 +1666,7 @@ declare module "graphql/type/introspection" { GraphQLList, GraphQLNonNull, } from 'graphql/type/definition'; - import { GraphQLFieldDefinition } from 'graphql/type/definition'; + import { GraphQLField } from 'graphql/type/definition'; const __Schema: GraphQLObjectType; const __Directive: GraphQLObjectType; @@ -1751,12 +1690,12 @@ declare module "graphql/type/introspection" { const __TypeKind: GraphQLEnumType; /** - * Note that these are GraphQLFieldDefinition and not GraphQLFieldConfig, + * Note that these are GraphQLField and not GraphQLFieldConfig, * so the format for args is different. */ - const SchemaMetaFieldDef: GraphQLFieldDefinition; - const TypeMetaFieldDef: GraphQLFieldDefinition; - const TypeNameMetaFieldDef: GraphQLFieldDefinition; + const SchemaMetaFieldDef: GraphQLField; + const TypeMetaFieldDef: GraphQLField; + const TypeNameMetaFieldDef: GraphQLField; } declare module "graphql/type/scalars" { @@ -1852,7 +1791,7 @@ declare module "graphql/validation" { } declare module "graphql/validation/index" { - export { validate } from 'graphql/validation/validate'; + export { validate, ValidationContext } from 'graphql/validation/validate'; export { specifiedRules } from 'graphql/validation/specifiedRules'; } @@ -1869,19 +1808,19 @@ declare module "graphql/validation/specifiedRules" { declare module "graphql/validation/validate" { import { GraphQLError } from 'graphql/error'; import { - Document, - OperationDefinition, - Variable, - SelectionSet, - FragmentSpread, - FragmentDefinition, + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, } from 'graphql/language/ast'; import { GraphQLSchema } from 'graphql/type/schema'; import { GraphQLInputType, GraphQLOutputType, GraphQLCompositeType, - GraphQLFieldDefinition, + GraphQLField, GraphQLArgument } from 'graphql/type/definition'; import { GraphQLDirective } from 'graphql/type/directives'; @@ -1905,7 +1844,7 @@ declare module "graphql/validation/validate" { */ function validate( schema: GraphQLSchema, - ast: Document, + ast: DocumentNode, rules?: Array ): Array; @@ -1918,13 +1857,13 @@ declare module "graphql/validation/validate" { function visitUsingRules( schema: GraphQLSchema, typeInfo: TypeInfo, - documentAST: Document, + documentAST: DocumentNode, rules: Array ): Array; - type HasSelectionSet = OperationDefinition | FragmentDefinition; + type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; interface VariableUsage { - node: Variable, + node: VariableNode, type: GraphQLInputType } @@ -1934,27 +1873,27 @@ declare module "graphql/validation/validate" { * validation rule. */ export class ValidationContext { - constructor(schema: GraphQLSchema, ast: Document, typeInfo: TypeInfo); + constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); reportError(error: GraphQLError): void; getErrors(): Array; getSchema(): GraphQLSchema; - getDocument(): Document; + getDocument(): DocumentNode; - getFragment(name: string): FragmentDefinition; + getFragment(name: string): FragmentDefinitionNode; - getFragmentSpreads(node: SelectionSet): Array; + getFragmentSpreads(node: SelectionSetNode): Array; getRecursivelyReferencedFragments( - operation: OperationDefinition - ): Array; + operation: OperationDefinitionNode + ): Array; - getVariableUsages(node: HasSelectionSet): Array; + getVariableUsages(node: NodeWithSelectionSet): Array; getRecursiveVariableUsages( - operation: OperationDefinition + operation: OperationDefinitionNode ): Array; getType(): GraphQLOutputType; @@ -1963,7 +1902,7 @@ declare module "graphql/validation/validate" { getInputType(): GraphQLInputType; - getFieldDef(): GraphQLFieldDefinition; + getFieldDef(): GraphQLField; getDirective(): GraphQLDirective; @@ -1981,20 +1920,21 @@ declare module "graphql/execution" { } declare module "graphql/execution/index" { - export { execute } from 'graphql/execution/execute'; + export { execute, defaultFieldResolver, responsePathAsArray, ExecutionResult } from 'graphql/execution/execute'; } declare module "graphql/execution/execute" { import { GraphQLError, locatedError } from 'graphql/error'; import { GraphQLSchema } from 'graphql/type/schema'; + import { GraphQLField, GraphQLFieldResolver, ResponsePath } from 'graphql/type/definition'; import { - Directive, - Document, - OperationDefinition, - SelectionSet, - Field, - InlineFragment, - FragmentDefinition + DirectiveNode, + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + InlineFragmentNode, + FragmentDefinitionNode, } from 'graphql/language/ast'; /** * Data that must be available at all points during query execution. @@ -2004,9 +1944,9 @@ declare module "graphql/execution/execute" { */ interface ExecutionContext { schema: GraphQLSchema; - fragments: { [key: string]: FragmentDefinition }; + fragments: { [key: string]: FragmentDefinitionNode }; rootValue: any; - operation: OperationDefinition; + operation: OperationDefinitionNode; variableValues: { [key: string]: any }; errors: Array; } @@ -2016,8 +1956,8 @@ declare module "graphql/execution/execute" { * query, `errors` is null if no errors occurred, and is a * non-empty array if an error occurred. */ - interface ExecutionResult { - data: Object; + export interface ExecutionResult { + data?: {[key: string]: any}; errors?: Array; } @@ -2031,20 +1971,39 @@ declare module "graphql/execution/execute" { */ function execute( schema: GraphQLSchema, - documentAST: Document, + document: DocumentNode, rootValue?: any, contextValue?: any, variableValues?: { [key: string]: any }, operationName?: string - ): Promise + ): Promise; + + /** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ + export function responsePathAsArray( + path: ResponsePath + ): Array; + + function addPath(prev: ResponsePath, key: string | number): any; + + /** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context. + */ + export const defaultFieldResolver: GraphQLFieldResolver; } declare module "graphql/execution/values" { - import { GraphQLInputType, GraphQLArgument } from 'graphql/type/definition'; + import { GraphQLInputType, GraphQLField, GraphQLArgument } from 'graphql/type/definition'; + import { GraphQLDirective } from 'graphql/type/directives'; import { GraphQLSchema } from 'graphql/type/schema'; - import { Argument, VariableDefinition } from 'graphql/language/ast'; + import { FieldNode, DirectiveNode, VariableDefinitionNode } from 'graphql/language/ast'; /** * Prepares an object map of variableValues of the correct type based on the * provided variable definitions and arbitrary input. If the input cannot be @@ -2052,7 +2011,7 @@ declare module "graphql/execution/values" { */ function getVariableValues( schema: GraphQLSchema, - definitionASTs: Array, + varDefNodes: Array, inputs: { [key: string]: any } ): { [key: string]: any } @@ -2061,8 +2020,8 @@ declare module "graphql/execution/values" { * definitions and list of argument AST nodes. */ function getArgumentValues( - argDefs: Array, - argASTs: Array, + def: GraphQLField | GraphQLDirective, + node: FieldNode | DirectiveNode, variableValues?: { [key: string]: any } ): { [key: string]: any }; } @@ -2078,7 +2037,7 @@ declare module "graphql/error/index" { export { GraphQLError } from 'graphql/error/GraphQLError'; export { syntaxError } from 'graphql/error/syntaxError'; export { locatedError } from 'graphql/error/locatedError'; - export { formatError } from 'graphql/error/formatError'; + export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from 'graphql/error/formatError'; } declare module "graphql/error/formatError" { @@ -2092,7 +2051,8 @@ declare module "graphql/error/formatError" { type GraphQLFormattedError = { message: string, - locations: Array + locations: Array, + path: Array }; type GraphQLErrorLocation = { @@ -2103,7 +2063,7 @@ declare module "graphql/error/formatError" { declare module "graphql/error/GraphQLError" { import { getLocation } from 'graphql/language'; - import { Node } from 'graphql/language/ast'; + import { ASTNode } from 'graphql/language/ast'; import { Source } from 'graphql/language/source'; /** @@ -2144,7 +2104,7 @@ declare module "graphql/error/GraphQLError" { /** * An array of GraphQL AST Nodes corresponding to this error. */ - nodes: Array | void; + nodes: Array | void; /** * The source GraphQL document corresponding to this error. @@ -2197,194 +2157,702 @@ declare module "graphql/error/syntaxError" { /////////////////////////// // graphql/utilities // /////////////////////////// -// declare module "graphql/utilities/index" { -// // The GraphQL query recommended for a full schema introspection. -// export { introspectionQuery } from 'graphql/utilities/introspectionQuery'; - -// // Gets the target Operation from a Document -// export { getOperationAST } from 'graphql/utilities/getOperationAST'; - -// // Build a GraphQLSchema from an introspection result. -// export { buildClientSchema } from 'graphql/utilities/buildClientSchema'; - -// // Build a GraphQLSchema from GraphQL Schema language. -// export { buildASTSchema, buildSchema } from 'graphql/utilities/buildASTSchema'; - -// // Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. -// export { extendSchema } from 'graphql/utilities/extendSchema'; - -// // Print a GraphQLSchema to GraphQL Schema language. -// export { printSchema, printIntrospectionSchema } from 'graphql/utilities/schemaPrinter'; - -// // Create a GraphQLType from a GraphQL language AST. -// export { typeFromAST } from 'graphql/utilities/typeFromAST'; - -// // Create a JavaScript value from a GraphQL language AST. -// export { valueFromAST } from 'graphql/utilities/valueFromAST'; - -// // Create a GraphQL language AST from a JavaScript value. -// export { astFromValue } from 'graphql/utilities/astFromValue'; - -// // A helper to use within recursive-descent visitors which need to be aware of -// // the GraphQL type system. -// export { TypeInfo } from 'graphql/utilities/TypeInfo'; - -// // Determine if JavaScript values adhere to a GraphQL type. -// export { isValidJSValue } from 'graphql/utilities/isValidJSValue'; - -// // Determine if AST values adhere to a GraphQL type. -// export { isValidLiteralValue } from 'graphql/utilities/isValidLiteralValue'; - -// // Concatenates multiple AST together. -// export { concatAST } from 'graphql/utilities/concatAST'; - -// // Separates an AST into an AST per Operation. -// export { separateOperations } from 'graphql/utilities/separateOperations'; - -// // Comparators for types -// export { -// isEqualType, -// isTypeSubTypeOf, -// doTypesOverlap -// } from 'graphql/utilities/typeComparators'; - -// // Asserts that a string is a valid GraphQL name -// export { assertValidName } from 'graphql/utilities/assertValidName'; -// } - -// declare module "graphql/utilities/assertValidName" { -// // Helper to assert that provided names are valid. -// function assertValidName(name: string): void; -// } - -// declare module "graphql/utilities/astFromValue" { -// import { -// Value, -// //IntValue, -// //FloatValue, -// //StringValue, -// //BooleanValue, -// //EnumValue, -// //ListValue, -// //ObjectValue, -// } from 'graphql/language/ast'; -// import { GraphQLInputType } from 'graphql/type/definition'; - -// /** -// * Produces a GraphQL Value AST given a JavaScript value. -// * -// * A GraphQL type must be provided, which will be used to interpret different -// * JavaScript values. -// * -// * | JSON Value | GraphQL Value | -// * | ------------- | -------------------- | -// * | Object | Input Object | -// * | Array | List | -// * | Boolean | Boolean | -// * | String | String / Enum Value | -// * | Number | Int / Float | -// * | Mixed | Enum Value | -// * -// */ -// // TODO: this should set overloads according to above the table -// export function astFromValue( -// value: any, -// type: GraphQLInputType -// ): Value // Warning: there is a code in bottom: throw new TypeError - -// } - -// declare module "graphql/utilities/buildASTSchema" { -// import { Document } from 'graphql/language/ast'; -// import { Source } from 'graphql/language/source'; -// import { GraphQLSchema } from 'graphql/type/schema'; - -// /** -// * This takes the ast of a schema document produced by the parse function in -// * src/language/parser.js. -// * -// * If no schema definition is provided, then it will look for types named Query -// * and Mutation. -// * -// * Given that AST it constructs a GraphQLSchema. The resulting schema -// * has no resolve methods, so execution will use default resolvers. -// */ -// function buildASTSchema(ast: Document): GraphQLSchema; - -// /** -// * Given an ast node, returns its string description based on a contiguous -// * block full-line of comments preceding it. -// */ -// function getDescription(node: { loc?: Location }): string; - -// /** -// * A helper function to build a GraphQLSchema directly from a source -// * document. -// */ -// function buildSchema(source: string | Source): GraphQLSchema; -// } - -// declare module "graphql/utilities/buildClientSchema" { -// import { IntrospectionQuery } from 'graphql/utilities/introspectionQuery'; -// import { GraphQLSchema } from 'graphql/type/schema'; -// /** -// * Build a GraphQLSchema for use by client tools. -// * -// * Given the result of a client running the introspection query, creates and -// * returns a GraphQLSchema instance which can be then used with all graphql-js -// * tools, but cannot be used to execute a query, as introspection does not -// * represent the "resolver", "parse" or "serialize" functions or any other -// * server-internal mechanisms. -// */ -// export function buildClientSchema( -// introspection: IntrospectionQuery -// ): GraphQLSchema; -// } - -// declare module "graphql/utilities/concatAST" { - -// } - -// declare module "graphql/utilities/extendSchema" { - -// } - -// declare module "graphql/utilities/getOperationAST" { - -// } - -// declare module "graphql/utilities/introspectionQuery" { - -// } - -// declare module "graphql/utilities/isValidJSValue" { - -// } - -// declare module "graphql/utilities/isValidLiteralValue" { - -// } - -// declare module "graphql/utilities/schemaPrinter" { - -// } - -// declare module "graphql/utilities/separateOperations" { - -// } - -// declare module "graphql/utilities/typeComparators" { - -// } - -// declare module "graphql/utilities/typeFromAST" { - -// } - -declare module "graphql/utilities/TypeInfo" { - class TypeInfo { } +declare module "graphql/utilities" { + export * from "graphql/utilities/index"; } -// declare module "graphql/utilities/valueFromAST" { +declare module "graphql/utilities/index" { + // The GraphQL query recommended for a full schema introspection. + export { introspectionQuery } from 'graphql/utilities/introspectionQuery'; + export { + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, + } from 'graphql/utilities/introspectionQuery'; -// } + // Gets the target Operation from a Document + export { getOperationAST } from 'graphql/utilities/getOperationAST'; + + // Build a GraphQLSchema from an introspection result. + export { buildClientSchema } from 'graphql/utilities/buildClientSchema'; + + // Build a GraphQLSchema from GraphQL Schema language. + export { buildASTSchema, buildSchema } from 'graphql/utilities/buildASTSchema'; + + // Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. + export { extendSchema } from 'graphql/utilities/extendSchema'; + + // Print a GraphQLSchema to GraphQL Schema language. + export { printSchema, printType, printIntrospectionSchema } from 'graphql/utilities/schemaPrinter'; + + // Create a GraphQLType from a GraphQL language AST. + export { typeFromAST } from 'graphql/utilities/typeFromAST'; + + // Create a JavaScript value from a GraphQL language AST. + export { valueFromAST } from 'graphql/utilities/valueFromAST'; + + // Create a GraphQL language AST from a JavaScript value. + export { astFromValue } from 'graphql/utilities/astFromValue'; + + // A helper to use within recursive-descent visitors which need to be aware of + // the GraphQL type system. + export { TypeInfo } from 'graphql/utilities/TypeInfo'; + + // Determine if JavaScript values adhere to a GraphQL type. + export { isValidJSValue } from 'graphql/utilities/isValidJSValue'; + + // Determine if AST values adhere to a GraphQL type. + export { isValidLiteralValue } from 'graphql/utilities/isValidLiteralValue'; + + // Concatenates multiple AST together. + export { concatAST } from 'graphql/utilities/concatAST'; + + // Separates an AST into an AST per Operation. + export { separateOperations } from 'graphql/utilities/separateOperations'; + + // Comparators for types + export { + isEqualType, + isTypeSubTypeOf, + doTypesOverlap + } from 'graphql/utilities/typeComparators'; + + // Asserts that a string is a valid GraphQL name + export { assertValidName } from 'graphql/utilities/assertValidName'; + + // Compares two GraphQLSchemas and detects breaking changes. + export { findBreakingChanges } from 'graphql/utilities/findBreakingChanges'; + export { BreakingChange } from 'graphql/utilities/findBreakingChanges'; +} + +declare module "graphql/utilities/assertValidName" { + // Helper to assert that provided names are valid. + function assertValidName(name: string): void; +} + +declare module "graphql/utilities/astFromValue" { + import { + ValueNode, + //IntValueNode, + //FloatValueNode, + //StringValueNode, + //BooleanValueNode, + //EnumValueNode, + //ListValueNode, + //ObjectValueNode, + } from 'graphql/language/ast'; + import { GraphQLInputType } from 'graphql/type/definition'; + + /** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * + */ + // TODO: this should set overloads according to above the table + export function astFromValue( + value: any, + type: GraphQLInputType + ): ValueNode // Warning: there is a code in bottom: throw new TypeError +} + +declare module "graphql/utilities/buildASTSchema" { + import { DocumentNode, Location } from 'graphql/language/ast'; + import { Source } from 'graphql/language/source'; + import { GraphQLSchema } from 'graphql/type/schema'; + + /** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + */ + function buildASTSchema(ast: DocumentNode): GraphQLSchema; + + /** + * Given an ast node, returns its string description based on a contiguous + * block full-line of comments preceding it. + */ + function getDescription(node: { loc?: Location }): string; + + /** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + function buildSchema(source: string | Source): GraphQLSchema; + + /** + * Given an ast node, returns its string description based on a contiguous + * block full-line of comments preceding it. + */ + function getDescription(node: { loc?: Location }): string; + + /** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + function buildSchema(source: string | Source): GraphQLSchema; +} + +declare module "graphql/utilities/buildClientSchema" { + import { IntrospectionQuery } from 'graphql/utilities/introspectionQuery'; + import { GraphQLSchema } from 'graphql/type/schema'; + /** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + */ + function buildClientSchema( + introspection: IntrospectionQuery + ): GraphQLSchema; +} + +declare module "graphql/utilities/concatAST" { + import { DocumentNode } from 'graphql/language/ast'; + /** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ + function concatAST(asts: Array): DocumentNode; +} + +declare module "graphql/utilities/extendSchema" { + import { DocumentNode } from 'graphql/language/ast'; + import { GraphQLSchema } from 'graphql/type/schema'; + + /** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + */ + function extendSchema( + schema: GraphQLSchema, + documentAST: DocumentNode + ): GraphQLSchema; +} + +declare module "graphql/utilities/findBreakingChanges" { + import { + getNamedType, + GraphQLScalarType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLObjectType, + GraphQLUnionType, + GraphQLNamedType, + } from 'graphql/type/definition'; + import { GraphQLSchema } from 'graphql/type/schema'; + + export const BreakingChangeType: { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + }; + + type BreakingChangeKey = 'FIELD_CHANGED_KIND' + | 'FIELD_REMOVED' + | 'TYPE_CHANGED_KIND' + | 'TYPE_REMOVED' + | 'TYPE_REMOVED_FROM_UNION' + | 'VALUE_REMOVED_FROM_ENUM'; + + export type BreakingChange = { + type: BreakingChangeKey; + description: string; + }; + + /** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ + export function findBreakingChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ + export function findRemovedTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ + export function findTypesThatChangedKind( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to the fields on a type. This includes if + * a field has been removed from a type or if a field has changed type. + */ + export function findFieldsThatChangedType( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ + export function findTypesRemovedFromUnions( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; + + /** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ + export function findValuesRemovedFromEnums( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema + ): Array; +} + +declare module "graphql/utilities/getOperationAST" { + import { DocumentNode, OperationDefinitionNode } from 'graphql/language/ast'; + + /** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ + export function getOperationAST( + documentAST: DocumentNode, + operationName: string + ): OperationDefinitionNode; +} + +declare module "graphql/utilities/introspectionQuery" { + import { DirectiveLocationEnum } from 'graphql/type/directives'; + + /* + query IntrospectionQuery { + __schema { + queryType { name } + mutationType { name } + subscriptionType { name } + types { + ...FullType + } + directives { + name + description + locations + args { + ...InputValue + } + } + } + } + + fragment FullType on __Type { + kind + name + description + fields(includeDeprecated: true) { + name + description + args { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + description + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } + + fragment InputValue on __InputValue { + name + description + type { ...TypeRef } + defaultValue + } + + fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } + } + } + } + } + } + } + */ + const introspectionQuery: string; + + + interface IntrospectionQuery { + __schema: IntrospectionSchema + } + + interface IntrospectionSchema { + queryType: IntrospectionNamedTypeRef; + mutationType?: IntrospectionNamedTypeRef; + subscriptionType?: IntrospectionNamedTypeRef; + types: Array; + directives: Array; + } + + type IntrospectionType = + IntrospectionScalarType | + IntrospectionObjectType | + IntrospectionInterfaceType | + IntrospectionUnionType | + IntrospectionEnumType | + IntrospectionInputObjectType; + + interface IntrospectionScalarType { + kind: 'SCALAR'; + name: string; + description?: string; + } + + interface IntrospectionObjectType { + kind: 'OBJECT'; + name: string; + description?: string; + fields: Array; + interfaces: Array; + } + + interface IntrospectionInterfaceType { + kind: 'INTERFACE'; + name: string; + description?: string; + fields: Array; + possibleTypes: Array; + } + + interface IntrospectionUnionType { + kind: 'UNION'; + name: string; + description?: string; + possibleTypes: Array; + } + + interface IntrospectionEnumType { + kind: 'ENUM'; + name: string; + description?: string; + enumValues: Array; + } + + interface IntrospectionInputObjectType { + kind: 'INPUT_OBJECT'; + name: string; + description?: string; + inputFields: Array; + } + + type IntrospectionTypeRef = + IntrospectionNamedTypeRef | + IntrospectionListTypeRef | + IntrospectionNonNullTypeRef + + interface IntrospectionNamedTypeRef { + kind: string; + name: string; + } + + interface IntrospectionListTypeRef { + kind: 'LIST'; + ofType?: IntrospectionTypeRef; + } + + interface IntrospectionNonNullTypeRef { + kind: 'NON_NULL'; + ofType?: IntrospectionTypeRef; + } + + interface IntrospectionField { + name: string; + description?: string; + args: Array; + type: IntrospectionTypeRef; + isDeprecated: boolean; + deprecationReason?: string; + } + + interface IntrospectionInputValue { + name: string; + description?: string; + type: IntrospectionTypeRef; + defaultValue?: string; + } + + interface IntrospectionEnumValue { + name: string; + description?: string; + isDeprecated: boolean; + deprecationReason?: string; + } + + interface IntrospectionDirective { + name: string; + description?: string; + locations: Array; + args: Array; + } +} + +declare module "graphql/utilities/isValidJSValue" { + import { GraphQLInputType } from 'graphql/type/definition'; + + /** + * Given a JavaScript value and a GraphQL type, determine if the value will be + * accepted for that type. This is primarily useful for validating the + * runtime values of query variables. + */ + function isValidJSValue( + value: any, + type: GraphQLInputType + ): Array +} + +declare module "graphql/utilities/isValidLiteralValue" { + import { ValueNode } from 'graphql/language/ast'; + import { GraphQLInputType } from 'graphql/type/definition'; + + /** + * Utility for validators which determines if a value literal AST is valid given + * an input type. + * + * Note that this only validates literal values, variables are assumed to + * provide values of the correct type. + */ + function isValidLiteralValue( + type: GraphQLInputType, + valueNode: ValueNode + ): Array +} + +declare module "graphql/utilities/schemaPrinter" { + import { GraphQLSchema } from 'graphql/type/schema'; + import { GraphQLType } from 'graphql/type/definition'; + + function printSchema(schema: GraphQLSchema): string; + + function printIntrospectionSchema(schema: GraphQLSchema): string; + + function printType(type: GraphQLType): string +} + +declare module "graphql/utilities/separateOperations" { + import { + DocumentNode, + OperationDefinitionNode, + } from 'graphql/language/ast'; + + function separateOperations( + documentAST: DocumentNode + ): { [operationName: string]: DocumentNode } +} + +declare module "graphql/utilities/typeComparators" { + import { + GraphQLType, + GraphQLCompositeType, + GraphQLAbstractType + } from 'graphql/type/definition'; + import { + GraphQLSchema + } from 'graphql/type/schema'; + + /** + * Provided two types, return true if the types are equal (invariant). + */ + function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean; + + /** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ + function isTypeSubTypeOf( + schema: GraphQLSchema, + maybeSubType: GraphQLType, + superType: GraphQLType + ): boolean; + + /** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ + function doTypesOverlap( + schema: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType + ): boolean; +} + +declare module "graphql/utilities/typeFromAST" { + import { TypeNode } from 'graphql/language/ast'; + import { GraphQLType, GraphQLNullableType } from 'graphql/type/definition'; + import { GraphQLSchema } from 'graphql/type/schema'; + + function typeFromAST( + schema: GraphQLSchema, + typeNode: TypeNode + ): GraphQLType +} + +declare module "graphql/utilities/TypeInfo" { + import { GraphQLSchema } from 'graphql/type/schema'; + import { + GraphQLOutputType, + GraphQLCompositeType, + GraphQLInputType, + GraphQLField, + GraphQLArgument, + GraphQLType, + } from 'graphql/type/definition'; + import { GraphQLDirective } from 'graphql/type/directives'; + import { ASTNode, FieldNode } from 'graphql/language/ast'; + + /** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ + class TypeInfo { + constructor( + schema: GraphQLSchema, + // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn: getFieldDef + ); + + getType(): GraphQLOutputType; + getParentType(): GraphQLCompositeType; + getInputType(): GraphQLInputType; + getFieldDef(): GraphQLField; + getDirective(): GraphQLDirective; + getArgument(): GraphQLArgument; + enter(node: ASTNode): any; + leave(node: ASTNode): any; + } + + export interface getFieldDef { + ( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode + ): GraphQLField + } +} + +declare module "graphql/utilities/valueFromAST" { + import { GraphQLInputType } from 'graphql/type/definition'; + import { + ValueNode, + VariableNode, + ListValueNode, + ObjectValueNode + } from 'graphql/language/ast'; + + function valueFromAST( + valueNode: ValueNode, + type: GraphQLInputType, + variables?: { + [key: string]: any + } + ): any; +} diff --git a/greensock/index.d.ts b/greensock/index.d.ts index 004ec79dab..95c2ad6a4c 100644 --- a/greensock/index.d.ts +++ b/greensock/index.d.ts @@ -44,7 +44,7 @@ declare type TweenConfig = { autoCSS?: boolean; callbackScope?: Object; } - + //com.greensock.core declare class Animation { static ticker: IDispatcher; @@ -198,109 +198,106 @@ declare class TimelineMax extends TimelineLite { } //com.greensock.easing -interface Back { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; +declare class Ease { + constructor(func:Function, extraParams:any[], type:number, power:number); + public getRatio(p: number): number; } -interface Bounce { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Circ { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Cubic { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Ease { - getRatio(p:number):number; -} -interface EaseLookup { - find(name:string):Ease; -} -interface Elastic { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Expo { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Linear { - ease:Linear; - easeIn:Linear; - easeInOut:Linear; - easeNone:Linear; - easeOut:Linear; -} -interface Power0 { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Power1 { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Power2 { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Power3 { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Power4 { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Quad { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Quart { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Quint { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface Sine { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; -} -interface SlowMo { - ease:SlowMo; - new (linearRatio:number, power:number, yoyoMode:boolean):SlowMo; - config(linearRatio:number, power:number, yoyoMode:boolean):SlowMo; - getRatio(p:number):number; +declare class EaseLookup { + public static find(name: string): Ease; } -interface SteppedEase { - config(steps:number):SteppedEase; - getRatio(p:number):number; + +declare class Back extends Ease { + public static easeIn: Back; + public static easeInOut: Back; + public static easeOut: Back; + public config(overshoot: number): Elastic; + } -interface Strong { - easeIn:Ease; - easeInOut:Ease; - easeOut:Ease; +declare class Bounce extends Ease { + public static easeIn: Bounce; + public static easeInOut: Bounce; + public static easeOut: Bounce; +} +declare class Circ extends Ease { + public static easeIn: Circ; + public static easeInOut: Circ; + public static easeOut: Circ; +} +declare class Cubic extends Ease { + public static easeIn: Cubic; + public static easeInOut: Cubic; + public static easeOut: Cubic; +} + +declare class Elastic extends Ease { + public static easeIn: Elastic; + public static easeInOut: Elastic; + public static easeOut: Elastic; + public config(amplitude: number, period: number): Elastic; +} + +declare class Expo extends Ease { + public static easeIn: Expo; + public static easeInOut: Expo; + public static easeOut: Expo; +} + +declare class Linear extends Ease { + public static ease: Linear; + public static easeIn: Linear; + public static easeInOut: Linear; + public static easeNone: Linear; + public static easeOut: Linear; +} + +declare class Quad extends Ease { + public static easeIn: Quad; + public static easeInOut: Quad; + public static easeOut: Quad; +} + +declare class Quart extends Ease { + public static easeIn: Quart; + public static easeInOut: Quart; + public static easeOut: Quart; +} + +declare class Quint extends Ease { + public static easeIn: Quint; + public static easeInOut: Quint; + public static easeOut: Quint; +} + +declare class Sine extends Ease { + public static easeIn: Sine; + public static easeInOut: Sine; + public static easeOut: Sine; +} + +declare class SlowMo extends Ease { + public static ease: SlowMo; + public config(linearRatio: number, power: number, yoyoMode: boolean): SlowMo; +} + +declare class SteppedEase extends Ease { + constructor(staps: number); + public config(steps: number): SteppedEase; +} + +declare type RoughEaseConfig = { + clamp?: boolean; + points?: number; + randomize?: boolean; + strength?: number; + taper?: string; /* one of "in" | "out" | "both" | "none" */ + template?: Ease; +} + +declare class RoughEase extends Ease { + public static ease: RoughEase; + constructor(vars: RoughEaseConfig); + public config(steps: number): SteppedEase; } //com.greensock.plugins @@ -335,27 +332,12 @@ interface TweenPlugin { } //com.greensock.easing -declare var Back:Back; -declare var Bounce:Bounce; -declare var Circ:Circ; -declare var Cubic:Cubic; -declare var Ease:Ease; -declare var EaseLookup:EaseLookup; -declare var Elastic:Elastic; -declare var Expo:Expo; -declare var Linear:Linear; -declare var Power0:Power0; -declare var Power1:Power1; -declare var Power2:Power2; -declare var Power3:Power3; -declare var Power4:Power4; -declare var Quad:Quad; -declare var Quart:Quart; -declare var Quint:Quint; -declare var Sine:Sine; -declare var SlowMo:SlowMo; -declare var SteppedEase:SteppedEase; -declare var Strong:Strong; +declare var Power0: typeof Linear; +declare var Power1: typeof Quad; +declare var Power2: typeof Cubic; +declare var Power3: typeof Quart; +declare var Power4: typeof Quint; +declare var Strong: typeof Quint; //com.greensock.plugins declare var BezierPlugin:BezierPlugin; diff --git a/gulp-cache/gulp-cache-tests.ts b/gulp-cache/gulp-cache-tests.ts new file mode 100644 index 0000000000..31df7b0259 --- /dev/null +++ b/gulp-cache/gulp-cache-tests.ts @@ -0,0 +1,34 @@ +import * as fs from "fs"; +import * as gulp from "gulp"; +import * as cache from "gulp-cache"; +import File = require("vinyl"); + +// Some gulp plugin +let jshint: any; + +gulp.task('lint', function () { + gulp.src('./non/existent/path/*.js') + .pipe(cache(jshint('.jshintrc'), { + key: makeHashKey, + success: function (jshintedFile) { + return jshintedFile.jshint.success; + }, + value: function (jshintedFile) { + return { + jshint: jshintedFile.jshint + }; + } + })) + .pipe(jshint.reporter('default')); +}); + +var jsHintVersion = '2.4.1', + jshintOptions = fs.readFileSync('.jshintrc'); + +function makeHashKey(file: File) { + return [(file.contents as Buffer).toString('utf8'), jsHintVersion, jshintOptions].join(''); +} + +gulp.task('clear', function (done: any) { + return cache.clearAll(done); +}); diff --git a/gulp-cache/index.d.ts b/gulp-cache/index.d.ts new file mode 100644 index 0000000000..d576427f3d --- /dev/null +++ b/gulp-cache/index.d.ts @@ -0,0 +1,90 @@ +// Type definitions for gulp-cache v0.4.5 +// Project: https://github.com/jgable/gulp-cache +// Definitions by: Arun Aravind +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import File = require("vinyl"); +import { Transform } from "stream"; +import { PluginError } from "gulp-util"; + +declare namespace gc { + type Predicate = (arg: T) => boolean; + + interface IGulpCacheOptions { + /** + * The cache instance to use for caching. + */ + fileCache?: IGulpCache; + + /** + * The name of the bucket which stores the cached objects. + * Default value = 'default' + */ + name?: string, + + /** + * The hash generator to use. + */ + key?: (file: File, callback?: (err: any, result: string) => void) => string | Promise; + + /** + * Value representing the success of a task. + */ + success?: boolean | Predicate; + + /** + * Content that is to be cached. + */ + value?: (result: any) => Object | Promise | string; + } + + interface ICacheOptions { + /** + * Specifies the name of the directory where the cache + * is to be stored. + */ + cacheDirName: string; + } + + interface IGulpCacheStatic { + /** + * Caches the result of a task. + * @param task The task whose result is to be cached. + */ + (task: NodeJS.ReadWriteStream): Transform; + + /** + * Caches the result of a task. + * @param task Task whose result is to be cached. + * @param options Override values for available settings. + */ + (task: NodeJS.ReadWriteStream, options: IGulpCacheOptions): Transform; + + clear(options: IGulpCacheOptions): Transform; + + /** + * Represents a cache store. + */ + Cache: IGulpCache; + + /** + * Purges the cache. + * @param err PluginError instance in case of a plugin error. + * If callback is not specified an exception of type + * 'PluginError' is thrown. + */ + clearAll(callback?: (err: PluginError) => void): void; + } + + /** + * Represents a cach store. + */ + interface IGulpCache { + new (options: ICacheOptions): any; + } +} + +declare const _: gc.IGulpCacheStatic; +export = _; diff --git a/gulp-cache/tsconfig.json b/gulp-cache/tsconfig.json new file mode 100644 index 0000000000..fb841a90ec --- /dev/null +++ b/gulp-cache/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-cache-tests.ts" + ] +} \ No newline at end of file diff --git a/gulp-copy/gulp-copy-tests.ts b/gulp-copy/gulp-copy-tests.ts new file mode 100644 index 0000000000..f4bc3ac023 --- /dev/null +++ b/gulp-copy/gulp-copy-tests.ts @@ -0,0 +1,7 @@ +import * as gulp from "gulp"; +import * as gulpCopy from "gulp-copy"; + +gulp.task("copy-files", () => { + gulp.src("*.nonexistent") + .pipe(gulpCopy("remove/target/some/non/existent/path", { prefix: 2 })); +}); diff --git a/gulp-copy/index.d.ts b/gulp-copy/index.d.ts new file mode 100644 index 0000000000..18a85d1292 --- /dev/null +++ b/gulp-copy/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for gulp-copy v0.0.2 +// Project: https://github.com/klaascuvelier/gulp-copy +// Definitions by: Arun Aravind +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import through = require("through"); + +/** + * Copy files to destination and expose those files as source streams for the gulp pipeline. + * + * @param outDirectory The name of the destination directory. If this directory + * does not exist, it will be created atomatically. + */ +declare function gulpCopy(outDirectory: string): through.ThroughStream; + +/** + * Copy files to destination and expose those files as source streams for the gulp pipeline. + * + * @param outDirectory The name of the destination directory. If this directory + * does not exist, it will be created atomatically. + * @param options Override values for available settings. + */ +declare function gulpCopy(outDirectory: string, options: gulpCopy.GulpCopyOptions): through.ThroughStream; + +declare namespace gulpCopy { + export interface GulpCopyOptions { + /** + * Specifies the number of parts of the path to be ignored as path prefixes. + */ + prefix: number; + } +} + +export = gulpCopy; diff --git a/gulp-copy/tsconfig.json b/gulp-copy/tsconfig.json new file mode 100644 index 0000000000..052c9b42f7 --- /dev/null +++ b/gulp-copy/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-copy-tests.ts" + ] +} \ No newline at end of file diff --git a/hapi-decorators/index.d.ts b/hapi-decorators/index.d.ts index 5c67fddbd1..c58a1a6052 100644 --- a/hapi-decorators/index.d.ts +++ b/hapi-decorators/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Ken Howard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - import * as hapi from 'hapi'; interface ControllerStatic { new (): Controller; diff --git a/hapi/index.d.ts b/hapi/index.d.ts index 16b58f005c..5eaf43d7fa 100644 --- a/hapi/index.d.ts +++ b/hapi/index.d.ts @@ -73,6 +73,37 @@ export interface ICatBoxCacheOptions { /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ shared?: boolean; } + + /** policy configuration for the "CatBox" module and server method options. */ + export interface ICatBoxCachePolicyOptions { + /** the cache name configured in server.cache. Defaults to the default cache. */ + cache?: string; + /** string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. */ + segment?: string; + /** if true, allows multiple cache provisions to share the same segment. Default to false. */ + shared?: boolean; + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: number; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. */ + expiresAt?: number; + /** a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. */ + generateFunc?: Function; + /** number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. */ + staleIn?: number; + /** number of milliseconds to wait before checking if an item is stale. */ + staleTimeout?: number; + /** number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ + generateTimeout?: number; + /** if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true */ + dropOnError?: boolean; + /** if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */ + generateOnReadError?: boolean; + /** if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. */ + generateIgnoreWriteError?: boolean; + /** number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). */ + pendingGenerateTimeout?: number; + } + /** Any connections configuration server defaults can be included to override and customize the individual connection. */ export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { @@ -103,6 +134,8 @@ export interface IServerConnectionOptions extends IConnectionConfigurationServer export interface IConnectionConfigurationServerDefaults { /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ app?: any; + /** if false, response content encoding is disabled. Defaults to true */ + compression?: boolean; /** connection load limits configuration where: */ load?: { /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ @@ -328,11 +361,12 @@ export interface IStrictReply extends IReplyMethods { export interface ISessionHandler { (request: Request, reply: IReply): void; -} + } -export interface IStrictSessionHandler { + export interface IStrictSessionHandler { (request: Request, reply: IStrictReply): void; } + export interface IRequestHandler { (request: Request): T; } @@ -496,7 +530,7 @@ export interface IRouteAdditionalConfigurationOptions { }; /** an alternative location for the route handler option. */ - handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** an optional unique identifier used to look up the route using server.lookup(). */ id?: number; /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ @@ -895,7 +929,7 @@ export interface IRouteConfiguration { /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ vhost?: string; /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ - handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** - additional route options.*/ config?: IRouteAdditionalConfigurationOptions; } @@ -1106,7 +1140,7 @@ export interface IServerMethod { generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ export interface IServerMethodOptions { bind?: any; - cache?: ICatBoxCacheOptions; + cache?: ICatBoxCachePolicyOptions; callback?: boolean; generateKey?(args: any[]): string; } @@ -1873,9 +1907,9 @@ export class Server extends Events.EventEmitter { } } });*/ - strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void; - strategy(name: string, scheme: string, mode?: boolean | string): void; - strategy(name: string, scheme: string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string): void; + strategy(name: string, scheme: string, options?:any): void; /** server.auth.test(strategy, request, next) Tests a request against an authentication strategy where: @@ -1942,7 +1976,7 @@ export class Server extends Events.EventEmitter { // value === { capital: 'oslo' }; }); });*/ - cache(options: ICatBoxCacheOptions): void; + cache(options: ICatBoxCachePolicyOptions): void; /** server.connection([options]) Adds an incoming server connection diff --git a/headroom/tsconfig.json b/headroom/tsconfig.json index 6b6f41a4b8..3dd7aec967 100644 --- a/headroom/tsconfig.json +++ b/headroom/tsconfig.json @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "Headroom-tests.ts" + "headroom-tests.ts" ] } \ No newline at end of file diff --git a/hellosign-embedded/index.d.ts b/hellosign-embedded/index.d.ts index f215dac6bc..45b70774ff 100644 --- a/hellosign-embedded/index.d.ts +++ b/hellosign-embedded/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hellosign-embedded v1.0.3 +// Type definitions for hellosign-embedded v1.2.0 // Project: https://github.com/HelloFax/hellosign-embedded // Definitions by: Brian Surowiec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -155,6 +155,13 @@ declare module HelloSign { */ EVENT_SIGNED: string; + /** + * The signature request was declined + * + * @default signature_request_declined + */ + EVENT_DECLINED: string; + /** * The user closed the iFrame before completing * diff --git a/highcharts-ng/index.d.ts b/highcharts-ng/index.d.ts index 3dab53bcda..123799e76c 100644 --- a/highcharts-ng/index.d.ts +++ b/highcharts-ng/index.d.ts @@ -3,41 +3,43 @@ // Definitions by: Scott Hatcher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { ChartObject, IndividualSeriesOptions, Options } from "highcharts"; -interface HighChartsNGConfig { - options: HighchartsOptions; - //The below properties are watched separately for changes. +declare global { + interface HighChartsNGConfig { + options: Options; + //The below properties are watched separately for changes. - //Series object (optional) - a list of series using normal highcharts series options. - series?: HighchartsIndividualSeriesOptions[]; - //Title configuration (optional) - title?: { - text?: string; - }; - //Boolean to control showng loading status on chart (optional) - //Could be a string if you want to show specific loading text. - loading?: boolean | string; - //Configuration for the xAxis (optional). Currently only one x axis can be dynamically controlled. - //properties currentMin and currentMax provied 2-way binding to the chart's maximimum and minimum - xAxis?: { - currentMin?: number; - currentMax?: number; - title?: { text?: string } - }; - //Whether to use HighStocks instead of HighCharts (optional). Defaults to false. - useHighStocks?: boolean; - //size (optional) if left out the chart will default to size of the div or something sensible. - size?: { - width?: number; - height?: number; - }; - //function (optional) - setup some logic for the chart - func?: (chart: HighchartsChartObject) => void; -} + //Series object (optional) - a list of series using normal highcharts series options. + series?: IndividualSeriesOptions[]; + //Title configuration (optional) + title?: { + text?: string; + }; + //Boolean to control showng loading status on chart (optional) + //Could be a string if you want to show specific loading text. + loading?: boolean | string; + //Configuration for the xAxis (optional). Currently only one x axis can be dynamically controlled. + //properties currentMin and currentMax provied 2-way binding to the chart's maximimum and minimum + xAxis?: { + currentMin?: number; + currentMax?: number; + title?: { text?: string } + }; + //Whether to use HighStocks instead of HighCharts (optional). Defaults to false. + useHighStocks?: boolean; + //size (optional) if left out the chart will default to size of the div or something sensible. + size?: { + width?: number; + height?: number; + }; + //function (optional) - setup some logic for the chart + func?: (chart: ChartObject) => void; + } -//Instantiated Chart -interface HighChartsNGChart extends HighChartsNGConfig { - //This is a simple way to access all the Highcharts API that is not currently managed by this directive. - getHighcharts(): HighchartsChartObject; + //Instantiated Chart + interface HighChartsNGChart extends HighChartsNGConfig { + //This is a simple way to access all the Highcharts API that is not currently managed by this directive. + getHighcharts(): ChartObject; + } } diff --git a/highcharts/highcharts-modules-no-data-to-display.d.ts b/highcharts/highcharts-modules-no-data-to-display.d.ts deleted file mode 100644 index ab5fdd1d0d..0000000000 --- a/highcharts/highcharts-modules-no-data-to-display.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for Highcharts No Data to Display -// Project: http://www.highcharts.com/ -// Definitions by: Andrey Zolotin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -interface HighchartsChartObject { - /** - * Returns true if there are data points within the plot area now - * @return {boolean} If chart has any data. - * @since 3.0.8 - */ - hasData(): boolean; - - /** - * Hide the 'No data to display' message added by the no-data-to-display plugin. - * @since 3.0.8 - */ - hideNoData(): void; - - /** - * Display a no-data message. - * @param {String} message An optional message to show in place of the default one - * @since 3.0.8 - */ - showNoData(message?: string): void; -} diff --git a/highcharts/highcharts-more-tests.ts b/highcharts/highcharts-more-tests.ts new file mode 100644 index 0000000000..e6e5e9af5c --- /dev/null +++ b/highcharts/highcharts-more-tests.ts @@ -0,0 +1 @@ +HighchartsMore(Highcharts); diff --git a/highcharts/highcharts-more.d.ts b/highcharts/highcharts-more.d.ts index 1d42764b3c..dd5950fe35 100644 --- a/highcharts/highcharts-more.d.ts +++ b/highcharts/highcharts-more.d.ts @@ -3,10 +3,6 @@ // Definitions by: Maciej Suchecki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -declare var HighchartsMore: (H: HighchartsStatic) => HighchartsStatic; - -declare module "highcharts/highcharts-more" { - export = HighchartsMore; -} +declare var HighchartsMore: (H: Highcharts.Static) => Highcharts.Static; +export = HighchartsMore; +export as namespace HighchartsMore; diff --git a/highcharts/highcharts-tests.ts b/highcharts/highcharts-tests.ts index d36085ac92..459d812bcc 100644 --- a/highcharts/highcharts-tests.ts +++ b/highcharts/highcharts-tests.ts @@ -1,5 +1,5 @@ - /// +import * as Highcharts from "highcharts"; // May also use /// function originalTests() { Highcharts.setOptions({ @@ -16,13 +16,13 @@ function originalTests() { }); - var animate: HighchartsAnimation = { + var animate: Highcharts.Animation = { duration: 200, easing: "linear" }; - var gradient: HighchartsGradient = { + var gradient: Highcharts.Gradient = { linearGradient: { x1: 0, y1: 0, @@ -42,19 +42,19 @@ function originalTests() { renderTo: "container" }, xAxis: {}, - series: [{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true }] }); - chart1.addSeries({ + chart1.addSeries({ enableMouseTracking: true, data: [1, 2, 3, 4, 5] }); - console.log((chart1.series[0].options).dashStyle); + console.log((chart1.series[0].options).dashStyle); var chart2 = new Highcharts.Chart({ chart: { @@ -85,7 +85,7 @@ function originalTests() { legend: { enabled: false }, - series: [{ + series: [{ data: [ [550, 870], [738, 362], [719, 711], [547, 665], [595, 197], [332, 144], [581, 555], [196, 862], [6, 837], [400, 924], [888, 148], [785, 730], @@ -113,14 +113,14 @@ function originalTests() { var r = new Highcharts.Renderer(div, 20, 30); var box = r.text("Hello", 10, 10).getBBox(); - var highChartSettings: HighchartsOptions = { + var highChartSettings: Highcharts.Options = { chart: { width: 400, height: 400 }, xAxis: [{ }], - series: [{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }; @@ -129,16 +129,16 @@ function originalTests() { chart.series[0].setVisible(true, true); }); - var singleYAxisOptions: HighchartsOptions = { + var singleYAxisOptions: Highcharts.Options = { yAxis: {} }; - var multipleYAxisOptions: HighchartsOptions = { + var multipleYAxisOptions: Highcharts.Options = { yAxis: [{}, {}] }; var renderToIdChart = new Highcharts.Chart("container", { xAxis: {}, - series: [{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -147,7 +147,7 @@ function originalTests() { var renderToElementChart = new Highcharts.Chart(div, { xAxis: {}, - series: [{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -156,7 +156,7 @@ function originalTests() { var createWithFunction = Highcharts.chart({ xAxis: {}, - series: [{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -165,7 +165,7 @@ function originalTests() { var createWithFunctionRenderToId = Highcharts.chart("container", { xAxis: {}, - series: [{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -174,7 +174,7 @@ function originalTests() { var createWithFunctionRenderToElement = Highcharts.chart(div, { xAxis: {}, - series: [{ + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true @@ -183,7 +183,7 @@ function originalTests() { } function test_alldefaults() { - var options: HighchartsOptions = { + var options: Highcharts.Options = { chart: {}, credits: {}, data: {}, @@ -207,19 +207,19 @@ function test_alldefaults() { } function test_ChartOptions() { - var emptyChartOptions: HighchartsChartOptions = { + var emptyChartOptions: Highcharts.ChartOptions = { events: {}, options3d: {}, resetZoomButton: {} }; - var allValuesSet: HighchartsChartOptions = { + var allValuesSet: Highcharts.ChartOptions = { alignTicks: false, animation: { duration: 500, easing: "linear" }, - backgroundColor: { + backgroundColor: { linearGradient: { x1: 0, y1: 0, @@ -233,7 +233,7 @@ function test_ChartOptions() { borderWidth: 5, className: "class", defaultSeriesType: "deprecated", - events: { + events: { addSeries: () => {}, afterPrint: () => {}, beforePrint: () => {}, @@ -252,21 +252,21 @@ function test_ChartOptions() { marginLeft: 10, marginRight: 10, marginTop: 10, - options3d: { + options3d: { alpha: 20, beta: 20, depth: 50, enabled: true, frame: { - back: { + back: { color: "black", size: 2 }, - bottom: { + bottom: { color: "black", size: 2 }, - side: { + side: { color: "black", size: 2 } @@ -280,7 +280,7 @@ function test_ChartOptions() { plotBackgroundImage: "http://image.url/image.jpg", plotBorderColor: "grey", plotBorderWidth: 5, - plotShadow: { + plotShadow: { color: "magenta", offsetX: 10, offsetY: 10, @@ -290,15 +290,15 @@ function test_ChartOptions() { polar: true, reflow: false, renderTo: "elementId", - resetZoomButton: { - position: { + resetZoomButton: { + position: { align: "left", verticalAlign: "top", x: 5, y: 5 }, relativeTo: "chart", - theme: { + theme: { display: "hidden", fill: "black", stroke: "white", @@ -364,7 +364,7 @@ function test_ChartOptions() { }); // animation example - $('#container').highcharts( { + $('#container').highcharts( { chart: { animation: { duration: 1500, @@ -449,7 +449,7 @@ function test_ChartOptions() { chart: { events: { addSeries: function () { - var label = (this).renderer.label('A series was added, about to redraw chart', 100, 120) + var label = (this).renderer.label('A series was added, about to redraw chart', 100, 120) .attr({ fill: Highcharts.getOptions().colors[0], padding: 10, @@ -578,7 +578,7 @@ function test_ChartOptions() { } function test_CreditsOptions() { - var allDefaults: HighchartsCreditsOptions = {}; + var allDefaults: Highcharts.CreditsOptions = {}; // custom url and text example $('#container').highcharts({ @@ -597,7 +597,7 @@ function test_CreditsOptions() { function test_Data() { // all defaults - var data: HighchartsDataOptions = {}; + var data: Highcharts.DataOptions = {}; // data from table example $('#container').highcharts({ @@ -631,10 +631,10 @@ function test_Data() { } }, series: [ - { + { lineWidth: 1 }, - { + { type: 'areaspline', color: '#c4392d', negativeColor: '#5679c4', @@ -645,7 +645,7 @@ function test_Data() { // limited data example $('#container').highcharts({ - data: { + data: { csv: document.getElementById('csv').innerHTML, startRow: 114, endRow: 134, @@ -655,7 +655,7 @@ function test_Data() { xAxis: { allowDecimals: false }, - series: [ { + series: [ { name: 'Annual mean' }] }); @@ -675,7 +675,7 @@ function test_Data() { } function test_Drilldown() { - var allDefaults: HighchartsDrilldownOptions = {}; + var allDefaults: Highcharts.DrilldownOptions = {}; // multiseries drilldown example $('#container').highcharts({ @@ -686,14 +686,14 @@ function test_Drilldown() { type: 'category' }, plotOptions: { - series: { + series: { borderWidth: 0, dataLabels: { enabled: true } } }, - series: [{ + series: [{ name: '2010', data: [{ name: 'Republican', @@ -708,7 +708,7 @@ function test_Drilldown() { y: 4, drilldown: 'other-2010' }] - }, { + }, { name: '2014', data: [{ name: 'Republican', @@ -725,7 +725,7 @@ function test_Drilldown() { }] }], drilldown: { - series: [{ + series: [{ id: 'republican-2010', data: [ ['East', 4], @@ -733,7 +733,7 @@ function test_Drilldown() { ['North', 1], ['South', 4] ] - }, { + }, { id: 'democrats-2010', data: [ ['East', 6], @@ -741,7 +741,7 @@ function test_Drilldown() { ['North', 2], ['South', 4] ] - }, { + }, { id: 'other-2010', data: [ ['East', 2], @@ -749,7 +749,7 @@ function test_Drilldown() { ['North', 3], ['South', 2] ] - }, { + }, { id: 'republican-2014', data: [ ['East', 2], @@ -757,7 +757,7 @@ function test_Drilldown() { ['North', 1], ['South', 7] ] - }, { + }, { id: 'democrats-2014', data: [ ['East', 4], @@ -765,7 +765,7 @@ function test_Drilldown() { ['North', 5], ['South', 3] ] - }, { + }, { id: 'other-2014', data: [ ['East', 7], @@ -783,14 +783,14 @@ function test_Drilldown() { type: 'column' }, plotOptions: { - series: { + series: { borderWidth: 0, dataLabels: { enabled: true } } }, - series: [{ + series: [{ name: 'Things', colorByPoint: true, data: [{ @@ -858,7 +858,7 @@ function test_Drilldown() { } function test_Exporting() { - var allDefaults: HighchartsExportingOptions = {}; + var allDefaults: Highcharts.ExportingOptions = {}; // source size example $('#container').highcharts({ @@ -890,13 +890,13 @@ function test_Exporting() { } function test_Loading() { - var allDefaults: HighchartsLoadingOptions = {}; + var allDefaults: Highcharts.LoadingOptions = {}; // examples // the button handler var isLoading = false, $button = $('#button'), - chart: HighchartsChartObject; + chart: Highcharts.ChartObject; $button.click(function () { if (!isLoading) { @@ -932,7 +932,7 @@ function test_Loading() { } function test_Navigation() { - var allDefaults: HighchartsNavigationOptions = {}; + var allDefaults: Highcharts.NavigationOptions = {}; // examples $('#container').highcharts({ @@ -974,7 +974,7 @@ function test_Navigation() { } function test_NoData() { - var allDefaults: HighchartsNoDataOptions = {}; + var allDefaults: Highcharts.NoDataOptions = {}; // example $('#container').highcharts({ @@ -1000,7 +1000,7 @@ function test_NoData() { } function test_AreaOptions() { - var allDefaults: HighchartsAreaChartSeriesOptions = {}; + var allDefaults: Highcharts.AreaChartSeriesOptions = {}; // examples $('#container').highcharts({ @@ -1011,12 +1011,12 @@ function test_AreaOptions() { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { - series: { + series: { fillColor: { linearGradient: [0, 0, 0, 300], stops: [ [0, Highcharts.getOptions().colors[0]], - [1, (Highcharts.Color(Highcharts.getOptions().colors[0])).setOpacity(0).get('rgba')] + [1, (Highcharts.Color(Highcharts.getOptions().colors[0])).setOpacity(0).get('rgba')] ] }, fillOpacity: 0.1, @@ -1036,7 +1036,7 @@ function test_AreaOptions() { } function test_AreaRange() { - var allDefaults: HighchartsAreaRangeChartSeriesOptions = {}; + var allDefaults: Highcharts.AreaRangeChartSeriesOptions = {}; // example $('#container').highcharts({ @@ -1044,7 +1044,7 @@ function test_AreaRange() { type: "arearange", zoomType: 'x' }, - series: [{ + series: [{ data: (function (arr: number[], len: number) { var i: number; for (i = 0; i < len; i = i + 1) { @@ -1090,7 +1090,7 @@ function test_AreaRange() { legend: { enabled: false }, - series: [ { + series: [ { name: 'Temperatures', data: data, dataLabels: { @@ -1105,7 +1105,7 @@ function test_AreaRange() { } function test_Bar() { - var allDefaults: HighchartsBarChartSeriesOptions = {}; + var allDefaults: Highcharts.BarChartSeriesOptions = {}; $('#container').highcharts({ chart: { @@ -1115,7 +1115,7 @@ function test_Bar() { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { - series: { + series: { borderColor: '#303030', borderRadius: 5, borderWidth: 2, @@ -1174,7 +1174,7 @@ function test_Bar() { // grouping example Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function (color: string) { - return (Highcharts.Color(color)) + return (Highcharts.Color(color)) .setOpacity(0.5) .get('rgba'); }); @@ -1209,19 +1209,19 @@ function test_Bar() { shadow: false } }, - series: [ { + series: [ { name: 'Tokyo', data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], pointPadding: 0 - }, { + }, { name: 'New York', data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3], pointPadding: 0.1 - }, { + }, { name: 'London', data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2], pointPadding: 0.2 - }, { + }, { name: 'Berlin', data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1], pointPadding: 0.3 @@ -1230,7 +1230,7 @@ function test_Bar() { } function test_BoxPlot() { - var allDefaults: HighchartsBoxPlotChartSeriesOptions = {}; + var allDefaults: Highcharts.BoxPlotChartSeriesOptions = {}; // boxplot example $('#container').highcharts({ @@ -1282,7 +1282,7 @@ function test_BoxPlot() { } function test_Bubble() { - var allDefaults: HighchartsBubbleChartSeriesOptions = {}; + var allDefaults: Highcharts.BubbleChartSeriesOptions = {}; // bubble example $('#container').highcharts({ @@ -1307,7 +1307,7 @@ function test_Bubble() { maxSize: 50 } }, - series: [ { + series: [ { data: [ [9, 81, 13], [98, 5, 39], @@ -1344,7 +1344,7 @@ function test_Bubble() { subtitle: { text: 'Size is computed by absolute value on negative bubbles' }, - series: [{ + series: [{ data: [ [-5, 0, -5], [-4, 0, -4], @@ -1365,19 +1365,19 @@ function test_Bubble() { } function test_Column() { - var allDefaults: HighchartsColumnChartSeriesOptions = {}; + var allDefaults: Highcharts.ColumnChartSeriesOptions = {}; // same options as bar chart } function test_ColumnRange() { - var allDefaults: HighchartsColumnRangeChartSeriesOptions = {}; + var allDefaults: Highcharts.ColumnRangeChartSeriesOptions = {}; // same options as bar chart and datalabels from arearange } function test_ErrorBar() { - var allDefaults: HighchartsErrorBarChartSeriesOptions = {}; + var allDefaults: Highcharts.ErrorBarChartSeriesOptions = {}; // error bar styling example $('#container').highcharts({ @@ -1401,7 +1401,7 @@ function test_ErrorBar() { tooltip: { shared: true }, - series: [{ + series: [{ name: 'Temperature', type: 'spline', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6], @@ -1411,7 +1411,7 @@ function test_ErrorBar() { tooltip: { pointFormat: '{series.name}: {point.y:.1f}°C
' } - }, { + }, { color: '#FF0000', name: 'Temperature error', type: 'errorbar', @@ -1428,7 +1428,7 @@ function test_ErrorBar() { } function test_Funnel() { - var allDefaults: HighchartsFunnelChartSeriesOptions = {}; + var allDefaults: Highcharts.FunnelChartSeriesOptions = {}; // funnel demo $('#container').highcharts({ @@ -1441,7 +1441,7 @@ function test_Funnel() { x: -50 }, plotOptions: { - series: { + series: { dataLabels: { enabled: true, format: '{point.name} ({point.y:,.0f})', @@ -1472,7 +1472,7 @@ function test_Funnel() { } function test_Gauge() { - var allDefaults: HighchartsGaugeChartSeriesOptions = {}; + var allDefaults: Highcharts.GaugeChartSeriesOptions = {}; // example $('#container').highcharts({ @@ -1518,7 +1518,7 @@ function test_Gauge() { } } }, - series: [ { + series: [ { data: [80], overshoot: 5 }] @@ -1526,7 +1526,7 @@ function test_Gauge() { } function test_HeatMap() { - var allDefaults: HighchartsHeatMapSeriesOptions = {}; + var allDefaults: Highcharts.HeatMapSeriesOptions = {}; // heatmap demo $('#container').highcharts({ @@ -1574,7 +1574,7 @@ function test_HeatMap() { ], min: -5 }, - series: [ { + series: [ { borderWidth: 0, colsize: 24 * 36e5, // one day tooltip: { @@ -1586,7 +1586,7 @@ function test_HeatMap() { } function test_Line() { - var allDefaults: HighchartsLineChartSeriesOptions = {}; + var allDefaults: Highcharts.LineChartSeriesOptions = {}; // step example $('#container').highcharts({ @@ -1596,17 +1596,17 @@ function test_Line() { xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, - series: [{ + series: [{ data: [1, 2, 3, 4, null, 6, 7, null, 9], step: 'right', name: 'Right', linecap: 'round' - }, { + }, { data: [5, 6, 7, 8, null, 10, 11, null, 13], step: 'center', name: 'Center', linecap: 'round' - }, { + }, { data: [9, 10, 11, 12, null, 14, 15, null, 17], step: 'left', name: 'Left', @@ -1616,7 +1616,7 @@ function test_Line() { } function test_Pie() { - var allDefaults: HighchartsPieChartSeriesOptions = {}; + var allDefaults: Highcharts.PieChartSeriesOptions = {}; // pie demo $('#container').highcharts({ @@ -1646,7 +1646,7 @@ function test_Pie() { } } }, - series: [{ + series: [{ name: "Brands", colorByPoint: true, data: [{ @@ -1705,7 +1705,7 @@ function test_Pie() { center: ['50%', '75%'] } }, - series: [{ + series: [{ type: 'pie', name: 'Browser share', innerSize: '50%', @@ -1757,7 +1757,7 @@ function test_Pie() { } function test_Polygon() { - var allDefaults: HighchartsPolygonChartSeriesOptions = {}; + var allDefaults: Highcharts.PolygonChartSeriesOptions = {}; $('#container').highcharts({ chart: { @@ -1786,7 +1786,7 @@ function test_Polygon() { } function test_Pyramid() { - var allDefaults: HighchartsPyramidChartSeriesOptions = {}; + var allDefaults: Highcharts.PyramidChartSeriesOptions = {}; // pyramid demo $('#container').highcharts({ @@ -1825,10 +1825,10 @@ function test_Pyramid() { } function test_SolidGauge() { - var allDefaults: HighchartsSolidGaugeChartSeriesOptions = {}; + var allDefaults: Highcharts.SolidGaugeChartSeriesOptions = {}; // partial solid gauge demo - var gaugeOptions: HighchartsOptions = { + var gaugeOptions: Highcharts.Options = { chart: { type: 'solidgauge' }, @@ -1848,6 +1848,13 @@ function test_SolidGauge() { tooltip: { enabled: false }, + colorAxis: { + stops: [ + [0.1, '#55BF3B'], // green + [0.5, '#DDDF0D'], // yellow + [0.9, '#DF5353'] // red + ] + }, yAxis: { lineWidth: 0, minorTickInterval: null, @@ -1873,10 +1880,10 @@ function test_SolidGauge() { } function test_TreeMap() { - var allDefaults: HighchartsTreeMapChartSeriesOptions = {}; + var allDefaults: Highcharts.TreeMapChartSeriesOptions = {}; // allowDrillToNode - var treeMap: HighchartsTreeMapChartSeriesOptions = { + var treeMap: Highcharts.TreeMapChartSeriesOptions = { type: "treemap", layoutAlgorithm: 'squarified', allowDrillToNode: true, @@ -1925,10 +1932,10 @@ function test_TreeMap() { } function test_Waterfall() { - var allDefaults: HighchartsWaterFallChartSeriesOptions = {}; + var allDefaults: Highcharts.WaterFallChartSeriesOptions = {}; // partial waterfall demo - var series: HighchartsWaterFallChartSeriesOptions = { + var series: Highcharts.WaterFallChartSeriesOptions = { upColor: Highcharts.getOptions().colors[2], color: Highcharts.getOptions().colors[3], data: [{ @@ -1971,9 +1978,9 @@ function test_Waterfall() { } function test_AxisOptions() { - var allDefaults: HighchartsAxisOptions = {}; + var allDefaults: Highcharts.AxisOptions = {}; - var axis: HighchartsAxisOptions = { + var axis: Highcharts.AxisOptions = { allowDecimals: false, alternateGridColor: '#000000', breaks: [{ @@ -2161,31 +2168,31 @@ function test_AxisObject() { axis.toPixels(10, true); axis.toValue(10); axis.toValue(10, true); - axis.update({}); - axis.update({}, true); + axis.update({}); + axis.update({}, true); } function test_ChartObject() { var chart = $("#container").highcharts(); - chart.addAxis({}); - chart.addAxis({}, true); - chart.addAxis({}, true, false); - chart.addAxis({}, true, true, false); - chart.addAxis({}, true, true, {duration: 50}); - chart.addSeries({}); - chart.addSeries({}, false); - chart.addSeries({}, false, false); - chart.addSeries({}, false, {duration: 50}); - chart.addSeriesAsDrilldown({}, {}); + chart.addAxis({}); + chart.addAxis({}, true); + chart.addAxis({}, true, false); + chart.addAxis({}, true, true, false); + chart.addAxis({}, true, true, {duration: 50}); + chart.addSeries({}); + chart.addSeries({}, false); + chart.addSeries({}, false, false); + chart.addSeries({}, false, {duration: 50}); + chart.addSeriesAsDrilldown({}, {}); var container = chart.container; console.log(container.id); chart.destroy(); chart.drillUp(); - chart.exportChart({}, {}); - chart.exportChartLocal({}, {}); + chart.exportChart({}, {}); + chart.exportChartLocal({}, {}); var object = chart.get('axisIdOrSeriesIdOrPointId'); var svg1 = chart.getSVG(); - var svg2 = chart.getSVG({}); + var svg2 = chart.getSVG({}); var selectedPoints = chart.getSelectedPoints(); var selectedSeries = chart.getSelectedSeries(); chart.hideLoading(); @@ -2250,7 +2257,7 @@ function test_ElementObject() { } function test_PointObject() { - var point = $('#container').highcharts().get('point1'); + var point = $('#container').highcharts().get('point1'); var category = point.category; var percentage = point.percentage; point.index; @@ -2291,7 +2298,7 @@ function test_RendererObject() { } function test_SeriesObject() { - var series = $('#container').highcharts().get('series1'); + var series = $('#container').highcharts().get('series1'); series.addPoint(0); series.addPoint([0, 0]); series.addPoint({}); diff --git a/highcharts/highstock-tests.ts b/highcharts/highstock-tests.ts index 07a98a6e42..ac7cb883f2 100644 --- a/highcharts/highstock-tests.ts +++ b/highcharts/highstock-tests.ts @@ -1,5 +1,5 @@ - /// +import * as Highcharts from "highcharts"; var someData = [1, 2, 3, 4, 5, 6, 7, 8, 9]; @@ -55,7 +55,7 @@ $(function () { } }, - series: [{ + series: [{ name: 'USD to EUR', data: someData, lineColor: "blue" diff --git a/highcharts/highstock.d.ts b/highcharts/highstock.d.ts index d1b21da62e..f312286745 100644 --- a/highcharts/highstock.d.ts +++ b/highcharts/highstock.d.ts @@ -3,116 +3,119 @@ // Definitions by: David Deutsch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface HighstockChartObject extends HighchartsChartObject { - options: HighstockOptions; +declare namespace __Highstock { + interface ChartObject extends Highcharts.ChartObject { + options: Options; + } + + interface NavigatorOptions { + adaptToUpdatedData?: boolean; + baseSeries?: string | number; + enabled?: boolean; + handles?: { + backgroundColor?: string; + borderColor?: string; + }; + height?: number; + margin?: number; + maskFill?: string; + maskInside?: boolean; + outlineColor?: string; + outlineWidth?: number; + series?: Highcharts.IndividualSeriesOptions; + xAxis?: Highcharts.AxisOptions; + yAxis?: Highcharts.AxisOptions; + } + + interface RangeSelectorButton { + type: string; //Defines the timespan, can be one of 'millisecond', 'second', 'minute', 'day', 'week', 'month', 'ytd' (year to date), 'year' and 'all'. + count?: number; + text: string; + dataGrouping?: any; //not sure how this works + } + + interface RangeSelectorOptions { + allButtonsEnabled?: boolean; + buttonSpacing?: number; + buttonTheme?: any; + buttons?: RangeSelectorButton[]; + enabled?: boolean; + inputBoxBorderColor?: string; + inputBoxHeight?: number; + inputBoxWidth?: number; + inputDateFormat?: string; + inputDateParser?: (date: string) => number; + inputEditDateFormat?: string; + inputEnabled?: boolean; + inputPosition?: { + align?: string; + verticalAlign?: string; + x?: number; + y?: number; + }; + inputStyle?: Highcharts.CSSObject; + labelStyle?: Highcharts.CSSObject; + selected?: number; + } + + interface ScrollbarOptions { + barBackgroundColor?: string; + barBorderColor?: string; + barBorderRadius?: number; + barBorderWidth?: number; + buttonArrowColor?: string; + buttonBackgroundColor?: string; + buttonBorderColor?: string; + buttonBorderRadius?: number; + buttonBorderWidth?: number; + enabled?: boolean; + height?: number; + liveRedraw?: boolean; + minWidth?: number; + rifleColor?: string; + trackBackgroundColor?: string; + trackBorderColor?: string; + trackBorderRadius?: number; + trackBorderWidth?: number; + } + + interface Options extends Highcharts.Options { + navigator?: NavigatorOptions; + rangeSelector?: RangeSelectorOptions; + scrollbar?: ScrollbarOptions; + } + + interface Chart { + new (options: Options): ChartObject; + new (options: Options, callback: (chart: ChartObject) => void): ChartObject; + } + + interface Static extends Highcharts.Static { + StockChart: Chart; + } } -interface HighstockNavigatorOptions { - adaptToUpdatedData?: boolean; - baseSeries?: string | number; - enabled?: boolean; - handles?: { - backgroundColor?: string; - borderColor?: string; - }; - height?: number; - margin?: number; - maskFill?: string; - maskInside?: boolean; - outlineColor?: string; - outlineWidth?: number; - series?: HighchartsIndividualSeriesOptions; - xAxis?: HighchartsAxisOptions; - yAxis?: HighchartsAxisOptions; -} - -interface RangeSelectorButton { - type: string; //Defines the timespan, can be one of 'millisecond', 'second', 'minute', 'day', 'week', 'month', 'ytd' (year to date), 'year' and 'all'. - count?: number; - text: string; - dataGrouping?: any; //not sure how this works -} - -interface HighstockRangeSelectorOptions { - allButtonsEnabled?: boolean; - buttonSpacing?: number; - buttonTheme?: any; - buttons?: RangeSelectorButton[]; - enabled?: boolean; - inputBoxBorderColor?: string; - inputBoxHeight?: number; - inputBoxWidth?: number; - inputDateFormat?: string; - inputDateParser?: (date: string) => number; - inputEditDateFormat?: string; - inputEnabled?: boolean; - inputPosition?: { - align?: string; - verticalAlign?: string; - x?: number; - y?: number; - }; - inputStyle?: HighchartsCSSObject; - labelStyle?: HighchartsCSSObject; - selected?: number; -} - -interface HighstockScrollbarOptions { - barBackgroundColor?: string; - barBorderColor?: string; - barBorderRadius?: number; - barBorderWidth?: number; - buttonArrowColor?: string; - buttonBackgroundColor?: string; - buttonBorderColor?: string; - buttonBorderRadius?: number; - buttonBorderWidth?: number; - enabled?: boolean; - height?: number; - liveRedraw?: boolean; - minWidth?: number; - rifleColor?: string; - trackBackgroundColor?: string; - trackBorderColor?: string; - trackBorderRadius?: number; - trackBorderWidth?: number; -} - -interface HighstockOptions extends HighchartsOptions { - navigator?: HighstockNavigatorOptions; - rangeSelector?: HighstockRangeSelectorOptions; - scrollbar?: HighstockScrollbarOptions; -} - -interface HighstockChart { - new (options: HighstockOptions): HighstockChartObject; - new (options: HighstockOptions, callback: (chart: HighstockChartObject) => void): HighstockChartObject; -} - -interface HighchartsStatic { - StockChart: HighstockChart; -} interface JQuery { - highcharts(type: "StockChart"): HighstockChartObject; + highcharts(type: "StockChart"): __Highstock.ChartObject; /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param {HighchartsOptions} options Options for this chart - * @return current {JQuery} selector the current JQuery selector - **/ - highcharts(type: "StockChart", options: HighstockOptions): JQuery; + * Creates a new Highcharts.Chart for the current JQuery selector; usually + * a div selected by $('#container') + * @param {Highcharts.Options} options Options for this chart + * @return current {JQuery} selector the current JQuery selector + **/ + highcharts(type: "StockChart", options: __Highstock.Options): JQuery; /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param {HighchartsOptions} options Options for this chart - * @param callback Callback function used to manipulate the constructed chart instance - * @return current {JQuery} selector the current JQuery selector - **/ - highcharts(type: "StockChart", options: HighstockOptions, callback: (chart: HighstockChartObject) => void): JQuery; + * Creates a new Highcharts.Chart for the current JQuery selector; usually + * a div selected by $('#container') + * @param {Highcharts.Options} options Options for this chart + * @param callback Callback function used to manipulate the constructed chart instance + * @return current {JQuery} selector the current JQuery selector + **/ + highcharts(type: "StockChart", options: __Highstock.Options, callback: (chart: __Highstock.ChartObject) => void): JQuery; - highcharts(type: string): HighchartsChartObject; - highcharts(type: string, options: HighchartsOptions): JQuery; - highcharts(type: string, options: HighchartsOptions, callback: (chart: HighchartsChartObject) => void): JQuery; + highcharts(type: string): Highcharts.ChartObject; + highcharts(type: string, options: Highcharts.Options): JQuery; + highcharts(type: string, options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; } diff --git a/highcharts/index.d.ts b/highcharts/index.d.ts index 2274e221d0..626ff59482 100644 --- a/highcharts/index.d.ts +++ b/highcharts/index.d.ts @@ -3,6364 +3,6482 @@ // Definitions by: Damiano Gambarotto , Dan Lewi Harkestad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface HighchartsPosition { - align?: string; - verticalAlign?: string; - x?: number; - y?: number; -} +declare namespace Highcharts { + interface Position { + align?: string; + verticalAlign?: string; + x?: number; + y?: number; + } -interface HighchartsDateTimeFormats { - /** - * @default '%H:%M:%S.%L' - */ - millisecond?: string; - /** - * @default '%H:%M:%S' - */ - second?: string; - /** - * @default '%H:%M' - */ - minute?: string; - /** - * @default '%H:%M' - */ - hour?: string; - /** - * @default '%e. %b' - */ - day?: string; - /** - * @default '%e. %b' - */ - week?: string; - /** - * @default '%b \ '%y' - */ - month?: string; - /** - * @default '%Y' - */ - year?: string; -} + interface DateTimeFormats { + /** + * @default '%H:%M:%S.%L' + */ + millisecond?: string; + /** + * @default '%H:%M:%S' + */ + second?: string; + /** + * @default '%H:%M' + */ + minute?: string; + /** + * @default '%H:%M' + */ + hour?: string; + /** + * @default '%e. %b' + */ + day?: string; + /** + * @default '%e. %b' + */ + week?: string; + /** + * @default '%b \ '%y' + */ + month?: string; + /** + * @default '%Y' + */ + year?: string; + } -interface HighchartsAxisEvent extends Event { - min: number; - max: number; -} + interface AxisEvent extends Event { + min: number; + max: number; + } -interface HighchartsAxisLabels { - /** - * What part of the string the given position is anchored to. Can be one of 'left', 'center' or 'right'. Defaults to - * an intelligent guess based on which side of the chart the axis is on and the rotation of the label. - * @default 'center' on xAxis, 'right' on yAxis - */ - align?: string; - /** - * For horizontal axes, the allowed degrees of label rotation to prevent overlapping labels. If there is enough - * space, labels are not rotated. As the chart gets narrower, it will start rotating the labels -45 degrees, then - * remove every second label and try again with rotations 0 and -45 etc. Set it to false to disable rotation, which - * will cause the labels to word-wrap if possible. - * @default [-45] - * @since 4.1.0 - */ - autoRotation?: number[]; - /** - * When each category width is more than this many pixels, we don't apply auto rotation. Instead, we lay out the - * axis label with word wrap. A lower limit makes sense when the label contains multiple short words that don't - * extend the available horizontal space for each label. - * @default 80 - * @since 4.1.5 - */ - autoRotationLimit?: number; - /** - * Polar charts only. The label's pixel distance from the perimeter of the plot area. - * @default 15 - */ - distance?: number; - /** - * Enable or disable the axis labels. - * @default true - */ - enabled?: boolean; - /** - * A {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting|format string} for the axis label. - * @default '{value}' - * @since 3.0 - */ - format?: string; - /** - * Callback JavaScript function to format the label. The value is given by this.value. Additional properties for - * this are axis, chart, isFirst and isLast. - * @default function() {return this.value;} - */ - formatter?: () => string; - /** - * Horizontal axis only. When staggerLines is not set, maxStaggerLines defines how many lines the axis is allowed to - * add to automatically avoid overlapping X labels. Set to 1 to disable overlap detection. - * @default 5 - * @since 3.0.3 - * @deprecated - */ - maxStaggerLines?: number; - /** - * How to handle overflowing labels on horizontal axis. Can be undefined, false or 'justify'. By default it aligns - * inside the chart area. If 'justify', labels will not render outside the plot area. If false, it will not be - * aligned at all. If there is room to move it, it will be aligned to the edge, else it will be removed. - * @since 2.2.5 - * @deprecated - */ - overflow?: string|boolean; - /** - * The pixel padding for axis labels, to ensure white space between them. - * @default 5 - */ - padding?: number; - /** - * Whether to reserve space for the labels. This can be turned off when for example the labels are rendered inside - * the plot area instead of outside. - * @default true - * @since 4.1.10 - */ - reserveSpace?: boolean; - /** - * Rotation of the labels in degrees. - * @default 0 - */ - rotation?: number; - /** - * Horizontal axes only. The number of lines to spread the labels over to make room or tighter labels. - * @since 2.1 - */ - staggerLines?: number; - /** - * To show only every n'th label on the axis, set the step to n. Setting the step to 2 shows every other label. By - * default, the step is calculated automatically to avoid overlap. To prevent this, set it to 1. This usually only - * happens on a category axis, and is often a sign that you have chosen the wrong axis type. - * Read more at {@link http://www.highcharts.com/docs/chart-concepts/axes|Axis docs} => What axis should I use? - * @since 2.1 - */ - step?: number; - /** - * CSS styles for the label. Use whiteSpace: 'nowrap' to prevent wrapping of category labels. Use textOverflow: - * 'none' to prevent ellipsis (dots). - * @default {'color':'#6D869F','fontWeight':'bold'}. - */ - style?: HighchartsCSSObject; - /** - * Whether to use HTML to render the labels. - * @default false - */ - useHTML?: boolean; - /** - * The x position offset of the label relative to the tick position on the axis. - * @default 0 - */ - x?: number; - /** - * The y position offset of the label relative to the tick position on the axis. The default makes it adapt to the - * font size on bottom axis. - * @default null - */ - y?: number; - /** - * The Z index for the axis labels. - * @default 7 - */ - zIndex?: number; -} + interface AxisLabels { + /** + * What part of the string the given position is anchored to. Can be one of 'left', 'center' or 'right'. Defaults to + * an intelligent guess based on which side of the chart the axis is on and the rotation of the label. + * @default 'center' on xAxis, 'right' on yAxis + */ + align?: string; + /** + * For horizontal axes, the allowed degrees of label rotation to prevent overlapping labels. If there is enough + * space, labels are not rotated. As the chart gets narrower, it will start rotating the labels -45 degrees, then + * remove every second label and try again with rotations 0 and -45 etc. Set it to false to disable rotation, which + * will cause the labels to word-wrap if possible. + * @default [-45] + * @since 4.1.0 + */ + autoRotation?: number[]; + /** + * When each category width is more than this many pixels, we don't apply auto rotation. Instead, we lay out the + * axis label with word wrap. A lower limit makes sense when the label contains multiple short words that don't + * extend the available horizontal space for each label. + * @default 80 + * @since 4.1.5 + */ + autoRotationLimit?: number; + /** + * Polar charts only. The label's pixel distance from the perimeter of the plot area. + * @default 15 + */ + distance?: number; + /** + * Enable or disable the axis labels. + * @default true + */ + enabled?: boolean; + /** + * A {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting|format string} for the axis label. + * @default '{value}' + * @since 3.0 + */ + format?: string; + /** + * Callback JavaScript function to format the label. The value is given by this.value. Additional properties for + * this are axis, chart, isFirst and isLast. + * @default function() {return this.value;} + */ + formatter?: () => string; + /** + * Horizontal axis only. When staggerLines is not set, maxStaggerLines defines how many lines the axis is allowed to + * add to automatically avoid overlapping X labels. Set to 1 to disable overlap detection. + * @default 5 + * @since 3.0.3 + * @deprecated + */ + maxStaggerLines?: number; + /** + * How to handle overflowing labels on horizontal axis. Can be undefined, false or 'justify'. By default it aligns + * inside the chart area. If 'justify', labels will not render outside the plot area. If false, it will not be + * aligned at all. If there is room to move it, it will be aligned to the edge, else it will be removed. + * @since 2.2.5 + * @deprecated + */ + overflow?: string | boolean; + /** + * The pixel padding for axis labels, to ensure white space between them. + * @default 5 + */ + padding?: number; + /** + * Whether to reserve space for the labels. This can be turned off when for example the labels are rendered inside + * the plot area instead of outside. + * @default true + * @since 4.1.10 + */ + reserveSpace?: boolean; + /** + * Rotation of the labels in degrees. + * @default 0 + */ + rotation?: number; + /** + * Horizontal axes only. The number of lines to spread the labels over to make room or tighter labels. + * @since 2.1 + */ + staggerLines?: number; + /** + * To show only every n'th label on the axis, set the step to n. Setting the step to 2 shows every other label. By + * default, the step is calculated automatically to avoid overlap. To prevent this, set it to 1. This usually only + * happens on a category axis, and is often a sign that you have chosen the wrong axis type. + * Read more at {@link http://www.highcharts.com/docs/chart-concepts/axes|Axis docs} => What axis should I use? + * @since 2.1 + */ + step?: number; + /** + * CSS styles for the label. Use whiteSpace: 'nowrap' to prevent wrapping of category labels. Use textOverflow: + * 'none' to prevent ellipsis (dots). + * @default {'color':'#6D869F','fontWeight':'bold'}. + */ + style?: CSSObject; + /** + * Whether to use HTML to render the labels. + * @default false + */ + useHTML?: boolean; + /** + * The x position offset of the label relative to the tick position on the axis. + * @default 0 + */ + x?: number; + /** + * The y position offset of the label relative to the tick position on the axis. The default makes it adapt to the + * font size on bottom axis. + * @default null + */ + y?: number; + /** + * The Z index for the axis labels. + * @default 7 + */ + zIndex?: number; + } -interface HighchartsMousePlotEvents { - click?: (event: Event) => void; - mouseover?: (event: Event) => void; - mouseout?: (event: Event) => void; - mousemove?: (event: Event) => void; -} + interface MousePlotEvents { + click?: (event: Event) => void; + mouseover?: (event: Event) => void; + mouseout?: (event: Event) => void; + mousemove?: (event: Event) => void; + } -/** - * Text labels for the plot bands - */ -interface HighchartsPlotLabel { - /** - * Horizontal alignment of the label. Can be one of 'left', 'center' or 'right'. - * @default 'center' - * @since 2.1 - */ - align?: string; - /** - * Rotation of the text label in degrees. - * @default 0 - * @since 2.1 - */ - rotation?: number; - /** - * CSS styles for the text label. - * @since 2.1 - */ - style?: HighchartsCSSObject; - /** - * The string text itself. A subset of HTML is supported. - * @since 2.1 - */ - text?: string; - /** - * The text alignment for the label. While align determines where the texts anchor point is placed within the plot - * band, textAlign determines how the text is aligned against its anchor point. Possible values are 'left', 'center' - * and 'right'. Defaults to the same as the align option. - * @since 2.1 - */ - textAlign?: string; - /** - * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the labels. - * @default false - * @since 3.0.3 - */ - useHTML?: boolean; - /** - * Vertical alignment of the label relative to the plot band. Can be one of 'top', 'middle' or 'bottom'. - * @default 'top' - * @since 2.1 - */ - verticalAlign?: string; - /** - * Horizontal position relative the alignment. Default varies by orientation. - * @since 2.1 - */ - x?: number; - /** - * Vertical position of the text baseline relative to the alignment. Default varies by orientation. - * @since 2.1 - */ - y?: number; -} - -interface HighchartsPlotBands { - /** - * Border color for the plot band. Also requires borderWidth to be set. - * @default null - */ - borderColor?: Color; - /** - * Border width for the plot band. Also requires borderColor to be set. - * @default 0 - */ - borderWidth?: number; - /** - * The color of the plot band. - */ - color?: Color; - /** - * An object defining mouse events for the plot band. Supported properties are click, mouseover, mouseout, - * mousemove. - * The this keyword refers to the PlotLineOrBand object. - * @since 1.2 - */ - events?: HighchartsMousePlotEvents; - /** - * The start position of the plot band in axis units. - */ - from?: number; - /** - * An id used for identifying the plot band in Axis.removePlotBand. - */ - id?: string; - /** - * In a gauge chart, this option determines the inner radius of the plot band that stretches along the perimeter. It - * can be given as a percentage string, like '100%', or as a pixel number, like 100. By default, the inner radius is - * controlled by the thickness option. - * Only defined for yAxis.plotBands - * @default null - * @since 2.3 - */ - innerRadius?: number|string; /** * Text labels for the plot bands */ - label?: HighchartsPlotLabel; - /** - * In a gauge chart, this option determines the outer radius of the plot band that stretches along the perimeter. It - * can be given as a percentage string, like '100%', or as a pixel number, like 100. - * Only defined for yAxis.plotBands - * @default '100%' - * @since 2.3 - */ - outerRadius?: number|string; - /** - * In a gauge chart, this option sets the width of the plot band stretching along the perimeter. It can be given as - * a percentage string, like '10%', or as a pixel number, like 10. The default value 10 is the same as the default - * tickLength, thus making the plot band act as a background for the tick markers. - * Only defined for yAxis.plotBands - * @default 10 - * @since 2.3 - */ - thickness?: number|string; - /** - * The end position of the plot band in axis units. - */ - to?: number; - /** - * The z index of the plot band within the chart, relative to other elements. Using the same z index as another - * element may give unpredictable results, as the last rendered element will be on top. Values from 0 to 20 make - * sense. - * @since 1.2 - */ - zIndex?: number; -} - -/** - * An array of lines stretching across the plot area, marking a specific value - * on one of the axes. - */ -interface HighchartsPlotLines { - /** - * The color of the line. - */ - color?: string | HighchartsGradient; - /** - * The dashing or dot style for the plot line. For possible values see - * {@link http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/|this overview}. - * (Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot) - * @default 'Solid' - * @since 1.2 - */ - dashStyle?: string; - /** - * An object defining mouse events for the plot line. Supported properties are click, mouseover, mouseout, - * mousemove. - * The this keyword refers to the PlotLineOrBand object. - * @since 1.2 - */ - events?: HighchartsMousePlotEvents; - /** - * An id used for identifying the plot line in Axis.removePlotLine. - */ - id?: string; - /** - * Text labels for the plot lines - */ - label?: HighchartsPlotLabel; - /** - * The position of the line in axis units. - */ - value?: number; - /** - * The width or thickness of the plot line. - */ - width?: number; - /** - * The z index of the plot line within the chart. - * @since 1.2 - */ - zIndex?: number; -} - -interface HighchartsAxisTitle { - /** - * Alignment of the title relative to the axis values. Possible values are 'low', 'middle' or 'high'. - * @default 'middle' - */ - align?: string; - /** - * Set the text to null to disable the title. - * @default 'middle' - * @deprecated - */ - enabled?: string; - /** - * The pixel distance between the axis labels or line and the title. - * @default xAxis: 0 for horizontal axes, 10 for vertical axes, yAxis: 40 - */ - margin?: number; - /** - * The distance of the axis title from the axis line. By default, this distance is computed from the offset width of - * the labels, the labels' distance from the axis and the title's margin. However when the offset option is set, it - * overrides all this. - * @since 2.2.0 - */ - offset?: number; - /** - * The rotation of the text in degrees. 0 is horizontal, 270 is vertical reading from bottom to top. - * @default xAxis: 0, yAxis: 270 - */ - rotation?: number; - /** - * CSS styles for the title. When titles are rotated they are rendered using vector graphic techniques and not all - * styles are applicable. - * @default { 'color': '#707070', 'fontWeight': 'bold' }. - */ - style?: HighchartsCSSObject; - /** - * The actual text of the axis title. It can contain basic HTML text markup like , and spans with style. - * @default xAxis: null, yAxis: 'Values' - */ - text?: string; - /** - * Horizontal pixel offset of the title position. - * @default 0 - * @since 4.1.6 - */ - x?: number; - /** - * Vertical pixel offset of the title position. - */ - y?: number; -} - -interface HighchartsAxisBreak { - /** - * A number indicating how much space should be left between the start and the end of the break. The break size is - * given in axis units, so for instance on a datetime axis, a break size of 3600000 would indicate the equivalent of - * an hour. - * @default 0 - * @since 4.1.0 - */ - breakSize?: number; - /** - * The point where the break starts. - * @since 4.1.0 - */ - from?: number; - /** - * Defines an interval after which the break appears again. By default the breaks do not repeat. - * @default 0 - * @since 4.1.0 - */ - repeat?: number; - /** - * The point where the break ends. - * @since 4.1.0 - */ - to?: number; -} - -interface HighchartsAxisOptions { - /** - * Whether to allow decimals in this axis' ticks. When counting integers, - * like persons or hits on a web page, decimals must be avoided in the axis - * tick labels. - * @default true - * @since 2.0 - */ - allowDecimals?: boolean; - /** - * When using an alternate grid color, a band is painted across the plot - * area between every other grid line. - */ - alternateGridColor?: string; - /** - * An array defining breaks in the axis, the sections defined will be left out and all the points shifted closer to - * each other. Requires that the broken-axis.js module is loaded. - * @since 4.1.0 - */ - breaks?: HighchartsAxisBreak[]; - /** - * If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highcharts 3.0, - * categories can also be extracted by giving each point a name and setting axis type to category. However, if you - * have multiple series, best practice remains defining the categories array. - * Example: - * categories: ['Apples', 'Bananas', 'Oranges'] - * @default null - */ - categories?: string[]; - /** - * The highest allowed value for automatically computed axis extremes. - * @since 4.0 - */ - ceiling?: number; - /** - * Configure a crosshair that follows either the mouse pointer or the hovered point. - */ - crosshair?: HighchartsCrosshairObject | boolean; - /** - * For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default - * string representations used for each unit. For an overview of the replacement codes, see dateFormat. - */ - dateTimeLabelFormats?: HighchartsDateTimeFormats; - /** - * Whether to force the axis to end on a tick. Use this option with the maxPadding option to control the axis end. - * @default false - */ - endOnTick?: boolean; - /** - * Event handlers for the axis - */ - events?: { + interface PlotLabel { /** - * An event fired after the breaks have rendered. - * @since 4.1.0 + * Horizontal alignment of the label. Can be one of 'left', 'center' or 'right'. + * @default 'center' + * @since 2.1 */ - afterBreaks?: (event: Event) => void; + align?: string; /** - * As opposed to the setExtremes event, this event fires after the final min and max values are computed and - * corrected for minRange. - * The this keyword refers to the {@link HighchartsAxisObject|Axis} object. + * Rotation of the text label in degrees. + * @default 0 + * @since 2.1 + */ + rotation?: number; + /** + * CSS styles for the text label. + * @since 2.1 + */ + style?: CSSObject; + /** + * The string text itself. A subset of HTML is supported. + * @since 2.1 + */ + text?: string; + /** + * The text alignment for the label. While align determines where the texts anchor point is placed within the plot + * band, textAlign determines how the text is aligned against its anchor point. Possible values are 'left', 'center' + * and 'right'. Defaults to the same as the align option. + * @since 2.1 + */ + textAlign?: string; + /** + * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the labels. + * @default false + * @since 3.0.3 + */ + useHTML?: boolean; + /** + * Vertical alignment of the label relative to the plot band. Can be one of 'top', 'middle' or 'bottom'. + * @default 'top' + * @since 2.1 + */ + verticalAlign?: string; + /** + * Horizontal position relative the alignment. Default varies by orientation. + * @since 2.1 + */ + x?: number; + /** + * Vertical position of the text baseline relative to the alignment. Default varies by orientation. + * @since 2.1 + */ + y?: number; + } + + interface PlotBands { + /** + * Border color for the plot band. Also requires borderWidth to be set. + * @default null + */ + borderColor?: Color; + /** + * Border width for the plot band. Also requires borderColor to be set. + * @default 0 + */ + borderWidth?: number; + /** + * The color of the plot band. + */ + color?: Color; + /** + * An object defining mouse events for the plot band. Supported properties are click, mouseover, mouseout, + * mousemove. + * The this keyword refers to the PlotLineOrBand object. + * @since 1.2 + */ + events?: MousePlotEvents; + /** + * The start position of the plot band in axis units. + */ + from?: number; + /** + * An id used for identifying the plot band in Axis.removePlotBand. + */ + id?: string; + /** + * In a gauge chart, this option determines the inner radius of the plot band that stretches along the perimeter. It + * can be given as a percentage string, like '100%', or as a pixel number, like 100. By default, the inner radius is + * controlled by the thickness option. + * Only defined for yAxis.plotBands + * @default null * @since 2.3 */ - afterSetExtremes?: (event: HighchartsAxisEvent) => void; + innerRadius?: number | string; /** - * An event fired when a break from this axis occurs on a point. - * The this keyword refers to the {@link HighchartsAxisObject|Axis} object. + * Text labels for the plot bands */ - pointBreak?: (event: Event) => void; + label?: PlotLabel; /** - * Fires when the minimum and maximum is set for the axis, either by calling the .setExtremes() method or by - * selecting an area in the chart. One parameter, event, is passed to the function. This contains common event - * information based on jQuery or MooTools depending on which library is used as the base for Highcharts. - * - * The new user set minimum and maximum values can be found by event.min and event.max. When an axis is zoomed - * all the way out from the 'Reset zoom' button, event.min and event.max are null, and the new extremes are set - * based on this.dataMin and this.dataMax. - * - * The this keyword refers to the {@link HighchartsAxisObject|Axis} object. + * In a gauge chart, this option determines the outer radius of the plot band that stretches along the perimeter. It + * can be given as a percentage string, like '100%', or as a pixel number, like 100. + * Only defined for yAxis.plotBands + * @default '100%' + * @since 2.3 + */ + outerRadius?: number | string; + /** + * In a gauge chart, this option sets the width of the plot band stretching along the perimeter. It can be given as + * a percentage string, like '10%', or as a pixel number, like 10. The default value 10 is the same as the default + * tickLength, thus making the plot band act as a background for the tick markers. + * Only defined for yAxis.plotBands + * @default 10 + * @since 2.3 + */ + thickness?: number | string; + /** + * The end position of the plot band in axis units. + */ + to?: number; + /** + * The z index of the plot band within the chart, relative to other elements. Using the same z index as another + * element may give unpredictable results, as the last rendered element will be on top. Values from 0 to 20 make + * sense. + * @since 1.2 + */ + zIndex?: number; + } + + /** + * An array of lines stretching across the plot area, marking a specific value + * on one of the axes. + */ + interface PlotLines { + /** + * The color of the line. + */ + color?: string | Gradient; + /** + * The dashing or dot style for the plot line. For possible values see + * {@link http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/|this overview}. + * (Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot) + * @default 'Solid' + * @since 1.2 + */ + dashStyle?: string; + /** + * An object defining mouse events for the plot line. Supported properties are click, mouseover, mouseout, + * mousemove. + * The this keyword refers to the PlotLineOrBand object. + * @since 1.2 + */ + events?: MousePlotEvents; + /** + * An id used for identifying the plot line in Axis.removePlotLine. + */ + id?: string; + /** + * Text labels for the plot lines + */ + label?: PlotLabel; + /** + * The position of the line in axis units. + */ + value?: number; + /** + * The width or thickness of the plot line. + */ + width?: number; + /** + * The z index of the plot line within the chart. + * @since 1.2 + */ + zIndex?: number; + } + + interface AxisTitle { + /** + * Alignment of the title relative to the axis values. Possible values are 'low', 'middle' or 'high'. + * @default 'middle' + */ + align?: string; + /** + * Set the text to null to disable the title. + * @default 'middle' + * @deprecated + */ + enabled?: string; + /** + * The pixel distance between the axis labels or line and the title. + * @default xAxis: 0 for horizontal axes, 10 for vertical axes, yAxis: 40 + */ + margin?: number; + /** + * The distance of the axis title from the axis line. By default, this distance is computed from the offset width of + * the labels, the labels' distance from the axis and the title's margin. However when the offset option is set, it + * overrides all this. + * @since 2.2.0 + */ + offset?: number; + /** + * The rotation of the text in degrees. 0 is horizontal, 270 is vertical reading from bottom to top. + * @default xAxis: 0, yAxis: 270 + */ + rotation?: number; + /** + * CSS styles for the title. When titles are rotated they are rendered using vector graphic techniques and not all + * styles are applicable. + * @default { 'color': '#707070', 'fontWeight': 'bold' }. + */ + style?: CSSObject; + /** + * The actual text of the axis title. It can contain basic HTML text markup like , and spans with style. + * @default xAxis: null, yAxis: 'Values' + */ + text?: string; + /** + * Horizontal pixel offset of the title position. + * @default 0 + * @since 4.1.6 + */ + x?: number; + /** + * Vertical pixel offset of the title position. + */ + y?: number; + } + + interface AxisBreak { + /** + * A number indicating how much space should be left between the start and the end of the break. The break size is + * given in axis units, so for instance on a datetime axis, a break size of 3600000 would indicate the equivalent of + * an hour. + * @default 0 + * @since 4.1.0 + */ + breakSize?: number; + /** + * The point where the break starts. + * @since 4.1.0 + */ + from?: number; + /** + * Defines an interval after which the break appears again. By default the breaks do not repeat. + * @default 0 + * @since 4.1.0 + */ + repeat?: number; + /** + * The point where the break ends. + * @since 4.1.0 + */ + to?: number; + } + + interface AxisOptions { + /** + * Whether to allow decimals in this axis' ticks. When counting integers, + * like persons or hits on a web page, decimals must be avoided in the axis + * tick labels. + * @default true + * @since 2.0 + */ + allowDecimals?: boolean; + /** + * When using an alternate grid color, a band is painted across the plot + * area between every other grid line. + */ + alternateGridColor?: string; + /** + * An array defining breaks in the axis, the sections defined will be left out and all the points shifted closer to + * each other. Requires that the broken-axis.js module is loaded. + * @since 4.1.0 + */ + breaks?: AxisBreak[]; + /** + * If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highcharts 3.0, + * categories can also be extracted by giving each point a name and setting axis type to category. However, if you + * have multiple series, best practice remains defining the categories array. + * Example: + * categories: ['Apples', 'Bananas', 'Oranges'] + * @default null + */ + categories?: string[]; + /** + * The highest allowed value for automatically computed axis extremes. + * @since 4.0 + */ + ceiling?: number; + /** + * Configure a crosshair that follows either the mouse pointer or the hovered point. + */ + crosshair?: CrosshairObject | boolean; + /** + * For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default + * string representations used for each unit. For an overview of the replacement codes, see dateFormat. + */ + dateTimeLabelFormats?: DateTimeFormats; + /** + * Whether to force the axis to end on a tick. Use this option with the maxPadding option to control the axis end. + * @default false + */ + endOnTick?: boolean; + /** + * Event handlers for the axis + */ + events?: { + /** + * An event fired after the breaks have rendered. + * @since 4.1.0 + */ + afterBreaks?: (event: Event) => void; + /** + * As opposed to the setExtremes event, this event fires after the final min and max values are computed and + * corrected for minRange. + * The this keyword refers to the {@link AxisObject|Axis} object. + * @since 2.3 + */ + afterSetExtremes?: (event: AxisEvent) => void; + /** + * An event fired when a break from this axis occurs on a point. + * The this keyword refers to the {@link AxisObject|Axis} object. + */ + pointBreak?: (event: Event) => void; + /** + * Fires when the minimum and maximum is set for the axis, either by calling the .setExtremes() method or by + * selecting an area in the chart. One parameter, event, is passed to the function. This contains common event + * information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * + * The new user set minimum and maximum values can be found by event.min and event.max. When an axis is zoomed + * all the way out from the 'Reset zoom' button, event.min and event.max are null, and the new extremes are set + * based on this.dataMin and this.dataMax. + * + * The this keyword refers to the {@link AxisObject|Axis} object. + * @since 1.2.0 + */ + setExtremes?: (event: AxisEvent) => void; + }; + /** + * The lowest allowed value for automatically computed axis extremes. + * @default null + * @since 4.0 + */ + floor?: number; + /** + * Color of the grid lines extending the ticks across the plot area. + * @defaults to '#D8D8D8'. + */ + gridLineColor?: string; + /** + * The dash or dot style of the grid lines. For possible values, see {@http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/|this demonstration}. Defaults to Solid. + * @since 1.2 + */ + gridLineDashStyle?: string; + /** + * The width of the grid lines extending the ticks across the plot area. + * @default 0 + */ + gridLineWidth?: number; + /** + * The Z index of the grid lines. + * @default 1 + */ + gridZIndex?: number; + /** + * An id for the axis. This can be used after render time to get a pointer to the axis object through chart.get(). * @since 1.2.0 */ - setExtremes?: (event: HighchartsAxisEvent) => void; - }; - /** - * The lowest allowed value for automatically computed axis extremes. - * @default null - * @since 4.0 - */ - floor?: number; - /** - * Color of the grid lines extending the ticks across the plot area. - * @defaults to '#D8D8D8'. - */ - gridLineColor?: string; - /** - * The dash or dot style of the grid lines. For possible values, see {@http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/|this demonstration}. Defaults to Solid. - * @since 1.2 - */ - gridLineDashStyle?: string; - /** - * The width of the grid lines extending the ticks across the plot area. - * @default 0 - */ - gridLineWidth?: number; - /** - * The Z index of the grid lines. - * @default 1 - */ - gridZIndex?: number; - /** - * An id for the axis. This can be used after render time to get a pointer to the axis object through chart.get(). - * @since 1.2.0 - */ - id?: string; - /** - * The axis labels show the number or category for each tick. - */ - labels?: HighchartsAxisLabels; - /** - * The color of the line marking the axis itself. - * @default '#C0D0E0'. - */ - lineColor?: string | HighchartsGradient; - /** - * The width of the line marking the axis itself. - * @default 1 - */ - lineWidth?: number; - /** - * Index of another axis that this axis is linked to. When an axis is linked to a master axis, it will take the same - * extremes as the master, but as assigned by min or max or by setExtremes. It can be used to show additional info, - * or to ease reading the chart by duplicating the scales. - * @since 2.0.2 - */ - linkedTo?: number; - /** - * The maximum value of the axis. If null, the max value is automatically calculated. If the endOnTick option is - * true, the max value might be rounded up. The actual maximum value is also influenced by chart.alignTicks. - */ - max?: number; - /** - * Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. - * This is useful when you don't want the highest data value to appear on the edge of the plot area. When the axis' - * max option is set or a max extreme is set using axis.setExtremes(), the maxPadding will be ignored. - * @default 0.01 - * @since 1.2.0 - */ - maxPadding?: number; - /** - * Renamed to minRange as of Highcharts 2.2. - * @deprecated - */ - maxZoom?: number; - /** - * The minimum value of the axis. If null the min value is automatically calculated. If the startOnTick option is - * true, the min value might be rounded down. - */ - min?: number; - /** - * Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. - * This is useful when you don't want the lowest data value to appear on the edge of the plot area. When the axis' - * min option is set or a min extreme is set using axis.setExtremes(), the minPadding will be ignored. - * @default 0.01 - * @since 1.2.0 - */ - minPadding?: number; - /** - * The minimum range to display on this axis. The entire axis will not be allowed to span over a smaller interval - * than this. For example, for a datetime axis the main unit is milliseconds. If minRange is set to 3600000, you - * can't zoom in more than to one hour. - * - * The default minRange for the x axis is five times the smallest interval between any of the data points. - * - * On a logarithmic axis, the unit for the minimum range is the power. So a minRange of 1 means that the axis can be - * zoomed to 10-100, 100-1000, 1000-10000 etc. - * - * Note that the minPadding, maxPadding, startOnTick and endOnTick settings also affect how the extremes of the axis - * are computed. - */ - minRange?: number; - /** - * The minimum tick interval allowed in axis values. For example on zooming in on an axis with daily data, this can - * be used to prevent the axis from showing hours. Defaults to the closest distance between two points on the axis. - * @since 2.3.0 - */ - minTickInterval?: number; - /** - * Color of the minor, secondary grid lines. - * @default '#E0E0E0' - */ - minorGridLineColor?: string; - /** - * The dash or dot style of the minor grid lines. For possible values, see {@link http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/|this demonstration}. - * @default 'Solid' - */ - minorGridLineDashStyle?: string; - /** - * Width of the minor, secondary grid lines. - * @default 1 - */ - minorGridLineWidth?: number; - /** - * Color for the minor tick marks. - * @default to '#A0A0A0' - */ - minorTickColor?: string; - /** - * Tick interval in scale units for the minor ticks. On a linear axis, if 'auto', the minor tick interval is - * calculated as a fifth of the tickInterval. If null, minor ticks are not shown. - * - * On logarithmic axes, the unit is the power of the value. For example, setting the minorTickInterval to 1 puts one - * tick on each of 0.1, 1, 10, 100 etc. Setting the minorTickInterval to 0.1 produces 9 ticks between 1 and 10, 10 - * and 100 etc. A minorTickInterval of 'auto' on a log axis results in a best guess, attempting to enter - * approximately 5 minor ticks between each major tick. - * - * If user settings dictate minor ticks to become too dense, they don't make sense, and will be ignored to prevent - * performance problems. - * - * On axes using categories, minor ticks are not supported. - */ - minorTickInterval?: number|string; - /** - * The pixel length of the minor tick marks. - * @default 2 - */ - minorTickLength?: number; - /** - * The position of the minor tick marks relative to the axis line. Can be one of 'inside' and 'outside'. - * @default 'outside' - */ - minorTickPosition?: string; - /** - * The pixel width of the minor tick mark. - * @default 0 - */ - minorTickWidth?: number; - /** - * The distance in pixels from the plot area to the axis line. A positive offset moves the axis with it's line, - * labels and ticks away from the plot area. This is typically used when two or more axes are displayed on the same - * side of the plot. - * @default 0 - */ - offset?: number; - /** - * Whether to display the axis on the opposite side of the normal. The normal is on the left side for vertical axes - * and bottom for horizontal, so the opposite sides will be right and top respectively. This is typically used with - * dual or multiple axes. - * @default false - */ - opposite?: boolean; - /** - * An array of colored bands stretching across the plot area marking an interval on the axis. - * - * In a gauge, a plot band on the Y axis (value axis) will stretch along the perimeter of the gauge. - */ - plotBands?: HighchartsPlotBands[]; - /** - * An array of lines stretching across the plot area, marking a specific value on one of the axes. - */ - plotLines?: HighchartsPlotLines[]; - /** - * Whether to reverse the axis so that the highest number is closest to the origin. If the chart is inverted, the x - * axis is reversed by default. - * @default false - */ - reversed?: boolean; - /** - * Whether to show the axis line and title when the axis has no data. - * @default true - * @since 1.1 - */ - showEmpty?: boolean; - /** - * Whether to show the first tick label. - * @default true - */ - showFirstLabel?: boolean; - /** - * Whether to show the last tick label. - * @default true - */ - showLastLabel?: boolean; - /** - * For datetime axes, this decides where to put the tick between weeks. 0 = Sunday, 1 = Monday. - * @default 1 - */ - startOfWeek?: number; - /** - * Whether to force the axis to start on a tick. Use this option with the minPadding option to control the axis - * start. - * @default false - * @since 1.2.0 - */ - startOnTick?: boolean; - /** - * The amount of ticks to draw on the axis. This opens up for aligning the ticks of multiple charts or panes within - * a chart. This option overrides the tickPixelInterval option. - * - * This option only has an effect on linear axes. Datetime, logarithmic or category axes are not affected. - */ - tickAmount?: number; - /** - * Color for the main tick marks. - * @default '#C0D0E0' - */ - tickColor?: string; - /** - * The interval of the tick marks in axis units. When null, the tick interval is computed to approximately follow - * the tickPixelInterval on linear and datetime axes. On categorized axes, a null tickInterval will default to 1, - * one category. Note that datetime axes are based on milliseconds, so for example an interval of one day is - * expressed as 24 * 3600 * 1000. - * - * On logarithmic axes, the tickInterval is based on powers, so a tickInterval of 1 means one tick on each of 0.1, - * 1, 10, 100 etc. A tickInterval of 2 means a tick of 0.1, 10, 1000 etc. A tickInterval of 0.2 puts a tick on 0.1, - * 0.2, 0.4, 0.6, 0.8, 1, 2, 4, 6, 8, 10, 20, 40 etc. - * - * If the tickInterval is too dense for labels to be drawn, Highcharts may remove ticks. - */ - tickInterval?: number; - /** - * The pixel length of the main tick marks. - * @default 10 - */ - tickLength?: number; - /** - * If tickInterval is null this option sets the approximate pixel interval of the tick marks. Not applicable to - * categorized axis. - * - * @default 72 for the Y axis, 100 for the X axis. - */ - tickPixelInterval?: number; - /** - * The position of the major tick marks relative to the axis line. Can be one of 'inside' and 'outside'. - * @default 'outside' - */ - tickPosition?: string; - /** - * A callback function returning array defining where the ticks are laid out on the axis. This overrides the default - * behaviour of tickPixelInterval and tickInterval. The automatic tick positions are accessible through - * this.tickPositions and can be modified by the callback. - */ - tickPositioner?: (min: number, max: number) => void; - /** - * An array defining where the ticks are laid out on the axis. This overrides the default behaviour of - * tickPixelInterval and tickInterval. - */ - tickPositions?: number[]; - /** - * The pixel width of the major tick marks. - * @default 1 - */ - tickWidth?: number; - /** - * For categorized axes only. If 'on' the tick mark is placed in the center of the category, if 'between' the tick - * mark is placed between categories. The default is 'between' if the tickInterval is 1, else 'on'. - * @default null - */ - tickmarkPlacement?: string; - /** - * The axis title, showing next to the axis line. - */ - title?: HighchartsAxisTitle; - /** - * The type of axis. Can be one of 'linear', 'logarithmic', 'datetime' or 'category'. In a datetime axis, the - * numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days. In a - * category axis, the point names of the chart's series are used for categories, if not a categories array is - * defined. - * @default 'linear' - */ - type?: string; - /** - * Datetime axis only. An array determining what time intervals the ticks are allowed to fall on. Each array item is - * an array where the first value is the time unit and the second value another array of allowed multiples. - */ - units?: [[string, [number]]]; - /** - * Whether axis, including axis title, line, ticks and labels, should be visible. - * @default true - * @since 4.1.9 - */ - visible?: boolean; -} - -interface HighchartsColorAxisDataClass { - from?: number; - to?: number; - color?: string | HighchartsGradient; - name?: string; -} - -/** - * A color axis for choropleth mapping. Visually, the color axis will appear as a gradient or as separate items inside - * the legend, depending on whether the axis is scalar or based on data classes. - * - * For supported color formats, see the docs article about colors. - * - * A scalar color axis is represented by a gradient. The colors either range between the minColor and the maxColor, or - * for more fine grained control the colors can be defined in stops. Often times, the color axis needs to be adjusted to - * get the right color spread for the data. In addition to stops, consider using a logarithmic axis type, or setting min - * and max to avoid the colors being determined by outliers. - * - * When dataClasses are used, the ranges are subdivided into separate classes like categories based on their values. - * This can be used for ranges between two values, but also for a true category. However, when your data is categorized, - * it may be as convenient to add each category to a separate series. - * - * See the Axis object for programmatic access to the axis. - */ -interface HighchartsColorAxisOptions { - /** - * Determines how to set each data class' color if no individual color is set. The default value, tween, computes - * intermediate colors between minColor and maxColor. The other possible value, category, pulls colors from the - * global or chart specific colors array. - * @default 'tween' - */ - dataClassColor?: string; - /** - * An array of data classes or ranges for the choropleth map. If none given, the color axis is scalar and values are - * distributed as a gradient between the minimum and maximum colors. - */ - dataClasses?: HighchartsColorAxisDataClass[]; - /** - * Whether to force the axis to end on a tick. Use this option with the maxPadding option to control the axis end. - * @default true - */ - endOnTick?: boolean; - events?: { + id?: string; /** - * As opposed to the setExtremes event, this event fires after the final min and max values are computed and - * corrected for minRange. - * The this keyword refers to the {@link HighchartsAxisObject|Axis} object. + * The axis labels show the number or category for each tick. */ - afterSetExtremes?: (event: HighchartsAxisEvent) => void; + labels?: AxisLabels; /** - * Fires when the minimum and maximum is set for the axis, either by calling the .setExtremes() method or by - * selecting an area in the chart. One parameter, event, is passed to the function. This contains common event - * information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * The color of the line marking the axis itself. + * @default '#C0D0E0'. + */ + lineColor?: string | Gradient; + /** + * The width of the line marking the axis itself. + * @default 1 + */ + lineWidth?: number; + /** + * Index of another axis that this axis is linked to. When an axis is linked to a master axis, it will take the same + * extremes as the master, but as assigned by min or max or by setExtremes. It can be used to show additional info, + * or to ease reading the chart by duplicating the scales. + * @since 2.0.2 + */ + linkedTo?: number; + /** + * The maximum value of the axis. If null, the max value is automatically calculated. If the endOnTick option is + * true, the max value might be rounded up. The actual maximum value is also influenced by chart.alignTicks. + */ + max?: number; + /** + * Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. + * This is useful when you don't want the highest data value to appear on the edge of the plot area. When the axis' + * max option is set or a max extreme is set using axis.setExtremes(), the maxPadding will be ignored. + * @default 0.01 + * @since 1.2.0 + */ + maxPadding?: number; + /** + * Renamed to minRange as of Highcharts 2.2. + * @deprecated + */ + maxZoom?: number; + /** + * The minimum value of the axis. If null the min value is automatically calculated. If the startOnTick option is + * true, the min value might be rounded down. + */ + min?: number; + /** + * Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. + * This is useful when you don't want the lowest data value to appear on the edge of the plot area. When the axis' + * min option is set or a min extreme is set using axis.setExtremes(), the minPadding will be ignored. + * @default 0.01 + * @since 1.2.0 + */ + minPadding?: number; + /** + * The minimum range to display on this axis. The entire axis will not be allowed to span over a smaller interval + * than this. For example, for a datetime axis the main unit is milliseconds. If minRange is set to 3600000, you + * can't zoom in more than to one hour. * - * The new user set minimum and maximum values can be found by event.min and event.max. When an axis is zoomed - * all the way out from the 'Reset zoom' button, event.min and event.max are null, and the new extremes are set - * based on this.dataMin and this.dataMax. + * The default minRange for the x axis is five times the smallest interval between any of the data points. * - * The this keyword refers to the {@link HighchartsAxisObject|Axis} object. + * On a logarithmic axis, the unit for the minimum range is the power. So a minRange of 1 means that the axis can be + * zoomed to 10-100, 100-1000, 1000-10000 etc. + * + * Note that the minPadding, maxPadding, startOnTick and endOnTick settings also affect how the extremes of the axis + * are computed. */ - setExtremes?: (event: HighchartsAxisEvent) => void; - }; - /** - * Color of the grid lines extending from the axis across the gradient. - * @default '#C0C0C0' - */ - gridLineColor?: string; - /** - * The dash or dot style of the grid lines. - * @default 'Solid' - */ - gridLineDashStyle?: string; - /** - * The width of the grid lines extending from the axis across the gradient of a scalar color axis. - * @default 1 - */ - gridLineWidth?: number; - /** - * An id for the axis. This can be used after render time to get a pointer to the axis object through chart.get(). - */ - id?: string; - /** - * The axis labels show the number for each tick. - */ - labels?: HighchartsAxisLabels; - /** - * The color of the line marking the axis itself. - * @default '#C0D0E0' - */ - lineColor?: string | HighchartsGradient; - /** - * The width of the line marking the axis itself. - * @default 0 - */ - lineWidth?: number; - /** - * The triangular marker on a scalar color axis that points to the value of the hovered area. To disable the marker, - * set marker: null. - */ - marker?: { + minRange?: number; /** - * Animation for the marker as it moves between values. Set to false to disable animation. - * @default {duration: 50} + * The minimum tick interval allowed in axis values. For example on zooming in on an axis with daily data, this can + * be used to prevent the axis from showing hours. Defaults to the closest distance between two points on the axis. + * @since 2.3.0 */ - animation?: boolean | HighchartsAnimation; + minTickInterval?: number; /** - * The color of the marker. - * @default 'gray' + * Color of the minor, secondary grid lines. + * @default '#E0E0E0' */ - color?: string | HighchartsGradient; - }; - /** - * The maximum value of the axis in terms of map point values. If null, the max value is automatically calculated. - * If the endOnTick option is true, the max value might be rounded up. - */ - max?: number; - /** - * The color to represent the maximum of the color axis. Unless dataClasses or stops are set, the gradient ends at - * this value. - * - * If dataClasses are set, the color is based on minColor and maxColor unless a color is set for each data class, or - * the dataClassColor is set. - * @default '#102D4C' - */ - maxColor?: string; - /** - * Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. - * @default 0.05 - */ - maxPadding?: number; - /** - * The minimum value of the axis in terms of map point values. If null, the min value is automatically calculated. - * If the startOnTick option is true, the min value might be rounded down. - */ - min?: number; - /** - * The color to represent the minimum of the color axis. Unless dataClasses or stops are set, the gradient starts at - * this value. - * - * If dataClasses are set, the color is based on minColor and maxColor unless a color is set for each data class, or - * the dataClassColor is set. - * @default '#EFEFFF' - */ - minColor?: string; - /** - * Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. - * @default 0.05 - */ - minPadding?: number; - /** - * Color of the minor, secondary grid lines. - * @default '#E0E0E0' - */ - minorGridLineColor?: string; - /** - * The dash or dot style of the minor grid lines. - * @default 'Solid' - */ - minorGridLineDashStyle?: string; - /** - * Width of the minor, secondary grid lines. - * @default 1 - */ - minorGridLineWidth?: number; - /** - * Color for the minor tick marks. - * @default '#A0A0A0' - */ - minorTickColor?: string; - /** - * Tick interval in scale units for the minor ticks. On a linear axis, if 'auto', the minor tick interval is - * calculated as a fifth of the tickInterval. If null, minor ticks are not shown. - * - * On logarithmic axes, the unit is the power of the value. For example, setting the minorTickInterval to 1 puts one - * tick on each of 0.1, 1, 10, 100 etc. Setting the minorTickInterval to 0.1 produces 9 ticks between 1 and 10, 10 - * and 100 etc. A minorTickInterval of 'auto' on a log axis results in a best guess, attempting to enter - * approximately 5 minor ticks between each major tick. - * - * If user settings dictate minor ticks to become too dense, they don't make sense, and will be ignored to prevent - * performance problems. - */ - minorTickInterval?: string | number; - /** - * The pixel length of the minor tick marks. - * @default 2 - */ - minorTickLength?: number; - /** - * The position of the minor tick marks relative to the axis line. Can be one of inside and outside. - * @default 'outside' - */ - minorTickPosition?: string; - /** - * The pixel width of the minor tick mark - * @default 0 - */ - minorTickWidth?: number; - /** - * Whether to reverse the axis so that the highest number is closest to the origin. Defaults to false in a - * horizontal legend and true in a vertical legend, where the smallest value starts on top. - */ - reversed?: boolean; - /** - * If labels are enabled, whether to show the first tick label. - * @default true - */ - showFirstLabel?: boolean; - /** - * If labels are enabled, whether to show the last tick label. - * @default true - */ - showLastLabel?: boolean; - /** - * Whether to force the axis to start on a tick. Use this option with the maxPadding option to control the axis - * start. - * @default true - */ - startOnTick?: boolean; - /** - * Color stops for the gradient of a scalar color axis. Use this in cases where a linear gradient between a minColor - * and maxColor is not sufficient. The stops is an array of tuples, where the first item is a float between 0 and 1 - * assigning the relative position in the gradient, and the second item is the color. - */ - stops?: [number, string][]; - /** - * Color for the main tick marks. - * @default '#C0D0E0' - */ - tickColor?: string; - /** - * The interval of the tick marks in axis units. When null, the tick interval is computed to approximately follow - * the tickPixelInterval. - */ - tickInterval?: number; - /** - * The pixel length of the main tick marks. - * @default 10 - */ - tickLength?: number; - /** - * If tickInterval is null this option sets the approximate pixel interval of the tick marks. - * @default 72 - */ - tickPixelInterval?: number; - /** - * The position of the major tick marks relative to the axis line. Can be one of 'inside' and 'outside'. - * @default 'outside' - */ - tickPosition?: string; - /** - * A callback function returning array defining where the ticks are laid out on the axis. This overrides the default - * behaviour of tickPixelInterval and tickInterval. - */ - tickPositioner?: (min: number, max: number) => void; - /** - * An array defining where the ticks are laid out on the axis. This overrides the default behaviour of - * tickPixelInterval and tickInterval. - */ - tickPositions?: number[]; - /** - * The pixel width of the major tick marks. - * @default 0 - */ - tickWidth?: number; - /** - * The type of interpolation to use for the color axis. Can be 'linear' or 'logarithmic'. - * @default 'linear' - */ - type?: string; -} - -interface HighchartsExtremes { - /** - * The maximum value of the axis' associated series. - */ - dataMax: number; - /** - * The minimum value of the axis' associated series. - */ - dataMin: number; - /** - * The maximum axis value, either automatic or set manually. If the max option is not set and maxPadding is 0, this - * value will be the same as dataMax. - */ - max: number; - /** - * The minimum axis value, either automatic or set manually. If the min option is not set and minPadding is 0, this - * value will be the same as dataMin. - */ - min: number; -} - -interface HighchartsAnimation { - /** - * The duration of the animation in milliseconds. - */ - duration?: number; - /** - * When using jQuery as the general framework, the easing can be set to linear or swing. More easing functions are - * available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the - * {@link http://api.jquery.com/animate/|jQuery docs}. When using MooTools as the general framework, use the - * property name transition instead of easing. - */ - easing?: string; -} - -interface HighchartsAddSeriesEvent extends Event { - /** - * The series options that was passed to the addSeries method. - */ - options: HighchartsChartOptions; -} - -interface HighchartsAxisValueOptions extends HighchartsAxisOptions { - /** - * The axis value at the clicked spot - */ - value: number; -} - -interface HighchartsChartClickEvent extends Event { - /** - * Array containing the axes of each dimension and each axis' value at the clicked spot - */ - xAxis: HighchartsAxisValueOptions[]; - /** - * Array containing the axes of each dimension and each axis' value at the clicked spot - */ - yAxis: HighchartsAxisValueOptions[]; -} - -interface HighchartsChartDrilldownEvent extends Event { - /** - * If a category label was clicked, which index. - */ - category?: number; - /** - * The originating point. - */ - point?: HighchartsPointObject; - /** - * If a category label was clicked, this array holds all points corresponing to the category. - */ - points?: HighchartsPointObject[]; - /** - * Options for the new series. - */ - seriesOptions?: HighchartsIndividualSeriesOptions; -} - -interface HighchartsChartSelectionEvent extends Event { - /** - * Array containing the axes of each dimension and each axis' min and max values - */ - xAxis: HighchartsAxisOptions[]; - /** - * Array containing the axes of each dimension and each axis' min and max values - */ - yAxis: HighchartsAxisOptions[]; -} - -interface HighchartsChartEvents { - /** - * Fires when a series is added to the chart after load time, using the addSeries method. One parameter, event, is - * passed to the function. This contains common event information based on jQuery or MooTools depending on which - * library is used as the base for Highcharts. Through event.options you can access the series options that was - * passed to the addSeries method. Returning false prevents the series from being added. - * - * The this keyword refers to the Chart object. - * @since 1.2.0 - */ - addSeries?: (event: HighchartsAddSeriesEvent) => boolean|void; - /** - * Fires after a chart is printed through the context menu item or the Chart.print method. Requires the exporting - * module. - * @since 4.1.0 - */ - afterPrint?: (event: Event) => void; - /** - * Fires before a chart is printed through the context menu item or the Chart.print method. Requires the exporting - * module. - * @since 4.1.0 - */ - beforePrint?: (event: Event) => void; - /** - * Fires when clicking on the plot background. One parameter, event, is passed to the function. This contains common - * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. - * - * Information on the clicked spot can be found through event.xAxis and event.yAxis, which are arrays containing the - * axes of each dimension and each axis' value at the clicked spot. The primary axes are event.xAxis[0] and - * event.yAxis[0]. Remember the unit of a datetime axis is milliseconds since 1970-01-01 00:00:00. - * - * click: function(e) { - * console.log(Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', e.xAxis[0].value), e.yAxis[0].value); - * } - * - * The this keyword refers to the Chart object. - * @since 1.2.0 - */ - click?: (event: HighchartsChartClickEvent) => void; - /** - * Fires when a drilldown point is clicked, before the new series is added. - * @since 3.0.8 - */ - drilldown?: (event: HighchartsChartDrilldownEvent) => void; - /** - * Fires when drilling up from a drilldown series. - * @since 3.0.8 - */ - drillup?: (event: Event) => void; - /** - * Fires when the chart is finished loading. One parameter, event, is passed to the function. This contains common - * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. - * - * From version 2.0.4, there is also a second parameter to Highcharts.Chart where a callback function can be passed - * to be executed on chart.load. - * - * The this keyword refers to the Chart object. - */ - load?: (event: Event) => void; - /** - * Fires when the chart is redrawn, either after a call to chart.redraw() or after an axis, series or point is - * modified with the redraw option set to true. One parameter, event, is passed to the function. This contains - * common event information based on jQuery or MooTools depending on which library is used as the base for - * Highcharts. - * - * The this keyword refers to the Chart object. - * @since 1.2.0 - */ - redraw?: (event: Event) => void; - /** - * Fires when an area of the chart has been selected. Selection is enabled by setting the chart's zoomType. One - * parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools - * depending on which library is used as the base for Highcharts. The default action for the selection event is to - * zoom the chart to the selected area. It can be prevented by calling event.preventDefault(). - * - * Information on the selected area can be found through event.xAxis and event.yAxis, which are arrays containing - * the axes of each dimension and each axis' min and max values. The primary axes are event.xAxis[0] and - * event.yAxis[0]. Remember the unit of a datetime axis is milliseconds since 1970-01-01 00:00:00. - * - * selection: function(event) { - * // log the min and max of the primary, datetime x-axis - * console.log( - * Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', event.xAxis[0].min), - * Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', event.xAxis[0].max) - * ); - * // log the min and max of the y axis - * console.log(event.yAxis[0].min, event.yAxis[0].max); - * } - */ - selection?: (event: HighchartsChartSelectionEvent) => void; -} - -interface HighchartsLinearGradient { - x1: number; - y1: number; - x2: number; - y2: number; -} - -interface HighchartsGradient { - linearGradient?: HighchartsLinearGradient | number[]; - radialGradient?: { - cx: number; cy: number; r: number; - }; - stops?: any[][]; - /** - * Brighten the color - * @param {number} alpha - */ - brighten?(alpha: number): HighchartsGradient; - /** - * Return the color a specified format - * @param {string} format - */ - get?(format: string): string; - /** - * The raw input - */ - raw?: string; - /** - * rgba array - */ - rgba?: number[]; - /** - * Set the color's opacity to a given alpha value - * @param {number} alpha - * @return {HighchartsGradient} - */ - setOpacity?(alpha: number): HighchartsGradient; -} - -/** - * Type equivalent to the 'Color' type mentioned throughout the documentation. - */ -type Color = string | HighchartsGradient; - -interface HighchartsChartOptions3dFrame { - /** - * The color of the panel. - * @default 'transparent' - * @since 4.0 - */ - color?: string | HighchartsGradient; - /** - * Thickness of the panel. - * @default 1 - * @since 4.0 - */ - size?: number; -} - -interface HighchartsChartOptions3d { - /** - * One of the two rotation angles for the chart. - * @default 0 - * @since 4.0 - */ - alpha?: number; - /** - * One of the two rotation angles for the chart. - * @default 0 - * @since 4.0 - */ - beta?: number; - /** - * The total depth of the chart. - * @default 100 - * @since 4.0 - */ - depth?: number; - /** - * Wether to render the chart using the 3D functionality. - * @default false - * @since 4.0 - */ - enabled?: boolean; - /** - * Provides the option to draw a frame around the charts by defining a bottom, front and back panel. - */ - frame?: { + minorGridLineColor?: string; /** - * Defines the back panel of the frame around 3D charts. - * @since 4.0 + * The dash or dot style of the minor grid lines. For possible values, see {@link http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/|this demonstration}. + * @default 'Solid' */ - back?: HighchartsChartOptions3dFrame; + minorGridLineDashStyle?: string; /** - * The bottom of the frame around a 3D chart. - * @since 4.0 + * Width of the minor, secondary grid lines. + * @default 1 */ - bottom?: HighchartsChartOptions3dFrame; + minorGridLineWidth?: number; /** - * The side for the frame around a 3D chart. - * @since 4.0 + * Color for the minor tick marks. + * @default to '#A0A0A0' */ - side?: HighchartsChartOptions3dFrame; - }; - /** - * Defines the distance the viewer is standing in front of the chart, this setting is important to calculate the - * perspective effect in column and scatter charts. It is not used for 3D pie charts. - * @default 100 - * @since 4.0 - */ - viewDistance?: number; -} - -interface HighchartsShadow { - /** - * @default 'black' - */ - color?: string | HighchartsGradient; - /** - * @default 1 - */ - offsetX?: number; - /** - * @default 1 - */ - offsetY?: number; - /** - * @default 0.15 / width - */ - opacity?: number; - /** - * @default 3 - */ - width?: number; -} - -interface HighchartsChartResetZoomButton { - /** - * The position of the button. This is an object that can hold the properties align, verticalAlign, x and y. - * @since 2.2 - */ - position?: HighchartsPosition; - /** - * What frame the button should be placed related to. Can be either 'plot' or 'chart'. - * @default 'plot' - * @since 2.2 - */ - relativeTo?: string; - /** - * A collection of attributes for the button. The object takes SVG attributes like fill, stroke, stroke-width or r, - * the border radius. The theme also supports style, a collection of CSS properties for the text. Equivalent - * attributes for the hover state are given in theme.states.hover. - * @since 2.2 - */ - theme?: HighchartsButtonStatesTheme; -} - -interface HighchartsButtonTheme { - display?: string; // css attr eg: 'none' - /** - * The button fill color, SVG color definition - */ - fill?: string | HighchartsGradient; - /** - * The button stroke color, SVG color definition - */ - stroke?: string; - /** - * The button stroke width - * @type {[type]} - */ - 'stroke-width'?: number; - /** - * The border radius - */ - r?: number; - /** - * CSS style - */ - style?: Object; -} - -interface HighchartsButtonStatesTheme extends HighchartsButtonTheme { - /** - * Themed button states. Only hover is supported for reset zoom button. - */ - states?: { + minorTickColor?: string; /** - * Attributes and styles applied when hovering. + * Tick interval in scale units for the minor ticks. On a linear axis, if 'auto', the minor tick interval is + * calculated as a fifth of the tickInterval. If null, minor ticks are not shown. + * + * On logarithmic axes, the unit is the power of the value. For example, setting the minorTickInterval to 1 puts one + * tick on each of 0.1, 1, 10, 100 etc. Setting the minorTickInterval to 0.1 produces 9 ticks between 1 and 10, 10 + * and 100 etc. A minorTickInterval of 'auto' on a log axis results in a best guess, attempting to enter + * approximately 5 minor ticks between each major tick. + * + * If user settings dictate minor ticks to become too dense, they don't make sense, and will be ignored to prevent + * performance problems. + * + * On axes using categories, minor ticks are not supported. */ - hover?: HighchartsButtonTheme; + minorTickInterval?: number | string; /** - * Attributes and styles applied when button is selected (tri-state). + * The pixel length of the minor tick marks. + * @default 2 */ - select?: HighchartsButtonTheme; - }; -} - -interface HighchartsChartOptions { - /** - * When using multiple axis, the ticks of two or more opposite axes will automatically be aligned by adding ticks to - * the axis or axes with the least ticks. This can be prevented by setting alignTicks to false. If the grid lines - * look messy, it's a good idea to hide them for the secondary axis by setting gridLineWidth to 0. - * @default true - */ - alignTicks?: boolean; - /** - * Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to - * false here. It can be overridden for each individual API method as a function parameter. The only animation not - * affected by this option is the initial series animation, see plotOptions.series.animation. - * - * The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery - * easing and a duration of 500 ms. - * - * @default true - */ - animation?: boolean | HighchartsAnimation; - /** - * The background color or gradient for the outer chart area. - * @default '#FFFFFF' - */ - backgroundColor?: string | HighchartsGradient; - /** - * The color of the outer chart border. - * @default '#4572A7' - */ - borderColor?: string | HighchartsGradient; - /** - * The corner radius of the outer chart border. - * @default 0 - */ - borderRadius?: number; - /** - * The pixel width of the outer chart border. - * @default 0 - */ - borderWidth?: number; - /** - * A CSS class name to apply to the charts container div, allowing unique CSS styling for each chart. - */ - className?: string; - /** - * Alias of type. Defaults to line. - * @default 'line' - * @deprecated - */ - defaultSeriesType?: string; - /** - * Event listeners for the chart. - */ - events?: HighchartsChartEvents; - /** - * An explicit height for the chart. By default the height is calculated from the offset height of the containing - * element, or 400 pixels if the containing element's height is 0. - */ - height?: number; - /** - * If true, the axes will scale to the remaining visible series once one series is hidden. If false, hiding and - * showing a series will not affect the axes or the other series. For stacks, once one series within the stack is - * hidden, the rest of the stack will close in around it even if the axis is not affected. - * @default true - * @since 1.2.0 - */ - ignoreHiddenSeries?: boolean; - /** - * Whether to invert the axes so that the x axis is vertical and y axis is horizontal. When true, the x axis is - * reversed by default. If a bar series is present in the chart, it will be inverted automatically. - * @default false - */ - inverted?: boolean; - /** - * The margin between the outer edge of the chart and the plot area. The numbers in the array designate top, right, - * bottom and left respectively. Use the options marginTop, marginRight, marginBottom and marginLeft for shorthand - * setting of one option. - * - * Since version 2.1, the margin is 0 by default. The actual space is dynamically calculated from the offset of axis - * labels, axis title, title, subtitle and legend in addition to the spacingTop, spacingRight, spacingBottom and - * spacingLeft options. - */ - margin?: number | number[]; - /** - * The margin between the bottom outer edge of the chart and the plot area. Use this to set a fixed pixel value for - * the margin as opposed to the default dynamic margin. See also spacingBottom. - * @since 2.0 - */ - marginBottom?: number; - /** - * The margin between the left outer edge of the chart and the plot area. Use this to set a fixed pixel value for - * the margin as opposed to the default dynamic margin. See also spacingLeft. - * @since 2.0 - */ - marginLeft?: number; - /** - * The margin between the right outer edge of the chart and the plot area. Use this to set a fixed pixel value for - * the margin as opposed to the default dynamic margin. See also spacingRight. - * @since 2.0 - */ - marginRight?: number; - /** - * The margin between the top outer edge of the chart and the plot area. Use this to set a fixed pixel value for the - * margin as opposed to the default dynamic margin. See also spacingTop. - * @since 2.0 - */ - marginTop?: number; - /** - * Options to render charts in 3 dimensions. This feature requires highcharts-3d.js, found in the download package - * or online at {@link code.highcharts.com/highcharts-3d.js}. - */ - options3d?: HighchartsChartOptions3d; - /** - * Allows setting a key to switch between zooming and panning. - * @since 4.0.3 - */ - panKey?: string; - /** - * Allow panning in a chart. Best used with panKey to combine zooming and panning. - * @default false - * @since 4.0.3 - */ - panning?: boolean; - /** - * Equivalent to zoomType, but for multitouch gestures only. By default, the pinchType is the same as the zoomType - * setting. However, pinching can be enabled separately in some cases, for example in stock charts where a mouse - * drag pans the chart, while pinching is enabled. - * @default null - * @since 3.0 - */ - pinchType?: string; - /** - * The background color or gradient for the plot area. - */ - plotBackgroundColor?: string | HighchartsGradient; - /** - * The URL for an image to use as the plot background. To set an image as the background for the entire chart, set a - * CSS background image to the container element. Note that for the image to be applied to exported charts, its URL - * needs to be accessible by the export server. - */ - plotBackgroundImage?: string; - /** - * The color of the inner chart or plot area border. - * @default 0 - */ - plotBorderColor?: string; - /** - * The pixel width of the plot area border. - * @default 0 - */ - plotBorderWidth?: number; - /** - * Whether to apply a drop shadow to the plot area. Requires that plotBackgroundColor be set. Since 2.3 the shadow - * can be an object configuration containing color, offsetX, offsetY, opacity and width. - * @default false - */ - plotShadow?: boolean | HighchartsShadow; - /** - * When true, cartesian charts like line, spline, area and column are transformed into the polar coordinate system. - * Requires highcharts-more.js. - * @default false - * @since 2.3.0 - */ - polar?: boolean; - /** - * Whether to reflow the chart to fit the width of the container div on resizing the window. - * @default true - * @since 2.1 - */ - reflow?: boolean; - /** - * The HTML element where the chart will be rendered. If it is a string, the element by that id is used. The HTML - * element can also be passed by direct reference. - */ - renderTo?: string | HTMLElement; - /** - * The button that appears after a selection zoom, allowing the user to reset zoom. - */ - resetZoomButton?: HighchartsChartResetZoomButton; - /** - * The background color of the marker square when selecting (zooming in on) an area of the chart. - * @default 'rgba(69,114,167,0.25)' - * @since 2.1.7 - */ - selectionMarkerFill?: string; - /** - * Whether to apply a drop shadow to the outer chart area. Requires that backgroundColor be set. Since 2.3 the - * shadow can be an object configuration containing color, offsetX, offsetY, opacity and width. - * @default false - */ - shadow?: boolean | HighchartsShadow; - /** - * Whether to show the axes initially. This only applies to empty charts where series are added dynamically, as axes - * are automatically added to cartesian series. - * @default false - * @since 1.2.5 - */ - showAxes?: boolean; - /** - * The distance between the outer edge of the chart and the content, like title, legend, axis title or labels. The - * numbers in the array designate top, right, bottom and left respectively. Use the options spacingTop, - * spacingRight, spacingBottom and spacingLeft options for shorthand setting of one option. - * @default [10, 10, 15, 10] - * @since 3.0.6 - */ - spacing?: number[]; - /** - * The space between the bottom edge of the chart and the content (plot area, axis title and labels, title, subtitle - * or legend in top position). - * @default 15 - * @since 2.1 - */ - spacingBottom?: number; - /** - * The space between the left edge of the chart and the content (plot area, axis title and labels, title, subtitle - * or legend in top position). - * @default 10 - * @since 2.1 - */ - spacingLeft?: number; - /** - * The space between the right edge of the chart and the content (plot area, axis title and labels, title, subtitle - * or legend in top position). - * @default 10 - * @since 2.1 - */ - spacingRight?: number; - /** - * The space between the top edge of the chart and the content (plot area, axis title and labels, title, subtitle or - * legend in top position). - * @default 10 - * @since 2.1 - */ - spacingTop?: number; - /** - * Additional CSS styles to apply inline to the container div. Note that since the default font styles are applied - * in the renderer, it is ignorant of the individual chart options and must be set globally. - */ - style?: HighchartsCSSObject; - /** - * The default series type for the chart. Can be any of the chart types listed under plotOptions. - * @default 'line' - * @since 2.1.0 - */ - type?: string; - /** - * An explicit width for the chart. By default the width is calculated from the offset width of the containing - * element. - */ - width?: number; - /** - * Decides in what dimensions the user can zoom by dragging the mouse. Can be one of x, y or xy. - */ - zoomType?: string; -} - -interface HighchartsCSSObject { - background?: string; - border?: string; - color?: string | HighchartsGradient; - cursor?: string; - font?: string; - fontFamily?: string; - fontSize?: string; - fontWeight?: string; - left?: string; - opacity?: number; - padding?: string | number; - position?: string; - top?: string; - textShadow?: string; -} - -interface HighchartsCreditsOptions { - /** - * Whether to show the credits text. - * @default true - */ - enabled?: boolean; - /** - * The URL for the credits label. - * @default 'http://www.highcharts.com' - */ - href?: string; - /** - * Position configuration for the credits label. Supported properties are align, verticalAlign, x and y. - */ - position?: HighchartsPosition; - /** - * CSS styles for the credits label. - */ - style?: Object; - /** - * The text for the credits label. - * @default 'Highcharts.com' - */ - text?: string; -} - -interface HighchartsDataSeriesMapping { - [pointPropertyName: string]: number; -} - -/** - * The Data module provides a simplified interface for adding data to a chart from sources like CVS, HTML tables or grid - * views. See also the tutorial article on the Data module. - * - * It requires the modules/data.js file to be loaded. - * - * Please note that the default way of adding data in Highcharts, without the need of a module, is through the - * series.data option. - */ -interface HighchartsDataOptions { - /** - * A two-dimensional array representing the input data on tabular form. This input can be used when the data is - * already parsed, for example from a grid view component. Each cell can be a string or number. If not - * switchRowsAndColumns is set, the columns are interpreted as series. - * @since 4.0 - */ - columns?: [string|number][]; - /** - * The callback that is evaluated when the data is finished loading, optionally from an external source, and parsed. - * The first argument passed is a finished chart options object, containing the series. These options can be - * extended with additional options and passed directly to the chart constructor. - * @since 4.0 - */ - complete?: (options: HighchartsOptions) => void; - /** - * A comma delimited string to be parsed. Related options are startRow, endRow, startColumn and endColumn to delimit - * what part of the table is used. The lineDelimiter and itemDelimiter options define the CSV delimiter formats. - * @since 4.0 - */ - csv?: string; - /** - * Which of the predefined date formats in Date.prototype.dateFormats to use to parse date values. Defaults to a - * best guess based on what format gives valid and ordered dates. - * - * Valid options include: - * 'YYYY-mm-dd' - * 'dd/mm/YYYY' - * 'mm/dd/YYYY' - * 'dd/mm/YY' - * 'mm/dd/YY' - * @since 4.0 - */ - dateFormat?: string; - /** - * The decimal point used for parsing numbers in the CSV. - * @default '.' - */ - decimalPoint?: string; - /** - * In tabular input data, the last column (indexed by 0) to use. Defaults to the last column containing data. - * @since 4.0 - */ - endColumn?: number; - /** - * In tabular input data, the last row (indexed by 0) to use. Defaults to the last row containing data. - * @since 4.0.4 - */ - endRow?: number; - /** - * Whether to use the first row in the data set as series names. - * @default true - * @since 4.1.0 - */ - firstRowAsNames?: boolean; - /** - * The key for a Google Spreadsheet to load. See {@link https://developers.google.com/gdata/samples/spreadsheet_sample|general information on GS}. - * @since 4.0 - */ - googleSpreadsheetKey?: string; - /** - * The Google Spreadsheet worksheet to use in combination with googleSpreadsheetKey. The available id's from your - * sheet can be read from https://spreadsheets.google.com/feeds/worksheets/{key}/public/basic - * @since 4.0 - */ - googleSpreadsheetWorksheet?: string; - /** - * Item or cell delimiter for parsing CSV. Defaults to the tab character \t if a tab character is found in the CSV - * string, if not it defaults to ,. - * @since 4.0 - */ - itemDelimiter?: string; - /** - * Line delimiter for parsing CSV. - * @default '\n' - * @since 4.0 - */ - lineDelimiter?: string; - /** - * A callback function to parse string representations of dates into JavaScript timestamps. Should return an integer - * timestamp on success. - * @since 4.0 - */ - parseDate?: (val: any) => number; - /** - * A callback function to access the parsed columns, the two-dimentional input data array directly, before they are - * interpreted into series data and categories. Return false to stop completion, or call this.complete() to continue - * async. - * @since 4.0 - */ - parsed?: (columns: [string|number][]) => boolean | void; - /** - * The same as the columns input option, but defining rows intead of columns. - * @since 4.0 - */ - rows?: [string|number][]; - /** - * An array containing object with Point property names along with what column id the property should be taken from. - * @since 4.0.4 - */ - seriesMapping?: HighchartsDataSeriesMapping[]; - /** - * In tabular input data, the first column (indexed by 0) to use. - * @default 0 - * @since 4.0 - */ - startColumn?: number; - /** - * In tabular input data, the first row (indexed by 0) to use. - * @default 0 - * @since 4.0 - */ - startRow?: number; - /** - * Switch rows and columns of the input data, so that this.columns effectively becomes the rows of the data set, and - * the rows are interpreted as series. - * @default false - * @since 4.0 - */ - switchRowsAndColumns?: boolean; - /** - * A HTML table or the id of such to be parsed as input data. Related options are startRow, endRow, startColumn and - * endColumn to delimit what part of the table is used. - */ - table?: string | HTMLElement; -} - -/** - * Options for drill down, the concept of inspecting increasingly high resolution data through clicking on chart items - * like columns or pie slices. - * - * The drilldown feature requires the drilldown.js file to be loaded, found in the modules directory of the download - * package, or online at code.highcharts.com/modules/drilldown.js. - */ -interface HighchartsDrilldownOptions { - /** - * Additional styles to apply to the X axis label for a point that has drilldown data. By default it is underlined - * and blue to invite to interaction. - * @default { cursor: 'pointer', color: '#0d233a', fontWeight: 'bold', textDecoration: 'underline' } - * @since 3.0.8 - */ - activeAxisLabelStyle?: Object; - /** - * Additional styles to apply to the data label of a point that has drilldown data. By default it is underlined and - * blue to invite to interaction. - * @default { cursor: 'pointer', color: '#0d233a', fontWeight: 'bold', textDecoration: 'underline' } - * @since 3.0.8 - */ - activeDataLabelStyle?: Object; - /** - * When this option is false, clicking a single point will drill down all points in the same category, equivalent to - * clicking the X axis label. - * @default true - * @since 4.1.7 - */ - allowPointDrilldown?: boolean; - /** - * Set the animation for all drilldown animations. Animation of a drilldown occurs when drilling between a column - * point and a column series, or a pie slice and a full pie series. Drilldown can still be used between series and - * points of different types, but animation will not occur. - * - * The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery - * easing and a duration of 500 ms. - * @since 3.0.8 - */ - animation?: boolean | HighchartsAnimation; - /** - * Options for the drill up button that appears when drilling down on a series. The text for the button is defined - * in lang.drillUpText. - */ - drillUpButton?: { + minorTickLength?: number; /** - * Positioning options for the button within the relativeTo box. Available properties are x, y, align and - * verticalAlign. + * The position of the minor tick marks relative to the axis line. Can be one of 'inside' and 'outside'. + * @default 'outside' + */ + minorTickPosition?: string; + /** + * The pixel width of the minor tick mark. + * @default 0 + */ + minorTickWidth?: number; + /** + * The distance in pixels from the plot area to the axis line. A positive offset moves the axis with it's line, + * labels and ticks away from the plot area. This is typically used when two or more axes are displayed on the same + * side of the plot. + * @default 0 + */ + offset?: number; + /** + * Whether to display the axis on the opposite side of the normal. The normal is on the left side for vertical axes + * and bottom for horizontal, so the opposite sides will be right and top respectively. This is typically used with + * dual or multiple axes. + * @default false + */ + opposite?: boolean; + /** + * An array of colored bands stretching across the plot area marking an interval on the axis. + * + * In a gauge, a plot band on the Y axis (value axis) will stretch along the perimeter of the gauge. + */ + plotBands?: PlotBands[]; + /** + * An array of lines stretching across the plot area, marking a specific value on one of the axes. + */ + plotLines?: PlotLines[]; + /** + * Whether to reverse the axis so that the highest number is closest to the origin. If the chart is inverted, the x + * axis is reversed by default. + * @default false + */ + reversed?: boolean; + /** + * Whether to show the axis line and title when the axis has no data. + * @default true + * @since 1.1 + */ + showEmpty?: boolean; + /** + * Whether to show the first tick label. + * @default true + */ + showFirstLabel?: boolean; + /** + * Whether to show the last tick label. + * @default true + */ + showLastLabel?: boolean; + /** + * Show the total value for each bar in a stacked column or bar chart. + * The label will be placed on top of positive columns and below negative columns. + * In case of an inverted column chart or a bar chart the label is placed to the right of positive bars and to the left of negative bars. + * Only used for yAxis + */ + stackLabels?: { + /** + * Defines the horizontal alignment of the stack total label. Can be one of "left", "center" or "right". + * @default calculated at runtime and depends on orientation and whether the stack is positive or negative. + * @since 2.1.5 + */ + align?: string; + /** + * Enable or disable the stack total labels. + * @default false + * @since 2.1.5 + */ + enabled?: boolean; + /** + * A format string for the data label. Available variables are the same as for formatter. + * @default {total} + * @since 3.0.2 + */ + format?: string; + /** + * Callback JavaScript function to format the label. The value is given by this.total. + * @default function() { return this.total; } + * @since 2.1.5 + */ + formatter?: Function; + /** + * Rotation of the labels in degrees. + * @default 0 + * @since 2.1.5 + */ + rotation?: number; + /** + * CSS styles for the label. + * @default { "color": "#000000", "fontSize": "11px", "fontWeight": "bold", "textShadow": "0 0 6px contrast, 00 3px contrast" } + * @since 2.1.5 + */ + style?: CSSObject; + /** + * The text alignment for the label. + * While align determines where the texts anchor point is placed with regards to the stack, textAlign determines how the text is aligned against its anchor point. + * Possible values are "left", "center" and "right". + * @default calculated at runtime and depends on orientation and whether the stack is positive or negative. + * @since 2.1.5 + */ + textAlign?: string; + /** + * Whether to use HTML to render the labels. + * @default false + * @since 3.0 + */ + useHTML?: boolean; + /** + * Defines the vertical alignment of the stack total label. Can be one of "top", "middle" or "bottom". + * @default calculated at runtime and depends on orientation and whether the stack is positive or negative. + * @since 2.1.5 + */ + verticalAlign?: string; + /** + * The x position offset of the label relative to the left of the stacked bar. + * @default calculated at runtime and depends on orientation and whether the stack is positive or negative. + * @since 2.1.5 + */ + x?: number; + /** + * The y position offset of the label relative to the tick position on the axis. + * @default calculated at runtime and depends on orientation and whether the stack is positive or negative. + * @since 2.1.5 + */ + y?: number; + } + /** + * For datetime axes, this decides where to put the tick between weeks. 0 = Sunday, 1 = Monday. + * @default 1 + */ + startOfWeek?: number; + /** + * Whether to force the axis to start on a tick. Use this option with the minPadding option to control the axis + * start. + * @default false + * @since 1.2.0 + */ + startOnTick?: boolean; + /** + * The amount of ticks to draw on the axis. This opens up for aligning the ticks of multiple charts or panes within + * a chart. This option overrides the tickPixelInterval option. + * + * This option only has an effect on linear axes. Datetime, logarithmic or category axes are not affected. + */ + tickAmount?: number; + /** + * Color for the main tick marks. + * @default '#C0D0E0' + */ + tickColor?: string; + /** + * The interval of the tick marks in axis units. When null, the tick interval is computed to approximately follow + * the tickPixelInterval on linear and datetime axes. On categorized axes, a null tickInterval will default to 1, + * one category. Note that datetime axes are based on milliseconds, so for example an interval of one day is + * expressed as 24 * 3600 * 1000. + * + * On logarithmic axes, the tickInterval is based on powers, so a tickInterval of 1 means one tick on each of 0.1, + * 1, 10, 100 etc. A tickInterval of 2 means a tick of 0.1, 10, 1000 etc. A tickInterval of 0.2 puts a tick on 0.1, + * 0.2, 0.4, 0.6, 0.8, 1, 2, 4, 6, 8, 10, 20, 40 etc. + * + * If the tickInterval is too dense for labels to be drawn, Highcharts may remove ticks. + */ + tickInterval?: number; + /** + * The pixel length of the main tick marks. + * @default 10 + */ + tickLength?: number; + /** + * If tickInterval is null this option sets the approximate pixel interval of the tick marks. Not applicable to + * categorized axis. + * + * @default 72 for the Y axis, 100 for the X axis. + */ + tickPixelInterval?: number; + /** + * The position of the major tick marks relative to the axis line. Can be one of 'inside' and 'outside'. + * @default 'outside' + */ + tickPosition?: string; + /** + * A callback function returning array defining where the ticks are laid out on the axis. This overrides the default + * behaviour of tickPixelInterval and tickInterval. The automatic tick positions are accessible through + * this.tickPositions and can be modified by the callback. + */ + tickPositioner?: (min: number, max: number) => void; + /** + * An array defining where the ticks are laid out on the axis. This overrides the default behaviour of + * tickPixelInterval and tickInterval. + */ + tickPositions?: number[]; + /** + * The pixel width of the major tick marks. + * @default 1 + */ + tickWidth?: number; + /** + * For categorized axes only. If 'on' the tick mark is placed in the center of the category, if 'between' the tick + * mark is placed between categories. The default is 'between' if the tickInterval is 1, else 'on'. + * @default null + */ + tickmarkPlacement?: string; + /** + * The axis title, showing next to the axis line. + */ + title?: AxisTitle; + /** + * The type of axis. Can be one of 'linear', 'logarithmic', 'datetime' or 'category'. In a datetime axis, the + * numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days. In a + * category axis, the point names of the chart's series are used for categories, if not a categories array is + * defined. + * @default 'linear' + */ + type?: string; + /** + * Datetime axis only. An array determining what time intervals the ticks are allowed to fall on. Each array item is + * an array where the first value is the time unit and the second value another array of allowed multiples. + */ + units?: [[string, [number]]]; + /** + * Whether axis, including axis title, line, ticks and labels, should be visible. + * @default true + * @since 4.1.9 + */ + visible?: boolean; + } + + interface ColorAxisDataClass { + from?: number; + to?: number; + color?: string | Gradient; + name?: string; + } + + /** + * A color axis for choropleth mapping. Visually, the color axis will appear as a gradient or as separate items inside + * the legend, depending on whether the axis is scalar or based on data classes. + * + * For supported color formats, see the docs article about colors. + * + * A scalar color axis is represented by a gradient. The colors either range between the minColor and the maxColor, or + * for more fine grained control the colors can be defined in stops. Often times, the color axis needs to be adjusted to + * get the right color spread for the data. In addition to stops, consider using a logarithmic axis type, or setting min + * and max to avoid the colors being determined by outliers. + * + * When dataClasses are used, the ranges are subdivided into separate classes like categories based on their values. + * This can be used for ranges between two values, but also for a true category. However, when your data is categorized, + * it may be as convenient to add each category to a separate series. + * + * See the Axis object for programmatic access to the axis. + */ + interface ColorAxisOptions { + /** + * Determines how to set each data class' color if no individual color is set. The default value, tween, computes + * intermediate colors between minColor and maxColor. The other possible value, category, pulls colors from the + * global or chart specific colors array. + * @default 'tween' + */ + dataClassColor?: string; + /** + * An array of data classes or ranges for the choropleth map. If none given, the color axis is scalar and values are + * distributed as a gradient between the minimum and maximum colors. + */ + dataClasses?: ColorAxisDataClass[]; + /** + * Whether to force the axis to end on a tick. Use this option with the maxPadding option to control the axis end. + * @default true + */ + endOnTick?: boolean; + events?: { + /** + * As opposed to the setExtremes event, this event fires after the final min and max values are computed and + * corrected for minRange. + * The this keyword refers to the {@link AxisObject|Axis} object. + */ + afterSetExtremes?: (event: AxisEvent) => void; + /** + * Fires when the minimum and maximum is set for the axis, either by calling the .setExtremes() method or by + * selecting an area in the chart. One parameter, event, is passed to the function. This contains common event + * information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * + * The new user set minimum and maximum values can be found by event.min and event.max. When an axis is zoomed + * all the way out from the 'Reset zoom' button, event.min and event.max are null, and the new extremes are set + * based on this.dataMin and this.dataMax. + * + * The this keyword refers to the {@link AxisObject|Axis} object. + */ + setExtremes?: (event: AxisEvent) => void; + }; + /** + * Color of the grid lines extending from the axis across the gradient. + * @default '#C0C0C0' + */ + gridLineColor?: string; + /** + * The dash or dot style of the grid lines. + * @default 'Solid' + */ + gridLineDashStyle?: string; + /** + * The width of the grid lines extending from the axis across the gradient of a scalar color axis. + * @default 1 + */ + gridLineWidth?: number; + /** + * An id for the axis. This can be used after render time to get a pointer to the axis object through chart.get(). + */ + id?: string; + /** + * The axis labels show the number for each tick. + */ + labels?: AxisLabels; + /** + * The color of the line marking the axis itself. + * @default '#C0D0E0' + */ + lineColor?: string | Gradient; + /** + * The width of the line marking the axis itself. + * @default 0 + */ + lineWidth?: number; + /** + * The triangular marker on a scalar color axis that points to the value of the hovered area. To disable the marker, + * set marker: null. + */ + marker?: { + /** + * Animation for the marker as it moves between values. Set to false to disable animation. + * @default {duration: 50} + */ + animation?: boolean | Animation; + /** + * The color of the marker. + * @default 'gray' + */ + color?: string | Gradient; + }; + /** + * The maximum value of the axis in terms of map point values. If null, the max value is automatically calculated. + * If the endOnTick option is true, the max value might be rounded up. + */ + max?: number; + /** + * The color to represent the maximum of the color axis. Unless dataClasses or stops are set, the gradient ends at + * this value. + * + * If dataClasses are set, the color is based on minColor and maxColor unless a color is set for each data class, or + * the dataClassColor is set. + * @default '#102D4C' + */ + maxColor?: string; + /** + * Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. + * @default 0.05 + */ + maxPadding?: number; + /** + * The minimum value of the axis in terms of map point values. If null, the min value is automatically calculated. + * If the startOnTick option is true, the min value might be rounded down. + */ + min?: number; + /** + * The color to represent the minimum of the color axis. Unless dataClasses or stops are set, the gradient starts at + * this value. + * + * If dataClasses are set, the color is based on minColor and maxColor unless a color is set for each data class, or + * the dataClassColor is set. + * @default '#EFEFFF' + */ + minColor?: string; + /** + * Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. + * @default 0.05 + */ + minPadding?: number; + /** + * Color of the minor, secondary grid lines. + * @default '#E0E0E0' + */ + minorGridLineColor?: string; + /** + * The dash or dot style of the minor grid lines. + * @default 'Solid' + */ + minorGridLineDashStyle?: string; + /** + * Width of the minor, secondary grid lines. + * @default 1 + */ + minorGridLineWidth?: number; + /** + * Color for the minor tick marks. + * @default '#A0A0A0' + */ + minorTickColor?: string; + /** + * Tick interval in scale units for the minor ticks. On a linear axis, if 'auto', the minor tick interval is + * calculated as a fifth of the tickInterval. If null, minor ticks are not shown. + * + * On logarithmic axes, the unit is the power of the value. For example, setting the minorTickInterval to 1 puts one + * tick on each of 0.1, 1, 10, 100 etc. Setting the minorTickInterval to 0.1 produces 9 ticks between 1 and 10, 10 + * and 100 etc. A minorTickInterval of 'auto' on a log axis results in a best guess, attempting to enter + * approximately 5 minor ticks between each major tick. + * + * If user settings dictate minor ticks to become too dense, they don't make sense, and will be ignored to prevent + * performance problems. + */ + minorTickInterval?: string | number; + /** + * The pixel length of the minor tick marks. + * @default 2 + */ + minorTickLength?: number; + /** + * The position of the minor tick marks relative to the axis line. Can be one of inside and outside. + * @default 'outside' + */ + minorTickPosition?: string; + /** + * The pixel width of the minor tick mark + * @default 0 + */ + minorTickWidth?: number; + /** + * Whether to reverse the axis so that the highest number is closest to the origin. Defaults to false in a + * horizontal legend and true in a vertical legend, where the smallest value starts on top. + */ + reversed?: boolean; + /** + * If labels are enabled, whether to show the first tick label. + * @default true + */ + showFirstLabel?: boolean; + /** + * If labels are enabled, whether to show the last tick label. + * @default true + */ + showLastLabel?: boolean; + /** + * Whether to force the axis to start on a tick. Use this option with the maxPadding option to control the axis + * start. + * @default true + */ + startOnTick?: boolean; + /** + * Color stops for the gradient of a scalar color axis. Use this in cases where a linear gradient between a minColor + * and maxColor is not sufficient. The stops is an array of tuples, where the first item is a float between 0 and 1 + * assigning the relative position in the gradient, and the second item is the color. + */ + stops?: [number, string][]; + /** + * Color for the main tick marks. + * @default '#C0D0E0' + */ + tickColor?: string; + /** + * The interval of the tick marks in axis units. When null, the tick interval is computed to approximately follow + * the tickPixelInterval. + */ + tickInterval?: number; + /** + * The pixel length of the main tick marks. + * @default 10 + */ + tickLength?: number; + /** + * If tickInterval is null this option sets the approximate pixel interval of the tick marks. + * @default 72 + */ + tickPixelInterval?: number; + /** + * The position of the major tick marks relative to the axis line. Can be one of 'inside' and 'outside'. + * @default 'outside' + */ + tickPosition?: string; + /** + * A callback function returning array defining where the ticks are laid out on the axis. This overrides the default + * behaviour of tickPixelInterval and tickInterval. + */ + tickPositioner?: (min: number, max: number) => void; + /** + * An array defining where the ticks are laid out on the axis. This overrides the default behaviour of + * tickPixelInterval and tickInterval. + */ + tickPositions?: number[]; + /** + * The pixel width of the major tick marks. + * @default 0 + */ + tickWidth?: number; + /** + * The type of interpolation to use for the color axis. Can be 'linear' or 'logarithmic'. + * @default 'linear' + */ + type?: string; + } + + interface Extremes { + /** + * The maximum value of the axis' associated series. + */ + dataMax: number; + /** + * The minimum value of the axis' associated series. + */ + dataMin: number; + /** + * The maximum axis value, either automatic or set manually. If the max option is not set and maxPadding is 0, this + * value will be the same as dataMax. + */ + max: number; + /** + * The minimum axis value, either automatic or set manually. If the min option is not set and minPadding is 0, this + * value will be the same as dataMin. + */ + min: number; + } + + interface Animation { + /** + * The duration of the animation in milliseconds. + */ + duration?: number; + /** + * When using jQuery as the general framework, the easing can be set to linear or swing. More easing functions are + * available with the use of jQuery plug-ins, most notably the jQuery UI suite. See the + * {@link http://api.jquery.com/animate/|jQuery docs}. When using MooTools as the general framework, use the + * property name transition instead of easing. + */ + easing?: string; + } + + interface AddSeriesEvent extends Event { + /** + * The series options that was passed to the addSeries method. + */ + options: ChartOptions; + } + + interface AxisValueOptions extends AxisOptions { + /** + * The axis value at the clicked spot + */ + value: number; + } + + interface ChartClickEvent extends Event { + /** + * Array containing the axes of each dimension and each axis' value at the clicked spot + */ + xAxis: AxisValueOptions[]; + /** + * Array containing the axes of each dimension and each axis' value at the clicked spot + */ + yAxis: AxisValueOptions[]; + } + + interface ChartDrilldownEvent extends Event { + /** + * If a category label was clicked, which index. + */ + category?: number; + /** + * The originating point. + */ + point?: PointObject; + /** + * If a category label was clicked, this array holds all points corresponing to the category. + */ + points?: PointObject[]; + /** + * Options for the new series. + */ + seriesOptions?: IndividualSeriesOptions; + } + + interface ChartSelectionEvent extends Event { + /** + * Array containing the axes of each dimension and each axis' min and max values + */ + xAxis: AxisOptions[]; + /** + * Array containing the axes of each dimension and each axis' min and max values + */ + yAxis: AxisOptions[]; + } + + interface ChartEvents { + /** + * Fires when a series is added to the chart after load time, using the addSeries method. One parameter, event, is + * passed to the function. This contains common event information based on jQuery or MooTools depending on which + * library is used as the base for Highcharts. Through event.options you can access the series options that was + * passed to the addSeries method. Returning false prevents the series from being added. + * + * The this keyword refers to the Chart object. + * @since 1.2.0 + */ + addSeries?: (event: AddSeriesEvent) => boolean | void; + /** + * Fires after a chart is printed through the context menu item or the Chart.print method. Requires the exporting + * module. + * @since 4.1.0 + */ + afterPrint?: (event: Event) => void; + /** + * Fires before a chart is printed through the context menu item or the Chart.print method. Requires the exporting + * module. + * @since 4.1.0 + */ + beforePrint?: (event: Event) => void; + /** + * Fires when clicking on the plot background. One parameter, event, is passed to the function. This contains common + * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * + * Information on the clicked spot can be found through event.xAxis and event.yAxis, which are arrays containing the + * axes of each dimension and each axis' value at the clicked spot. The primary axes are event.xAxis[0] and + * event.yAxis[0]. Remember the unit of a datetime axis is milliseconds since 1970-01-01 00:00:00. + * + * click: function(e) { + * console.log(Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', e.xAxis[0].value), e.yAxis[0].value); + * } + * + * The this keyword refers to the Chart object. + * @since 1.2.0 + */ + click?: (event: ChartClickEvent) => void; + /** + * Fires when a drilldown point is clicked, before the new series is added. * @since 3.0.8 */ - position?: HighchartsPosition; + drilldown?: (event: ChartDrilldownEvent) => void; /** - * What box to align the button to. Can be either 'plotBox' or 'spacingBox'. - * @default 'plotBox' + * Fires when drilling up from a drilldown series. * @since 3.0.8 */ + drillup?: (event: Event) => void; + /** + * Fires when the chart is finished loading. One parameter, event, is passed to the function. This contains common + * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * + * From version 2.0.4, there is also a second parameter to Highcharts.Chart where a callback function can be passed + * to be executed on chart.load. + * + * The this keyword refers to the Chart object. + */ + load?: (event: Event) => void; + /** + * Fires when the chart is redrawn, either after a call to chart.redraw() or after an axis, series or point is + * modified with the redraw option set to true. One parameter, event, is passed to the function. This contains + * common event information based on jQuery or MooTools depending on which library is used as the base for + * Highcharts. + * + * The this keyword refers to the Chart object. + * @since 1.2.0 + */ + redraw?: (event: Event) => void; + /** + * Fires when an area of the chart has been selected. Selection is enabled by setting the chart's zoomType. One + * parameter, event, is passed to the function. This contains common event information based on jQuery or MooTools + * depending on which library is used as the base for Highcharts. The default action for the selection event is to + * zoom the chart to the selected area. It can be prevented by calling event.preventDefault(). + * + * Information on the selected area can be found through event.xAxis and event.yAxis, which are arrays containing + * the axes of each dimension and each axis' min and max values. The primary axes are event.xAxis[0] and + * event.yAxis[0]. Remember the unit of a datetime axis is milliseconds since 1970-01-01 00:00:00. + * + * selection: function(event) { + * // log the min and max of the primary, datetime x-axis + * console.log( + * Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', event.xAxis[0].min), + * Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', event.xAxis[0].max) + * ); + * // log the min and max of the y axis + * console.log(event.yAxis[0].min, event.yAxis[0].max); + * } + */ + selection?: (event: ChartSelectionEvent) => void; + } + + interface LinearGradient { + x1: number; + y1: number; + x2: number; + y2: number; + } + + interface Gradient { + linearGradient?: LinearGradient | number[]; + radialGradient?: { + cx: number; cy: number; r: number; + }; + stops?: any[][]; + /** + * Brighten the color + * @param {number} alpha + */ + brighten?(alpha: number): Gradient; + /** + * Return the color a specified format + * @param {string} format + */ + get?(format: string): string; + /** + * The raw input + */ + raw?: string; + /** + * rgba array + */ + rgba?: number[]; + /** + * Set the color's opacity to a given alpha value + * @param {number} alpha + * @return {Gradient} + */ + setOpacity?(alpha: number): Gradient; + } + + /** + * Type equivalent to the 'Color' type mentioned throughout the documentation. + */ + type Color = string | Gradient; + + interface ChartOptions3dFrame { + /** + * The color of the panel. + * @default 'transparent' + * @since 4.0 + */ + color?: string | Gradient; + /** + * Thickness of the panel. + * @default 1 + * @since 4.0 + */ + size?: number; + } + + interface ChartOptions3d { + /** + * One of the two rotation angles for the chart. + * @default 0 + * @since 4.0 + */ + alpha?: number; + /** + * One of the two rotation angles for the chart. + * @default 0 + * @since 4.0 + */ + beta?: number; + /** + * The total depth of the chart. + * @default 100 + * @since 4.0 + */ + depth?: number; + /** + * Wether to render the chart using the 3D functionality. + * @default false + * @since 4.0 + */ + enabled?: boolean; + /** + * Provides the option to draw a frame around the charts by defining a bottom, front and back panel. + */ + frame?: { + /** + * Defines the back panel of the frame around 3D charts. + * @since 4.0 + */ + back?: ChartOptions3dFrame; + /** + * The bottom of the frame around a 3D chart. + * @since 4.0 + */ + bottom?: ChartOptions3dFrame; + /** + * The side for the frame around a 3D chart. + * @since 4.0 + */ + side?: ChartOptions3dFrame; + }; + /** + * Defines the distance the viewer is standing in front of the chart, this setting is important to calculate the + * perspective effect in column and scatter charts. It is not used for 3D pie charts. + * @default 100 + * @since 4.0 + */ + viewDistance?: number; + } + + interface Shadow { + /** + * @default 'black' + */ + color?: string | Gradient; + /** + * @default 1 + */ + offsetX?: number; + /** + * @default 1 + */ + offsetY?: number; + /** + * @default 0.15 / width + */ + opacity?: number; + /** + * @default 3 + */ + width?: number; + } + + interface ChartResetZoomButton { + /** + * The position of the button. This is an object that can hold the properties align, verticalAlign, x and y. + * @since 2.2 + */ + position?: Position; + /** + * What frame the button should be placed related to. Can be either 'plot' or 'chart'. + * @default 'plot' + * @since 2.2 + */ relativeTo?: string; /** - * A collection of attributes for the button. The object takes SVG attributes like fill, stroke, stroke-width or - * r, the border radius. The theme also supports style, a collection of CSS properties for the text. Equivalent + * A collection of attributes for the button. The object takes SVG attributes like fill, stroke, stroke-width or r, + * the border radius. The theme also supports style, a collection of CSS properties for the text. Equivalent * attributes for the hover state are given in theme.states.hover. - * @since 3.0.8 + * @since 2.2 */ - theme?: HighchartsButtonStatesTheme; + theme?: ButtonStatesTheme; } - /** - * An array of series configurations for the drill down. Each series configuration uses the same syntax as the - * series option set. These drilldown series are hidden by default. The drilldown series is linked to the parent - * series' point by its id. - * @since 3.0.8 - */ - series?: HighchartsIndividualSeriesOptions[]; -} -interface HighchartsMenuItem { - /** - * String to show in the menu item. - */ - text: string; - /** - * Callback function to run on click. - */ - onclick: () => void; -} - -interface HighchartsButton { - /** - * Alignment for the buttons. - * @default 'right' - * @since 2.0 - */ - align?: string; - /** - * Whether to enable buttons. - * @default true - * @since 2.0 - */ - enabled?: boolean; - /** - * Pixel height of the buttons. - * @default 20 - * @since 2.0 - */ - height?: number; - /** - * Fill color for the symbol within the button. - * @default '#E0E0E0' - * @since 2.0 - */ - symbolFill?: string; - /** - * The pixel size of the symbol on the button. - * @default 14 - * @since 2.0 - */ - symbolSize?: number; - /** - * The color of the symbol's stroke or line. - * @default '#666' - * @since 2.0 - */ - symbolStroke?: string; - /** - * The pixel stroke width of the symbol on the button. - * @default 1 - * @since 2.0 - */ - symbolStrokeWidth?: number; - /** - * The x position of the center of the symbol inside the button. - * @default 12.5 - * @since 2.0 - */ - symbolX?: number; - /** - * The y position of the center of the symbol inside the button. - * @default 10.5 - * @since 2.0 - */ - symbolY?: number; - /** - * A text string to add to the individual button. - * @default null - * @since 3.0 - */ - text?: string; - /** - * A configuration object for the button theme. The object accepts SVG properties like stroke-width, stroke and - * fill. Tri-state button styles are supported by the states.hover and states.select objects. - * @since 3.0 - */ - theme?: HighchartsButtonStatesTheme; - /** - * The vertical alignment of the buttons. Can be one of 'top', 'middle' or 'bottom'. - * @default 'top' - * @since 2.0 - */ - verticalAlign?: string; - /** - * The pixel width of the button. - * @default 24 - * @since 2.0 - */ - width?: number; - /** - * The vertical offset of the button's position relative to its verticalAlign. - * @default 0 - * @since 2.0 - */ - y?: number; -} - -interface HighchartsExportingContextButton extends HighchartsButton { - /** - * A collection of config options for the menu items. Each options object consists of a text option which is a - * string to show in the menu item, as well as an onclick parameter which is a callback function to run on click. - * - * By default, there is the 'Print' menu item plus one menu item for each of the available export types. Menu items - * can be customized by defining a new array of items and assigning null to unwanted positions. - * @since 2.0 - */ - menuItems?: HighchartsMenuItem[]; - /** - * A click handler callback to use on the button directly instead of the popup menu. - * @since 2.0 - */ - onclick?: () => void; - /** - * The symbol for the button. Points to a definition function in the Highcharts.Renderer.symbols collection. The - * default exportIcon function is part of the exporting module. - * @default 'menu' - */ - symbol?: string; - /** - * The horizontal position of the button relative to the align option. - * @default -10 - */ - x?: number; -} - -interface HighchartsExportingOptions { - /** - * Experimental setting to allow HTML inside the chart (added through the useHTML options), directly in the exported - * image. This allows you to preserve complicated HTML structures like tables or bi-directional text in exported - * charts. - * - * Disclaimer: The HTML is rendered in a foreignObject tag in the generated SVG. The official export server is based - * on PhantomJS, which supports this, but other SVG clients, like Batik, does not support it. This also applies to - * downloaded SVG that you want to open in a desktop client. - * @default false - * @since 4.1.8 - */ - allowHTML?: boolean; - /** - * Options for the export related buttons, print and export. In addition to the default buttons listed here, custom - * buttons can be added. See navigation.buttonOptions for general options. - */ - buttons?: { - contextButton?: HighchartsExportingContextButton; - }; - /** - * Additional chart options to be merged into an exported chart. For example, the exported chart can be given a - * specific width and height, or a printer-friendly color scheme. - * @default null - */ - chartOptions?: HighchartsOptions; - /** - * Whether to enable the exporting module. Disabling the module will hide the context button, but API methods will - * still be available. - * @default true - * @since 2.0 - */ - enabled?: boolean; - /** - * Whether or not to fall back to the export server if the offline-exporting module is unable to export the chart on - * the client side. - * @default true - * @since 4.1.8 - */ - fallbackToExportServer?: boolean; - /** - * The filename, without extension, to use for the exported chart. - * @default 'chart' - * @since 2.0 - */ - filename?: string; - /** - * An object containing additional attributes for the POST form that sends the SVG to the export server. For - * example, a target can be set to make sure the generated image is received in another frame, or a custom enctype - * or encoding can be set. - * @since 3.0.8 - */ - formAttributes?: any; - /** - * Defines the scale or zoom factor for the exported image compared to the on-screen display. While for instance a - * 600px wide chart may look good on a website, it will look bad in print. The default scale of 2 makes this chart - * export to a 1200px PNG or JPG. - * @default 2 - * @since 3.0 - */ - scale?: number; - /** - * The height of the original chart when exported, unless an explicit chart.height is set. The height exported - * raster image is then multiplied by scale. - * @since 3.0 - */ - sourceHeight?: number; - /** - * The width of the original chart when exported, unless an explicit chart.width is set. The width exported - * raster image is then multiplied by scale. - * @since 3.0 - */ - sourceWidth?: number; - /** - * Default MIME type for exporting if chart.exportChart() is called without specifying a type option. Possible - * values are image/png, image/jpeg, application/pdf and image/svg+xml. - * @default 'image/png' - * @since 2.0 - */ - type?: string; - /** - * The URL for the server module converting the SVG string to an image format. By default this points to Highslide - * Software's free web service. - * @default 'http://export.highcharts.com' - * @since 2.0 - */ - url?: string; - /** - * The pixel width of charts exported to PNG or JPG. As of Highcharts 3.0, the default pixel width is a function of - * the chart.width or exporting.sourceWidth and the exporting.scale. - * @since 2.0 - */ - width?: number; -} - -/** - * Global options that don't apply to each chart. These options, like the lang options, must be set using the - * Highcharts.setOptions method. - */ -interface HighchartsGlobalObject { - /** - * A custom Date class for advanced date handling. For example, JDate can be hooked in to handle Jalali dates. - * @since 4.0.4 - */ - Date?: any; - /** - * Path to the pattern image required by VML browsers in order to draw radial gradients. - * @default 'http://code.highcharts.com/{version}/gfx/vml-radial-gradient.png' - * @since 2.3.0 - */ - VMLRadialGradientURL?: string; - /** - * The URL to the additional file to lazy load for Android 2.x devices. These devices don't support SVG, so we - * download a helper file that contains canvg, its dependency rbcolor, and our own CanVG Renderer class. To avoid - * hotlinking to our site, you can install canvas-tools.js on your own server and change this option accordingly. - * @default 'http://code.highcharts.com/{version}/modules/canvas-tools.js' - */ - canvasToolsURL?: string; - /** - * A callback to return the time zone offset for a given datetime. It takes the timestamp in terms of milliseconds - * since January 1 1970, and returns the timezone offset in minutes. This provides a hook for drawing time based - * charts in specific time zones using their local DST crossover dates, with the help of external libraries. - * @since 4.1.0 - */ - getTimezoneOffset?: (timestamp: number) => number; - /** - * The timezone offset in minutes. Positive values are west, negative values are east of UTC, as in the ECMAScript - * getTimezoneOffset method. Use this to display UTC based data in a predefined time zone. - * @default 0 - * @since 3.0.8 - */ - timezoneOffset?: number; - /** - * Whether to use UTC time for axis scaling, tickmark placement and time display in Highcharts.dateFormat. - * Advantages of using UTC is that the time displays equally regardless of the user agent's time zone settings. - * Local time can be used when the data is loaded in real time or when correct Daylight Saving Time transitions are - * required. - * @default true - */ - useUTC?: boolean; -} - -interface HighchartsLabelItem { - html: string; - style: HighchartsCSSObject; -} - -interface HighchartsLabelsOptions { - items?: HighchartsLabelItem[]; - style?: HighchartsCSSObject; -} - -interface HighchartsLangObject { - /** - * Exporting module menu. The tooltip title for the context menu holding print and export menu items. - * @default 'Chart context menu' - * @since 3.0 - */ - contextButtonTitle?: string; - /** - * The default decimal point used in the Highcharts.numberFormat method unless otherwise specified in the function - * arguments. - * @default '.' - * @since 1.2.2 - */ - decimalPoint?: string; - /** - * Exporting module only. The text for the JPEG download menu item. - * @default 'Download JPEG image' - * @since 2.0 - */ - downloadJPEG?: string; - /** - * Exporting module only. The text for the PDF download menu item. - * @default 'Download PDF document' - * @since 2.0 - */ - downloadPDF?: string; - /** - * Exporting module only. The text for the PNG download menu item. - * @default 'Download PNG image' - * @since 2.0 - */ - downloadPNG?: string; - /** - * Exporting module only. The text for the SVG download menu item. - * @default 'Download SVG vector image' - * @since 2.0 - */ - downloadSVG?: string; - /** - * The text for the button that appears when drilling down, linking back to the parent series. The parent series' - * name is inserted for {series.name} - * @default 'Back to {series.name}' - * @since 3.0.8 - */ - drillUpText?: string; - /** - * What to show in a date field for invalid dates. - * @default '' - * @since 4.1.8 - */ - invalidDate?: string; - /** - * The loading text that appears when the chart is set into the loading state following a call to chart.showLoading. - * @default 'Loading...' - */ - loading?: string; - /** - * An array containing the months names. Corresponds to the %B format in Highcharts.dateFormat(). - * @default ['January' , 'February' , 'March' , 'April' , 'May' , 'June' , 'July' , 'August' , 'September' , 'October' , 'November' , 'December'] - */ - months?: string[]; - /** - * The text to display when the chart contains no data. Requires the no-data module, see noData. - * @default 'No data to display' - * @since 3.0.8 - */ - noData?: string; - /** - * Metric prefixes used to shorten high numbers in axis labels. Replacing any of the positions with null causes the - * full number to be written. Setting numericSymbols to null disables shortening altogether. - * @default ['k', 'M', 'G', 'T', 'P', 'E'] - * @since 2.3.0 - */ - numericSymbols?: string[]; - /** - * Exporting module only. The text for the menu item to print the chart. - * @default 'Print chart' - * @since 3.0.1 - */ - printChart?: string; - /** - * The text for the label appearing when a chart is zoomed. - * @default 'Reset zoom' - * @since 1.2.4 - */ - resetZoom?: string; - /** - * The tooltip title for the label appearing when a chart is zoomed. - * @default 'Reset zoom level 1:1' - * @since 1.2.4 - */ - resetZoomTitle?: string; - /** - * An array containing the months names in abbreviated form. Corresponds to the %b format in - * Highcharts.dateFormat(). - * @default ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - */ - shortMonths?: string[]; - /** - * The default thousands separator used in the Highcharts.numberFormat method unless otherwise specified in the - * function arguments. Since Highcharts 4.1 it defaults to a single space character, which is compatible with ISO - * and works across Anglo-American and continental European languages. - * @default ' ' - * @since 1.2.2 - */ - thousandsSep?: string; - /** - * An array containing the weekday names. - * @default ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] - */ - weekdays?: string[]; -} - -interface HighchartsLegendNavigationOptions { - /** - * The color for the active up or down arrow in the legend page navigation. - * @default '#3E576F' - * @since 2.2.4 - */ - activeColor?: string; - /** - * How to animate the pages when navigating up or down. A value of true applies the default navigation given in the - * chart.animation option. Additional options can be given as an object containing values for easing and duration. - * @default true - * @since 2.2.4 - */ - animation?: boolean | HighchartsAnimation; - /** - * The pixel size of the up and down arrows in the legend paging navigation. - * @default 12 - * @since 2.2.4 - */ - arrowSize?: number; - /** - * The color of the inactive up or down arrow in the legend page navigation. - * @default '#CCC' - */ - inactiveColor?: string; - /** - * Text styles for the legend page navigation. - * @since 2.2.4 - */ - style?: HighchartsCSSObject; -} - -interface HighchartsLegendTitleOptions { - /** - * Generic CSS styles for the legend title. - * @default {'fontWeight':'bold'} - * @since 3.0 - */ - style?: HighchartsCSSObject; - /** - * A text or HTML string for the title. - * @default null - * @since 3.0 - */ - text?: string; -} - -interface HighchartsLegendOptions { - /** - * The horizontal alignment of the legend box within the chart area. Valid values are 'left', 'center' and 'right'. - * In the case that the legend is aligned in a corner position, the layout option will determine whether to place it - * above/below or on the side of the plot area. - * @default 'center' - * @since 2.0 - */ - align?: string; - /** - * The background color of the legend. - */ - backgroundColor?: string | HighchartsGradient; - /** - * The color of the drawn border around the legend. - * @default '#909090' - */ - borderColor?: string | HighchartsGradient; - /** - * The border corner radius of the legend. - * @default 0 - */ - borderRadius?: number; - /** - * The width of the drawn border around the legend. - * @default 0 - */ - borderWidth?: number; - /** - * Enable or disable the legend. - * @default true - */ - enabled?: boolean; - /** - * When the legend is floating, the plot area ignores it and is allowed to be placed below it. - * @default false - * @since 2.1 - */ - floating?: boolean; - /** - * In a legend with horizontal layout, the itemDistance defines the pixel distance between each item. - * @default 20 - * @since 3.0.3 - */ - itemDistance?: number; - /** - * CSS styles for each legend item when the corresponding series or point is hidden. Only a subset of CSS is - * supported, notably those options related to text. Properties are inherited from style unless overridden here. - * @default {color: '#CCC'} - */ - itemHiddenStyle?: HighchartsCSSObject; - /** - * CSS styles for each legend item in hover mode. Only a subset of CSS is supported, notably those options related - * to text. Properties are inherited from style unless overridden here. - * @default {color: '#000'} - */ - itemHoverStyle?: HighchartsCSSObject; - /** - * The pixel bottom margin for each legend item. - * @default 0 - * @since 2.2.0 - */ - itemMarginBottom?: number; - /** - * The pixel top margin for each legend item. - * @default 0 - * @since 2.2.0 - */ - itemMarginTop?: number; - /** - * CSS styles for each legend item. Only a subset of CSS is supported, notably those options related to text. - * @default { 'color': '#333333', 'cursor': 'pointer', 'fontSize': '12px', 'fontWeight': 'bold' } - */ - itemStyle?: HighchartsCSSObject; - /** - * The width for each legend item. This is useful in a horizontal layout with many items when you want the items to - * align vertically. - * @since 2.0 - */ - itemWidth?: number; - /** - * A format string for each legend label. Available variables relates to properties on the series, or the point in - * case of pies. - * @default '{name}' - * @since 1.3 - */ - labelFormat?: string; - /** - * Callback function to format each of the series' labels. The this keyword refers to the series object, or the - * point object in case of pie charts. By default the series or point name is printed. - */ - labelFormatter?: () => string; - /** - * The layout of the legend items. Can be one of 'horizontal' or 'vertical'. - * @default 'horizontal' - */ - layout?: string; - /** - * Line height for the legend items. Deprecated as of 2.1. Instead, the line height for each item can be set using - * itemStyle.lineHeight, and the padding between items using itemMarginTop and itemMarginBottom. - * @default 16 - * @since 2.0 - * @deprecated - */ - lineHeight?: number; - /** - * If the plot area sized is calculated automatically and the legend is not floating, the legend margin is the space - * between the legend and the axis labels or plot area. - * @default 12 - * @since 2.1 - */ - margin?: number; - /** - * Maximum pixel height for the legend. When the maximum height is extended, navigation will show. - * @since 2.3.0 - */ - maxHeight?: number; - /** - * Options for the paging or navigation appearing when the legend is overflown. - */ - navigation?: HighchartsLegendNavigationOptions; - /** - * The inner padding of the legend box. - * @default 8 - * @since 2.2.0 - */ - padding?: number; - /** - * Whether to reverse the order of the legend items compared to the order of the series or points as defined in the - * configuration object. - * @default false - * @since 1.2.5 - */ - reversed?: boolean; - /** - * Whether to show the symbol on the right side of the text rather than the left side. This is common in Arabic and - * Hebraic. - * @default false - * @since 2.2 - */ - rtl?: boolean; - /** - * Whether to apply a drop shadow to the legend. A backgroundColor also needs to be applied for this to take effect. - * Since 2.3 the shadow can be an object configuration containing color, offsetX, offsetY, opacity and width. - * @default false - */ - shadow?: boolean | HighchartsShadow; - /** - * CSS styles for the legend area. In the 1.x versions the position of the legend area was determined by CSS. In - * 2.x, the position is determined by properties like align, verticalAlign, x and y, but the styles are still parsed - * for backwards compatibility. - * @deprecated - */ - style?: HighchartsCSSObject; - /** - * The pixel height of the symbol for series types that use a rectangle in the legend. Defaults to the font size of - * legend items. - * @since 3.0.8 - */ - symbolHeight?: number; - /** - * The pixel padding between the legend item symbol and the legend item text. - * @default 5 - */ - symbolPadding?: number; - /** - * The border radius of the symbol for series types that use a rectangle in the legend. - * @default 0 - * @since 3.0.8 - */ - symbolRadius?: number; - /** - * The pixel width of the legend item symbol. - * @default 16 - */ - symbolWidth?: number; - /** - * A title to be added on top of the legend. - * @since 3.0 - */ - title?: HighchartsLegendTitleOptions; - /** - * Whether to use HTML to render the legend item texts. Prior to 4.1.7, when using HTML, legend.navigation was - * disabled. - * @default false - */ - useHTML?: boolean; - /** - * The vertical alignment of the legend box. Can be one of 'top', 'middle' or 'bottom'. Vertical position can be - * further determined by the y option. - * - * In the case that the legend is aligned in a corner position, the layout option will determine whether to place it - * above/below or on the side of the plot area. - * - * @default 'bottom' - * @since 2.0 - */ - verticalAlign?: string; - /** - * The width of the legend box. - * @since 2.0 - */ - width?: number; - /** - * The x offset of the legend relative to its horizontal alignment align within chart.spacingLeft and - * chart.spacingRight. Negative x moves it to the left, positive x moves it to the right. - * @default 0 - * @since 2.0 - */ - x?: number; - /** - * The vertical offset of the legend relative to it's vertical alignment verticalAlign within chart.spacingTop and - * chart.spacingBottom. Negative y moves it up, positive y moves it down. - * @default 0 - * @since 2.0 - */ - y?: number; -} - -/** - * The loading options control the appearance of the loading screen that covers the plot area on chart operations. This - * screen only appears after an explicit call to chart.showLoading(). It is a utility for developers to communicate to - * the end user that something is going on, for example while retrieving new data via an XHR connection. The - * 'Loading...' text itself is not part of this configuration object, but part of the lang object. - */ -interface HighchartsLoadingOptions { - /** - * The duration in milliseconds of the fade out effect. - * @default 100 - * @since 1.2.0 - */ - hideDuration?: number; - /** - * CSS styles for the loading label span. - * @default { 'fontWeight': 'bold', 'position': 'relative', 'top': '45%' } - */ - labelStyle?: HighchartsCSSObject; - /** - * The duration in milliseconds of the fade in effect. - * @default 100 - * @since 1.2.0 - */ - showDuration?: number; - /** - * CSS styles for the loading screen that covers the plot area. - * @default { position: 'absolute', backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } - */ - style?: Object; -} - -/** - * A collection of options for buttons and menus appearing in the exporting module. - */ -interface HighchartsNavigationOptions { - /** - * A collection of options for buttons appearing in the exporting module. - */ - buttonOptions?: HighchartsButton; - /** - * CSS styles for the hover state of the individual items within the popup menu appearing by default when the export - * icon is clicked. The menu items are rendered in HTML. - * @default {background: '#4572A5', color: '#FFFFFF'} - * @since 2.0 - */ - menuItemHoverStyle?: Object; - /** - * CSS styles for the individual items within the popup menu appearing by default when the export icon is clicked. - * The menu items are rendered in HTML. - * @default { padding: '0 5px', background: NONE, color: '#303030'} - * @since 2.0 - */ - menuItemStyle?: Object; - /** - * CSS styles for the popup menu appearing by default when the export icon is clicked. This menu is rendered in - * HTML. - * @default { border: '1px solid #A0A0A0', background: '#FFFFFF' } - * @since 2.0 - */ - menuStyle?: Object; -} - -/** - * Options for displaying a message like 'No data to display'. This feature requires the file no-data-to-display.js to - * be loaded in the page. The actual text to display is set in the lang.noData option. - */ -interface HighchartsNoDataOptions { - /** - * An object of additional SVG attributes for the no-data label. - * @since 3.0.8 - */ - attr?: {}; - /** - * The position of the no-data label, relative to the plot area. - * @default { 'x': 0, 'y': 0, 'align': 'center', 'verticalAlign': 'middle' } - * @since 3.0.8 - */ - position?: HighchartsPosition; - /** - * CSS styles for the no-data label. - * @default { 'fontSize': '12px', 'fontWeight': 'bold', 'color': '#60606a' } - */ - style?: HighchartsCSSObject; -} - -interface HighchartsPaneBackground { - /** - * @default {linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [[0, '#FFF'],[1, '#DDD']]} - */ - backgroundColor: string | HighchartsGradient; - /** - * @default 'silver' - */ - borderColor?: string | HighchartsGradient; - /** - * @default 1 - */ - borderWidth?: number; - /** - * @default 0 - */ - innerRadius?: number | string; - /** - * @default '105%' - */ - outerRadius?: number | string; - /** - * @default 'circle' - */ - shape?: string; -} - -/** - * Applies only to polar charts and angular gauges. This configuration object holds general options for the combined X - * and Y axes set. Each xAxis or yAxis can reference the pane by index. - */ -interface HighchartsPaneOptions { - /** - * An object, or array of objects, for backgrounds. Sub options include backgroundColor (can be solid or gradient), - * shape ('solid', 'arc' or 'circle'), innerWidth, outerWidth, borderWidth, borderColor. - * @since 2.3.0 - */ - background?: HighchartsPaneBackground | HighchartsPaneBackground[]; - /** - * The center of a polar chart or angular gauge, given as an array of [x, y] positions. Positions can be given as - * integers that transform to pixels, or as percentages of the plot area size. - * @default ['50%', '50%'] - * @since 2.3.0 - */ - center?: [number|string, number|string]; - /** - * The end angle of the polar X axis or gauge value axis, given in degrees where 0 is north. - * @default startAngle + 360 - * @since 2.3.0 - */ - endAngle?: number; - /** - * The size of the pane, either as a number defining pixels, or a percentage defining a percentage of the plot are. - * @default '85%' - */ - size?: number | string; - /** - * The size of the pane, either as a number defining pixels, or a percentage defining a percentage of the plot are - * @since 2.3.0 - */ - startAngle?: number; -} - -interface HighchartsDataLabels { - /** - * The alignment of the data label compared to the point. If right, the right side of the label should be touching - * the point. For points with an extent, like columns, the alignments also dictates how to align it inside the box, - * as given with the inside option. Can be one of 'left', 'center' or 'right'. - * @default 'center' - */ - align?: string; - /** - * Whether to allow data labels to overlap. To make the labels less sensitive for overlapping, the - * dataLabels.padding can be set to 0. - * @default false - * @since 4.1.0 - */ - allowOverlap?: boolean; - /** - * The background color or gradient for the data label. - * @since 2.2.1 - */ - backgroundColor?: string | HighchartsGradient; - /** - * The border color for the data label. - * @since 2.2.1 - */ - borderColor?: string | HighchartsGradient; - /** - * The border radius in pixels for the data label. - * @default 0 - * @since 2.2.1 - */ - borderRadius?: number; - /** - * The border width in pixels for the data label. - * @default 0 - * @since 2.2.1 - */ - borderWidth?: number; - /** - * The text color for the data labels. - * @default null - */ - color?: string | HighchartsGradient; - /** - * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot - * area according to the overflow option. - * @default 2.3.3 - */ - crop?: boolean; - /** - * Whether to defer displaying the data labels until the initial series animation has finished. - * @default true - * @since 4.0 - */ - defer?: boolean; - /** - * Enable or disable the data labels. - * @default false - */ - enabled?: boolean; - /** - * A format string for the data label. Available variables are the same as for formatter. - * @default {y} - * @since 3.0 - */ - format?: string; - /** - * Callback JavaScript function to format the data label. Note that if a format is defined, the format takes - * precedence and the formatter is ignored. - * Available data are: - * - this.percentage Stacked series and pies only. The point's percentage of the total. - * - this.point The point object. The point name, if defined, is available through this.point.name. - * - this.series The series object. The series name is available through this.series.name. - * - this.total Stacked series only. The total value at this point's x value. - * - this.x: The x value. - * - this.y: The y value. - */ - formatter?: () => string; - /** - * For points with an extent, like columns, whether to align the data label inside the box or to the actual value - * point. Defaults to false in most cases, true in stacked columns. - * @since 3.0 - */ - inside?: boolean; - /** - * How to handle data labels that flow outside the plot area. The default is 'justify', which aligns them inside the - * plot area. For columns and bars, this means it will be moved inside the bar. To display data labels outside the - * plot area, set crop to false and overflow to 'none'. - * @default 'justify' - * @since 3.0.6 - */ - overflow?: string; - /** - * When either the borderWidth or the backgroundColor is set, this is the padding within the box. - * @default 5 - * @since 2.2.1 - */ - padding?: number; - /** - * Text rotation in degrees. Note that due to a more complex structure, backgrounds, borders and padding will be - * lost on a rotated data label. - * @default 0 - */ - rotation?: number; - /** - * The shadow of the box. Works best with borderWidth or backgroundColor. Since 2.3 the shadow can be an object - * configuration containing color, offsetX, offsetY, opacity and width. - * @default false - */ - shadow?: boolean | HighchartsShadow; - /** - * The name of a symbol to use for the border around the label. Symbols are predefined functions on the Renderer - * object. - * @default 'square' - * @since 4.1.2 - */ - shape?: string; - /** - * Styles for the label. - * @default {'color': 'contrast', 'fontSize': '11px', 'fontWeight': 'bold', 'textShadow': '0 0 6px contrast, 0 0 3px contrast' } - * @since 4.1.0 - */ - style?: HighchartsCSSObject; - /** - * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the labels. - * @default false - */ - useHTML?: boolean; - /** - * The vertical alignment of a data label. Can be one of top, middle or bottom. The default value depends on the - * data, for instance in a column chart, the label is above positive values and below negative values. - * @since 2.3.3 - */ - verticalAlign?: string; - /** - * The x position offset of the label relative to the point. - * @default 0 - */ - x?: number; - /** - * The y position offset of the label relative to the point. - * @default -6 - */ - y?: number; - /** - * The Z index of the data labels. The default Z index puts it above the series. Use a Z index of 2 to display it - * behind the series. - * @default 6 - * @since 2.3.5 - */ - zIndex?: number; -} - -interface HighchartsPieDataLabels extends HighchartsDataLabels { - /** - * The color of the line connecting the data label to the pie slice. The default color is the same as the point's - * color. Defaults to {point.color}. - * @since 2.1 - */ - connectorColor?: string; - /** - * The distance from the data label to the connector. - * @default 5 - * @since 2.1 - */ - connectorPadding?: number; - /** - * The width of the line connecting the data label to the pie slice. - * @default 1 - * @since 2.1 - */ - connectorWidth?: number; - /** - * The distance of the data label from the pie's edge. Negative numbers put the data label on top of the pie slices. - * Connectors are only shown for data labels outside the pie. - * @default 30 - * @since 2.1 - */ - distance?: number; - /** - * Whether to render the connector as a soft arc or a line with sharp break. - * @default true - * @since 2.1.7 - */ - softConnector?: boolean; -} - -interface HighchartsAreaCheckboxEvent extends Event { - /** - * The state of the checkbox - */ - checked: boolean; - /** - * The checked item - */ - item: HighchartsSeriesObject | HighchartsPointObject; -} - -interface HighchartsAreaClickEvent extends Event { - /** - * A pointer to the nearest point on the graph - */ - point: HighchartsPointObject; -} - -interface HighchartsPlotEvents { - /** - * Fires after the series has finished its initial animation, or in case animation is disabled, immediately as the - * series is displayed. - * - * The this keyword refers to the Series object. - * @since 4.0 - */ - afterAnimate?: (event: Event) => void; - /** - * Fires when the checkbox next to the series' name in the legend is clicked. One parameter, event, is passed to the - * function. The state of the checkbox is found by event.checked. The checked item is found by event.item. Return - * false to prevent the default action which is to toggle the select state of the series. - * - * The this keyword refers to the Series object. - * @since 1.2.0 - */ - checkboxClick?: (event: HighchartsAreaCheckboxEvent) => boolean|void; - /** - * Fires when the series is clicked. One parameter, event, is passed to the function. This contains common event - * information based on jQuery or MooTools depending on which library is used as the base for Highcharts. - * Additionally, event.point holds a pointer to the nearest point on the graph. - * - * The this keyword refers to the Series object. - */ - click?: (event: HighchartsAreaClickEvent) => void; - /** - * Fires when the series is hidden after chart generation time, either by clicking the legend item or by calling - * .hide(). - * - * The this keyword refers to the Series object. - */ - hide?: () => void; - /** - * Fires when the legend item belonging to the series is clicked. One parameter, event, is passed to the function. - * This contains common event information based on jQuery or MooTools depending on which library is used as the base - * for Highcharts. The default action is to toggle the visibility of the series. This can be prevented by returning - * false or calling event.preventDefault(). - * - * The this keyword refers to the Series object. - */ - legendItemClick?: (event: Event) => boolean|void; - /** - * Fires when the mouse leaves the graph. One parameter, event, is passed to the function. This contains common - * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. If - * the stickyTracking option is true, mouseOut doesn't happen before the mouse enters another graph or leaves the - * plot area. - * - * The this keyword refers to the Series object. - */ - mouseOut?: (event: Event) => void; - /** - * Fires when the mouse enters the graph. One parameter, event, is passed to the function. This contains common - * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. - * - * The this keyword refers to the Series object. - */ - mouseOver?: (event: Event) => void; - /** - * Fires when the series is shown after chart generation time, either by clicking the legend item or by calling - * .show(). - * - * The this keyword refers to the Series object. - * @since 1.2.0 - */ - show?: () => void; -} - -interface HighchartsMarkerState { - /** - * Enable or disable the point marker. If null, the markers are hidden when the data is dense, and shown for more - * widespread data points. - * @default null, true for hover and select - */ - enabled?: boolean; - /** - * The fill color of the point marker. When null, the series' or point's color is used. - */ - fillColor?: string; - /** - * The color of the point marker's outline. When null, the series' or point's color is used. - * @default '#FFFFFF', '#000000' for select state - */ - lineColor?: string | HighchartsGradient; - /** - * The width of the point marker's outline. - * @default 0 - */ - lineWidth?: number; - /** - * The radius of the point marker. - * @default 4, undefined for hover and select - */ - radius?: number; -} - -interface HighchartsMarkerHoverState extends HighchartsMarkerState { - /** - * The additional line width for a hovered point. - * @default 1 - * @since 4.0.3 - */ - lineWidthPlus?: number; - /** - * The number of pixels to increase the radius of the hovered point. - * @default 2 - * @since 4.0.3 - */ - radiusPlus?: number; -} - -interface HighchartsMarker extends HighchartsMarkerState { - /** - * Image markers only. Set the image width explicitly. When using this option, a width must also be set. - * @default null - * @since 4.0.4 - */ - height?: number; - states?: { - hover?: HighchartsMarkerHoverState; + interface ButtonTheme { + display?: string; // css attr eg: 'none' /** - * The appearance of the point marker when selected. In order to allow a point to be selected, set the - * series.allowPointSelect option to true. + * The button fill color, SVG color definition */ - select?: HighchartsMarkerState; - }; - /** - * A predefined shape or symbol for the marker. When null, the symbol is pulled from options.symbols. Other possible - * values are 'circle', 'square', 'diamond', 'triangle' and 'triangle-down'. - * - * Additionally, the URL to a graphic can be given on this form: 'url(graphic.png)'. Note that for the image to be - * applied to exported charts, its URL needs to be accessible by the export server. - * - * Custom callbacks for symbol path generation can also be added to Highcharts.SVGRenderer.prototype.symbols. The - * callback is then used by its method name. - */ - symbol?: string; // null, 'circle', 'square', 'diamond', 'triangle' 'triangle-down' or 'url(graphic.png)' - /** - * Image markers only. Set the image width explicitly. When using this option, a height must also be set. - * @default null. - * @since 4.0.4 - */ - width?: number; -} - -interface HighchartsPointEvents { - /** - * Fires when a point is clicked. One parameter, event, is passed to the function. This contains common event - * information based on jQuery or MooTools depending on which library is used as the base for Highcharts. - * - * If the series.allowPointSelect option is true, the default action for the point's click event is to toggle the - * point's select state. Returning false cancels this action. - * - * The this keyword refers to the Point object. - */ - click?: (event: Event) => boolean; - /** - * Fires when the mouse leaves the area close to the point. One parameter, event, is passed to the function. This - * contains common event information based on jQuery or MooTools depending on which library is used as the base for - * Highcharts. - * - * The this keyword refers to the Point object. - */ - mouseOut?: (event: Event) => void; - /** - * Fires when the mouse enters the area close to the point. One parameter, event, is passed to the function. This - * contains common event information based on jQuery or MooTools depending on which library is used as the base for - * Highcharts. - * - * The this keyword refers to the Point object. - */ - mouseOver?: (event: Event) => void; - /** - * Fires when the point is removed using the .remove() method. One parameter, event, is passed to the function. - * Returning false cancels the operation. - * - * The this keyword refers to the Point object. - * @since 1.2.0 - */ - remove?: (event: Event) => boolean|void; - /** - * Fires when the point is selected either programmatically or following a click on the point. One parameter, event, - * is passed to the function. Returning false cancels the operation. - * - * The this keyword refers to the Point object. - * @since 1.2.0 - */ - select?: (event: Event) => boolean|void; - /** - * Fires when the point is unselected either programmatically or following a click on the point. One parameter, - * event, is passed to the function. Returning false cancels the operation. - * - * The this keyword refers to the Point object. - * @since 1.2.0 - */ - unselect?: (event: Event) => boolean|void; - /** - * Fires when the point is updated programmatically through the .update() method. One parameter, event, is passed to - * the function. The new point options can be accessed through event.options. Returning false cancels the operation. - * - * The this keyword refers to the Point object. - * @since 1.2.0 - */ - update?: (event: Event) => boolean|void; - /** - * Fires when the legend item belonging to the pie point (slice) is clicked. - * The this keyword refers to the point itself. One parameter, event, is passed to the function. - * This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. - * The default action is to toggle the visibility of the point. This can be prevented by calling event.preventDefault(). - */ - legendItemClick?: (event: Event) => boolean | void; - -} - -interface HighchartsHalo { - /** - * A collection of SVG attributes to override the appearance of the halo, for example fill, stroke and stroke-width. - * @since 4.0 - */ - attributes?: {}; - /** - * Opacity for the halo unless a specific fill is overridden using the attributes setting. Note that Highcharts is - * only able to apply opacity to colors of hex or rgb(a) formats. - * @default 0.25 - * @since 4.0 - */ - opacity?: number; - /** - * The pixel size of the halo. For point markers this is the radius of the halo. For pie slices it is the width of - * the halo outside the slice. For bubbles it defaults to 5 and is the width of the halo outside the bubble. - * Defaults to 10. - */ - size?: number; -} - -interface HighchartsLineStates { - /** - * Enable separate styles for the hovered series to visualize that the user hovers either the series itself or the - * legend. - * @default true - * @since 1.2 - */ - enabled?: boolean; - /** - * Options for the halo appearing around the hovered point in line-type series as well as outside the hovered slice - * in pie charts. By default the halo is filled by the current point or series color with an opacity of 0.25. The - * halo can be disabled by setting the halo option to false. - * @since 4.0 - */ - halo?: boolean | HighchartsHalo; - /** - * Pixel with of the graph line. - * @default 2 - */ - lineWidth?: number; - /** - * The additional line width for the graph of a hovered series. - * @default 1 - * @since 4.0.3 - */ - lineWidthPlus?: number; - marker?: HighchartsMarker; -} - -interface HighchartsBarStates { - /** - * A specific border color for the hovered point. Defaults to inherit the normal state border color. - */ - borderColor?: string | HighchartsGradient; - /** - * How much to brighten the point on interaction. Requires the main color to be defined in hex or rgb(a) format. - * @default 0.1 - */ - brightness?: number; - /** - * - */ - color?: string | HighchartsGradient; - /** - * Enable separate styles for the hovered series to visualize that the user hovers either the series itself or the - * legend. - * @default true - * @since 1.2 - */ - enabled?: boolean; - /** - * Options for the halo appearing around the hovered point in line-type series as well as outside the hovered slice - * in pie charts. By default the halo is filled by the current point or series color with an opacity of 0.25. The - * halo can be disabled by setting the halo option to false. - * @since 4.0 - */ - halo?: boolean | HighchartsHalo; -} - -interface HighchartsPieStates extends HighchartsBarStates, HighchartsLineStates { } - -interface HighchartsAreaZone { - /** - * Defines the color of the series. - * @since 4.1.0 - */ - color?: string | HighchartsGradient; - /** - * A name for the dash style to use for the graph. - * @since 4.1.0 - */ - dashStyle?: string; - /** - * Defines the fill color for the series (in area type series) - * @since 4.1.0 - */ - fillColor?: string; - /** - * The value up to where the zone extends, if undefined the zones stretches to the last value in the series. - * @default undefined - * @since 4.1.0 - */ - value?: number; -} - -interface HighchartsRangeDataLabels { - /** - * The alignment of the data label compared to the point. If right, the right side of the label should be touching - * the point. For points with an extent, like columns, the alignments also dictates how to align it inside the box, - * as given with the inside option. Can be one of 'left', 'center' or 'right'. - * @default 'center' - */ - align?: string; - /** - * Whether to allow data labels to overlap. To make the labels less sensitive for overlapping, the - * dataLabels.padding can be set to 0. - * @default false - * @since 4.1.0 - */ - allowOverlap?: boolean; - /** - * The background color or gradient for the data label. - * @default undefined - * @since 2.2.1 - */ - backgroundColor?: string | HighchartsGradient; - /** - * The border color for the data label. - * @default undefined - * @since 2.2.1 - */ - borderColor?: string | HighchartsGradient; - /** - * The border radius in pixels for the data label. - * @default 0 - * @since 2.2.1 - */ - borderRadius?: number; - /** - * The border width in pixels for the data label. - * @default 0 - * @since 2.2.1 - */ - borderWidth?: number; - /** - * The text color for the data labels. - * @default null - */ - color?: string | HighchartsGradient; - /** - * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot - * area according to the overflow option. - * @default true - * @since 2.3.3 - */ - crop?: boolean; - /** - * Whether to defer displaying the data labels until the initial series animation has finished. - * @default true - * @since 4.0 - */ - defer?: boolean; - /** - * Enable or disable the data labels. - * @default false - */ - enabled?: boolean; - /** - * A format string for the data label. Available variables are the same as for formatter. - * @default '{y}' - * @since 3.0 - */ - format?: string; - /** - * Callback JavaScript function to format the data label. Note that if a format is defined, the format takes - * precedence and the formatter is ignored. - * Available data are: - * - this.percentage Stacked series and pies only. The point's percentage of the total. - * - this.point The point object. The point name, if defined, is available through this.point.name. - * - this.series The series object. The series name is available through this.series.name. - * - this.total Stacked series only. The total value at this point's x value. - * - this.x: The x value. - * - this.y: The y value. - */ - formatter?: () => string; - /** - * For points with an extent, like columns, whether to align the data label inside the box or to the actual value - * point. Defaults to false in most cases, true in stacked columns. - * @since 3.0 - */ - inside?: boolean; - /** - * How to handle data labels that flow outside the plot area. The default is justify, which aligns them inside the - * plot area. For columns and bars, this means it will be moved inside the bar. To display data labels outside the - * plot area, set crop to false and overflow to 'none'. - * @default 'justify' - * @since 3.0.6 - */ - overflow?: string; - /** - * When either the borderWidth or the backgroundColor is set, this is the padding within the box. - * @default 5 - * @since 2.2.1 - */ - padding?: number; - /** - * Text rotation in degrees. Note that due to a more complex structure, backgrounds, borders and padding will be - * lost on a rotated data label. - * @default 0 - */ - rotation?: number; - /** - * The shadow of the box. Works best with borderWidth or backgroundColor. Since 2.3 the shadow can be an object - * configuration containing color, offsetX, offsetY, opacity and width. - * @default false - * @since 2.2.1 - */ - shadow?: boolean | HighchartsShadow; - /** - * The name of a symbol to use for the border around the label. Symbols are predefined functions on the Renderer - * object. - * @default 'square' - * @since 4.1.2 - */ - shape?: string; - /** - * Styles for the label. - * @default {'color': 'contrast', 'fontSize': '11px', 'fontWeight': 'bold', 'textShadow': '0 0 6px contrast, 0 0 3px contrast' } - * @since 4.1.0 - */ - style?: HighchartsCSSObject; - /** - * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the labels. - * @default false - */ - useHTML?: boolean; - /** - * The vertical alignment of a data label. Can be one of 'top', 'middle' or 'bottom'. The default value depends on the - * data, for instance in a column chart, the label is above positive values and below negative values. - * @since 2.3.3 - */ - verticalAlign?: string; - /** - * X offset of the higher data labels relative to the point value. - * @default 0 - * @since 2.3.0 - */ - xHigh?: number; - /** - * X offset of the lower data labels relative to the point value. - * @default 0 - * @since 2.3.0 - */ - xLow?: number; - /** - * Y offset of the higher data labels relative to the point value. - * @default -6 - * @since 2.3.0 - */ - yHigh?: number; - /** - * Y offset of the lower data labels relative to the point value. - * @default 16 - * @since 2.3.0 - */ - yLow?: number; - /** - * The Z index of the data labels. The default Z index puts it above the series. Use a Z index of 2 to display it - * behind the series. - * @default 6 - * @since 2.3.5 - */ - zIndex?: number; -} - -interface HighchartsDial { - /** - * The background or fill color of the gauge's dial. - * @default 'black' - * @since 2.3.0 - */ - backgroundColor?: string | HighchartsGradient; - /** - * The length of the dial's base part, relative to the total radius or length of the dial. - * @default '70%'. - * @since 2.3.0 - */ - baseLength?: string; - /** - * The pixel width of the base of the gauge dial. The base is the part closest to the pivot, defined by baseLength. - * @default 3 - * @since 2.3.0 - */ - baseWidth?: number; - /** - * The border color or stroke of the gauge's dial. By default, the borderWidth is 0, so this must be set in addition - * to a custom border color. - * @default 'silver' - * @since 2.3.0 - */ - borderColor?: string | HighchartsGradient; - /** - * The width of the gauge dial border in pixels. - * @default 0 - * @since 2.3.0 - */ - borderWidth?: number; - /** - * The radius or length of the dial, in percentages relative to the radius of the gauge itself. - * @default '80%' - * @since 2.3.0 - */ - radius?: string; - /** - * The length of the dial's rear end, the part that extends out on the other side of the pivot. Relative to the - * dial's length. - * @default '10%' - * @since 2.3.0 - */ - rearLength?: string; - /** - * The width of the top of the dial, closest to the perimeter. The pivot narrows in from the base to the top. - * @default 1 - * @since 2.3.0 - */ - topWidth?: number; -} - -interface HighchartsPivot { - /** - * The background color or fill of the pivot. - * @default 'black' - * @since 2.3.0 - */ - backgroundColor?: string | HighchartsGradient; - /** - * The border or stroke color of the pivot. In able to change this, the borderWidth must also be set to something - * other than the default 0. - * @default 'silver' - * @since 2.3.0 - */ - borderColor?: string | HighchartsGradient; - /** - * The border or stroke width of the pivot. - * @default 0 - * @since 2.3.0 - */ - borderWidth?: number; - /** - * The pixel radius of the pivot. - * @default 5 - * @since 2.3.0 - */ - radius?: number; -} - -/** - * Set options on specific levels. Takes precedence over series options, but not point options. - */ -interface HighchartsTreeMapLevel { - /** - * Can set borderColor on all points which lies on the same level. - * @since 4.1.0 - */ - borderColor?: string | HighchartsGradient; - /** - * et the dash style of the border of all the point which lies on the level. - * @since 4.1.0 - */ - borderDashStyle?: string; - /** - * Can set the borderWidth on all points which lies on the same level. - * @since 4.1.0 - */ - borderWidth?: number; - /** - * Can set a color on all points which lies on the same level. - * @since 4.1.0 - */ - color?: string | HighchartsGradient; - /** - * Can set the options of dataLabels on each point which lies on the level. - * @default undefined - * @since 4.1.0 - */ - dataLabels?: HighchartsDataLabels; - /** - * Can set the layoutAlgorithm option on a specific level. - * @since 4.1.0 - */ - layoutAlgorithm?: string; - /** - * Can set the layoutStartingDirection option on a specific level. - * @since 4.1.0 - */ - layoutStartingDirection?: string; - /** - * Decides which level takes effect from the options set in the levels object. - * @since 4.1.0 - */ - level?: number; -} - -/** - * General options for all series types. - */ -interface HighchartsSeriesChart { - /** - * Allow this series' points to be selected by clicking on the markers, bars or pie slices. - * @default false - * @since 1.2.0 - */ - allowPointSelect?: boolean; - /** - * Enable or disable the initial animation when a series is displayed. The animation can also be set as a - * configuration object. Please note that this option only applies to the initial animation of the series itself. - * For other animations, see chart.animation and the animation parameter under the API methods. - * @default true - */ - animation?: boolean | HighchartsAnimation; - /** - * The main color or the series. In line type series it applies to the line and the point markers unless otherwise - * specified. In bar type series it applies to the bars unless a color is specified per point. The default value is - * pulled from the options.colors array. - */ - color?: string | HighchartsGradient; - /** - * Polar charts only. Whether to connect the ends of a line series plot across the extremes. - * @default true - * @since 2.3.0 - */ - connectEnds?: boolean; - /** - * Whether to connect a graph line across null points. - * @default false - */ - connectNulls?: boolean; - /** - * When the series contains less points than the crop threshold, all points are drawn, event if the points fall - * outside the visible plot area at the current zoom. The advantage of drawing all points (including markers and - * columns), is that animation is performed on updates. On the other hand, when the series contains more points than - * the crop threshold, the series data is cropped to only contain points that fall within the plot area. The - * advantage of cropping away invisible points is to increase performance on large series. - * @default 300 - * @since 2.2 - */ - cropThreshold?: number; - /** - * You can set the cursor to 'pointer' if you have click events attached to the series, to signal to the user that - * the points and lines can be clicked. - */ - cursor?: string; - /** - * A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, - * area and scatter in case it has a lineWidth. The value for the dashStyle include: - * - Solid - * - ShortDash - * - ShortDot - * - ShortDashDot - * - ShortDashDotDot - * - Dot - * - Dash - * - LongDash - * - DashDot - * - LongDashDot - * - LongDashDotDot - * @default 'Solid' - */ - dashStyle?: string; - dataLabels?: HighchartsDataLabels; - /** - * Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on - * graphs and points. For large datasets it improves performance. - * @default true - */ - enableMouseTracking?: boolean; - events?: HighchartsPlotEvents; - /** - * Whether to use the Y extremes of the total chart width or only the zoomed area when zooming in on parts of the X - * axis. By default, the Y axis adjusts to the min and max of the visible data. Cartesian series only. - * @default false - * @since 4.1.6 - */ - getExtremesFromAll?: boolean; - /** - * An array specifying which option maps to which key in the data point array. This makes it convenient to work with - * unstructured data arrays from different sources. - * @since 4.1.6 - */ - keys?: string[]; - /** - * Pixel with of the graph line. - * @default 2 - */ - lineWidth?: number; - /** - * The line cap used for line ends and line joins on the graph. - * @default 'round' - */ - linecap?: string; - /** - * The id of another series to link to. Additionally, the value can be ':previous' to link to the previous series. - * When two series are linked, only the first one appears in the legend. Toggling the visibility of this also - * toggles the linked series. - * @since 3.0 - */ - linkedTo?: string; - marker?: HighchartsMarker; - /** - * The color for the parts of the graph or points that are below the threshold. - * @default null. - * @since 3.0 - */ - negativeColor?: string; - point?: { - events: HighchartsPointEvents; - }; - /** - * If no x values are given for the points in a series, pointInterval defines the interval of the x values. For - * example, if a series contains one value every decade starting from year 0, set pointInterval to 10. - * - * Since Highcharts 4.1, it can be combined with pointIntervalUnit to draw irregular intervals. - * @default 1 - */ - pointInterval?: number; - /** - * On datetime series, this allows for setting the pointInterval to the two irregular time units, month and year. - * Combine it with pointInterval to draw quarters, 6 months, 10 years etc. - * @since 4.1.0 - */ - pointIntervalUnit?: string; - /** - * Possible values: null, 'on', 'between'. - * - * In a column chart, when pointPlacement is 'on', the point will not create any padding of the X axis. In a polar - * column chart this means that the first column points directly north. If the pointPlacement is 'between', the - * columns will be laid out between ticks. This is useful for example for visualising an amount between two points - * in time or in a certain sector of a polar chart. - * - * Since Highcharts 3.0.2, the point placement can also be numeric, where 0 is on the axis value, -0.5 is between - * this value and the previous, and 0.5 is between this value and the next. Unlike the textual options, numeric - * point placement options won't affect axis padding. - * - * Note that pointPlacement needs a pointRange to work. For column series this is computed, but for line-type series - * it needs to be set. - * - * Defaults to null in cartesian charts, 'between' in polar charts. - * @since 2.3.0 - */ - pointPlacement?: string | number; - /** - * If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a - * series contains one yearly value starting from 1945, set pointStart to 1945. - * @default 0 - */ - pointStart?: number; - /** - * Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be - * checked for a selected series. - * @default false - * @since 1.2.0 - */ - selected?: boolean; - /** - * Whether to apply a drop shadow to the graph line. Since 2.3 the shadow can be an object configuration containing - * color, offsetX, offsetY, opacity and width. - * @default false - */ - shadow?: boolean | HighchartsShadow; - /** - * If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox - * is determined by the selected option. - * @default false - * @since 1.2.0 - */ - showCheckbox?: boolean; - /** - * Whether to display this particular series or series type in the legend. The default value is true for standalone - * series, false for linked series. Defaults to true. - */ - showInLegend?: boolean; - /** - * When this is true, the series will not cause the Y axis to cross the zero plane (or threshold option) unless the - * data actually crosses the plane. - * - * For example, if softThreshold is false, a series of 0, 1, 2, 3 will make the Y axis show negative values - * according to the minPadding option. If softThreshold is true, the Y axis starts at 0. - * @default true - * @since 4.1.9 - */ - softTreshold?: boolean; - /** - * Whether to stack the values of each series on top of each other. Possible values are null to disable, 'normal' to - * stack by value or 'percent'. - */ - stacking?: string; - /** - * A wrapper object for all the series options in specific states. - */ - states?: { + fill?: string | Gradient; /** - * Options for the hovered series + * The button stroke color, SVG color definition */ - hover?: HighchartsLineStates; - }; - /** - * Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves - * over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the - * mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is - * false and tooltip.shared is false, the tooltip will be hidden when moving the mouse between series. Defaults to - * true for line and area type series, but to false for columns, pies etc. - * @default true - * @since 2.0 - */ - stickyTracking?: boolean; - /** - * The Y axis value to serve as the base for the area, for distinguishing between values above and below a - * threshold. If null, the area behaves like a line series with fill between the graph and the Y axis minimum. - * @default 0 - * @since 2.0 - */ - threshold?: number; - /** - * A configuration object for the tooltip rendering of each single series. Properties are inherited from tooltip, - * but only the following properties can be defined on a series level. - * @since 2.3 - */ - tooltip?: HighchartsSeriesTooltipOptions; - /** - * When a series contains a data array that is longer than this, only one dimensional arrays of numbers, or two - * dimensional arrays with x and y values are allowed. Also, only the first point is tested, and the rest are - * assumed to be the same format. This saves expensive data checking and indexing in long series. Set it to 0 - * disable. - * @default 1000 - * @since 2.2 - */ - turboThreshold?: number; - /** - * Set the initial visibility of the series. - * @default true - */ - visible?: boolean; - /** - * Defines the Axis on which the zones are applied. - * @default 'y' - * @since 4.1.0 - */ - zoneAxis?: string; - /** - * An array defining zones within a series. Zones can be applied to the X axis, Y axis or Z axis for bubbles, - * according to the zoneAxis option. - */ - zones?: HighchartsAreaZone[]; -} - -interface HighchartsAreaChart extends HighchartsSeriesChart { - /** - * Fill color or gradient for the area. When null, the series' color is used with the series' fillOpacity. - */ - fillColor?: string | HighchartsGradient; - /** - * Fill opacity for the area. Note that when you set an explicit fillColor, the fillOpacity is not applied. Instead, - * you should define the opacity in the fillColor with an rgba color definition. - * @default 0.75 - */ - fillOpacity?: number; - /** - * A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting - * allows setting a separate color for the line without altering the fillColor. - */ - lineColor?: string | HighchartsGradient; - /** - * A separate color for the negative part of the area. - * @since 3.0 - */ - negativeFillColor?: string; - /** - * Whether to apply steps to the line. Possible values are left, center and right. Prior to 2.3.5, only left was - * supported. - * - * @default 'false' - * @since 1.2.5 - */ - step?: string; - /** - * Whether the whole area or just the line should respond to mouseover tooltips and other mouse or touch events. - * @default false - * @since 1.1.6 - */ - trackByArea?: boolean; -} - -interface HighchartsAreaRangeChart extends HighchartsAreaChart { - /** - * Extended data labels for range series types. Range series data labels have no x and y options. Instead, they have - * xLow, xHigh, yLow and yHigh options to allow the higher and lower data label sets individually. - * @since 2.3.0 - */ - dataLabels?: HighchartsRangeDataLabels; -} - -interface HighchartsAreaSplineChart extends HighchartsAreaChart { -} - -interface HighchartsAreaSplineRangeChart extends HighchartsAreaRangeChart { -} - -interface HighchartsBarChart extends HighchartsSeriesChart { - /** - * The color of the border surrounding each column or bar. - * @default '#FFFFFF' - */ - borderColor?: string | HighchartsGradient; - /** - * The corner radius of the border surrounding each column or bar. - * @default 0 - */ - borderRadius?: number; - /** - * The width of the border surrounding each column or bar. - * @default 1 - */ - borderWidth?: number; - /** - * When using automatic point colors pulled from the options.colors collection, this option determines whether the - * chart should receive one color per series or one color per point. Defaults to false. - * @default false - * @since 2.0 - */ - colorByPoint?: boolean; - /** - * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is - * true. - * @since 3.0 - */ - colors?: string[]; - /** - * Depth of the columns in a 3D column chart. Requires highcharts-3d.js. - * @default 25 - * @since 4.0 - */ - depth?: number; - /** - * 3D columns only. The color of the edges. Similar to borderColor, except it defaults to the same color as the - * column. - */ - edgeColor?: string; - /** - * 3D columns only. The width of the colored edges. - * @default 1 - */ - edgeWidth?: number; - /** - * Padding between each value groups, in x axis units. - * @default 0.2 - */ - groupPadding?: number; - /** - * The spacing between columns on the Z Axis in a 3D chart. Requires highcharts-3d.js. - * @default 1 - * @since 4.0 - */ - groupZPadding?: number; - /** - * Whether to group non-stacked columns or to let them render independent of each other. Non-grouped columns will be - * laid out individually and overlap each other. - * @default true - * @since 2.3.0 - */ - grouping?: boolean; - /** - * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the - * columns from becoming too wide when there is a small number of points in the chart. - * @default null - * @since 4.1.8 - */ - maxPointWidth?: number; - /** - * The minimal height for a column or width for a bar. By default, 0 values are not shown. To visualize a 0 (or - * close to zero) point, set the minimal point length to a pixel value like 3. In stacked column charts, - * minPointLength might not be respected for tightly packed values. - * @default 0 - */ - minPointLength?: number; - /** - * Padding between each column or bar, in x axis units. - * @default 0.1 - */ - pointPadding?: string | number; - /** - * The X axis range that each point is valid for. This determines the width of the column. On a categorized axis, - * the range will be 1 by default (one category unit). On linear and datetime axes, the range will be computed as - * the distance between the two closest data points. - * @since 2.3 - */ - pointRange?: number; - /** - * A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from the - * pointPadding and groupPadding. - * @since 1.2.5 - */ - pointWidth?: number; - /** - * A wrapper object for all the series options in specific states. - */ - states?: { + stroke?: string; /** - * Options for the hovered series + * The button stroke width + * @type {[type]} */ - hover?: HighchartsBarStates; - }; -} - -/** - * A box plot is a convenient way of depicting groups of data through their five-number summaries: the smallest - * observation (sample minimum), lower quartile (Q1), median (Q2), upper quartile (Q3), and largest observation (sample - * maximum). - */ -interface HighchartsBoxPlotChart extends HighchartsErrorBarChart { - /** - * The fill color of the box. - * @default '#FFFFFF' - * @since 3.0 - */ - fillColor?: string; - /** - * Padding between each value groups, in x axis units. - * @default 0.2 - */ - groupPadding?: number; - /** - * Whether to group non-stacked columns or to let them render independent of each other. Non-grouped columns will be - * laid out individually and overlap each other. - * @default true - * @since 2.3.0 - */ - grouping?: boolean; - /** - * The id of another series to link to. Additionally, the value can be ':previous' to link to the previous series. - * When two series are linked, only the first one appears in the legend. Toggling the visibility of this also - * toggles the linked series. - * @since 3.0 - */ - linkedTo?: string; - /** - * The color of the median line. If null, the general series color applies. - * @default null - * @since 3.0 - */ - medianColor?: string; - /** - * The pixel width of the median line. If null, the lineWidth is used. - * @default 2 - * @since 3.0 - */ - medianWidth?: number; -} - -/** - * A bubble series is a three dimensional series type where each point renders an X, Y and Z value. Each points is drawn - * as a bubble where the position along the X and Y axes mark the X and Y values, and the size of the bubble relates to - * the Z value. - */ -interface HighchartsBubbleChart extends HighchartsSeriesChart { - /** - * Whether to display negative sized bubbles. The threshold is given by the zThreshold option, and negative bubbles - * can be visualized by setting negativeColor. - * @default true - * @since 3.0 - */ - displayNegative?: boolean; - /** - * Maximum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of - * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width - * and height. - * @default '20%' - * @since 3.0 - */ - maxSize?: string | number; - /** - * Minimum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of - * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width - * and height. - * @default 8 - * @since 3.0 - */ - minSize?: string | number; - /** - * When a point's Z value is below the zThreshold setting, this color is used. - * @default null - * @since 3.0 - */ - negativeColor?: string; - /** - * Whether the bubble's value should be represented by the area or the width of the bubble. The default, area, - * corresponds best to the human perception of the size of each bubble. - * @default 'area' - * @since 3.0.7 - */ - sizeBy?: string; - /** - * When this is true, the absolute value of z determines the size of the bubble. This means that with the default - * zThreshold of 0, a bubble of value -1 will have the same size as a bubble of value 1, while a bubble of value 0 - * will have a smaller size according to minSize. - * @default false - * @since 4.1.9 - */ - sizeByAbsoluteValues?: boolean; - /** - * The maximum for the Z value range. Defaults to the highest Z value in the data. - * @default null - * @since 4.0.3 - */ - zMax?: number; - /** - * The minimum for the Z value range. Defaults to the lowest Z value in the data. - * @default null - * @since 4.0.3 - */ - zMin?: number; - /** - * When displayNegative is false, bubbles with lower Z values are skipped. When displayNegative is true and a - * negativeColor is given, points with lower Z is colored. - * @default 0 - * @since 3.0 - */ - zThreshold?: number; -} - -interface HighchartsColumnChart extends HighchartsBarChart { -} - -/** - * The column range is a cartesian series type with higher and lower Y values along an X axis. Requires - * highcharts-more.js. To display horizontal bars, set chart.inverted to true. - */ -interface HighchartsColumnRangeChart extends HighchartsColumnChart { - dataLabels?: HighchartsRangeDataLabels; -} - -/** - * Error bars are a graphical representation of the variability of data and are used on graphs to indicate the error, or - * uncertainty in a reported measurement. - */ -interface HighchartsErrorBarChart extends HighchartsSeriesChart { - /** - * When using automatic point colors pulled from the options.colors collection, this option determines whether the - * chart should receive one color per series or one color per point. - * @default false - * @since 2.0 - */ - colorByPoint?: boolean; - /** - * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is - * true. - * @since 3.0 - */ - colors?: string[]; - /** - * Depth of the columns in a 3D column chart. Requires highcharts-3d.js. - * @default 25 - * @since 4.0 - */ - depth?: number; - /** - * 3D columns only. The color of the edges. Similar to borderColor, except it defaults to the same color as the - * column. - */ - edgeColor?: string; - /** - * 3D columns only. The width of the colored edges. - * @default 1 - */ - edgeWidth?: number; - /** - * The spacing between columns on the Z Axis in a 3D chart. Requires highcharts-3d.js. - * @default 1 - * @since 4.0 - */ - groupZPadding?: number; - /** - * The parent series of the error bar. The default value links it to the previous series. Otherwise, use the id of - * the parent series. - * @default ':previous' - * @since 3.0 - */ - linkedTo?: string; - /** - * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the - * columns from becoming too wide when there is a small number of points in the chart. - * @default null - * @since 4.1.8 - */ - maxPointWidth?: number; - /** - * Padding between each column or bar, in x axis units. - * @default 0.1 - */ - pointPadding?: number; - /** - * The X axis range that each point is valid for. This determines the width of the column. On a categorized axis, - * the range will be 1 by default (one category unit). On linear and datetime axes, the range will be computed as - * the distance between the two closest data points. - * @since 2.3 - */ - pointRange?: number; - /** - * A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from the - * pointPadding and groupPadding. - * @since 1.2.5 - */ - pointWidth?: number; - /** - * A wrapper object for all the series options in specific states. - */ - states?: { + 'stroke-width'?: number; /** - * Options for the hovered series + * The border radius */ - hover?: HighchartsBarStates; - }; - /** - * The color of the stem, the vertical line extending from the box to the whiskers. If null, the series color is - * used. - * @default null - * @since 3.0 - */ - stemColor?: string; - /** - * The dash style of the stem, the vertical line extending from the box to the whiskers. - * @default 'Solid' - * @since 3.0 - */ - stemDashStyle?: string; - /** - * The width of the stem, the vertical line extending from the box to the whiskers. If null, the width is inherited - * from the lineWidth option. - * @default null - * @since 3.0 - */ - stemWidth?: number; - /** - * The color of the whiskers, the horizontal lines marking low and high values. When null, the general series color - * is used. - * @default null - * @since 3.0 - */ - whiskerColor?: string; - /** - * The length of the whiskers, the horizontal lines marking low and high values. It can be a numerical pixel value, - * or a percentage value of the box width. Set 0 to disable whiskers. - * @default '50%' - * @since 3.0 - */ - whiskerLength?: number | string; - /** - * The line width of the whiskers, the horizontal lines marking low and high values. When null, the general - * lineWidth applies. - * @default 2 - * @since 3.0 - */ - whiskerWidth?: number; -} - -/** - * Funnel charts are a type of chart often used to visualize stages in a sales project, where the top are the initial - * stages with the most clients. It requires that the modules/funnel.js file is loaded - */ -interface HighchartsFunnelChart extends HighchartsSeriesChart { - /** - * The color of the border surrounding each column or bar. - * @default '#FFFFFF' - */ - borderColor?: string | HighchartsGradient; - /** - * The width of the border surrounding each column or bar. - * @default 1 - */ - borderWidth?: number; - /** - * The center of the series. By default, it is centered in the middle of the plot area, so it fills the plot area - * height. - * @default ['50%', '50%'] - * @since 3.0 - */ - center?: [string|number, string|number]; - /** - * A series specific or series type specific color set to use instead of the global colors. - * @since 3.0 - */ - colors?: string[]; - dataLabels?: HighchartsPieDataLabels; - /** - * The thickness of a 3D pie. Requires highcharts-3d.js - * @default 0 - * @since 4.0 - */ - depth?: number; - /** - * The height of the funnel or pyramid. If it is a number it defines the pixel height, if it is a percentage string - * it is the percentage of the plot area height. - * @since 3.0 - */ - height?: number | string; - /** - * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels - * in side the plot area, but only to this size. - * @default 80 - * @since 3.0 - */ - minSize?: number; - /** - * The height of the neck, the lower part of the funnel. A number defines pixel width, a percentage string defines a - * percentage of the plot area height. - * @default '25%' - */ - neckHeight?: number | string; - /** - * The width of the neck, the lower part of the funnel. A number defines pixel width, a percentage string defines a - * percentage of the plot area width. - * @default '30%' - * @since 3.0 - */ - neckWidth?: number | string; - /** - * A reversed funnel has the widest area down. A reversed funnel with no neck width and neck height is a pyramid. - * @default false - * @since 3.0.10 - */ - reversed?: boolean; - /** - * If a point is sliced, moved out from the center, how many pixels should it be moved? - * @default 10 - */ - slicedOffset?: number; - /** - * A wrapper object for all the series options in specific states. - */ - states?: { + r?: number; /** - * Options for the hovered series + * CSS style */ - hover?: HighchartsPieStates; - }; - /** - * The width of the funnel compared to the width of the plot area, or the pixel width if it is a number. - * @default '90%' - * @since 3.0 - */ - width?: number | string; -} - -/** - * General plotting options for the gauge series type. Requires highcharts-more.js - */ -interface HighchartsGaugeChart extends HighchartsSeriesChart { - /** - * Data labels for the gauge. For gauges, the data labels are enabled by default and shown in a bordered box below - * the point. - */ - datalabels?: HighchartsDataLabels; - /** - * Options for the dial or arrow pointer of the gauge. - */ - dial?: HighchartsDial; - /** - * Allow the dial to overshoot the end of the perimeter axis by this many degrees. Say if the gauge axis goes from 0 - * to 60, a value of 100, or 1000, will show 5 degrees beyond the end of the axis. Defaults to 0. - * @default 0 - * @since 3.0.10 - */ - overshoot?: number; - /** - * Options for the pivot or the center point of the gauge. - * @since 2.3.0 - */ - pivot?: HighchartsPivot; - /** - * When this option is true, the dial will wrap around the axes. For instance, in a full-range gauge going from 0 to - * 360, a value of 400 will point to 40. When wrap is false, the dial stops at 360. - * @default true - * @since 3.0 - */ - wrap?: boolean; -} - -/** - * The heatmap series type. This series type is available both in Highcharts and Highmaps. - * The colors of each heat map point is usually determined by its value and controlled by settings on the colorAxis. - */ -interface HighchartsHeatMapChart extends HighchartsSeriesChart { - /** - * The color of the border surrounding each column or bar. - * @default '#FFFFFF' - */ - borderColor?: string | HighchartsGradient; - /** - * The corner radius of the border surrounding each column or bar. - * @default 0 - */ - borderRadius?: number; - /** - * The width of the border surrounding each column or bar. - * @default 1 - */ - borderWidth?: number; - /** - * When using automatic point colors pulled from the options.colors collection, this option determines whether the - * chart should receive one color per series or one color per point. Defaults to false. - * @default false - * @since 2.0 - */ - colorByPoint?: boolean; - /** - * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is - * true. - * @since 3.0 - */ - colors?: string[]; - /** - * The columns size - how many X axis units each column in the heatmap should span. - * @default 1 - * @since 4.0 - */ - colsize?: number; - /** - * When the series contains less points than the crop threshold, all points are drawn, event if the points fall - * outside the visible plot area at the current zoom. The advantage of drawing all points (including markers and - * columns), is that animation is performed on updates. On the other hand, when the series contains more points than - * the crop threshold, the series data is cropped to only contain points that fall within the plot area. The - * advantage of cropping away invisible points is to increase performance on large series. - * @default 50 - */ - cropTreshold?: number; - /** - * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the - * columns from becoming too wide when there is a small number of points in the chart. - * @default null - * @since 4.1.8 - */ - maxPointWidth?: number; - /** - * The row size - how many Y axis units each heatmap row should span. - * @default 1 - * @since 4.0 - */ - rowsize?: number; - /** - * A wrapper object for all the series options in specific states. - */ - states?: { - /** - * Options for the hovered series - */ - hover?: HighchartsBarStates; + style?: Object; } -} -interface HighchartsLineChart extends HighchartsSeriesChart { - /** - * Whether to apply steps to the line. Possible values are left, center and right. Prior to 2.3.5, only left was - * supported. - * @default false - * @since 1.2.5 - */ - step?: boolean|string; -} - -/** - * A pie chart is a circular chart divided into sectors, illustrating numerical proportion. - */ -interface HighchartsPieChart extends HighchartsSeriesChart { - /** - * The color of the border surrounding each slice. When null, the border takes the same color as the slice fill. - * This can be used together with a borderWidth to fill drawing gaps created by antialiazing artefacts in - * borderless pies. - * @default '#FFFFFF' - */ - borderColor?: string | HighchartsGradient; - /** - * The width of the border surrounding each column or bar. - * @default 1 - */ - borderWidth?: number; - /** - * The center of the pie chart relative to the plot area. Can be percentages or pixel values. The default behaviour - * (as of 3.0) is to center the pie so that all slices and data labels are within the plot area. As a consequence, - * the pie may actually jump around in a chart with dynamic values, as the data labels move. In that case, the - * center should be explicitly set, for example to ['50%', '50%']. - * @default [null, null] - */ - center?: [string|number, string|number]; - /** - * A series specific or series type specific color set to use instead of the global colors. - * @since 3.0 - */ - colors?: string[]; - dataLabels?: HighchartsPieDataLabels; - /** - * The thickness of a 3D pie. Requires highcharts-3d.js - * @default 0 - * @since 4.0 - */ - depth?: number; - /** - * The end angle of the pie in degrees where 0 is top and 90 is right. Defaults to startAngle plus 360. - * @default null - * @since 1.3.6 - */ - endAngle?: number; - /** - * Equivalent to chart.ignoreHiddenSeries, this option tells whether the series shall be redrawn as if the hidden - * point were null. - * - * The default value changed from false to true with Highcharts 3.0. - * - * @default true - * @since 2.3.0 - */ - ignoreHiddenPoint?: boolean; - /** - * The size of the inner diameter for the pie. A size greater than 0 renders a donut chart. Can be a percentage or - * pixel value. Percentages are relative to the pie size. Pixel values are given as integers. - * - * Note: in Highcharts < 4.1.2, the percentage was relative to the plot area, not the pie size. - * @default 0 - * @since 2.0 - */ - innerSize?: number | string; - /** - * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels - * in side the plot area, but only to this size. - * @default 80 - * @since 3.0 - */ - minSize?: number; - /** - * The diameter of the pie relative to the plot area. Can be a percentage or pixel value. Pixel values are given as - * integers. The default behaviour (as of 3.0) is to scale to the plot area and give room for data labels within the - * plot area. As a consequence, the size of the pie may vary when points are updated and data labels more around. In - * that case it is best to set a fixed value, for example '75%'. - */ - size?: number | string; - /** - * If a point is sliced, moved out from the center, how many pixels should it be moved? - * @default 10 - */ - slicedOffset?: number; - /** - * The start angle of the pie slices in degrees where 0 is top and 90 right. - * @default 0 - * @since 2.3.4 - */ - startAngle?: number; - /** - * A wrapper object for all the series options in specific states. - */ - states?: { + interface ButtonStatesTheme extends ButtonTheme { /** - * Options for the hovered series + * Themed button states. Only hover is supported for reset zoom button. */ - hover?: HighchartsPieStates; - }; -} - -/** - * A polygon series can be used to draw any freeform shape in the cartesian coordinate system. A fill is applied with - * the color option, and stroke is applied through lineWidth and lineColor options. Requires the highcharts-more.js - * file. - */ -interface HighchartsPolygonChart extends HighchartsSeriesChart { - /** - * The width of the line connecting the data points. - * @default 0 - */ - lineWidth?: number; -} - -interface HighchartsPyramidChart extends HighchartsSeriesChart { - /** - * The color of the border surrounding each slice - * @default '#FFFFFF' - */ - borderColor?: string | HighchartsGradient; - /** - * The width of the border surrounding each slice - * @default 1 - */ - borderWidth?: number; - /** - * The center of the series. By default, it is centered in the middle of the plot area, so it fills the plot area - * height. - * @default ['50%', '50%'] - * @since 3.0 - */ - center?: [string|number, string|number]; - /** - * A series specific or series type specific color set to use instead of the global colors. - * @since 3.0 - */ - colors?: string[]; - dataLabels?: HighchartsPieDataLabels; - /** - * The thickness of a 3D pie. Requires highcharts-3d.js - * @default 0 - * @since 4.0 - */ - depth?: number; - /** - * The height of the funnel or pyramid. If it is a number it defines the pixel height, if it is a percentage string - * it is the percentage of the plot area height. - * @since 3.0 - */ - height?: number | string; - /** - * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels - * in side the plot area, but only to this size. - * @default 80 - * @since 3.0 - */ - minSize?: number; - /** - * The pyramid is reversed by default, as opposed to the funnel, which shares the layout engine, and is not - * reversed. - * @default true - * @since 3.0.10 - */ - reversed?: boolean; - /** - * If a point is sliced, moved out from the center, how many pixels should it be moved? - * @default 10 - */ - slicedOffset?: number; - /** - * A wrapper object for all the series options in specific states. - */ - states?: { - /** - * Options for the hovered series - */ - hover?: HighchartsPieStates; - }; - /** - * The width of the pyramid compared to the width of the plot area, or the pixel width if it is a number. - * @default '90%' - * @since 3.0 - */ - width?: number | string; -} - -interface HighchartsScatterChart extends HighchartsSeriesChart { } - -/** - * A gauge showing values using a filled arc with colors indicating the value. The solid gauge plots values against the - * yAxis, which is extended with some color options, minColor, maxColor and stops, to control the color of the gauge - * itself. - */ -interface HighchartsSolidGaugeChart extends HighchartsSeriesChart { - /** - * Allow the dial to overshoot the end of the perimeter axis by this many degrees. Say if the gauge axis goes from 0 - * to 60, a value of 100, or 1000, will show 5 degrees beyond the end of the axis. - * @default 0 - * @since 3.0.10 - */ - overshoot?: number; - /** - * When this option is true, the dial will wrap around the axes. For instance, in a full-range gauge going from 0 to - * 360, a value of 400 will point to 40. When wrap is false, the dial stops at 360. - * @default true - * @since 3.0 - */ - wrap?: boolean; -} - -interface HighchartsSplineChart extends HighchartsSeriesChart { } - -/** - * The size of the point shape is determined by its value relative to its siblings values. Requires the module - * heatmap.js as well, if functionality such as the colorAxis is to be used. - */ -interface HighchartsTreeMapChart extends HighchartsSeriesChart { - /** - * When enabled the user can click on a point which is a parent and zoom in on its children. - * @default false - * @since 4.1.0 - */ - allowDrillToNode?: boolean; - /** - * Enabling this option will make the treemap alternate the drawing direction between vertical and horizontal. The - * next levels starting direction will always be the opposite of the previous. - * @default false - * @since 4.1.0 - */ - alternateStartingDirection?: boolean; - /** - * The color of the border surrounding each tree map item. - * @default '#E0E0E0' - */ - borderColor?: string | HighchartsGradient; - /** - * The width of the border surrounding each column or bar. - * @default 1 - */ - borderWidth?: number; - /** - * When using automatic point colors pulled from the options.colors collection, this option determines whether the - * chart should receive one color per series or one color per point. - * @default false - * @since 2.0 - */ - colorByPoint?: boolean; - /** - * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is - * true. - * @since 3.0 - */ - colors?: string[]; - /** - * This option decides if the user can interact with the parent nodes or just the leaf nodes. When this option is - * undefined, it will be true by default. However when allowDrillToNode is true, then it will be false by default. - * @since 4.1.2 - */ - interactByLeaf?: boolean; - /** - * This option decides which algorithm is used for setting position and dimensions of the points. Can be one of - * 'sliceAndDice', 'stripes', 'squarified' or 'strip'. - * @default 'sliceAndDice' - * @since 4.1.0 - */ - layoutAlgorithm?: string; - /** - * Defines which direction the layout algorithm will start drawing. Possible values are 'vertical' and 'horizontal'. - * @default 'vertical' - * @since 4.1.0 - */ - layoutStartingDirection?: string; - /** - * Used together with the levels and allowDrillToNode options. When set to false the first level visible when - * drilling is considered to be level one. Otherwise the level will be the same as the tree structure. - * @default true - * @since 4.1.0 - */ - levelIsConstant?: boolean; - /** - * Set options on specific levels. Takes precedence over series options, but not point options. - */ - levels?: HighchartsTreeMapLevel[]; - /** - * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the - * columns from becoming too wide when there is a small number of points in the chart. - * @default null - * @since 4.1.8 - */ - maxPointWidth?: number; - /** - * The sort index of the point inside the treemap level. - * @since 4.1.10 - */ - sortIndex?: number; - /** - * A wrapper object for all the series options in specific states. - */ - states?: { - /** - * Options for the hovered series - */ - hover?: HighchartsBarStates; + states?: { + /** + * Attributes and styles applied when hovering. + */ + hover?: ButtonTheme; + /** + * Attributes and styles applied when button is selected (tri-state). + */ + select?: ButtonTheme; + }; } -} -interface HighchartsWaterFallChart extends HighchartsBarChart { - /** - * A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, - * area and scatter in case it has a lineWidth. The value for the dashStyle include: - * - Solid - * - ShortDash - * - ShortDot - * - ShortDashDot - * - ShortDashDotDot - * - Dot - * - Dash - * - LongDash - * - DashDot - * - LongDashDot - * - LongDashDotDot - * @default 'Dot' - */ - dashStyle?: string; - /** - * The color of the line that connects columns in a waterfall series. - * @default '#333333' - * @since 3.0 - */ - lineColor?: string | HighchartsGradient; - /** - * The color used specifically for positive point columns. When not specified, the general series color is used. - */ - upColor?: string; -} + interface ChartOptions { + /** + * When using multiple axis, the ticks of two or more opposite axes will automatically be aligned by adding ticks to + * the axis or axes with the least ticks. This can be prevented by setting alignTicks to false. If the grid lines + * look messy, it's a good idea to hide them for the secondary axis by setting gridLineWidth to 0. + * @default true + */ + alignTicks?: boolean; + /** + * Set the overall animation for all chart updating. Animation can be disabled throughout the chart by setting it to + * false here. It can be overridden for each individual API method as a function parameter. The only animation not + * affected by this option is the initial series animation, see plotOptions.series.animation. + * + * The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery + * easing and a duration of 500 ms. + * + * @default true + */ + animation?: boolean | Animation; + /** + * The background color or gradient for the outer chart area. + * @default '#FFFFFF' + */ + backgroundColor?: string | Gradient; + /** + * The color of the outer chart border. + * @default '#4572A7' + */ + borderColor?: string | Gradient; + /** + * The corner radius of the outer chart border. + * @default 0 + */ + borderRadius?: number; + /** + * The pixel width of the outer chart border. + * @default 0 + */ + borderWidth?: number; + /** + * A CSS class name to apply to the charts container div, allowing unique CSS styling for each chart. + */ + className?: string; + /** + * Alias of type. Defaults to line. + * @default 'line' + * @deprecated + */ + defaultSeriesType?: string; + /** + * Event listeners for the chart. + */ + events?: ChartEvents; + /** + * An explicit height for the chart. By default the height is calculated from the offset height of the containing + * element, or 400 pixels if the containing element's height is 0. + */ + height?: number; + /** + * If true, the axes will scale to the remaining visible series once one series is hidden. If false, hiding and + * showing a series will not affect the axes or the other series. For stacks, once one series within the stack is + * hidden, the rest of the stack will close in around it even if the axis is not affected. + * @default true + * @since 1.2.0 + */ + ignoreHiddenSeries?: boolean; + /** + * Whether to invert the axes so that the x axis is vertical and y axis is horizontal. When true, the x axis is + * reversed by default. If a bar series is present in the chart, it will be inverted automatically. + * @default false + */ + inverted?: boolean; + /** + * The margin between the outer edge of the chart and the plot area. The numbers in the array designate top, right, + * bottom and left respectively. Use the options marginTop, marginRight, marginBottom and marginLeft for shorthand + * setting of one option. + * + * Since version 2.1, the margin is 0 by default. The actual space is dynamically calculated from the offset of axis + * labels, axis title, title, subtitle and legend in addition to the spacingTop, spacingRight, spacingBottom and + * spacingLeft options. + */ + margin?: number | number[]; + /** + * The margin between the bottom outer edge of the chart and the plot area. Use this to set a fixed pixel value for + * the margin as opposed to the default dynamic margin. See also spacingBottom. + * @since 2.0 + */ + marginBottom?: number; + /** + * The margin between the left outer edge of the chart and the plot area. Use this to set a fixed pixel value for + * the margin as opposed to the default dynamic margin. See also spacingLeft. + * @since 2.0 + */ + marginLeft?: number; + /** + * The margin between the right outer edge of the chart and the plot area. Use this to set a fixed pixel value for + * the margin as opposed to the default dynamic margin. See also spacingRight. + * @since 2.0 + */ + marginRight?: number; + /** + * The margin between the top outer edge of the chart and the plot area. Use this to set a fixed pixel value for the + * margin as opposed to the default dynamic margin. See also spacingTop. + * @since 2.0 + */ + marginTop?: number; + /** + * Options to render charts in 3 dimensions. This feature requires highcharts-3d.js, found in the download package + * or online at {@link code.highcharts.com/highcharts-3d.js}. + */ + options3d?: ChartOptions3d; + /** + * Allows setting a key to switch between zooming and panning. + * @since 4.0.3 + */ + panKey?: string; + /** + * Allow panning in a chart. Best used with panKey to combine zooming and panning. + * @default false + * @since 4.0.3 + */ + panning?: boolean; + /** + * Equivalent to zoomType, but for multitouch gestures only. By default, the pinchType is the same as the zoomType + * setting. However, pinching can be enabled separately in some cases, for example in stock charts where a mouse + * drag pans the chart, while pinching is enabled. + * @default null + * @since 3.0 + */ + pinchType?: string; + /** + * The background color or gradient for the plot area. + */ + plotBackgroundColor?: string | Gradient; + /** + * The URL for an image to use as the plot background. To set an image as the background for the entire chart, set a + * CSS background image to the container element. Note that for the image to be applied to exported charts, its URL + * needs to be accessible by the export server. + */ + plotBackgroundImage?: string; + /** + * The color of the inner chart or plot area border. + * @default 0 + */ + plotBorderColor?: string; + /** + * The pixel width of the plot area border. + * @default 0 + */ + plotBorderWidth?: number; + /** + * Whether to apply a drop shadow to the plot area. Requires that plotBackgroundColor be set. Since 2.3 the shadow + * can be an object configuration containing color, offsetX, offsetY, opacity and width. + * @default false + */ + plotShadow?: boolean | Shadow; + /** + * When true, cartesian charts like line, spline, area and column are transformed into the polar coordinate system. + * Requires highcharts-more.js. + * @default false + * @since 2.3.0 + */ + polar?: boolean; + /** + * Whether to reflow the chart to fit the width of the container div on resizing the window. + * @default true + * @since 2.1 + */ + reflow?: boolean; + /** + * The HTML element where the chart will be rendered. If it is a string, the element by that id is used. The HTML + * element can also be passed by direct reference. + */ + renderTo?: string | HTMLElement; + /** + * The button that appears after a selection zoom, allowing the user to reset zoom. + */ + resetZoomButton?: ChartResetZoomButton; + /** + * The background color of the marker square when selecting (zooming in on) an area of the chart. + * @default 'rgba(69,114,167,0.25)' + * @since 2.1.7 + */ + selectionMarkerFill?: string; + /** + * Whether to apply a drop shadow to the outer chart area. Requires that backgroundColor be set. Since 2.3 the + * shadow can be an object configuration containing color, offsetX, offsetY, opacity and width. + * @default false + */ + shadow?: boolean | Shadow; + /** + * Whether to show the axes initially. This only applies to empty charts where series are added dynamically, as axes + * are automatically added to cartesian series. + * @default false + * @since 1.2.5 + */ + showAxes?: boolean; + /** + * The distance between the outer edge of the chart and the content, like title, legend, axis title or labels. The + * numbers in the array designate top, right, bottom and left respectively. Use the options spacingTop, + * spacingRight, spacingBottom and spacingLeft options for shorthand setting of one option. + * @default [10, 10, 15, 10] + * @since 3.0.6 + */ + spacing?: number[]; + /** + * The space between the bottom edge of the chart and the content (plot area, axis title and labels, title, subtitle + * or legend in top position). + * @default 15 + * @since 2.1 + */ + spacingBottom?: number; + /** + * The space between the left edge of the chart and the content (plot area, axis title and labels, title, subtitle + * or legend in top position). + * @default 10 + * @since 2.1 + */ + spacingLeft?: number; + /** + * The space between the right edge of the chart and the content (plot area, axis title and labels, title, subtitle + * or legend in top position). + * @default 10 + * @since 2.1 + */ + spacingRight?: number; + /** + * The space between the top edge of the chart and the content (plot area, axis title and labels, title, subtitle or + * legend in top position). + * @default 10 + * @since 2.1 + */ + spacingTop?: number; + /** + * Additional CSS styles to apply inline to the container div. Note that since the default font styles are applied + * in the renderer, it is ignorant of the individual chart options and must be set globally. + */ + style?: CSSObject; + /** + * The default series type for the chart. Can be any of the chart types listed under plotOptions. + * @default 'line' + * @since 2.1.0 + */ + type?: string; + /** + * An explicit width for the chart. By default the width is calculated from the offset width of the containing + * element. + */ + width?: number; + /** + * Decides in what dimensions the user can zoom by dragging the mouse. Can be one of x, y or xy. + */ + zoomType?: string; + } -/** - * The plotOptions is a wrapper object for config objects for each series type. The config objects for each series can - * also be overridden for each series item as given in the series array. - * - * Configuration options for the series are given in three levels. Options for all series in a chart are given in the - * plotOptions.series object. Then options for all series of a specific type are given in the plotOptions of that type, - * for example plotOptions.line. Next, options for one single series are given in the series array. - */ -interface HighchartsPlotOptions { - area?: HighchartsAreaChart; - arearange?: HighchartsAreaRangeChart; - areaspline?: HighchartsAreaSplineChart; - areasplinerange?: HighchartsAreaSplineRangeChart; - bar?: HighchartsBarChart; - boxplot?: HighchartsBoxPlotChart; - bubble?: HighchartsBubbleChart; - column?: HighchartsColumnChart; - columnrange?: HighchartsColumnRangeChart; - errorbar?: HighchartsErrorBarChart; - funnel?: HighchartsFunnelChart; - gauge?: HighchartsGaugeChart; - heatmap?: HighchartsHeatMapChart; - line?: HighchartsLineChart; - pie?: HighchartsPieChart; - polygon?: HighchartsPolygonChart; - pyramid?: HighchartsPyramidChart; - scatter?: HighchartsScatterChart; - series?: HighchartsSeriesChart; - solidgauge?: HighchartsSolidGaugeChart; - spline?: HighchartsSplineChart; - treemap?: HighchartsTreeMapChart; - waterfall?: HighchartsWaterFallChart; -} + interface CSSObject { + background?: string; + border?: string; + color?: string | Gradient; + cursor?: string; + font?: string; + fontFamily?: string; + fontSize?: string; + fontWeight?: string; + left?: string; + opacity?: number; + padding?: string | number; + position?: string; + top?: string; + textShadow?: string; + } -/* You will rarely, if ever, want to use this interface directly. Instead it is much more useful to use one of the derived - * interfaces (HighchartsAreaChartSeriesOptions, HighchartsLineChartSeriesOptions, etc.) - */ -interface HighchartsIndividualSeriesOptions { - type?: string; - /** - * The main color or the series. In line type series it applies to the line and the point markers unless otherwise - * specified. In bar type series it applies to the bars unless a color is specified per point. The default - * value is pulled from the options.colors array. - */ - color?: string | HighchartsGradient; - /** - * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user - * that the points and lines can be clicked. - */ - cursor?: string; - /** - * An array of data points for the series. For the area series type, points can be given in the following ways: - * - * 1. An array of numerical values. In this case, the numerical values will be interpreted as y options. The x - * values will be automatically calculated, either starting at 0 and incremented by 1, or from pointStart and - * pointInterval given in the series options. If the axis has categories, these will be used. Example: - * data: [0, 5, 3, 5] - * - * 2. An array of arrays with 2 values. In this case, the values correspond to x,y. If the first value is a string, - * it is applied as the name of the point, and the x value is inferred. - * data: [ - * [0, 9], - * [1, 7], - * [2, 6] - * ] - * - * 3. An array of objects with named values. The objects are point configuration objects as seen below. If the total - * number of data points exceeds the series' turboThreshold, this option is not available. - * data: [{ - * x: 1, - * y: 9, - * name: 'Point2', - * color: '#00FF00' - * }, { - * x: 1, - * y: 6, - * name: 'Point1', - * color: '#FF00FF' - * }] - */ - data?: number[] | [number, number][] | [string, number][] | HighchartsDataPoint[]; - /** - * An id for the series. This can be used after render time to get a pointer to the series object through - * chart.get(). - */ - id?: string; - /** - * The index of the series in the chart, affecting the internal index in the chart.series array, the visible Z index - * as well as the order in the legend. - * @since 2.3.0 - */ - index?: number; - /** - * The sequential index of the series in the legend. - */ - legendIndex?: number; - /** - * The name of the series as shown in the legend, tooltip etc. - */ - name?: string; - /** - * A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from - * the pointPadding and groupPadding. - */ - pointWidth?: number; - /** - * This option allows grouping series in a stacked chart. The stack option can be a string or a number or anything - * else, as long as the grouped series' stack options match each other. - * @since 2.1 - */ - stack?: any; - /** - * When using dual or multiple x axes, this number defines which xAxis the particular series is connected to. It - * refers to either the axis id or the index of the axis in the xAxis array, with 0 being the first. - * @default 0 - */ - xAxis?: string | number; - /** - * When using dual or multiple x axes, this number defines which xAxis the particular series is connected to. It - * refers to either the axis id or the index of the axis in the xAxis array, with 0 being the first. - * @default 0 - */ - yAxis?: string | number; - /** - * Define the visual z index of the series. - */ - zIndex?: number; -} + interface CreditsOptions { + /** + * Whether to show the credits text. + * @default true + */ + enabled?: boolean; + /** + * The URL for the credits label. + * @default 'http://www.highcharts.com' + */ + href?: string; + /** + * Position configuration for the credits label. Supported properties are align, verticalAlign, x and y. + */ + position?: Position; + /** + * CSS styles for the credits label. + */ + style?: Object; + /** + * The text for the credits label. + * @default 'Highcharts.com' + */ + text?: string; + } -interface HighchartsSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsSeriesChart { } + interface DataSeriesMapping { + [pointPropertyName: string]: number; + } -interface HighchartsAreaChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsAreaChart { } -interface HighchartsAreaRangeChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsAreaRangeChart { } -interface HighchartsAreaSplineChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsAreaSplineChart { } -interface HighchartsAreaSplineRangeChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsAreaSplineRangeChart { } -interface HighchartsBarChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsBarChart { } -interface HighchartsBoxPlotChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsBoxPlotChart { } -interface HighchartsBubbleChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsBubbleChart { } -interface HighchartsColumnChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsColumnChart { } -interface HighchartsColumnRangeChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsColumnRangeChart { } -interface HighchartsErrorBarChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsErrorBarChart { } -interface HighchartsFunnelChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsFunnelChart { } -interface HighchartsGaugeChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsGaugeChart { } -interface HighchartsHeatMapSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsHeatMapChart { } -interface HighchartsLineChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsLineChart { } -interface HighchartsPieChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsPieChart { } -interface HighchartsPolygonChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsPolygonChart { } -interface HighchartsPyramidChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsPyramidChart { } -interface HighchartsScatterChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsScatterChart { } -interface HighchartsSolidGaugeChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsSolidGaugeChart { } -interface HighchartsSplineChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsSplineChart { } -interface HighchartsTreeMapChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsTreeMapChart { } -interface HighchartsWaterFallChartSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsWaterFallChart { } - -interface HighchartsDataPoint { /** - * Individual color for the point. By default the color is pulled from the global colors array. - * @default undefined - */ - color?: string | HighchartsGradient; - /** - * Serves a purpose only if a colorAxis object is defined in the chart options. This value will decide which color - * the point gets from the scale of the colorAxis. - * @default undefined - */ - colorValue?: number; - /** - * Individual data label for each point. The options are the same as the ones for plotOptions.series.dataLabels - */ - dataLabels?: HighchartsDataLabels; - /** - * The id of a series in the drilldown.series array to use for a drilldown for this point. - * @since 3.0.8 - */ - drilldown?: string; - /** - * Individual point events - */ - events?: HighchartsPointEvents; - /** - * The high or maximum value for each data point. - */ - high?: number; - /** - * An id for the point. This can be used after render time to get a pointer to the point object through chart.get(). - * @since 1.2.0 - */ - id?: string; - /** - * The inner radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. - * @since 4.1.6 - */ - innerRadius?: number|string; - /** - * When this property is true, the points acts as a summary column for the values added or substracted since the - * last intermediate sum, or since the start of the series. The y value is ignored. - * @default false - */ - isIntermediateSum?: boolean; - /** - * When this property is true, the point display the total sum across the entire series. The y value is ignored. - * @default false - */ - isSum?: boolean; - /** - * The sequential index of the data point in the legend. - */ - legendIndex?: number; - /** - * The low or minimum value for each data point. - */ - low?: number; - marker?: HighchartsMarker; - /** - * The median for each data point. This is drawn as a line through the middle area of the box. - */ - median?: number; - /** - * The name of the point as shown in the legend, tooltip, dataLabel etc. - * - * If the xAxis.type is set to category, and no categories option exists, the category will be pulled from the - * point.name of the last series defined. For multiple series, best practice however is to define xAxis.categories. - */ - name?: string; - /** - * Only for treemap. Use this option to build a tree structure. The value should be the id of the point which is the - * parent. If no points has a matching id, or this option is undefined, then the parent will be set to the root. - * @default undefined - * @since 4.1.0 - */ - parent?: string; - /** - * The lower quartile for each data point. This is the bottom of the box. - */ - q1?: number; - /** - * The higher quartile for each data point. This is the top of the box. - */ - q3?: number; - /** - * The outer radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. - * @since 4.1.6 - */ - radius?: number|string; - /** - * Whether the data point is selected initially. - * @default false - */ - selected?: boolean; - /** - * Whether to display a slice offset from the center. - * @default false - */ - sliced?: boolean; - /** - * The value of the point, resulting in a relative area of the point in the treemap. - */ - value?: number; - /** - * The x value of the point. For datetime axes, the X value is the timestamp in milliseconds since 1970. - */ - x?: number; - /** - * The y value of the point. - */ - y?: number; - /** - * The size value for each bubble. The bubbles' diameters are computed based on the z, and controlled by series - * options like minSize, maxSize, sizeBy, zMin and zMax. - */ - z?: number; -} - -/** - * The chart's subtitle - */ -interface HighchartsSubtitleOptions { - /** - * The horizontal alignment of the subtitle. Can be one of 'left', 'center' and 'right'. - * @default 'center' - * @since 2.0 - */ - align?: string; - /** - * When the subtitle is floating, the plot area will not move to make space for it. - * @default false - * @since 2.1 - */ - floating?: boolean; - /** - * CSS styles for the title. Exact positioning of the title can be achieved by changing the margin property, or by - * adding position: 'absolute' and left and top properties. - * @default { 'color': '#555555' } - */ - style?: Object; - /** - * The subtitle of the chart. - */ - text?: string; - /** - * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the text. - * @default false - */ - useHTML?: boolean; - /** - * The vertical alignment of the title. Can be one of 'top', 'middle' and 'bottom'. When a value is given, the title - * behaves as floating. - * @since 2.1 - */ - verticalAlign?: string; - /** - * The x position of the subtitle relative to the alignment within chart.spacingLeft and chart.spacingRight. - * @default 0 - * @since 2.0 - */ - x?: number; - /** - * The y position of the subtitle relative to the alignment within chart.spacingTop and chart.spacingBottom. By - * default the subtitle is laid out below the title unless the title is floating. - * @default null - * @since 2.0 - */ - y?: number; -} - -interface HighchartsTitleOptions { - /** - * The horizontal alignment of the title. Can be one of 'left', 'center' and 'right'. - * @default 'center' - * @since 2.0 - */ - align?: string; - /** - * When the title is floating, the plot area will not move to make space for it. - * @default false - * @since 2.1 - */ - floating?: boolean; - /** - * The margin between the title and the plot area, or if a subtitle is present, the margin between the subtitle and - * the plot area. - * @default 15 - * @since 2.1 - */ - margin?: number; - /** - * CSS styles for the title. Exact positioning of the title can be achieved by changing the margin property, or by - * adding position: 'absolute' and left and top properties. - * @default { 'color': '#333333', 'fontSize': '18px' } - */ - style?: Object; - /** - * The title of the chart. To disable the title, set the text to null. - * @default 'Chart title' - */ - text?: string; - /** - * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the text. - * @default false - */ - useHTML?: boolean; - /** - * The vertical alignment of the title. Can be one of 'top', 'middle' and 'bottom'. When a value is given, the title - * behaves as floating. - * @since 2.1 - */ - verticalAlign?: string; - /** - * The x position of the title relative to the alignment within chart.spacingLeft and chart.spacingRight. - * @default 0 - * @since 2.0 - */ - x?: number; - /** - * The y position of the title relative to the alignment within chart.spacingTop and chart.spacingBottom. By default - * it depends on the font size. - * @default null - * @since 2.0 - */ - y?: number; -} - -interface HighchartsCrosshairObject { - color?: string | HighchartsGradient; - width?: number; - dashStyle?: string; //Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot - zIndex?: number; -} - -interface HighchartsPlotPoint { - plotX: number; - plotY: number; -} - -interface HighchartsTooltipOptions extends HighchartsSeriesTooltipOptions { - /** - * Enable or disable animation of the tooltip. In slow legacy IE browsers the animation is disabled by default. - * @default true - * @since 2.3.0 - */ - animation?: boolean; - /** - * The background color or gradient for the tooltip. - * @default 'rgba(255, 255, 255, 0.85)' - */ - backgroundColor?: string | HighchartsGradient; - /** - * The color of the tooltip border. When null, the border takes the color of the corresponding series or point. - * @default null - */ - borderColor?: string | HighchartsGradient; - /** - * The radius of the rounded border corners. - * @default 3 - */ - borderRadius?: number; - /** - * The pixel width of the tooltip border. - * @default 1 - */ - borderWidth?: number; - /** - * Display crosshairs to connect the points with their corresponding axis values. The crosshairs can be defined as a - * boolean, an array of booleans or an object. - * - * Boolean - * If the crosshairs option is true, a single crosshair relating to the x axis will be shown. - * - * Array of booleans - * In an array of booleans, the first value turns on the x axis crosshair and the second value to the y axis - * crosshair. Use [true, true] to show complete crosshairs. - * - * Array of objects - * In an array of objects, the first value applies to the x axis crosshair and the second value to the y axis - * crosshair. For each dimension, a width, color, dashStyle and zIndex can be given. - * - * @default null - */ - crosshairs?: boolean | [boolean, boolean] | HighchartsCrosshairObject | [HighchartsCrosshairObject, HighchartsCrosshairObject]; - /** - * Enable or disable the tooltip. - * @default true - */ - enabled?: boolean; - /** - * Callback function to format the text of the tooltip. Return false to disable tooltip for a specific point on - * series. - * - * A subset of HTML is supported. The HTML of the tooltip is parsed and converted to SVG, therefore this isn't a - * complete HTML renderer. The following tabs are supported: , , , ,
, . Spans can be - * styled with a style attribute, but only text-related CSS that is shared with SVG is handled. - * - * Since version 2.1 the tooltip can be shared between multiple series through the shared option. The available data - * in the formatter differ a bit depending on whether the tooltip is shared or not. In a shared tooltip, all - * properties except x, which is common for all points, are kept in an array, this.points. - * - * Available data are: - * this.percentage (not shared) / this.points[i].percentage (shared) - * Stacked series and pies only. The point's percentage of the total. - * this.point (not shared) / this.points[i].point (shared) - * The point object. The point name, if defined, is available through this.point.name. - * this.points - * In a shared tooltip, this is an array containing all other properties for each point. - * this.series (not shared) / this.points[i].series (shared) - * The series object. The series name is available through this.series.name. - * this.total (not shared) / this.points[i].total (shared) - * Stacked series only. The total value at this point's x value. - * this.x - * The x value. This property is the same regardless of the tooltip being shared or not. - * this.y (not shared) / this.points[i].y (shared) - * The y value. - */ - formatter?: () => boolean | string; - /** - * A callback function to place the tooltip in a default position. The callback receives three parameters: - * labelWidth, labelHeight and point, where point contains values for plotX and plotY telling where the reference - * point is in the plot area. Add chart.plotLeft and chart.plotTop to get the full coordinates. - * - * The return should be an object containing x and y values, for example { x: 100, y: 100 }. - * @since 2.2.4 - */ - positioner?: (labelWidth: number, labelHeight: number, point: HighchartsPlotPoint) => { x: number; y: number; }; - /** - * Whether to apply a drop shadow to the tooltip. - * @default true - */ - shadow?: boolean; - /** - * The name of a symbol to use for the border around the tooltip. In Highcharts 3.x and less, the shape was square. - * @default 'callout' - * @since 4.0 - */ - shape?: string; - /** - * When the tooltip is shared, the entire plot area will capture mouse movement or touch events. Tooltip texts for - * series types with ordered data (not pie, scatter, flags etc) will be shown in a single bubble. This is - * recommended for single series charts and for tablet/mobile optimized charts. - * @default false - * @since 2.1 - */ - shared?: boolean; - /** - * Proximity snap for graphs or single points. Does not apply to bars, columns and pie slices. It defaults to 10 for - * mouse-powered devices and 25 for touch devices. Note that since Highcharts 4.1 the whole plot area by default - * captures pointer events in order to show the tooltip, so for tooltip.snap to make sense, stickyTracking must be - * false. - * @since 1.2.0 - */ - snap?: number; - /** - * CSS styles for the tooltip. The tooltip can also be styled through the CSS class .highcharts-tooltip - * @default { color: '#333333', fontSize: '12px', padding: '8px' } - */ - style?: Object; - /** - * Use HTML to render the contents of the tooltip instead of SVG. Using HTML allows advanced formatting like tables - * and images in the tooltip. It is also recommended for rtl languages as it works around rtl bugs in early Firefox. - * @default false - * @since 2.2 - */ - useHTML?: boolean; -} - -interface HighchartsSeriesTooltipOptions { - /** - * For series on a datetime axes, the date format in the tooltip's header will by default be guessed based on the - * closest data points. This member gives the default string representations used for each unit. - */ - dateTimeLabelFormats?: HighchartsDateTimeFormats; - /** - * Whether the tooltip should follow the mouse as it moves across columns, pie slices and other point types with an - * extent. By default it behaves this way for scatter, bubble and pie series by override in the plotOptions for - * those series types. - * - * For touch moves to behave the same way, followTouchMove must be true also. - * @default false - * @since 3.0 - */ - followPointer?: boolean; - /** - * Whether the tooltip should follow the finger as it moves on a touch device. If chart.zoomType is set, it will - * override followTouchMove. - * @default true - * @since 3.0.1 - */ - followTouchMove?: boolean; - /** - * A string to append to the tooltip format. - * @default 'false' - * @since 2.2 - */ - footerFormat?: string; - /** - * The HTML of the tooltip header line. Variables are enclosed by curly brackets. Available variables are point.key, - * series.name, series.color and other members from the point and series objects. The point.key variable contains - * the category name, x value or datetime string depending on the type of axis. For datetime axes, the point.key - * date format can be set using tooltip.xDateFormat. - * - * @default '{point.key}
' - */ - headerFormat?: string; - /** - * The number of milliseconds to wait until the tooltip is hidden when mouse out from a point or chart. - * @default 500 - * @since 3.0 - */ - hideDelay?: number; - /** - * The HTML of the point's line in the tooltip. Variables are enclosed by curly brackets. Available variables are - * point.x, point.y, series.name and series.color and other properties on the same form. Furthermore, point.y can be - * extended by the tooltip.valuePrefix and tooltip.valueSuffix variables. This can also be overridden for each - * series, which makes it a good hook for displaying units. - * - * @default '\u25CF {series.name}: {point.y}
' - * @since 2.2 - */ - pointFormat?: string; - /** - * A callback function for formatting the HTML output for a single point in the tooltip. Like the pointFormat - * string, but with more flexibility. - * - * The this keyword refers to the Point object. - * @since 4.1.0 - */ - pointFormatter?: () => string; - /** - * How many decimals to show in each series' y value. This is overridable in each series' tooltip options object. - * The default is to preserve all decimals. - * @since 2.2 - */ - valueDecimals?: number; - /** - * A string to prepend to each series' y value. Overridable in each series' tooltip options object. - * @since 2.2 - */ - valuePrefix?: string; - /** - * A string to append to each series' y value. Overridable in each series' tooltip options object. - * @since 2.2 - */ - valueSuffix?: string; - /** - * The format for the date in the tooltip header if the X axis is a datetime axis. The default is a best guess based - * on the smallest distance between points in the chart. - */ - xDateFormat?: string; -} - -interface HighchartsOptions { - /** - * Options regarding the chart area and plot area as well as general chart options. - */ - chart?: HighchartsChartOptions; - colorAxis?: HighchartsColorAxisOptions | HighchartsColorAxisOptions[]; - /** - * An array containing the default colors for the chart's series. When all colors are used, new colors are pulled - * from the start again. - * - * Default colors can also be set on a series or series.type basis, see column.colors, pie.colors. - * - * @default ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'] - */ - colors?: string[]; - /** - * Highchart by default puts a credits label in the lower right corner of the chart. This can be changed using these options. - */ - credits?: HighchartsCreditsOptions; - /** - * The Data module provides a simplified interface for adding data to a chart from sources like CVS, HTML tables or - * grid views. See also the tutorial article on the Data module. + * The Data module provides a simplified interface for adding data to a chart from sources like CVS, HTML tables or grid + * views. See also the tutorial article on the Data module. * * It requires the modules/data.js file to be loaded. * * Please note that the default way of adding data in Highcharts, without the need of a module, is through the * series.data option. */ - data?: HighchartsDataOptions; + interface DataOptions { + /** + * A two-dimensional array representing the input data on tabular form. This input can be used when the data is + * already parsed, for example from a grid view component. Each cell can be a string or number. If not + * switchRowsAndColumns is set, the columns are interpreted as series. + * @since 4.0 + */ + columns?: [string | number][]; + /** + * The callback that is evaluated when the data is finished loading, optionally from an external source, and parsed. + * The first argument passed is a finished chart options object, containing the series. These options can be + * extended with additional options and passed directly to the chart constructor. + * @since 4.0 + */ + complete?: (options: Options) => void; + /** + * A comma delimited string to be parsed. Related options are startRow, endRow, startColumn and endColumn to delimit + * what part of the table is used. The lineDelimiter and itemDelimiter options define the CSV delimiter formats. + * @since 4.0 + */ + csv?: string; + /** + * Which of the predefined date formats in Date.prototype.dateFormats to use to parse date values. Defaults to a + * best guess based on what format gives valid and ordered dates. + * + * Valid options include: + * 'YYYY-mm-dd' + * 'dd/mm/YYYY' + * 'mm/dd/YYYY' + * 'dd/mm/YY' + * 'mm/dd/YY' + * @since 4.0 + */ + dateFormat?: string; + /** + * The decimal point used for parsing numbers in the CSV. + * @default '.' + */ + decimalPoint?: string; + /** + * In tabular input data, the last column (indexed by 0) to use. Defaults to the last column containing data. + * @since 4.0 + */ + endColumn?: number; + /** + * In tabular input data, the last row (indexed by 0) to use. Defaults to the last row containing data. + * @since 4.0.4 + */ + endRow?: number; + /** + * Whether to use the first row in the data set as series names. + * @default true + * @since 4.1.0 + */ + firstRowAsNames?: boolean; + /** + * The key for a Google Spreadsheet to load. See {@link https://developers.google.com/gdata/samples/spreadsheet_sample|general information on GS}. + * @since 4.0 + */ + googleSpreadsheetKey?: string; + /** + * The Google Spreadsheet worksheet to use in combination with googleSpreadsheetKey. The available id's from your + * sheet can be read from https://spreadsheets.google.com/feeds/worksheets/{key}/public/basic + * @since 4.0 + */ + googleSpreadsheetWorksheet?: string; + /** + * Item or cell delimiter for parsing CSV. Defaults to the tab character \t if a tab character is found in the CSV + * string, if not it defaults to ,. + * @since 4.0 + */ + itemDelimiter?: string; + /** + * Line delimiter for parsing CSV. + * @default '\n' + * @since 4.0 + */ + lineDelimiter?: string; + /** + * A callback function to parse string representations of dates into JavaScript timestamps. Should return an integer + * timestamp on success. + * @since 4.0 + */ + parseDate?: (val: any) => number; + /** + * A callback function to access the parsed columns, the two-dimentional input data array directly, before they are + * interpreted into series data and categories. Return false to stop completion, or call this.complete() to continue + * async. + * @since 4.0 + */ + parsed?: (columns: [string | number][]) => boolean | void; + /** + * The same as the columns input option, but defining rows intead of columns. + * @since 4.0 + */ + rows?: [string | number][]; + /** + * An array containing object with Point property names along with what column id the property should be taken from. + * @since 4.0.4 + */ + seriesMapping?: DataSeriesMapping[]; + /** + * In tabular input data, the first column (indexed by 0) to use. + * @default 0 + * @since 4.0 + */ + startColumn?: number; + /** + * In tabular input data, the first row (indexed by 0) to use. + * @default 0 + * @since 4.0 + */ + startRow?: number; + /** + * Switch rows and columns of the input data, so that this.columns effectively becomes the rows of the data set, and + * the rows are interpreted as series. + * @default false + * @since 4.0 + */ + switchRowsAndColumns?: boolean; + /** + * A HTML table or the id of such to be parsed as input data. Related options are startRow, endRow, startColumn and + * endColumn to delimit what part of the table is used. + */ + table?: string | HTMLElement; + } + /** - * Options for drill down, the concept of inspecting increasingly high resolution data through clicking on chart - * items like columns or pie slices. + * Options for drill down, the concept of inspecting increasingly high resolution data through clicking on chart items + * like columns or pie slices. * * The drilldown feature requires the drilldown.js file to be loaded, found in the modules directory of the download * package, or online at code.highcharts.com/modules/drilldown.js. */ - drilldown?: HighchartsDrilldownOptions; - /** - * Options for the exporting module. - */ - exporting?: HighchartsExportingOptions; - /** - * HTML labels that can be positioned anywhere in the chart area. - */ - labels?: HighchartsLabelsOptions; - lang?: HighchartsLangObject; - /** - * The legend is a box containing a symbol and name for each series item or point item in the chart. - */ - legend?: HighchartsLegendOptions; - /** - * The loading options control the appearance of the loading screen that covers the plot area on chart operations. - * This screen only appears after an explicit call to chart.showLoading(). It is a utility for developers to - * communicate to the end user that something is going on, for example while retrieving new data via an XHR - * connection. The 'Loading...' text itself is not part of this configuration object, but part of the lang object. - */ - loading?: HighchartsLoadingOptions; - /** - * A collection of options for buttons and menus appearing in the exporting module. - */ - navigation?: HighchartsNavigationOptions; - /** - * Options for displaying a message like 'No data to display'. This feature requires the file no-data-to-display.js - * to be loaded in the page. The actual text to display is set in the lang.noData option. - */ - noData?: HighchartsNoDataOptions; - /** - * Applies only to polar charts and angular gauges. This configuration object holds general options for the combined - * X and Y axes set. Each xAxis or yAxis can reference the pane by index. - */ - pane?: HighchartsPaneOptions; - /** - * The plotOptions is a wrapper object for config objects for each series type. The config objects for each series - * can also be overridden for each series item as given in the series array. - * - * Configuration options for the series are given in three levels. Options for all series in a chart are given in - * the plotOptions.series object. Then options for all series of a specific type are given in the plotOptions of - * that type, for example plotOptions.line. Next, options for one single series are given in the series array. - */ - plotOptions?: HighchartsPlotOptions; - /** - * The actual series to append to the chart. In addition to the members listed below, any member of the plotOptions - * for that specific type of plot can be added to a series individually. For example, even though a general - * lineWidth is specified in plotOptions.series, an individual lineWidth can be specified for each series. - */ - series?: HighchartsIndividualSeriesOptions[]; - /** - * The chart's subtitle - */ - subtitle?: HighchartsSubtitleOptions; - /** - * The chart's main title. - */ - title?: HighchartsTitleOptions; - /** - * Options for the tooltip that appears when the user hovers over a series or point. - */ - tooltip?: HighchartsTooltipOptions; - /** - * The X axis or category axis. Normally this is the horizontal axis, though if the chart is inverted this is the - * vertical axis. In case of multiple axes, the xAxis node is an array of configuration objects. - */ - xAxis?: HighchartsAxisOptions[] | HighchartsAxisOptions; - /** - * The Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the - * horizontal axis. In case of multiple axes, the yAxis node is an array of configuration objects. - */ - yAxis?: HighchartsAxisOptions[] | HighchartsAxisOptions; -} + interface DrilldownOptions { + /** + * Additional styles to apply to the X axis label for a point that has drilldown data. By default it is underlined + * and blue to invite to interaction. + * @default { cursor: 'pointer', color: '#0d233a', fontWeight: 'bold', textDecoration: 'underline' } + * @since 3.0.8 + */ + activeAxisLabelStyle?: Object; + /** + * Additional styles to apply to the data label of a point that has drilldown data. By default it is underlined and + * blue to invite to interaction. + * @default { cursor: 'pointer', color: '#0d233a', fontWeight: 'bold', textDecoration: 'underline' } + * @since 3.0.8 + */ + activeDataLabelStyle?: Object; + /** + * When this option is false, clicking a single point will drill down all points in the same category, equivalent to + * clicking the X axis label. + * @default true + * @since 4.1.7 + */ + allowPointDrilldown?: boolean; + /** + * Set the animation for all drilldown animations. Animation of a drilldown occurs when drilling between a column + * point and a column series, or a pie slice and a full pie series. Drilldown can still be used between series and + * points of different types, but animation will not occur. + * + * The animation can either be set as a boolean or a configuration object. If true, it will use the 'swing' jQuery + * easing and a duration of 500 ms. + * @since 3.0.8 + */ + animation?: boolean | Animation; + /** + * Options for the drill up button that appears when drilling down on a series. The text for the button is defined + * in lang.drillUpText. + */ + drillUpButton?: { + /** + * Positioning options for the button within the relativeTo box. Available properties are x, y, align and + * verticalAlign. + * @since 3.0.8 + */ + position?: Position; + /** + * What box to align the button to. Can be either 'plotBox' or 'spacingBox'. + * @default 'plotBox' + * @since 3.0.8 + */ + relativeTo?: string; + /** + * A collection of attributes for the button. The object takes SVG attributes like fill, stroke, stroke-width or + * r, the border radius. The theme also supports style, a collection of CSS properties for the text. Equivalent + * attributes for the hover state are given in theme.states.hover. + * @since 3.0.8 + */ + theme?: ButtonStatesTheme; + } + /** + * An array of series configurations for the drill down. Each series configuration uses the same syntax as the + * series option set. These drilldown series are hidden by default. The drilldown series is linked to the parent + * series' point by its id. + * @since 3.0.8 + */ + series?: IndividualSeriesOptions[]; + } + + interface MenuItem { + /** + * String to show in the menu item. + */ + text: string; + /** + * Callback function to run on click. + */ + onclick: () => void; + } + + interface Button { + /** + * Alignment for the buttons. + * @default 'right' + * @since 2.0 + */ + align?: string; + /** + * Whether to enable buttons. + * @default true + * @since 2.0 + */ + enabled?: boolean; + /** + * Pixel height of the buttons. + * @default 20 + * @since 2.0 + */ + height?: number; + /** + * Fill color for the symbol within the button. + * @default '#E0E0E0' + * @since 2.0 + */ + symbolFill?: string; + /** + * The pixel size of the symbol on the button. + * @default 14 + * @since 2.0 + */ + symbolSize?: number; + /** + * The color of the symbol's stroke or line. + * @default '#666' + * @since 2.0 + */ + symbolStroke?: string; + /** + * The pixel stroke width of the symbol on the button. + * @default 1 + * @since 2.0 + */ + symbolStrokeWidth?: number; + /** + * The x position of the center of the symbol inside the button. + * @default 12.5 + * @since 2.0 + */ + symbolX?: number; + /** + * The y position of the center of the symbol inside the button. + * @default 10.5 + * @since 2.0 + */ + symbolY?: number; + /** + * A text string to add to the individual button. + * @default null + * @since 3.0 + */ + text?: string; + /** + * A configuration object for the button theme. The object accepts SVG properties like stroke-width, stroke and + * fill. Tri-state button styles are supported by the states.hover and states.select objects. + * @since 3.0 + */ + theme?: ButtonStatesTheme; + /** + * The vertical alignment of the buttons. Can be one of 'top', 'middle' or 'bottom'. + * @default 'top' + * @since 2.0 + */ + verticalAlign?: string; + /** + * The pixel width of the button. + * @default 24 + * @since 2.0 + */ + width?: number; + /** + * The vertical offset of the button's position relative to its verticalAlign. + * @default 0 + * @since 2.0 + */ + y?: number; + } + + interface ExportingContextButton extends Button { + /** + * A collection of config options for the menu items. Each options object consists of a text option which is a + * string to show in the menu item, as well as an onclick parameter which is a callback function to run on click. + * + * By default, there is the 'Print' menu item plus one menu item for each of the available export types. Menu items + * can be customized by defining a new array of items and assigning null to unwanted positions. + * @since 2.0 + */ + menuItems?: MenuItem[]; + /** + * A click handler callback to use on the button directly instead of the popup menu. + * @since 2.0 + */ + onclick?: () => void; + /** + * The symbol for the button. Points to a definition function in the Highcharts.Renderer.symbols collection. The + * default exportIcon function is part of the exporting module. + * @default 'menu' + */ + symbol?: string; + /** + * The horizontal position of the button relative to the align option. + * @default -10 + */ + x?: number; + } + + interface ExportingOptions { + /** + * Experimental setting to allow HTML inside the chart (added through the useHTML options), directly in the exported + * image. This allows you to preserve complicated HTML structures like tables or bi-directional text in exported + * charts. + * + * Disclaimer: The HTML is rendered in a foreignObject tag in the generated SVG. The official export server is based + * on PhantomJS, which supports this, but other SVG clients, like Batik, does not support it. This also applies to + * downloaded SVG that you want to open in a desktop client. + * @default false + * @since 4.1.8 + */ + allowHTML?: boolean; + /** + * Options for the export related buttons, print and export. In addition to the default buttons listed here, custom + * buttons can be added. See navigation.buttonOptions for general options. + */ + buttons?: { + contextButton?: ExportingContextButton; + }; + /** + * Additional chart options to be merged into an exported chart. For example, the exported chart can be given a + * specific width and height, or a printer-friendly color scheme. + * @default null + */ + chartOptions?: Options; + /** + * Whether to enable the exporting module. Disabling the module will hide the context button, but API methods will + * still be available. + * @default true + * @since 2.0 + */ + enabled?: boolean; + /** + * Function to call if the offline-exporting module fails to export a chart on the client side, and + * fallbackToExportServer is disabled. If left undefined, an exception is thrown instead. + * @default undefined + * @since 5.0.0 + */ + error?: Function; + /** + * Whether or not to fall back to the export server if the offline-exporting module is unable to export the chart on + * the client side. + * @default true + * @since 4.1.8 + */ + fallbackToExportServer?: boolean; + /** + * The filename, without extension, to use for the exported chart. + * @default 'chart' + * @since 2.0 + */ + filename?: string; + /** + * An object containing additional attributes for the POST form that sends the SVG to the export server. For + * example, a target can be set to make sure the generated image is received in another frame, or a custom enctype + * or encoding can be set. + * @since 3.0.8 + */ + formAttributes?: any; + /** + * Path where Highcharts will look for export module dependencies to load on demand if they don't already exist on + * window. Should currently point to location of CanVG library (https://github.com/canvg/canvg) and RGBColor.js, + * required for client side export in certain browsers. + * @default 'http://code.highcharts.com/{version}/lib' + * @since 5.0.0 + */ + libUrl?: string; + /** + * When printing the chart from the menu item in the burger menu, if the on-screen chart exceeds this width, it is + * resized. After printing or cancelled, it is restored. The default width makes the chart fit into typical paper + * format. Note that this does not affect the chart when printing the web page as a whole. + * @default 780 + * @since 4.2.5 + */ + printMaxWidth?: number; + /** + * Defines the scale or zoom factor for the exported image compared to the on-screen display. While for instance a + * 600px wide chart may look good on a website, it will look bad in print. The default scale of 2 makes this chart + * export to a 1200px PNG or JPG. + * @default 2 + * @since 3.0 + */ + scale?: number; + /** + * The height of the original chart when exported, unless an explicit chart.height is set. The height exported + * raster image is then multiplied by scale. + * @since 3.0 + */ + sourceHeight?: number; + /** + * The width of the original chart when exported, unless an explicit chart.width is set. The width exported + * raster image is then multiplied by scale. + * @since 3.0 + */ + sourceWidth?: number; + /** + * Default MIME type for exporting if chart.exportChart() is called without specifying a type option. Possible + * values are image/png, image/jpeg, application/pdf and image/svg+xml. + * @default 'image/png' + * @since 2.0 + */ + type?: string; + /** + * The URL for the server module converting the SVG string to an image format. By default this points to Highslide + * Software's free web service. + * @default 'http://export.highcharts.com' + * @since 2.0 + */ + url?: string; + /** + * The pixel width of charts exported to PNG or JPG. As of Highcharts 3.0, the default pixel width is a function of + * the chart.width or exporting.sourceWidth and the exporting.scale. + * @since 2.0 + */ + width?: number; + } -interface HighchartsGlobalOptions extends HighchartsOptions { /** * Global options that don't apply to each chart. These options, like the lang options, must be set using the * Highcharts.setOptions method. */ - global?: HighchartsGlobalObject; - /** - * Language object. The language object is global and it can't be set on each chart initiation. Instead, use - * Highcharts.setOptions to set it before any chart is initiated. - */ - lang?: HighchartsLangObject; -} + interface GlobalObject { + /** + * A custom Date class for advanced date handling. For example, JDate can be hooked in to handle Jalali dates. + * @since 4.0.4 + */ + Date?: any; + /** + * Path to the pattern image required by VML browsers in order to draw radial gradients. + * @default 'http://code.highcharts.com/{version}/gfx/vml-radial-gradient.png' + * @since 2.3.0 + */ + VMLRadialGradientURL?: string; + /** + * The URL to the additional file to lazy load for Android 2.x devices. These devices don't support SVG, so we + * download a helper file that contains canvg, its dependency rbcolor, and our own CanVG Renderer class. To avoid + * hotlinking to our site, you can install canvas-tools.js on your own server and change this option accordingly. + * @default 'http://code.highcharts.com/{version}/modules/canvas-tools.js' + */ + canvasToolsURL?: string; + /** + * A callback to return the time zone offset for a given datetime. It takes the timestamp in terms of milliseconds + * since January 1 1970, and returns the timezone offset in minutes. This provides a hook for drawing time based + * charts in specific time zones using their local DST crossover dates, with the help of external libraries. + * @since 4.1.0 + */ + getTimezoneOffset?: (timestamp: number) => number; + /** + * The timezone offset in minutes. Positive values are west, negative values are east of UTC, as in the ECMAScript + * getTimezoneOffset method. Use this to display UTC based data in a predefined time zone. + * @default 0 + * @since 3.0.8 + */ + timezoneOffset?: number; + /** + * Whether to use UTC time for axis scaling, tickmark placement and time display in Highcharts.dateFormat. + * Advantages of using UTC is that the time displays equally regardless of the user agent's time zone settings. + * Local time can be used when the data is loaded in real time or when correct Daylight Saving Time transitions are + * required. + * @default true + */ + useUTC?: boolean; + } -interface HighchartsDateFormatSpecifiers -{ - [index: string]: (timestamp: number) => string; -} + interface LabelItem { + html: string; + style: CSSObject; + } -/** - * A chart can have from 0 axes (pie chart) to multiples. In a normal, single series cartesian chart, there is one X - * axis and one Y axis. - * - * The X axis or axes are referenced by chart.xAxis, which is an array of Axis objects. If there is only one axis, it - * can be referenced through chart.xAxis[0], and multiple axes have increasing indices. The same pattern goes for Y - * axes. - * - * If you need to get the axes from a series object, use the series.xAxis andseries.yAxis properties. These are not - * arrays, as one series can only be associated to one X and one Y axis. - * - * A third way to reference the axis programmatically is by id. Add an id in the axis configuration options, and get the - * axis by chart.get(id). - * - * Configuration options for the axes are given in options.xAxis and options.yAxis. - */ -interface HighchartsAxisObject { - /** - * Add a plot band after render time. - * @param {HighchartsPlotBands} options A configuration object consisting of the same members as options.xAxis.plotBands - * @since 1.2.0 - */ - addPlotBand(options: HighchartsPlotBands): void; - /** - * Add a plot line after render time. - * @param {HighchartsPlotLines} options A configuration object consisting of the same members as options.xAxis.plotLines - * @since 1.2.0 - */ - addPlotLine(options: HighchartsPlotLines): void; - /** - * Get the current extremes for the axis. - * @since 1.2.0 - */ - getExtremes(): HighchartsExtremes; - /** - * Remove an axis from the chart. - * @param [boolean] redraw Defaults to true. Whether to redraw the chart following the remove. - * @since 3.0 - */ - remove(redraw?: boolean): void; - /** - * Remove a plot band by its id. - * @param {string} id The plot band's id as given in the original configuration object or in the addPlotBand method. - * @since 1.2.0 - */ - removePlotBand(id: string): void; - /** - * Remove a plot line by its id. - * @param {string} id The plot line's id as given in the original configuration object or in the addPlotLine method. - * @since 1.2.0 - */ - removePlotLine(id: string): void; - /** - * Set new categories for the axis. Redraws. - * @param {string[]} categories The new category names. - * @since 1.2.0 - */ - setCategories(categories: string[]): void; - /** - * Set new categories for the axis. - * @param {string[]} categories The new category names. - * @param {boolean} redraw Whether to redraw the axis or wait for an explicit call to chart.redraw(). - * @since 1.2.0 - */ - setCategories(categories: string[], redraw: boolean): void; - /** - * Set the minimum and maximum of the axes after render time. If the startOnTick and endOnTick options are true, the - * minimum and maximum values are rounded off to the nearest tick. To prevent this, these options can be set to - * false before calling setExtremes. Also, setExtremes will not allow a range lower than the minRange option, which - * by default is the range of five points. - * @param {number} min The new minimum value - * @param {number} max The new maximum value - * @param {boolean} redraw Whether to redraw the chart or wait for an explicit call to chart.redraw(). - * @param {boolean | HighchartsAnimation} animation When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. - * @since 1.2.0 - */ - setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation, eventArguments?: any): void; - /** - * Update the title of the axis after render time. - * @param {HighchartsAxisTitle} title The new title options on the same format as given in xAxis.title. - * @param {boolean} redraw Whether to redraw the chart now or hold until the next chart.redraw() - * @since 2.2 - */ - setTitle(title: HighchartsAxisTitle, redraw?: boolean): void; - /** - * Translates a value in terms of axis units in to pixels within the chart. - * @param {number} value A value in terms of axis units. - * @param {boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart or just the axis/pane itself. - * @return {number} - * @since 3.0 - */ - toPixels(value: number, paneCoordinates?: boolean): number; - /** - * Translate a pixel position along the axis to a value in terms of axis units. - * @param {number} pixel A pixel position along the axis. - * @param {boolean} paneCoordinates Whether the input pixel position is relative to the chart or just the axis/pane itself. - * @return {number} - * @since 3.0 - */ - toValue(pixel: number, paneCoordinates?: boolean): number; - /** - * Update an axis object with a new set of options. The options are merged with the existing options, so only new or - * altered options need to be specified. - * @param {HighchartsAxisOptions} options The new options that will be merged in with existing options on the axis. - * @param {boolean} redraw Defaults to true. Whether to redraw the chart after the new options are set. - * @since 3.0 - */ - update(options: HighchartsAxisOptions, redraw?: boolean): void; -} + interface LabelsOptions { + items?: LabelItem[]; + style?: CSSObject; + } -/** - * The chart object is the JavaScript object representing a single chart in the web page.The pointer to your chart - * object is returned when a chart is created using the Highcharts.Chart() constructor: - * var chart1 = new Highcharts.Chart(options); - */ -interface HighchartsChartObject { - /** - * Add an axis to the chart after render time. Note that this method should never be used when adding data - * synchronously at chart render time, as it adds expense to the calculations and rendering. When adding data at the - * same time as the chart is initiated, add the axis as a configuration option instead. - * @param {HighchartsAxisOptions} options The Axis options, as documented under xAxis and yAxis. - * @param [boolean] isX Whether it is an X axis or Y axis - * @param [boolean] redraw Defaults to true. Whether to redraw the chart after the series is added. See the redraw() method. - * @param [boolean | HighchartsAnimation] animation Defaults to true. When true, the series' updating will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. - * @return {HighchartsAxisObject} - * @since 3.0 - */ - addAxis(options: HighchartsAxisOptions, isX?: boolean, redraw?: boolean, animation?: boolean | HighchartsAnimation): HighchartsAxisObject; - /** - * Add a series to the chart after render time. Note that this method should never be used when adding data - * synchronously at chart render time, as it adds expense to the calculations and rendering. When adding data at the - * same time as the chart is initiated, add the series as a configuration option instead. - * @param {T} options The series options, as documented under plotOptions.series and under the plotOptions for each series type. - * @param [boolean] redraw - * @since 1.2.0 - */ - addSeries(options: T, redraw?: boolean, animation?: boolean | HighchartsAnimation): T; - /** - * Add a series to the chart as drilldown from a specific point in the parent series. This method is used for async - * drilldown, when clicking a point in a series should result in loading and displaying a more high-resolution - * series. When not async, the setup is simpler using the drilldown.series options structure. - * @param {HighchartsPointObject} point The existing Point object from which the drilldown will start. - * @param {HighchartsIndividualSeriesOptions} seriesOptions The series options, as documented under plotOptions.series and under the plotOptions for each series type. - * @since 3.0.8 - */ - addSeriesAsDrilldown(point: HighchartsPointObject, seriesOptions: HighchartsIndividualSeriesOptions): void; - /** - * A reference to the containing HTML element, dynamically inserted into the element given in chart.renderTo. - * @since 1.2.5 - */ - container: HTMLElement; - /** - * Removes the chart and purges memory. This method should be called before writing a new chart into the same - * container. It is called internally on window unload to prevent leaks. - * @since 1.2.2 - */ - destroy(): void; - /** - * When the chart is drilled down to a child series, calling chart.drillUp() will drill up to the parent series. - * @since 3.0.8 - */ - drillUp(): void; - /** - * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for - * conversion. - * @since 2.0 - */ - exportChart(): void; - /** - * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for - * conversion. - * @param {HighchartsExportingOptions} options Exporting options. Out of the exporting options, the following options can be given as parameters to the exportChart method. All options default to the values given in the exporting config options. filename: the filename for the export without extension, url: the URL for the server module to do the conversion, width: the width of the PNG or JPEG image generated on the server, type: the MIME type of the converted image, sourceWidth: the width of the source (in-page) chart, sourceHeight: the height of the source chart. - * @since 2.0 - */ - exportChart(options: HighchartsExportingOptions): void; - /** - * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for - * conversion. - * @param {HighchartsExportingOptions} options Exporting options. Out of the exporting options, the following options can be given as parameters to the exportChart method. All options default to the values given in the exporting config options. filename: the filename for the export without extension, url: the URL for the server module to do the conversion, width: the width of the PNG or JPEG image generated on the server, type: the MIME type of the converted image, sourceWidth: the width of the source (in-page) chart, sourceHeight: the height of the source chart. - * @param {HighchartsOptions} chartOptions Additional chart options for the exported chart. For example a different background color can be added here. - * @since 2.0 - */ - exportChart(options: HighchartsExportingOptions, chartOptions: HighchartsOptions): void; - /** - * Export the chart to a PNG or SVG without sending it to a server. Requires - * modules/exporting.js and modules/offline-exporting.js. - * @since 2.0 - */ - exportChartLocal(): void; - /** - * Export the chart to a PNG or SVG without sending it to a server. Requires - * modules/exporting.js and modules/offline-exporting.js. - * @param {HighchartsExportingOptions} options Exporting options. Same as - * the exportChart params. - * @since 2.0 - */ - exportChartLocal(options: HighchartsExportingOptions): void; - /** - * Export the chart to a PNG or SVG without sending it to a server. - * Requires modules/exporting.js and modules/offline-exporting.js. - * @param {HighchartsExportingOptions} options Exporting options. Same as - * the exportChart params. - * @param {HighchartsOptions} chartOptions Additional chart options for the - * exported chart. Same as the exportChart params. - * @since 2.0 - */ - exportChartLocal(options: HighchartsExportingOptions, chartOptions: HighchartsOptions): void; - /** - * Get an axis, series or point by its id as given in the configuration options. - * @param {string} id The id of the axis, series or point to get. - * @return {HighchartsAxisObject|HighchartsSeriesObject|HighchartsPointObject} - * @since 1.2.0 - */ - get(id: string): HighchartsAxisObject | HighchartsSeriesObject | HighchartsPointObject; - /** - * Exporting module required. Get an SVG string representing the chart. - * @param {HighchartsOptions} additionalOptions Chart options to add to the exported chart in addition to the options given for the original chart. For example if series.lineWidth should be greater in the exported chart than in the original, or the chart should have a different background color, this is added here. - * @return {string} - * @since 2.0 - */ - getSVG(additionalOptions?: HighchartsOptions): string; - /** - * Returns an array of all currently selected points in the chart. Points can be selected either programmatically by - * the point.select() method or by clicking. - * @return {HighchartsPointObject[]} An array of the selected points. - * @since 1.2.0 - */ - getSelectedPoints(): HighchartsPointObject[]; - /** - * Returns an array of all currently selected series in the chart. Series can be selected either programmatically by - * the series.select() method or by checking the checkbox next to the legend item if series.showCheckBox is true. - * @return {HighchartsSeriesObject[]} An array of the selected Series items. - * @since 1.2.0 - */ - getSelectedSeries(): HighchartsSeriesObject[]; - /** - * Hide the loading screen. Options for the loading screen are defined at options.loading. - * @since 1.2.0 - */ - hideLoading(): void; - /** - * The options structure for the chart. - * @since 1.2.0 - */ - options: HighchartsOptions; - /** - * Exporting module required. Clears away other elements in the page and prints the chart as it is displayed. By - * default, when the exporting module is enabled, a button at the upper left calls this method. - * @since 2.0 - */ - print(): void; - /** - * Redraw the chart after changes have been done to the data or axis extremes. All methods for updating axes, series - * or points have a parameter for redrawing the chart. This is true by default. But in many cases you want to do - * more than one operation on the chart before redrawing, for example add a number of points. In those cases it is a - * waste of resources to redraw the chart for each new point added. So you add the points and call chart.redraw() - * after. - * @param [boolean | HighchartsAnimation] animation Defaults to true. When true, the update will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. - * @since 1.2.0 - */ - redraw(animation?: boolean | HighchartsAnimation): void; - /** - * Reflows the chart to its container. By default, the chart reflows automatically to its container following a - * window.resize event, as per the chart.reflow option. However, there are no reliable events for div resize, so if - * the container is resized without a window resize event, this must be called explicitly. - */ - reflow(): void; - /** - * An array of all the chart's series. - * @type {HighchartsSeriesObject[]} - * @since 1.2.0 - */ - series: HighchartsSeriesObject[]; - /** - * Resize the chart to a given width and height. - * @param {number} width The new pixel width of the chart. - * @param {number} height The new pixel height of the chart. - * @param {boolean | HighchartsAnimation} animation Defaults to true. When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. - */ - setSize(width: number, height: number, animation?: boolean | HighchartsAnimation): void; - /** - * Set a new title or subtitle for the chart - * @param {HighchartsTitleOptions} title A configuration object for the new title as defined at #title. - * @param [HighchartsSubtitleOptions] subtitle A configuration object for the new subtitle as defined at #subtitle. - * @param [boolean] redraw Whether to redraw the chart. Defaults to true. - * @since 2.1.0 - */ - setTitle(title: HighchartsTitleOptions, subtitle?: HighchartsSubtitleOptions, redraw?: boolean): void; - /** - * Dim the chart's plot area and show a loading label text. Options for the loading screen are defined at - * options.loading. A custom text can be given as a parameter for loading. - * @since 2.0.5 - */ - showLoading(str?: string): void; - /** - * This method is deprecated as of 2.0.1. Updating the chart position after a move operation is no longer necessary. - * @since 1.2.5 - * @deprecated - */ - updatePosition(): void; - /** - * An array of the chart's x axes. If only one x axis, it is referenced by chart.xAxis[0]. - * @since 1.2.0 - */ - xAxis: HighchartsAxisObject[]; - /** - * An array of the chart's y axes. If only one y axis, it is referenced by chart.yAxis[0]. - * @since 1.2.0 - */ - yAxis: HighchartsAxisObject[]; + interface LangObject { + /** + * Exporting module menu. The tooltip title for the context menu holding print and export menu items. + * @default 'Chart context menu' + * @since 3.0 + */ + contextButtonTitle?: string; + /** + * The default decimal point used in the Highcharts.numberFormat method unless otherwise specified in the function + * arguments. + * @default '.' + * @since 1.2.2 + */ + decimalPoint?: string; + /** + * Exporting module only. The text for the JPEG download menu item. + * @default 'Download JPEG image' + * @since 2.0 + */ + downloadJPEG?: string; + /** + * Exporting module only. The text for the PDF download menu item. + * @default 'Download PDF document' + * @since 2.0 + */ + downloadPDF?: string; + /** + * Exporting module only. The text for the PNG download menu item. + * @default 'Download PNG image' + * @since 2.0 + */ + downloadPNG?: string; + /** + * Exporting module only. The text for the SVG download menu item. + * @default 'Download SVG vector image' + * @since 2.0 + */ + downloadSVG?: string; + /** + * The text for the button that appears when drilling down, linking back to the parent series. The parent series' + * name is inserted for {series.name} + * @default 'Back to {series.name}' + * @since 3.0.8 + */ + drillUpText?: string; + /** + * What to show in a date field for invalid dates. + * @default '' + * @since 4.1.8 + */ + invalidDate?: string; + /** + * The loading text that appears when the chart is set into the loading state following a call to chart.showLoading. + * @default 'Loading...' + */ + loading?: string; + /** + * An array containing the months names. Corresponds to the %B format in Highcharts.dateFormat(). + * @default ['January' , 'February' , 'March' , 'April' , 'May' , 'June' , 'July' , 'August' , 'September' , 'October' , 'November' , 'December'] + */ + months?: string[]; + /** + * The text to display when the chart contains no data. Requires the no-data module, see noData. + * @default 'No data to display' + * @since 3.0.8 + */ + noData?: string; + /** + * Metric prefixes used to shorten high numbers in axis labels. Replacing any of the positions with null causes the + * full number to be written. Setting numericSymbols to null disables shortening altogether. + * @default ['k', 'M', 'G', 'T', 'P', 'E'] + * @since 2.3.0 + */ + numericSymbols?: string[]; + /** + * Exporting module only. The text for the menu item to print the chart. + * @default 'Print chart' + * @since 3.0.1 + */ + printChart?: string; + /** + * The text for the label appearing when a chart is zoomed. + * @default 'Reset zoom' + * @since 1.2.4 + */ + resetZoom?: string; + /** + * The tooltip title for the label appearing when a chart is zoomed. + * @default 'Reset zoom level 1:1' + * @since 1.2.4 + */ + resetZoomTitle?: string; + /** + * An array containing the months names in abbreviated form. Corresponds to the %b format in + * Highcharts.dateFormat(). + * @default ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + */ + shortMonths?: string[]; + /** + * The default thousands separator used in the Highcharts.numberFormat method unless otherwise specified in the + * function arguments. Since Highcharts 4.1 it defaults to a single space character, which is compatible with ISO + * and works across Anglo-American and continental European languages. + * @default ' ' + * @since 1.2.2 + */ + thousandsSep?: string; + /** + * An array containing the weekday names. + * @default ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] + */ + weekdays?: string[]; + } - renderer: HighchartsRendererObject; -} + interface LegendNavigationOptions { + /** + * The color for the active up or down arrow in the legend page navigation. + * @default '#3E576F' + * @since 2.2.4 + */ + activeColor?: string; + /** + * How to animate the pages when navigating up or down. A value of true applies the default navigation given in the + * chart.animation option. Additional options can be given as an object containing values for easing and duration. + * @default true + * @since 2.2.4 + */ + animation?: boolean | Animation; + /** + * The pixel size of the up and down arrows in the legend paging navigation. + * @default 12 + * @since 2.2.4 + */ + arrowSize?: number; + /** + * The color of the inactive up or down arrow in the legend page navigation. + * @default '#CCC' + */ + inactiveColor?: string; + /** + * Text styles for the legend page navigation. + * @since 2.2.4 + */ + style?: CSSObject; + } -interface HighchartsChart { - /** - * This is the constructor for creating a new chart object. - * @param {HighchartsOptions} options The chart options - * @return {HighchartsChartObject} - */ - new (options: HighchartsOptions): HighchartsChartObject; - /** - * This is the constructor for creating a new chart object. - * @param {HighchartsOptions} options The chart options - * @param callback A function to execute when the chart object is finished loading and rendering. In most cases the chart is built in one thread, but in Internet Explorer version 8 or less the chart is sometimes initiated before the document is ready, and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). As a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. - * @return {HighchartsChartObject} - */ - new (options: HighchartsOptions, callback: (chart: HighchartsChartObject) => void): HighchartsChartObject; - /** - * This is the constructor for creating a new chart object. - * @param {string|HTMLElement} renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). - * @param {HighchartsOptions} options The chart options - * @return {HighchartsChartObject} - */ - new (renderTo: string | HTMLElement, options: HighchartsOptions): HighchartsChartObject; - /** - * This is the constructor for creating a new chart object. - * @param {string|HTMLElement} renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). - * @param {HighchartsOptions} options The chart options - * @param callback A function to execute when the chart object is finished loading and rendering. In most cases the chart is built in one thread, but in Internet Explorer version 8 or less the chart is sometimes initiated before the document is ready, and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). As a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. - * @return {HighchartsChartObject} - */ - new (renderTo: string | HTMLElement, options: HighchartsOptions, callback: (chart: HighchartsChartObject) => void): HighchartsChartObject; -} + interface LegendTitleOptions { + /** + * Generic CSS styles for the legend title. + * @default {'fontWeight':'bold'} + * @since 3.0 + */ + style?: CSSObject; + /** + * A text or HTML string for the title. + * @default null + * @since 3.0 + */ + text?: string; + } + + interface LegendOptions { + /** + * The horizontal alignment of the legend box within the chart area. Valid values are 'left', 'center' and 'right'. + * In the case that the legend is aligned in a corner position, the layout option will determine whether to place it + * above/below or on the side of the plot area. + * @default 'center' + * @since 2.0 + */ + align?: string; + /** + * The background color of the legend. + */ + backgroundColor?: string | Gradient; + /** + * The color of the drawn border around the legend. + * @default '#909090' + */ + borderColor?: string | Gradient; + /** + * The border corner radius of the legend. + * @default 0 + */ + borderRadius?: number; + /** + * The width of the drawn border around the legend. + * @default 0 + */ + borderWidth?: number; + /** + * Enable or disable the legend. + * @default true + */ + enabled?: boolean; + /** + * When the legend is floating, the plot area ignores it and is allowed to be placed below it. + * @default false + * @since 2.1 + */ + floating?: boolean; + /** + * In a legend with horizontal layout, the itemDistance defines the pixel distance between each item. + * @default 20 + * @since 3.0.3 + */ + itemDistance?: number; + /** + * CSS styles for each legend item when the corresponding series or point is hidden. Only a subset of CSS is + * supported, notably those options related to text. Properties are inherited from style unless overridden here. + * @default {color: '#CCC'} + */ + itemHiddenStyle?: CSSObject; + /** + * CSS styles for each legend item in hover mode. Only a subset of CSS is supported, notably those options related + * to text. Properties are inherited from style unless overridden here. + * @default {color: '#000'} + */ + itemHoverStyle?: CSSObject; + /** + * The pixel bottom margin for each legend item. + * @default 0 + * @since 2.2.0 + */ + itemMarginBottom?: number; + /** + * The pixel top margin for each legend item. + * @default 0 + * @since 2.2.0 + */ + itemMarginTop?: number; + /** + * CSS styles for each legend item. Only a subset of CSS is supported, notably those options related to text. + * @default { 'color': '#333333', 'cursor': 'pointer', 'fontSize': '12px', 'fontWeight': 'bold' } + */ + itemStyle?: CSSObject; + /** + * The width for each legend item. This is useful in a horizontal layout with many items when you want the items to + * align vertically. + * @since 2.0 + */ + itemWidth?: number; + /** + * A format string for each legend label. Available variables relates to properties on the series, or the point in + * case of pies. + * @default '{name}' + * @since 1.3 + */ + labelFormat?: string; + /** + * Callback function to format each of the series' labels. The this keyword refers to the series object, or the + * point object in case of pie charts. By default the series or point name is printed. + */ + labelFormatter?: () => string; + /** + * The layout of the legend items. Can be one of 'horizontal' or 'vertical'. + * @default 'horizontal' + */ + layout?: string; + /** + * Line height for the legend items. Deprecated as of 2.1. Instead, the line height for each item can be set using + * itemStyle.lineHeight, and the padding between items using itemMarginTop and itemMarginBottom. + * @default 16 + * @since 2.0 + * @deprecated + */ + lineHeight?: number; + /** + * If the plot area sized is calculated automatically and the legend is not floating, the legend margin is the space + * between the legend and the axis labels or plot area. + * @default 12 + * @since 2.1 + */ + margin?: number; + /** + * Maximum pixel height for the legend. When the maximum height is extended, navigation will show. + * @since 2.3.0 + */ + maxHeight?: number; + /** + * Options for the paging or navigation appearing when the legend is overflown. + */ + navigation?: LegendNavigationOptions; + /** + * The inner padding of the legend box. + * @default 8 + * @since 2.2.0 + */ + padding?: number; + /** + * Whether to reverse the order of the legend items compared to the order of the series or points as defined in the + * configuration object. + * @default false + * @since 1.2.5 + */ + reversed?: boolean; + /** + * Whether to show the symbol on the right side of the text rather than the left side. This is common in Arabic and + * Hebraic. + * @default false + * @since 2.2 + */ + rtl?: boolean; + /** + * Whether to apply a drop shadow to the legend. A backgroundColor also needs to be applied for this to take effect. + * Since 2.3 the shadow can be an object configuration containing color, offsetX, offsetY, opacity and width. + * @default false + */ + shadow?: boolean | Shadow; + /** + * CSS styles for the legend area. In the 1.x versions the position of the legend area was determined by CSS. In + * 2.x, the position is determined by properties like align, verticalAlign, x and y, but the styles are still parsed + * for backwards compatibility. + * @deprecated + */ + style?: CSSObject; + /** + * The pixel height of the symbol for series types that use a rectangle in the legend. Defaults to the font size of + * legend items. + * @since 3.0.8 + */ + symbolHeight?: number; + /** + * The pixel padding between the legend item symbol and the legend item text. + * @default 5 + */ + symbolPadding?: number; + /** + * The border radius of the symbol for series types that use a rectangle in the legend. + * @default 0 + * @since 3.0.8 + */ + symbolRadius?: number; + /** + * The pixel width of the legend item symbol. + * @default 16 + */ + symbolWidth?: number; + /** + * A title to be added on top of the legend. + * @since 3.0 + */ + title?: LegendTitleOptions; + /** + * Whether to use HTML to render the legend item texts. Prior to 4.1.7, when using HTML, legend.navigation was + * disabled. + * @default false + */ + useHTML?: boolean; + /** + * The vertical alignment of the legend box. Can be one of 'top', 'middle' or 'bottom'. Vertical position can be + * further determined by the y option. + * + * In the case that the legend is aligned in a corner position, the layout option will determine whether to place it + * above/below or on the side of the plot area. + * + * @default 'bottom' + * @since 2.0 + */ + verticalAlign?: string; + /** + * The width of the legend box. + * @since 2.0 + */ + width?: number; + /** + * The x offset of the legend relative to its horizontal alignment align within chart.spacingLeft and + * chart.spacingRight. Negative x moves it to the left, positive x moves it to the right. + * @default 0 + * @since 2.0 + */ + x?: number; + /** + * The vertical offset of the legend relative to it's vertical alignment verticalAlign within chart.spacingTop and + * chart.spacingBottom. Negative y moves it up, positive y moves it down. + * @default 0 + * @since 2.0 + */ + y?: number; + } -/** - * The Element class is a JavaScript wrapper for SVG elements used in the rendering layer of Highchart. Combined with - * the Renderer object, these elements allows freeform annotation in the charts or even in your HTML pages without - * creating a chart at all. - */ -interface HighchartsElementObject { /** - * Add the element to the renderer canvas. - * @param {HighchartsElementObject} parent The element can be added to a g (group) element. - * @return {HighchartsElementObject} - * @since 2.0 + * The loading options control the appearance of the loading screen that covers the plot area on chart operations. This + * screen only appears after an explicit call to chart.showLoading(). It is a utility for developers to communicate to + * the end user that something is going on, for example while retrieving new data via an XHR connection. The + * 'Loading...' text itself is not part of this configuration object, but part of the lang object. */ - add(parent?: HighchartsElementObject): HighchartsElementObject; + interface LoadingOptions { + /** + * The duration in milliseconds of the fade out effect. + * @default 100 + * @since 1.2.0 + */ + hideDuration?: number; + /** + * CSS styles for the loading label span. + * @default { 'fontWeight': 'bold', 'position': 'relative', 'top': '45%' } + */ + labelStyle?: CSSObject; + /** + * The duration in milliseconds of the fade in effect. + * @default 100 + * @since 1.2.0 + */ + showDuration?: number; + /** + * CSS styles for the loading screen that covers the plot area. + * @default { position: 'absolute', backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } + */ + style?: Object; + } + /** - * Apply numeric attributes to the SVG/VML element by animation. See Element.attr() for more information on setting - * attributes. - * @param {any} attributes A set of attributes to apply. - * @param {any} animation Optional animation parameters that are passed over to jQuery or other framework. Valid properties depend on the library, but options like duration, easing and complete are supported by jQuery. - * @return {HighchartsElementObject} - * @since 2.0 + * A collection of options for buttons and menus appearing in the exporting module. */ - animate(attributes: any, animation?: any): HighchartsElementObject; + interface NavigationOptions { + /** + * A collection of options for buttons appearing in the exporting module. + */ + buttonOptions?: Button; + /** + * CSS styles for the hover state of the individual items within the popup menu appearing by default when the export + * icon is clicked. The menu items are rendered in HTML. + * @default {background: '#4572A5', color: '#FFFFFF'} + * @since 2.0 + */ + menuItemHoverStyle?: Object; + /** + * CSS styles for the individual items within the popup menu appearing by default when the export icon is clicked. + * The menu items are rendered in HTML. + * @default { padding: '0 5px', background: NONE, color: '#303030'} + * @since 2.0 + */ + menuItemStyle?: Object; + /** + * CSS styles for the popup menu appearing by default when the export icon is clicked. This menu is rendered in + * HTML. + * @default { border: '1px solid #A0A0A0', background: '#FFFFFF' } + * @since 2.0 + */ + menuStyle?: Object; + } + /** - * Apply attributes to the SVG/VML elements. These attributes for the most parts correspond to SVG, but some are - * specific to Highcharts, like zIndex and rotation. + * Options for displaying a message like 'No data to display'. This feature requires the file no-data-to-display.js to + * be loaded in the page. The actual text to display is set in the lang.noData option. + */ + interface NoDataOptions { + /** + * An object of additional SVG attributes for the no-data label. + * @since 3.0.8 + */ + attr?: {}; + /** + * The position of the no-data label, relative to the plot area. + * @default { 'x': 0, 'y': 0, 'align': 'center', 'verticalAlign': 'middle' } + * @since 3.0.8 + */ + position?: Position; + /** + * CSS styles for the no-data label. + * @default { 'fontSize': '12px', 'fontWeight': 'bold', 'color': '#60606a' } + */ + style?: CSSObject; + } + + interface PaneBackground { + /** + * @default {linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [[0, '#FFF'],[1, '#DDD']]} + */ + backgroundColor: string | Gradient; + /** + * @default 'silver' + */ + borderColor?: string | Gradient; + /** + * @default 1 + */ + borderWidth?: number; + /** + * @default 0 + */ + innerRadius?: number | string; + /** + * @default '105%' + */ + outerRadius?: number | string; + /** + * @default 'circle' + */ + shape?: string; + } + + /** + * Applies only to polar charts and angular gauges. This configuration object holds general options for the combined X + * and Y axes set. Each xAxis or yAxis can reference the pane by index. + */ + interface PaneOptions { + /** + * An object, or array of objects, for backgrounds. Sub options include backgroundColor (can be solid or gradient), + * shape ('solid', 'arc' or 'circle'), innerWidth, outerWidth, borderWidth, borderColor. + * @since 2.3.0 + */ + background?: PaneBackground | PaneBackground[]; + /** + * The center of a polar chart or angular gauge, given as an array of [x, y] positions. Positions can be given as + * integers that transform to pixels, or as percentages of the plot area size. + * @default ['50%', '50%'] + * @since 2.3.0 + */ + center?: [number | string, number | string]; + /** + * The end angle of the polar X axis or gauge value axis, given in degrees where 0 is north. + * @default startAngle + 360 + * @since 2.3.0 + */ + endAngle?: number; + /** + * The size of the pane, either as a number defining pixels, or a percentage defining a percentage of the plot are. + * @default '85%' + */ + size?: number | string; + /** + * The size of the pane, either as a number defining pixels, or a percentage defining a percentage of the plot are + * @since 2.3.0 + */ + startAngle?: number; + } + + interface DataLabels { + /** + * The alignment of the data label compared to the point. If right, the right side of the label should be touching + * the point. For points with an extent, like columns, the alignments also dictates how to align it inside the box, + * as given with the inside option. Can be one of 'left', 'center' or 'right'. + * @default 'center' + */ + align?: string; + /** + * Whether to allow data labels to overlap. To make the labels less sensitive for overlapping, the + * dataLabels.padding can be set to 0. + * @default false + * @since 4.1.0 + */ + allowOverlap?: boolean; + /** + * The background color or gradient for the data label. + * @since 2.2.1 + */ + backgroundColor?: string | Gradient; + /** + * The border color for the data label. + * @since 2.2.1 + */ + borderColor?: string | Gradient; + /** + * The border radius in pixels for the data label. + * @default 0 + * @since 2.2.1 + */ + borderRadius?: number; + /** + * The border width in pixels for the data label. + * @default 0 + * @since 2.2.1 + */ + borderWidth?: number; + /** + * A class name for the data label. Particularly in styled mode, this can be used to give each series' or point's + * data label unique styling. In addition to this option, a default color class name is added so that we can give + * the labels a contrast text shadow. + * @since 5.0.0 + */ + className?: string; + /** + * The text color for the data labels. + * @default null + */ + color?: string | Gradient; + /** + * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot + * area according to the overflow option. + * @default 2.3.3 + */ + crop?: boolean; + /** + * Whether to defer displaying the data labels until the initial series animation has finished. + * @default true + * @since 4.0 + */ + defer?: boolean; + /** + * Enable or disable the data labels. + * @default false + */ + enabled?: boolean; + /** + * A format string for the data label. Available variables are the same as for formatter. + * @default {y} + * @since 3.0 + */ + format?: string; + /** + * Callback JavaScript function to format the data label. Note that if a format is defined, the format takes + * precedence and the formatter is ignored. + * Available data are: + * - this.percentage Stacked series and pies only. The point's percentage of the total. + * - this.point The point object. The point name, if defined, is available through this.point.name. + * - this.series The series object. The series name is available through this.series.name. + * - this.total Stacked series only. The total value at this point's x value. + * - this.x: The x value. + * - this.y: The y value. + */ + formatter?: () => string; + /** + * For points with an extent, like columns, whether to align the data label inside the box or to the actual value + * point. Defaults to false in most cases, true in stacked columns. + * @since 3.0 + */ + inside?: boolean; + /** + * How to handle data labels that flow outside the plot area. The default is 'justify', which aligns them inside the + * plot area. For columns and bars, this means it will be moved inside the bar. To display data labels outside the + * plot area, set crop to false and overflow to 'none'. + * @default 'justify' + * @since 3.0.6 + */ + overflow?: string; + /** + * When either the borderWidth or the backgroundColor is set, this is the padding within the box. + * @default 5 + * @since 2.2.1 + */ + padding?: number; + /** + * Whether to reserve space for the labels. This can be turned off when for example the labels are rendered inside + * the plot area instead of outside. + * @default true + * @since 4.1.10 + */ + reserveSpace?: boolean; + /** + * Text rotation in degrees. Note that due to a more complex structure, backgrounds, borders and padding will be + * lost on a rotated data label. + * @default 0 + */ + rotation?: number; + /** + * The shadow of the box. Works best with borderWidth or backgroundColor. Since 2.3 the shadow can be an object + * configuration containing color, offsetX, offsetY, opacity and width. + * @default false + */ + shadow?: boolean | Shadow; + /** + * The name of a symbol to use for the border around the label. Symbols are predefined functions on the Renderer + * object. + * @default 'square' + * @since 4.1.2 + */ + shape?: string; + /** + * Styles for the label. + * @default {'color': 'contrast', 'fontSize': '11px', 'fontWeight': 'bold', 'textShadow': '0 0 6px contrast, 0 0 3px contrast' } + * @since 4.1.0 + */ + style?: CSSObject; + /** + * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the labels. + * @default false + */ + useHTML?: boolean; + /** + * The vertical alignment of a data label. Can be one of top, middle or bottom. The default value depends on the + * data, for instance in a column chart, the label is above positive values and below negative values. + * @since 2.3.3 + */ + verticalAlign?: string; + /** + * The x position offset of the label relative to the point. + * @default 0 + */ + x?: number; + /** + * The y position offset of the label relative to the point. + * @default -6 + */ + y?: number; + /** + * The Z index of the data labels. The default Z index puts it above the series. Use a Z index of 2 to display it + * behind the series. + * @default 6 + * @since 2.3.5 + */ + zIndex?: number; + } + + interface PieDataLabels extends DataLabels { + /** + * The color of the line connecting the data label to the pie slice. The default color is the same as the point's + * color. Defaults to {point.color}. + * @since 2.1 + */ + connectorColor?: string; + /** + * The distance from the data label to the connector. + * @default 5 + * @since 2.1 + */ + connectorPadding?: number; + /** + * The width of the line connecting the data label to the pie slice. + * @default 1 + * @since 2.1 + */ + connectorWidth?: number; + /** + * The distance of the data label from the pie's edge. Negative numbers put the data label on top of the pie slices. + * Connectors are only shown for data labels outside the pie. + * @default 30 + * @since 2.1 + */ + distance?: number; + /** + * Whether to render the connector as a soft arc or a line with sharp break. + * @default true + * @since 2.1.7 + */ + softConnector?: boolean; + } + + interface AreaCheckboxEvent extends Event { + /** + * The state of the checkbox + */ + checked: boolean; + /** + * The checked item + */ + item: SeriesObject | PointObject; + } + + interface AreaClickEvent extends Event { + /** + * A pointer to the nearest point on the graph + */ + point: PointObject; + } + + interface PlotEvents { + /** + * Fires after the series has finished its initial animation, or in case animation is disabled, immediately as the + * series is displayed. + * + * The this keyword refers to the Series object. + * @since 4.0 + */ + afterAnimate?: (event: Event) => void; + /** + * Fires when the checkbox next to the series' name in the legend is clicked. One parameter, event, is passed to the + * function. The state of the checkbox is found by event.checked. The checked item is found by event.item. Return + * false to prevent the default action which is to toggle the select state of the series. + * + * The this keyword refers to the Series object. + * @since 1.2.0 + */ + checkboxClick?: (event: AreaCheckboxEvent) => boolean | void; + /** + * Fires when the series is clicked. One parameter, event, is passed to the function. This contains common event + * information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * Additionally, event.point holds a pointer to the nearest point on the graph. + * + * The this keyword refers to the Series object. + */ + click?: (event: AreaClickEvent) => void; + /** + * Fires when the series is hidden after chart generation time, either by clicking the legend item or by calling + * .hide(). + * + * The this keyword refers to the Series object. + */ + hide?: () => void; + /** + * Fires when the legend item belonging to the series is clicked. One parameter, event, is passed to the function. + * This contains common event information based on jQuery or MooTools depending on which library is used as the base + * for Highcharts. The default action is to toggle the visibility of the series. This can be prevented by returning + * false or calling event.preventDefault(). + * + * The this keyword refers to the Series object. + */ + legendItemClick?: (event: Event) => boolean | void; + /** + * Fires when the mouse leaves the graph. One parameter, event, is passed to the function. This contains common + * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. If + * the stickyTracking option is true, mouseOut doesn't happen before the mouse enters another graph or leaves the + * plot area. + * + * The this keyword refers to the Series object. + */ + mouseOut?: (event: Event) => void; + /** + * Fires when the mouse enters the graph. One parameter, event, is passed to the function. This contains common + * event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * + * The this keyword refers to the Series object. + */ + mouseOver?: (event: Event) => void; + /** + * Fires when the series is shown after chart generation time, either by clicking the legend item or by calling + * .show(). + * + * The this keyword refers to the Series object. + * @since 1.2.0 + */ + show?: () => void; + } + + interface MarkerState { + /** + * Enable or disable the point marker. If null, the markers are hidden when the data is dense, and shown for more + * widespread data points. + * @default null, true for hover and select + */ + enabled?: boolean; + /** + * The fill color of the point marker. When null, the series' or point's color is used. + */ + fillColor?: string; + /** + * The color of the point marker's outline. When null, the series' or point's color is used. + * @default '#FFFFFF', '#000000' for select state + */ + lineColor?: string | Gradient; + /** + * The width of the point marker's outline. + * @default 0 + */ + lineWidth?: number; + /** + * The radius of the point marker. + * @default 4, undefined for hover and select + */ + radius?: number; + } + + interface MarkerHoverState extends MarkerState { + /** + * The additional line width for a hovered point. + * @default 1 + * @since 4.0.3 + */ + lineWidthPlus?: number; + /** + * The number of pixels to increase the radius of the hovered point. + * @default 2 + * @since 4.0.3 + */ + radiusPlus?: number; + } + + interface Marker extends MarkerState { + /** + * Image markers only. Set the image width explicitly. When using this option, a width must also be set. + * @default null + * @since 4.0.4 + */ + height?: number; + states?: { + hover?: MarkerHoverState; + /** + * The appearance of the point marker when selected. In order to allow a point to be selected, set the + * series.allowPointSelect option to true. + */ + select?: MarkerState; + }; + /** + * A predefined shape or symbol for the marker. When null, the symbol is pulled from options.symbols. Other possible + * values are 'circle', 'square', 'diamond', 'triangle' and 'triangle-down'. + * + * Additionally, the URL to a graphic can be given on this form: 'url(graphic.png)'. Note that for the image to be + * applied to exported charts, its URL needs to be accessible by the export server. + * + * Custom callbacks for symbol path generation can also be added to Highcharts.SVGRenderer.prototype.symbols. The + * callback is then used by its method name. + */ + symbol?: string; // null, 'circle', 'square', 'diamond', 'triangle' 'triangle-down' or 'url(graphic.png)' + /** + * Image markers only. Set the image width explicitly. When using this option, a height must also be set. + * @default null. + * @since 4.0.4 + */ + width?: number; + } + + interface PointEvents { + /** + * Fires when a point is clicked. One parameter, event, is passed to the function. This contains common event + * information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * + * If the series.allowPointSelect option is true, the default action for the point's click event is to toggle the + * point's select state. Returning false cancels this action. + * + * The this keyword refers to the Point object. + */ + click?: (event: Event) => boolean; + /** + * Fires when the mouse leaves the area close to the point. One parameter, event, is passed to the function. This + * contains common event information based on jQuery or MooTools depending on which library is used as the base for + * Highcharts. + * + * The this keyword refers to the Point object. + */ + mouseOut?: (event: Event) => void; + /** + * Fires when the mouse enters the area close to the point. One parameter, event, is passed to the function. This + * contains common event information based on jQuery or MooTools depending on which library is used as the base for + * Highcharts. + * + * The this keyword refers to the Point object. + */ + mouseOver?: (event: Event) => void; + /** + * Fires when the point is removed using the .remove() method. One parameter, event, is passed to the function. + * Returning false cancels the operation. + * + * The this keyword refers to the Point object. + * @since 1.2.0 + */ + remove?: (event: Event) => boolean | void; + /** + * Fires when the point is selected either programmatically or following a click on the point. One parameter, event, + * is passed to the function. Returning false cancels the operation. + * + * The this keyword refers to the Point object. + * @since 1.2.0 + */ + select?: (event: Event) => boolean | void; + /** + * Fires when the point is unselected either programmatically or following a click on the point. One parameter, + * event, is passed to the function. Returning false cancels the operation. + * + * The this keyword refers to the Point object. + * @since 1.2.0 + */ + unselect?: (event: Event) => boolean | void; + /** + * Fires when the point is updated programmatically through the .update() method. One parameter, event, is passed to + * the function. The new point options can be accessed through event.options. Returning false cancels the operation. + * + * The this keyword refers to the Point object. + * @since 1.2.0 + */ + update?: (event: Event) => boolean | void; + /** + * Fires when the legend item belonging to the pie point (slice) is clicked. + * The this keyword refers to the point itself. One parameter, event, is passed to the function. + * This contains common event information based on jQuery or MooTools depending on which library is used as the base for Highcharts. + * The default action is to toggle the visibility of the point. This can be prevented by calling event.preventDefault(). + */ + legendItemClick?: (event: Event) => boolean | void; + + } + + interface Halo { + /** + * A collection of SVG attributes to override the appearance of the halo, for example fill, stroke and stroke-width. + * @since 4.0 + */ + attributes?: {}; + /** + * Opacity for the halo unless a specific fill is overridden using the attributes setting. Note that Highcharts is + * only able to apply opacity to colors of hex or rgb(a) formats. + * @default 0.25 + * @since 4.0 + */ + opacity?: number; + /** + * The pixel size of the halo. For point markers this is the radius of the halo. For pie slices it is the width of + * the halo outside the slice. For bubbles it defaults to 5 and is the width of the halo outside the bubble. + * Defaults to 10. + */ + size?: number; + } + + interface LineStates { + /** + * Enable separate styles for the hovered series to visualize that the user hovers either the series itself or the + * legend. + * @default true + * @since 1.2 + */ + enabled?: boolean; + /** + * Options for the halo appearing around the hovered point in line-type series as well as outside the hovered slice + * in pie charts. By default the halo is filled by the current point or series color with an opacity of 0.25. The + * halo can be disabled by setting the halo option to false. + * @since 4.0 + */ + halo?: boolean | Halo; + /** + * Pixel with of the graph line. + * @default 2 + */ + lineWidth?: number; + /** + * The additional line width for the graph of a hovered series. + * @default 1 + * @since 4.0.3 + */ + lineWidthPlus?: number; + marker?: Marker; + } + + interface BarStates { + /** + * A specific border color for the hovered point. Defaults to inherit the normal state border color. + */ + borderColor?: string | Gradient; + /** + * How much to brighten the point on interaction. Requires the main color to be defined in hex or rgb(a) format. + * @default 0.1 + */ + brightness?: number; + /** + * + */ + color?: string | Gradient; + /** + * Enable separate styles for the hovered series to visualize that the user hovers either the series itself or the + * legend. + * @default true + * @since 1.2 + */ + enabled?: boolean; + /** + * Options for the halo appearing around the hovered point in line-type series as well as outside the hovered slice + * in pie charts. By default the halo is filled by the current point or series color with an opacity of 0.25. The + * halo can be disabled by setting the halo option to false. + * @since 4.0 + */ + halo?: boolean | Halo; + } + + interface PieStates extends BarStates, LineStates { } + + interface AreaZone { + /** + * Defines the color of the series. + * @since 4.1.0 + */ + color?: string | Gradient; + /** + * A name for the dash style to use for the graph. + * @since 4.1.0 + */ + dashStyle?: string; + /** + * Defines the fill color for the series (in area type series) + * @since 4.1.0 + */ + fillColor?: string; + /** + * The value up to where the zone extends, if undefined the zones stretches to the last value in the series. + * @default undefined + * @since 4.1.0 + */ + value?: number; + } + + interface RangeDataLabels { + /** + * The alignment of the data label compared to the point. If right, the right side of the label should be touching + * the point. For points with an extent, like columns, the alignments also dictates how to align it inside the box, + * as given with the inside option. Can be one of 'left', 'center' or 'right'. + * @default 'center' + */ + align?: string; + /** + * Whether to allow data labels to overlap. To make the labels less sensitive for overlapping, the + * dataLabels.padding can be set to 0. + * @default false + * @since 4.1.0 + */ + allowOverlap?: boolean; + /** + * The background color or gradient for the data label. + * @default undefined + * @since 2.2.1 + */ + backgroundColor?: string | Gradient; + /** + * The border color for the data label. + * @default undefined + * @since 2.2.1 + */ + borderColor?: string | Gradient; + /** + * The border radius in pixels for the data label. + * @default 0 + * @since 2.2.1 + */ + borderRadius?: number; + /** + * The border width in pixels for the data label. + * @default 0 + * @since 2.2.1 + */ + borderWidth?: number; + /** + * The text color for the data labels. + * @default null + */ + color?: string | Gradient; + /** + * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot + * area according to the overflow option. + * @default true + * @since 2.3.3 + */ + crop?: boolean; + /** + * Whether to defer displaying the data labels until the initial series animation has finished. + * @default true + * @since 4.0 + */ + defer?: boolean; + /** + * Enable or disable the data labels. + * @default false + */ + enabled?: boolean; + /** + * A format string for the data label. Available variables are the same as for formatter. + * @default '{y}' + * @since 3.0 + */ + format?: string; + /** + * Callback JavaScript function to format the data label. Note that if a format is defined, the format takes + * precedence and the formatter is ignored. + * Available data are: + * - this.percentage Stacked series and pies only. The point's percentage of the total. + * - this.point The point object. The point name, if defined, is available through this.point.name. + * - this.series The series object. The series name is available through this.series.name. + * - this.total Stacked series only. The total value at this point's x value. + * - this.x: The x value. + * - this.y: The y value. + */ + formatter?: () => string; + /** + * For points with an extent, like columns, whether to align the data label inside the box or to the actual value + * point. Defaults to false in most cases, true in stacked columns. + * @since 3.0 + */ + inside?: boolean; + /** + * How to handle data labels that flow outside the plot area. The default is justify, which aligns them inside the + * plot area. For columns and bars, this means it will be moved inside the bar. To display data labels outside the + * plot area, set crop to false and overflow to 'none'. + * @default 'justify' + * @since 3.0.6 + */ + overflow?: string; + /** + * When either the borderWidth or the backgroundColor is set, this is the padding within the box. + * @default 5 + * @since 2.2.1 + */ + padding?: number; + /** + * Text rotation in degrees. Note that due to a more complex structure, backgrounds, borders and padding will be + * lost on a rotated data label. + * @default 0 + */ + rotation?: number; + /** + * The shadow of the box. Works best with borderWidth or backgroundColor. Since 2.3 the shadow can be an object + * configuration containing color, offsetX, offsetY, opacity and width. + * @default false + * @since 2.2.1 + */ + shadow?: boolean | Shadow; + /** + * The name of a symbol to use for the border around the label. Symbols are predefined functions on the Renderer + * object. + * @default 'square' + * @since 4.1.2 + */ + shape?: string; + /** + * Styles for the label. + * @default {'color': 'contrast', 'fontSize': '11px', 'fontWeight': 'bold', 'textShadow': '0 0 6px contrast, 0 0 3px contrast' } + * @since 4.1.0 + */ + style?: CSSObject; + /** + * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the labels. + * @default false + */ + useHTML?: boolean; + /** + * The vertical alignment of a data label. Can be one of 'top', 'middle' or 'bottom'. The default value depends on the + * data, for instance in a column chart, the label is above positive values and below negative values. + * @since 2.3.3 + */ + verticalAlign?: string; + /** + * X offset of the higher data labels relative to the point value. + * @default 0 + * @since 2.3.0 + */ + xHigh?: number; + /** + * X offset of the lower data labels relative to the point value. + * @default 0 + * @since 2.3.0 + */ + xLow?: number; + /** + * Y offset of the higher data labels relative to the point value. + * @default -6 + * @since 2.3.0 + */ + yHigh?: number; + /** + * Y offset of the lower data labels relative to the point value. + * @default 16 + * @since 2.3.0 + */ + yLow?: number; + /** + * The Z index of the data labels. The default Z index puts it above the series. Use a Z index of 2 to display it + * behind the series. + * @default 6 + * @since 2.3.5 + */ + zIndex?: number; + } + + interface Dial { + /** + * The background or fill color of the gauge's dial. + * @default 'black' + * @since 2.3.0 + */ + backgroundColor?: string | Gradient; + /** + * The length of the dial's base part, relative to the total radius or length of the dial. + * @default '70%'. + * @since 2.3.0 + */ + baseLength?: string; + /** + * The pixel width of the base of the gauge dial. The base is the part closest to the pivot, defined by baseLength. + * @default 3 + * @since 2.3.0 + */ + baseWidth?: number; + /** + * The border color or stroke of the gauge's dial. By default, the borderWidth is 0, so this must be set in addition + * to a custom border color. + * @default 'silver' + * @since 2.3.0 + */ + borderColor?: string | Gradient; + /** + * The width of the gauge dial border in pixels. + * @default 0 + * @since 2.3.0 + */ + borderWidth?: number; + /** + * The radius or length of the dial, in percentages relative to the radius of the gauge itself. + * @default '80%' + * @since 2.3.0 + */ + radius?: string; + /** + * The length of the dial's rear end, the part that extends out on the other side of the pivot. Relative to the + * dial's length. + * @default '10%' + * @since 2.3.0 + */ + rearLength?: string; + /** + * The width of the top of the dial, closest to the perimeter. The pivot narrows in from the base to the top. + * @default 1 + * @since 2.3.0 + */ + topWidth?: number; + } + + interface Pivot { + /** + * The background color or fill of the pivot. + * @default 'black' + * @since 2.3.0 + */ + backgroundColor?: string | Gradient; + /** + * The border or stroke color of the pivot. In able to change this, the borderWidth must also be set to something + * other than the default 0. + * @default 'silver' + * @since 2.3.0 + */ + borderColor?: string | Gradient; + /** + * The border or stroke width of the pivot. + * @default 0 + * @since 2.3.0 + */ + borderWidth?: number; + /** + * The pixel radius of the pivot. + * @default 5 + * @since 2.3.0 + */ + radius?: number; + } + + /** + * Set options on specific levels. Takes precedence over series options, but not point options. + */ + interface TreeMapLevel { + /** + * Can set borderColor on all points which lies on the same level. + * @since 4.1.0 + */ + borderColor?: string | Gradient; + /** + * et the dash style of the border of all the point which lies on the level. + * @since 4.1.0 + */ + borderDashStyle?: string; + /** + * Can set the borderWidth on all points which lies on the same level. + * @since 4.1.0 + */ + borderWidth?: number; + /** + * Can set a color on all points which lies on the same level. + * @since 4.1.0 + */ + color?: string | Gradient; + /** + * Can set the options of dataLabels on each point which lies on the level. + * @default undefined + * @since 4.1.0 + */ + dataLabels?: DataLabels; + /** + * Can set the layoutAlgorithm option on a specific level. + * @since 4.1.0 + */ + layoutAlgorithm?: string; + /** + * Can set the layoutStartingDirection option on a specific level. + * @since 4.1.0 + */ + layoutStartingDirection?: string; + /** + * Decides which level takes effect from the options set in the levels object. + * @since 4.1.0 + */ + level?: number; + } + + /** + * General options for all series types. + */ + interface SeriesChart { + /** + * Allow this series' points to be selected by clicking on the markers, bars or pie slices. + * @default false + * @since 1.2.0 + */ + allowPointSelect?: boolean; + /** + * Enable or disable the initial animation when a series is displayed. The animation can also be set as a + * configuration object. Please note that this option only applies to the initial animation of the series itself. + * For other animations, see chart.animation and the animation parameter under the API methods. + * @default true + */ + animation?: boolean | Animation; + /** + * The main color or the series. In line type series it applies to the line and the point markers unless otherwise + * specified. In bar type series it applies to the bars unless a color is specified per point. The default value is + * pulled from the options.colors array. + */ + color?: string | Gradient; + /** + * Polar charts only. Whether to connect the ends of a line series plot across the extremes. + * @default true + * @since 2.3.0 + */ + connectEnds?: boolean; + /** + * Whether to connect a graph line across null points. + * @default false + */ + connectNulls?: boolean; + /** + * When the series contains less points than the crop threshold, all points are drawn, event if the points fall + * outside the visible plot area at the current zoom. The advantage of drawing all points (including markers and + * columns), is that animation is performed on updates. On the other hand, when the series contains more points than + * the crop threshold, the series data is cropped to only contain points that fall within the plot area. The + * advantage of cropping away invisible points is to increase performance on large series. + * @default 300 + * @since 2.2 + */ + cropThreshold?: number; + /** + * You can set the cursor to 'pointer' if you have click events attached to the series, to signal to the user that + * the points and lines can be clicked. + */ + cursor?: string; + /** + * A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, + * area and scatter in case it has a lineWidth. The value for the dashStyle include: + * - Solid + * - ShortDash + * - ShortDot + * - ShortDashDot + * - ShortDashDotDot + * - Dot + * - Dash + * - LongDash + * - DashDot + * - LongDashDot + * - LongDashDotDot + * @default 'Solid' + */ + dashStyle?: string; + dataLabels?: DataLabels; + /** + * Enable or disable the mouse tracking for a specific series. This includes point tooltips and click events on + * graphs and points. For large datasets it improves performance. + * @default true + */ + enableMouseTracking?: boolean; + events?: PlotEvents; + /** + * Whether to use the Y extremes of the total chart width or only the zoomed area when zooming in on parts of the X + * axis. By default, the Y axis adjusts to the min and max of the visible data. Cartesian series only. + * @default false + * @since 4.1.6 + */ + getExtremesFromAll?: boolean; + /** + * An array specifying which option maps to which key in the data point array. This makes it convenient to work with + * unstructured data arrays from different sources. + * @since 4.1.6 + */ + keys?: string[]; + /** + * Pixel with of the graph line. + * @default 2 + */ + lineWidth?: number; + /** + * The line cap used for line ends and line joins on the graph. + * @default 'round' + */ + linecap?: string; + /** + * The id of another series to link to. Additionally, the value can be ':previous' to link to the previous series. + * When two series are linked, only the first one appears in the legend. Toggling the visibility of this also + * toggles the linked series. + * @since 3.0 + */ + linkedTo?: string; + marker?: Marker; + /** + * The color for the parts of the graph or points that are below the threshold. + * @default null. + * @since 3.0 + */ + negativeColor?: string; + point?: { + events: PointEvents; + }; + /** + * If no x values are given for the points in a series, pointInterval defines the interval of the x values. For + * example, if a series contains one value every decade starting from year 0, set pointInterval to 10. + * + * Since Highcharts 4.1, it can be combined with pointIntervalUnit to draw irregular intervals. + * @default 1 + */ + pointInterval?: number; + /** + * On datetime series, this allows for setting the pointInterval to the two irregular time units, month and year. + * Combine it with pointInterval to draw quarters, 6 months, 10 years etc. + * @since 4.1.0 + */ + pointIntervalUnit?: string; + /** + * Possible values: null, 'on', 'between'. + * + * In a column chart, when pointPlacement is 'on', the point will not create any padding of the X axis. In a polar + * column chart this means that the first column points directly north. If the pointPlacement is 'between', the + * columns will be laid out between ticks. This is useful for example for visualising an amount between two points + * in time or in a certain sector of a polar chart. + * + * Since Highcharts 3.0.2, the point placement can also be numeric, where 0 is on the axis value, -0.5 is between + * this value and the previous, and 0.5 is between this value and the next. Unlike the textual options, numeric + * point placement options won't affect axis padding. + * + * Note that pointPlacement needs a pointRange to work. For column series this is computed, but for line-type series + * it needs to be set. + * + * Defaults to null in cartesian charts, 'between' in polar charts. + * @since 2.3.0 + */ + pointPlacement?: string | number; + /** + * If no x values are given for the points in a series, pointStart defines on what value to start. For example, if a + * series contains one yearly value starting from 1945, set pointStart to 1945. + * @default 0 + */ + pointStart?: number; + /** + * Whether to select the series initially. If showCheckbox is true, the checkbox next to the series name will be + * checked for a selected series. + * @default false + * @since 1.2.0 + */ + selected?: boolean; + /** + * Whether to apply a drop shadow to the graph line. Since 2.3 the shadow can be an object configuration containing + * color, offsetX, offsetY, opacity and width. + * @default false + */ + shadow?: boolean | Shadow; + /** + * If true, a checkbox is displayed next to the legend item to allow selecting the series. The state of the checkbox + * is determined by the selected option. + * @default false + * @since 1.2.0 + */ + showCheckbox?: boolean; + /** + * Whether to display this particular series or series type in the legend. The default value is true for standalone + * series, false for linked series. Defaults to true. + */ + showInLegend?: boolean; + /** + * When this is true, the series will not cause the Y axis to cross the zero plane (or threshold option) unless the + * data actually crosses the plane. + * + * For example, if softThreshold is false, a series of 0, 1, 2, 3 will make the Y axis show negative values + * according to the minPadding option. If softThreshold is true, the Y axis starts at 0. + * @default true + * @since 4.1.9 + */ + softTreshold?: boolean; + /** + * Whether to stack the values of each series on top of each other. Possible values are null to disable, 'normal' to + * stack by value or 'percent'. + */ + stacking?: string; + /** + * A wrapper object for all the series options in specific states. + */ + states?: { + /** + * Options for the hovered series + */ + hover?: LineStates; + }; + /** + * Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered until the mouse moves + * over another series, or out of the plot area. When false, the mouseOut event on a series is triggered when the + * mouse leaves the area around the series' graph or markers. This also implies the tooltip. When stickyTracking is + * false and tooltip.shared is false, the tooltip will be hidden when moving the mouse between series. Defaults to + * true for line and area type series, but to false for columns, pies etc. + * @default true + * @since 2.0 + */ + stickyTracking?: boolean; + /** + * The Y axis value to serve as the base for the area, for distinguishing between values above and below a + * threshold. If null, the area behaves like a line series with fill between the graph and the Y axis minimum. + * @default 0 + * @since 2.0 + */ + threshold?: number; + /** + * A configuration object for the tooltip rendering of each single series. Properties are inherited from tooltip, + * but only the following properties can be defined on a series level. + * @since 2.3 + */ + tooltip?: SeriesTooltipOptions; + /** + * When a series contains a data array that is longer than this, only one dimensional arrays of numbers, or two + * dimensional arrays with x and y values are allowed. Also, only the first point is tested, and the rest are + * assumed to be the same format. This saves expensive data checking and indexing in long series. Set it to 0 + * disable. + * @default 1000 + * @since 2.2 + */ + turboThreshold?: number; + /** + * Set the initial visibility of the series. + * @default true + */ + visible?: boolean; + /** + * Defines the Axis on which the zones are applied. + * @default 'y' + * @since 4.1.0 + */ + zoneAxis?: string; + /** + * An array defining zones within a series. Zones can be applied to the X axis, Y axis or Z axis for bubbles, + * according to the zoneAxis option. + */ + zones?: AreaZone[]; + } + + interface AreaChart extends SeriesChart { + /** + * Fill color or gradient for the area. When null, the series' color is used with the series' fillOpacity. + */ + fillColor?: string | Gradient; + /** + * Fill opacity for the area. Note that when you set an explicit fillColor, the fillOpacity is not applied. Instead, + * you should define the opacity in the fillColor with an rgba color definition. + * @default 0.75 + */ + fillOpacity?: number; + /** + * A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting + * allows setting a separate color for the line without altering the fillColor. + */ + lineColor?: string | Gradient; + /** + * A separate color for the negative part of the area. + * @since 3.0 + */ + negativeFillColor?: string; + /** + * Whether to apply steps to the line. Possible values are left, center and right. Prior to 2.3.5, only left was + * supported. + * + * @default 'false' + * @since 1.2.5 + */ + step?: string; + /** + * Whether the whole area or just the line should respond to mouseover tooltips and other mouse or touch events. + * @default false + * @since 1.1.6 + */ + trackByArea?: boolean; + } + + interface AreaRangeChart extends AreaChart { + /** + * Extended data labels for range series types. Range series data labels have no x and y options. Instead, they have + * xLow, xHigh, yLow and yHigh options to allow the higher and lower data label sets individually. + * @since 2.3.0 + */ + dataLabels?: RangeDataLabels; + } + + interface AreaSplineChart extends AreaChart { + } + + interface AreaSplineRangeChart extends AreaRangeChart { + } + + interface BarChart extends SeriesChart { + /** + * The color of the border surrounding each column or bar. + * @default '#FFFFFF' + */ + borderColor?: string | Gradient; + /** + * The corner radius of the border surrounding each column or bar. + * @default 0 + */ + borderRadius?: number; + /** + * The width of the border surrounding each column or bar. + * @default 1 + */ + borderWidth?: number; + /** + * When using automatic point colors pulled from the options.colors collection, this option determines whether the + * chart should receive one color per series or one color per point. Defaults to false. + * @default false + * @since 2.0 + */ + colorByPoint?: boolean; + /** + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is + * true. + * @since 3.0 + */ + colors?: string[]; + /** + * Depth of the columns in a 3D column chart. Requires highcharts-3d.js. + * @default 25 + * @since 4.0 + */ + depth?: number; + /** + * 3D columns only. The color of the edges. Similar to borderColor, except it defaults to the same color as the + * column. + */ + edgeColor?: string; + /** + * 3D columns only. The width of the colored edges. + * @default 1 + */ + edgeWidth?: number; + /** + * Padding between each value groups, in x axis units. + * @default 0.2 + */ + groupPadding?: number; + /** + * The spacing between columns on the Z Axis in a 3D chart. Requires highcharts-3d.js. + * @default 1 + * @since 4.0 + */ + groupZPadding?: number; + /** + * Whether to group non-stacked columns or to let them render independent of each other. Non-grouped columns will be + * laid out individually and overlap each other. + * @default true + * @since 2.3.0 + */ + grouping?: boolean; + /** + * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the + * columns from becoming too wide when there is a small number of points in the chart. + * @default null + * @since 4.1.8 + */ + maxPointWidth?: number; + /** + * The minimal height for a column or width for a bar. By default, 0 values are not shown. To visualize a 0 (or + * close to zero) point, set the minimal point length to a pixel value like 3. In stacked column charts, + * minPointLength might not be respected for tightly packed values. + * @default 0 + */ + minPointLength?: number; + /** + * Padding between each column or bar, in x axis units. + * @default 0.1 + */ + pointPadding?: string | number; + /** + * The X axis range that each point is valid for. This determines the width of the column. On a categorized axis, + * the range will be 1 by default (one category unit). On linear and datetime axes, the range will be computed as + * the distance between the two closest data points. + * @since 2.3 + */ + pointRange?: number; + /** + * A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from the + * pointPadding and groupPadding. + * @since 1.2.5 + */ + pointWidth?: number; + /** + * A wrapper object for all the series options in specific states. + */ + states?: { + /** + * Options for the hovered series + */ + hover?: BarStates; + }; + } + + /** + * A box plot is a convenient way of depicting groups of data through their five-number summaries: the smallest + * observation (sample minimum), lower quartile (Q1), median (Q2), upper quartile (Q3), and largest observation (sample + * maximum). + */ + interface BoxPlotChart extends ErrorBarChart { + /** + * The fill color of the box. + * @default '#FFFFFF' + * @since 3.0 + */ + fillColor?: string; + /** + * Padding between each value groups, in x axis units. + * @default 0.2 + */ + groupPadding?: number; + /** + * Whether to group non-stacked columns or to let them render independent of each other. Non-grouped columns will be + * laid out individually and overlap each other. + * @default true + * @since 2.3.0 + */ + grouping?: boolean; + /** + * The id of another series to link to. Additionally, the value can be ':previous' to link to the previous series. + * When two series are linked, only the first one appears in the legend. Toggling the visibility of this also + * toggles the linked series. + * @since 3.0 + */ + linkedTo?: string; + /** + * The color of the median line. If null, the general series color applies. + * @default null + * @since 3.0 + */ + medianColor?: string; + /** + * The pixel width of the median line. If null, the lineWidth is used. + * @default 2 + * @since 3.0 + */ + medianWidth?: number; + } + + /** + * A bubble series is a three dimensional series type where each point renders an X, Y and Z value. Each points is drawn + * as a bubble where the position along the X and Y axes mark the X and Y values, and the size of the bubble relates to + * the Z value. + */ + interface BubbleChart extends SeriesChart { + /** + * Whether to display negative sized bubbles. The threshold is given by the zThreshold option, and negative bubbles + * can be visualized by setting negativeColor. + * @default true + * @since 3.0 + */ + displayNegative?: boolean; + /** + * Maximum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of + * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width + * and height. + * @default '20%' + * @since 3.0 + */ + maxSize?: string | number; + /** + * Minimum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of + * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width + * and height. + * @default 8 + * @since 3.0 + */ + minSize?: string | number; + /** + * When a point's Z value is below the zThreshold setting, this color is used. + * @default null + * @since 3.0 + */ + negativeColor?: string; + /** + * Whether the bubble's value should be represented by the area or the width of the bubble. The default, area, + * corresponds best to the human perception of the size of each bubble. + * @default 'area' + * @since 3.0.7 + */ + sizeBy?: string; + /** + * When this is true, the absolute value of z determines the size of the bubble. This means that with the default + * zThreshold of 0, a bubble of value -1 will have the same size as a bubble of value 1, while a bubble of value 0 + * will have a smaller size according to minSize. + * @default false + * @since 4.1.9 + */ + sizeByAbsoluteValues?: boolean; + /** + * The maximum for the Z value range. Defaults to the highest Z value in the data. + * @default null + * @since 4.0.3 + */ + zMax?: number; + /** + * The minimum for the Z value range. Defaults to the lowest Z value in the data. + * @default null + * @since 4.0.3 + */ + zMin?: number; + /** + * When displayNegative is false, bubbles with lower Z values are skipped. When displayNegative is true and a + * negativeColor is given, points with lower Z is colored. + * @default 0 + * @since 3.0 + */ + zThreshold?: number; + } + + interface ColumnChart extends BarChart { + } + + /** + * The column range is a cartesian series type with higher and lower Y values along an X axis. Requires + * highcharts-more.js. To display horizontal bars, set chart.inverted to true. + */ + interface ColumnRangeChart extends ColumnChart { + dataLabels?: RangeDataLabels; + } + + /** + * Error bars are a graphical representation of the variability of data and are used on graphs to indicate the error, or + * uncertainty in a reported measurement. + */ + interface ErrorBarChart extends SeriesChart { + /** + * When using automatic point colors pulled from the options.colors collection, this option determines whether the + * chart should receive one color per series or one color per point. + * @default false + * @since 2.0 + */ + colorByPoint?: boolean; + /** + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is + * true. + * @since 3.0 + */ + colors?: string[]; + /** + * Depth of the columns in a 3D column chart. Requires highcharts-3d.js. + * @default 25 + * @since 4.0 + */ + depth?: number; + /** + * 3D columns only. The color of the edges. Similar to borderColor, except it defaults to the same color as the + * column. + */ + edgeColor?: string; + /** + * 3D columns only. The width of the colored edges. + * @default 1 + */ + edgeWidth?: number; + /** + * The spacing between columns on the Z Axis in a 3D chart. Requires highcharts-3d.js. + * @default 1 + * @since 4.0 + */ + groupZPadding?: number; + /** + * The parent series of the error bar. The default value links it to the previous series. Otherwise, use the id of + * the parent series. + * @default ':previous' + * @since 3.0 + */ + linkedTo?: string; + /** + * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the + * columns from becoming too wide when there is a small number of points in the chart. + * @default null + * @since 4.1.8 + */ + maxPointWidth?: number; + /** + * Padding between each column or bar, in x axis units. + * @default 0.1 + */ + pointPadding?: number; + /** + * The X axis range that each point is valid for. This determines the width of the column. On a categorized axis, + * the range will be 1 by default (one category unit). On linear and datetime axes, the range will be computed as + * the distance between the two closest data points. + * @since 2.3 + */ + pointRange?: number; + /** + * A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from the + * pointPadding and groupPadding. + * @since 1.2.5 + */ + pointWidth?: number; + /** + * A wrapper object for all the series options in specific states. + */ + states?: { + /** + * Options for the hovered series + */ + hover?: BarStates; + }; + /** + * The color of the stem, the vertical line extending from the box to the whiskers. If null, the series color is + * used. + * @default null + * @since 3.0 + */ + stemColor?: string; + /** + * The dash style of the stem, the vertical line extending from the box to the whiskers. + * @default 'Solid' + * @since 3.0 + */ + stemDashStyle?: string; + /** + * The width of the stem, the vertical line extending from the box to the whiskers. If null, the width is inherited + * from the lineWidth option. + * @default null + * @since 3.0 + */ + stemWidth?: number; + /** + * The color of the whiskers, the horizontal lines marking low and high values. When null, the general series color + * is used. + * @default null + * @since 3.0 + */ + whiskerColor?: string; + /** + * The length of the whiskers, the horizontal lines marking low and high values. It can be a numerical pixel value, + * or a percentage value of the box width. Set 0 to disable whiskers. + * @default '50%' + * @since 3.0 + */ + whiskerLength?: number | string; + /** + * The line width of the whiskers, the horizontal lines marking low and high values. When null, the general + * lineWidth applies. + * @default 2 + * @since 3.0 + */ + whiskerWidth?: number; + } + + /** + * Funnel charts are a type of chart often used to visualize stages in a sales project, where the top are the initial + * stages with the most clients. It requires that the modules/funnel.js file is loaded + */ + interface FunnelChart extends SeriesChart { + /** + * The color of the border surrounding each column or bar. + * @default '#FFFFFF' + */ + borderColor?: string | Gradient; + /** + * The width of the border surrounding each column or bar. + * @default 1 + */ + borderWidth?: number; + /** + * The center of the series. By default, it is centered in the middle of the plot area, so it fills the plot area + * height. + * @default ['50%', '50%'] + * @since 3.0 + */ + center?: [string | number, string | number]; + /** + * A series specific or series type specific color set to use instead of the global colors. + * @since 3.0 + */ + colors?: string[]; + dataLabels?: PieDataLabels; + /** + * The thickness of a 3D pie. Requires highcharts-3d.js + * @default 0 + * @since 4.0 + */ + depth?: number; + /** + * The height of the funnel or pyramid. If it is a number it defines the pixel height, if it is a percentage string + * it is the percentage of the plot area height. + * @since 3.0 + */ + height?: number | string; + /** + * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels + * in side the plot area, but only to this size. + * @default 80 + * @since 3.0 + */ + minSize?: number; + /** + * The height of the neck, the lower part of the funnel. A number defines pixel width, a percentage string defines a + * percentage of the plot area height. + * @default '25%' + */ + neckHeight?: number | string; + /** + * The width of the neck, the lower part of the funnel. A number defines pixel width, a percentage string defines a + * percentage of the plot area width. + * @default '30%' + * @since 3.0 + */ + neckWidth?: number | string; + /** + * A reversed funnel has the widest area down. A reversed funnel with no neck width and neck height is a pyramid. + * @default false + * @since 3.0.10 + */ + reversed?: boolean; + /** + * If a point is sliced, moved out from the center, how many pixels should it be moved? + * @default 10 + */ + slicedOffset?: number; + /** + * A wrapper object for all the series options in specific states. + */ + states?: { + /** + * Options for the hovered series + */ + hover?: PieStates; + }; + /** + * The width of the funnel compared to the width of the plot area, or the pixel width if it is a number. + * @default '90%' + * @since 3.0 + */ + width?: number | string; + } + + /** + * General plotting options for the gauge series type. Requires highcharts-more.js + */ + interface GaugeChart extends SeriesChart { + /** + * Data labels for the gauge. For gauges, the data labels are enabled by default and shown in a bordered box below + * the point. + */ + datalabels?: DataLabels; + /** + * Options for the dial or arrow pointer of the gauge. + */ + dial?: Dial; + /** + * Allow the dial to overshoot the end of the perimeter axis by this many degrees. Say if the gauge axis goes from 0 + * to 60, a value of 100, or 1000, will show 5 degrees beyond the end of the axis. Defaults to 0. + * @default 0 + * @since 3.0.10 + */ + overshoot?: number; + /** + * Options for the pivot or the center point of the gauge. + * @since 2.3.0 + */ + pivot?: Pivot; + /** + * When this option is true, the dial will wrap around the axes. For instance, in a full-range gauge going from 0 to + * 360, a value of 400 will point to 40. When wrap is false, the dial stops at 360. + * @default true + * @since 3.0 + */ + wrap?: boolean; + } + + /** + * The heatmap series type. This series type is available both in Highcharts and Highmaps. + * The colors of each heat map point is usually determined by its value and controlled by settings on the colorAxis. + */ + interface HeatMapChart extends SeriesChart { + /** + * The color of the border surrounding each column or bar. + * @default '#FFFFFF' + */ + borderColor?: string | Gradient; + /** + * The corner radius of the border surrounding each column or bar. + * @default 0 + */ + borderRadius?: number; + /** + * The width of the border surrounding each column or bar. + * @default 1 + */ + borderWidth?: number; + /** + * When using automatic point colors pulled from the options.colors collection, this option determines whether the + * chart should receive one color per series or one color per point. Defaults to false. + * @default false + * @since 2.0 + */ + colorByPoint?: boolean; + /** + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is + * true. + * @since 3.0 + */ + colors?: string[]; + /** + * The columns size - how many X axis units each column in the heatmap should span. + * @default 1 + * @since 4.0 + */ + colsize?: number; + /** + * When the series contains less points than the crop threshold, all points are drawn, event if the points fall + * outside the visible plot area at the current zoom. The advantage of drawing all points (including markers and + * columns), is that animation is performed on updates. On the other hand, when the series contains more points than + * the crop threshold, the series data is cropped to only contain points that fall within the plot area. The + * advantage of cropping away invisible points is to increase performance on large series. + * @default 50 + */ + cropTreshold?: number; + /** + * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the + * columns from becoming too wide when there is a small number of points in the chart. + * @default null + * @since 4.1.8 + */ + maxPointWidth?: number; + /** + * The row size - how many Y axis units each heatmap row should span. + * @default 1 + * @since 4.0 + */ + rowsize?: number; + /** + * A wrapper object for all the series options in specific states. + */ + states?: { + /** + * Options for the hovered series + */ + hover?: BarStates; + } + } + + interface LineChart extends SeriesChart { + /** + * Whether to apply steps to the line. Possible values are left, center and right. Prior to 2.3.5, only left was + * supported. + * @default false + * @since 1.2.5 + */ + step?: boolean | string; + } + + /** + * A pie chart is a circular chart divided into sectors, illustrating numerical proportion. + */ + interface PieChart extends SeriesChart { + /** + * The color of the border surrounding each slice. When null, the border takes the same color as the slice fill. + * This can be used together with a borderWidth to fill drawing gaps created by antialiazing artefacts in + * borderless pies. + * @default '#FFFFFF' + */ + borderColor?: string | Gradient; + /** + * The width of the border surrounding each column or bar. + * @default 1 + */ + borderWidth?: number; + /** + * The center of the pie chart relative to the plot area. Can be percentages or pixel values. The default behaviour + * (as of 3.0) is to center the pie so that all slices and data labels are within the plot area. As a consequence, + * the pie may actually jump around in a chart with dynamic values, as the data labels move. In that case, the + * center should be explicitly set, for example to ['50%', '50%']. + * @default [null, null] + */ + center?: [string | number, string | number]; + /** + * A series specific or series type specific color set to use instead of the global colors. + * @since 3.0 + */ + colors?: string[]; + dataLabels?: PieDataLabels; + /** + * The thickness of a 3D pie. Requires highcharts-3d.js + * @default 0 + * @since 4.0 + */ + depth?: number; + /** + * The end angle of the pie in degrees where 0 is top and 90 is right. Defaults to startAngle plus 360. + * @default null + * @since 1.3.6 + */ + endAngle?: number; + /** + * Equivalent to chart.ignoreHiddenSeries, this option tells whether the series shall be redrawn as if the hidden + * point were null. + * + * The default value changed from false to true with Highcharts 3.0. + * + * @default true + * @since 2.3.0 + */ + ignoreHiddenPoint?: boolean; + /** + * The size of the inner diameter for the pie. A size greater than 0 renders a donut chart. Can be a percentage or + * pixel value. Percentages are relative to the pie size. Pixel values are given as integers. + * + * Note: in Highcharts < 4.1.2, the percentage was relative to the plot area, not the pie size. + * @default 0 + * @since 2.0 + */ + innerSize?: number | string; + /** + * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels + * in side the plot area, but only to this size. + * @default 80 + * @since 3.0 + */ + minSize?: number; + /** + * The diameter of the pie relative to the plot area. Can be a percentage or pixel value. Pixel values are given as + * integers. The default behaviour (as of 3.0) is to scale to the plot area and give room for data labels within the + * plot area. As a consequence, the size of the pie may vary when points are updated and data labels more around. In + * that case it is best to set a fixed value, for example '75%'. + */ + size?: number | string; + /** + * If a point is sliced, moved out from the center, how many pixels should it be moved? + * @default 10 + */ + slicedOffset?: number; + /** + * The start angle of the pie slices in degrees where 0 is top and 90 right. + * @default 0 + * @since 2.3.4 + */ + startAngle?: number; + /** + * A wrapper object for all the series options in specific states. + */ + states?: { + /** + * Options for the hovered series + */ + hover?: PieStates; + }; + } + + /** + * A polygon series can be used to draw any freeform shape in the cartesian coordinate system. A fill is applied with + * the color option, and stroke is applied through lineWidth and lineColor options. Requires the highcharts-more.js + * file. + */ + interface PolygonChart extends SeriesChart { + /** + * The width of the line connecting the data points. + * @default 0 + */ + lineWidth?: number; + } + + interface PyramidChart extends SeriesChart { + /** + * The color of the border surrounding each slice + * @default '#FFFFFF' + */ + borderColor?: string | Gradient; + /** + * The width of the border surrounding each slice + * @default 1 + */ + borderWidth?: number; + /** + * The center of the series. By default, it is centered in the middle of the plot area, so it fills the plot area + * height. + * @default ['50%', '50%'] + * @since 3.0 + */ + center?: [string | number, string | number]; + /** + * A series specific or series type specific color set to use instead of the global colors. + * @since 3.0 + */ + colors?: string[]; + dataLabels?: PieDataLabels; + /** + * The thickness of a 3D pie. Requires highcharts-3d.js + * @default 0 + * @since 4.0 + */ + depth?: number; + /** + * The height of the funnel or pyramid. If it is a number it defines the pixel height, if it is a percentage string + * it is the percentage of the plot area height. + * @since 3.0 + */ + height?: number | string; + /** + * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels + * in side the plot area, but only to this size. + * @default 80 + * @since 3.0 + */ + minSize?: number; + /** + * The pyramid is reversed by default, as opposed to the funnel, which shares the layout engine, and is not + * reversed. + * @default true + * @since 3.0.10 + */ + reversed?: boolean; + /** + * If a point is sliced, moved out from the center, how many pixels should it be moved? + * @default 10 + */ + slicedOffset?: number; + /** + * A wrapper object for all the series options in specific states. + */ + states?: { + /** + * Options for the hovered series + */ + hover?: PieStates; + }; + /** + * The width of the pyramid compared to the width of the plot area, or the pixel width if it is a number. + * @default '90%' + * @since 3.0 + */ + width?: number | string; + } + + interface ScatterChart extends SeriesChart { } + + /** + * A gauge showing values using a filled arc with colors indicating the value. The solid gauge plots values against the + * yAxis, which is extended with some color options, minColor, maxColor and stops, to control the color of the gauge + * itself. + */ + interface SolidGaugeChart extends SeriesChart { + /** + * Allow the dial to overshoot the end of the perimeter axis by this many degrees. Say if the gauge axis goes from 0 + * to 60, a value of 100, or 1000, will show 5 degrees beyond the end of the axis. + * @default 0 + * @since 3.0.10 + */ + overshoot?: number; + /** + * When this option is true, the dial will wrap around the axes. For instance, in a full-range gauge going from 0 to + * 360, a value of 400 will point to 40. When wrap is false, the dial stops at 360. + * @default true + * @since 3.0 + */ + wrap?: boolean; + } + + interface SplineChart extends SeriesChart { } + + /** + * The size of the point shape is determined by its value relative to its siblings values. Requires the module + * heatmap.js as well, if functionality such as the colorAxis is to be used. + */ + interface TreeMapChart extends SeriesChart { + /** + * When enabled the user can click on a point which is a parent and zoom in on its children. + * @default false + * @since 4.1.0 + */ + allowDrillToNode?: boolean; + /** + * Enabling this option will make the treemap alternate the drawing direction between vertical and horizontal. The + * next levels starting direction will always be the opposite of the previous. + * @default false + * @since 4.1.0 + */ + alternateStartingDirection?: boolean; + /** + * The color of the border surrounding each tree map item. + * @default '#E0E0E0' + */ + borderColor?: string | Gradient; + /** + * The width of the border surrounding each column or bar. + * @default 1 + */ + borderWidth?: number; + /** + * When using automatic point colors pulled from the options.colors collection, this option determines whether the + * chart should receive one color per series or one color per point. + * @default false + * @since 2.0 + */ + colorByPoint?: boolean; + /** + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is + * true. + * @since 3.0 + */ + colors?: string[]; + /** + * This option decides if the user can interact with the parent nodes or just the leaf nodes. When this option is + * undefined, it will be true by default. However when allowDrillToNode is true, then it will be false by default. + * @since 4.1.2 + */ + interactByLeaf?: boolean; + /** + * This option decides which algorithm is used for setting position and dimensions of the points. Can be one of + * 'sliceAndDice', 'stripes', 'squarified' or 'strip'. + * @default 'sliceAndDice' + * @since 4.1.0 + */ + layoutAlgorithm?: string; + /** + * Defines which direction the layout algorithm will start drawing. Possible values are 'vertical' and 'horizontal'. + * @default 'vertical' + * @since 4.1.0 + */ + layoutStartingDirection?: string; + /** + * Used together with the levels and allowDrillToNode options. When set to false the first level visible when + * drilling is considered to be level one. Otherwise the level will be the same as the tree structure. + * @default true + * @since 4.1.0 + */ + levelIsConstant?: boolean; + /** + * Set options on specific levels. Takes precedence over series options, but not point options. + */ + levels?: TreeMapLevel[]; + /** + * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the + * columns from becoming too wide when there is a small number of points in the chart. + * @default null + * @since 4.1.8 + */ + maxPointWidth?: number; + /** + * The sort index of the point inside the treemap level. + * @since 4.1.10 + */ + sortIndex?: number; + /** + * A wrapper object for all the series options in specific states. + */ + states?: { + /** + * Options for the hovered series + */ + hover?: BarStates; + } + } + + interface WaterFallChart extends BarChart { + /** + * A name for the dash style to use for the graph. Applies only to series type having a graph, like line, spline, + * area and scatter in case it has a lineWidth. The value for the dashStyle include: + * - Solid + * - ShortDash + * - ShortDot + * - ShortDashDot + * - ShortDashDotDot + * - Dot + * - Dash + * - LongDash + * - DashDot + * - LongDashDot + * - LongDashDotDot + * @default 'Dot' + */ + dashStyle?: string; + /** + * The color of the line that connects columns in a waterfall series. + * @default '#333333' + * @since 3.0 + */ + lineColor?: string | Gradient; + /** + * The color used specifically for positive point columns. When not specified, the general series color is used. + */ + upColor?: string; + } + + /** + * The plotOptions is a wrapper object for config objects for each series type. The config objects for each series can + * also be overridden for each series item as given in the series array. * - * In order to set the rotation center for rotation, set x and y to 0 and use translateX and translateY attributes - * to position the element instead. + * Configuration options for the series are given in three levels. Options for all series in a chart are given in the + * plotOptions.series object. Then options for all series of a specific type are given in the plotOptions of that type, + * for example plotOptions.line. Next, options for one single series are given in the series array. + */ + interface PlotOptions { + area?: AreaChart; + arearange?: AreaRangeChart; + areaspline?: AreaSplineChart; + areasplinerange?: AreaSplineRangeChart; + bar?: BarChart; + boxplot?: BoxPlotChart; + bubble?: BubbleChart; + column?: ColumnChart; + columnrange?: ColumnRangeChart; + errorbar?: ErrorBarChart; + funnel?: FunnelChart; + gauge?: GaugeChart; + heatmap?: HeatMapChart; + line?: LineChart; + pie?: PieChart; + polygon?: PolygonChart; + pyramid?: PyramidChart; + scatter?: ScatterChart; + series?: SeriesChart; + solidgauge?: SolidGaugeChart; + spline?: SplineChart; + treemap?: TreeMapChart; + waterfall?: WaterFallChart; + } + + /* You will rarely, if ever, want to use this interface directly. Instead it is much more useful to use one of the derived + * interfaces (AreaChartSeriesOptions, LineChartSeriesOptions, etc.) + */ + interface IndividualSeriesOptions { + type?: string; + /** + * The main color or the series. In line type series it applies to the line and the point markers unless otherwise + * specified. In bar type series it applies to the bars unless a color is specified per point. The default + * value is pulled from the options.colors array. + */ + color?: string | Gradient; + /** + * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user + * that the points and lines can be clicked. + */ + cursor?: string; + /** + * An array of data points for the series. For the area series type, points can be given in the following ways: + * + * 1. An array of numerical values. In this case, the numerical values will be interpreted as y options. The x + * values will be automatically calculated, either starting at 0 and incremented by 1, or from pointStart and + * pointInterval given in the series options. If the axis has categories, these will be used. Example: + * data: [0, 5, 3, 5] + * + * 2. An array of arrays with 2 values. In this case, the values correspond to x,y. If the first value is a string, + * it is applied as the name of the point, and the x value is inferred. + * data: [ + * [0, 9], + * [1, 7], + * [2, 6] + * ] + * + * 3. An array of objects with named values. The objects are point configuration objects as seen below. If the total + * number of data points exceeds the series' turboThreshold, this option is not available. + * data: [{ + * x: 1, + * y: 9, + * name: 'Point2', + * color: '#00FF00' + * }, { + * x: 1, + * y: 6, + * name: 'Point1', + * color: '#FF00FF' + * }] + */ + data?: number[] | [number, number][] | [string, number][] | DataPoint[]; + /** + * An id for the series. This can be used after render time to get a pointer to the series object through + * chart.get(). + */ + id?: string; + /** + * The index of the series in the chart, affecting the internal index in the chart.series array, the visible Z index + * as well as the order in the legend. + * @since 2.3.0 + */ + index?: number; + /** + * The sequential index of the series in the legend. + */ + legendIndex?: number; + /** + * The name of the series as shown in the legend, tooltip etc. + */ + name?: string; + /** + * A pixel value specifying a fixed width for each column or bar. When null, the width is calculated from + * the pointPadding and groupPadding. + */ + pointWidth?: number; + /** + * This option allows grouping series in a stacked chart. The stack option can be a string or a number or anything + * else, as long as the grouped series' stack options match each other. + * @since 2.1 + */ + stack?: any; + /** + * When using dual or multiple x axes, this number defines which xAxis the particular series is connected to. It + * refers to either the axis id or the index of the axis in the xAxis array, with 0 being the first. + * @default 0 + */ + xAxis?: string | number; + /** + * When using dual or multiple x axes, this number defines which xAxis the particular series is connected to. It + * refers to either the axis id or the index of the axis in the xAxis array, with 0 being the first. + * @default 0 + */ + yAxis?: string | number; + /** + * Define the visual z index of the series. + */ + zIndex?: number; + } + + interface SeriesOptions extends IndividualSeriesOptions, SeriesChart { } + + interface AreaChartSeriesOptions extends IndividualSeriesOptions, AreaChart { } + interface AreaRangeChartSeriesOptions extends IndividualSeriesOptions, AreaRangeChart { } + interface AreaSplineChartSeriesOptions extends IndividualSeriesOptions, AreaSplineChart { } + interface AreaSplineRangeChartSeriesOptions extends IndividualSeriesOptions, AreaSplineRangeChart { } + interface BarChartSeriesOptions extends IndividualSeriesOptions, BarChart { } + interface BoxPlotChartSeriesOptions extends IndividualSeriesOptions, BoxPlotChart { } + interface BubbleChartSeriesOptions extends IndividualSeriesOptions, BubbleChart { } + interface ColumnChartSeriesOptions extends IndividualSeriesOptions, ColumnChart { } + interface ColumnRangeChartSeriesOptions extends IndividualSeriesOptions, ColumnRangeChart { } + interface ErrorBarChartSeriesOptions extends IndividualSeriesOptions, ErrorBarChart { } + interface FunnelChartSeriesOptions extends IndividualSeriesOptions, FunnelChart { } + interface GaugeChartSeriesOptions extends IndividualSeriesOptions, GaugeChart { } + interface HeatMapSeriesOptions extends IndividualSeriesOptions, HeatMapChart { } + interface LineChartSeriesOptions extends IndividualSeriesOptions, LineChart { } + interface PieChartSeriesOptions extends IndividualSeriesOptions, PieChart { } + interface PolygonChartSeriesOptions extends IndividualSeriesOptions, PolygonChart { } + interface PyramidChartSeriesOptions extends IndividualSeriesOptions, PyramidChart { } + interface ScatterChartSeriesOptions extends IndividualSeriesOptions, ScatterChart { } + interface SolidGaugeChartSeriesOptions extends IndividualSeriesOptions, SolidGaugeChart { } + interface SplineChartSeriesOptions extends IndividualSeriesOptions, SplineChart { } + interface TreeMapChartSeriesOptions extends IndividualSeriesOptions, TreeMapChart { } + interface WaterFallChartSeriesOptions extends IndividualSeriesOptions, WaterFallChart { } + + interface DataPoint { + /** + * Individual color for the point. By default the color is pulled from the global colors array. + * @default undefined + */ + color?: string | Gradient; + /** + * Serves a purpose only if a colorAxis object is defined in the chart options. This value will decide which color + * the point gets from the scale of the colorAxis. + * @default undefined + */ + colorValue?: number; + /** + * Individual data label for each point. The options are the same as the ones for plotOptions.series.dataLabels + */ + dataLabels?: DataLabels; + /** + * The id of a series in the drilldown.series array to use for a drilldown for this point. + * @since 3.0.8 + */ + drilldown?: string; + /** + * Individual point events + */ + events?: PointEvents; + /** + * The high or maximum value for each data point. + */ + high?: number; + /** + * An id for the point. This can be used after render time to get a pointer to the point object through chart.get(). + * @since 1.2.0 + */ + id?: string; + /** + * The inner radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. + * @since 4.1.6 + */ + innerRadius?: number | string; + /** + * When this property is true, the points acts as a summary column for the values added or substracted since the + * last intermediate sum, or since the start of the series. The y value is ignored. + * @default false + */ + isIntermediateSum?: boolean; + /** + * When this property is true, the point display the total sum across the entire series. The y value is ignored. + * @default false + */ + isSum?: boolean; + /** + * The sequential index of the data point in the legend. + */ + legendIndex?: number; + /** + * The low or minimum value for each data point. + */ + low?: number; + marker?: Marker; + /** + * The median for each data point. This is drawn as a line through the middle area of the box. + */ + median?: number; + /** + * The name of the point as shown in the legend, tooltip, dataLabel etc. + * + * If the xAxis.type is set to category, and no categories option exists, the category will be pulled from the + * point.name of the last series defined. For multiple series, best practice however is to define xAxis.categories. + */ + name?: string; + /** + * Only for treemap. Use this option to build a tree structure. The value should be the id of the point which is the + * parent. If no points has a matching id, or this option is undefined, then the parent will be set to the root. + * @default undefined + * @since 4.1.0 + */ + parent?: string; + /** + * The lower quartile for each data point. This is the bottom of the box. + */ + q1?: number; + /** + * The higher quartile for each data point. This is the top of the box. + */ + q3?: number; + /** + * The outer radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. + * @since 4.1.6 + */ + radius?: number | string; + /** + * Whether the data point is selected initially. + * @default false + */ + selected?: boolean; + /** + * Whether to display a slice offset from the center. + * @default false + */ + sliced?: boolean; + /** + * The value of the point, resulting in a relative area of the point in the treemap. + */ + value?: number; + /** + * The x value of the point. For datetime axes, the X value is the timestamp in milliseconds since 1970. + */ + x?: number; + /** + * The y value of the point. + */ + y?: number; + /** + * The size value for each bubble. The bubbles' diameters are computed based on the z, and controlled by series + * options like minSize, maxSize, sizeBy, zMin and zMax. + */ + z?: number; + } + + /** + * The chart's subtitle + */ + interface SubtitleOptions { + /** + * The horizontal alignment of the subtitle. Can be one of 'left', 'center' and 'right'. + * @default 'center' + * @since 2.0 + */ + align?: string; + /** + * When the subtitle is floating, the plot area will not move to make space for it. + * @default false + * @since 2.1 + */ + floating?: boolean; + /** + * CSS styles for the title. Exact positioning of the title can be achieved by changing the margin property, or by + * adding position: 'absolute' and left and top properties. + * @default { 'color': '#555555' } + */ + style?: Object; + /** + * The subtitle of the chart. + */ + text?: string; + /** + * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the text. + * @default false + */ + useHTML?: boolean; + /** + * The vertical alignment of the title. Can be one of 'top', 'middle' and 'bottom'. When a value is given, the title + * behaves as floating. + * @since 2.1 + */ + verticalAlign?: string; + /** + * The x position of the subtitle relative to the alignment within chart.spacingLeft and chart.spacingRight. + * @default 0 + * @since 2.0 + */ + x?: number; + /** + * The y position of the subtitle relative to the alignment within chart.spacingTop and chart.spacingBottom. By + * default the subtitle is laid out below the title unless the title is floating. + * @default null + * @since 2.0 + */ + y?: number; + } + + interface TitleOptions { + /** + * The horizontal alignment of the title. Can be one of 'left', 'center' and 'right'. + * @default 'center' + * @since 2.0 + */ + align?: string; + /** + * When the title is floating, the plot area will not move to make space for it. + * @default false + * @since 2.1 + */ + floating?: boolean; + /** + * The margin between the title and the plot area, or if a subtitle is present, the margin between the subtitle and + * the plot area. + * @default 15 + * @since 2.1 + */ + margin?: number; + /** + * CSS styles for the title. Exact positioning of the title can be achieved by changing the margin property, or by + * adding position: 'absolute' and left and top properties. + * @default { 'color': '#333333', 'fontSize': '18px' } + */ + style?: Object; + /** + * The title of the chart. To disable the title, set the text to null. + * @default 'Chart title' + */ + text?: string; + /** + * Whether to {@link http://www.highcharts.com/docs/chart-concepts/labels-and-string-formatting#html|use HTML} to render the text. + * @default false + */ + useHTML?: boolean; + /** + * The vertical alignment of the title. Can be one of 'top', 'middle' and 'bottom'. When a value is given, the title + * behaves as floating. + * @since 2.1 + */ + verticalAlign?: string; + /** + * The x position of the title relative to the alignment within chart.spacingLeft and chart.spacingRight. + * @default 0 + * @since 2.0 + */ + x?: number; + /** + * The y position of the title relative to the alignment within chart.spacingTop and chart.spacingBottom. By default + * it depends on the font size. + * @default null + * @since 2.0 + */ + y?: number; + } + + interface CrosshairObject { + color?: string | Gradient; + width?: number; + dashStyle?: string; //Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot + zIndex?: number; + } + + interface PlotPoint { + plotX: number; + plotY: number; + } + + interface TooltipOptions extends SeriesTooltipOptions { + /** + * Enable or disable animation of the tooltip. In slow legacy IE browsers the animation is disabled by default. + * @default true + * @since 2.3.0 + */ + animation?: boolean; + /** + * The background color or gradient for the tooltip. + * @default 'rgba(255, 255, 255, 0.85)' + */ + backgroundColor?: string | Gradient; + /** + * The color of the tooltip border. When null, the border takes the color of the corresponding series or point. + * @default null + */ + borderColor?: string | Gradient; + /** + * The radius of the rounded border corners. + * @default 3 + */ + borderRadius?: number; + /** + * The pixel width of the tooltip border. + * @default 1 + */ + borderWidth?: number; + /** + * Display crosshairs to connect the points with their corresponding axis values. The crosshairs can be defined as a + * boolean, an array of booleans or an object. + * + * Boolean + * If the crosshairs option is true, a single crosshair relating to the x axis will be shown. + * + * Array of booleans + * In an array of booleans, the first value turns on the x axis crosshair and the second value to the y axis + * crosshair. Use [true, true] to show complete crosshairs. + * + * Array of objects + * In an array of objects, the first value applies to the x axis crosshair and the second value to the y axis + * crosshair. For each dimension, a width, color, dashStyle and zIndex can be given. + * + * @default null + */ + crosshairs?: boolean | [boolean, boolean] | CrosshairObject | [CrosshairObject, CrosshairObject]; + /** + * Enable or disable the tooltip. + * @default true + */ + enabled?: boolean; + /** + * Callback function to format the text of the tooltip. Return false to disable tooltip for a specific point on + * series. + * + * A subset of HTML is supported. The HTML of the tooltip is parsed and converted to SVG, therefore this isn't a + * complete HTML renderer. The following tabs are supported: , , , ,
, . Spans can be + * styled with a style attribute, but only text-related CSS that is shared with SVG is handled. + * + * Since version 2.1 the tooltip can be shared between multiple series through the shared option. The available data + * in the formatter differ a bit depending on whether the tooltip is shared or not. In a shared tooltip, all + * properties except x, which is common for all points, are kept in an array, this.points. + * + * Available data are: + * this.percentage (not shared) / this.points[i].percentage (shared) + * Stacked series and pies only. The point's percentage of the total. + * this.point (not shared) / this.points[i].point (shared) + * The point object. The point name, if defined, is available through this.point.name. + * this.points + * In a shared tooltip, this is an array containing all other properties for each point. + * this.series (not shared) / this.points[i].series (shared) + * The series object. The series name is available through this.series.name. + * this.total (not shared) / this.points[i].total (shared) + * Stacked series only. The total value at this point's x value. + * this.x + * The x value. This property is the same regardless of the tooltip being shared or not. + * this.y (not shared) / this.points[i].y (shared) + * The y value. + */ + formatter?: () => boolean | string; + /** + * A callback function to place the tooltip in a default position. The callback receives three parameters: + * labelWidth, labelHeight and point, where point contains values for plotX and plotY telling where the reference + * point is in the plot area. Add chart.plotLeft and chart.plotTop to get the full coordinates. + * + * The return should be an object containing x and y values, for example { x: 100, y: 100 }. + * @since 2.2.4 + */ + positioner?: (labelWidth: number, labelHeight: number, point: PlotPoint) => { x: number; y: number; }; + /** + * Whether to apply a drop shadow to the tooltip. + * @default true + */ + shadow?: boolean; + /** + * The name of a symbol to use for the border around the tooltip. In Highcharts 3.x and less, the shape was square. + * @default 'callout' + * @since 4.0 + */ + shape?: string; + /** + * When the tooltip is shared, the entire plot area will capture mouse movement or touch events. Tooltip texts for + * series types with ordered data (not pie, scatter, flags etc) will be shown in a single bubble. This is + * recommended for single series charts and for tablet/mobile optimized charts. + * @default false + * @since 2.1 + */ + shared?: boolean; + /** + * Proximity snap for graphs or single points. Does not apply to bars, columns and pie slices. It defaults to 10 for + * mouse-powered devices and 25 for touch devices. Note that since Highcharts 4.1 the whole plot area by default + * captures pointer events in order to show the tooltip, so for tooltip.snap to make sense, stickyTracking must be + * false. + * @since 1.2.0 + */ + snap?: number; + /** + * CSS styles for the tooltip. The tooltip can also be styled through the CSS class .highcharts-tooltip + * @default { color: '#333333', fontSize: '12px', padding: '8px' } + */ + style?: Object; + /** + * Use HTML to render the contents of the tooltip instead of SVG. Using HTML allows advanced formatting like tables + * and images in the tooltip. It is also recommended for rtl languages as it works around rtl bugs in early Firefox. + * @default false + * @since 2.2 + */ + useHTML?: boolean; + } + + interface SeriesTooltipOptions { + /** + * For series on a datetime axes, the date format in the tooltip's header will by default be guessed based on the + * closest data points. This member gives the default string representations used for each unit. + */ + dateTimeLabelFormats?: DateTimeFormats; + /** + * Whether the tooltip should follow the mouse as it moves across columns, pie slices and other point types with an + * extent. By default it behaves this way for scatter, bubble and pie series by override in the plotOptions for + * those series types. + * + * For touch moves to behave the same way, followTouchMove must be true also. + * @default false + * @since 3.0 + */ + followPointer?: boolean; + /** + * Whether the tooltip should follow the finger as it moves on a touch device. If chart.zoomType is set, it will + * override followTouchMove. + * @default true + * @since 3.0.1 + */ + followTouchMove?: boolean; + /** + * A string to append to the tooltip format. + * @default 'false' + * @since 2.2 + */ + footerFormat?: string; + /** + * The HTML of the tooltip header line. Variables are enclosed by curly brackets. Available variables are point.key, + * series.name, series.color and other members from the point and series objects. The point.key variable contains + * the category name, x value or datetime string depending on the type of axis. For datetime axes, the point.key + * date format can be set using tooltip.xDateFormat. + * + * @default '{point.key}
' + */ + headerFormat?: string; + /** + * The number of milliseconds to wait until the tooltip is hidden when mouse out from a point or chart. + * @default 500 + * @since 3.0 + */ + hideDelay?: number; + /** + * The HTML of the point's line in the tooltip. Variables are enclosed by curly brackets. Available variables are + * point.x, point.y, series.name and series.color and other properties on the same form. Furthermore, point.y can be + * extended by the tooltip.valuePrefix and tooltip.valueSuffix variables. This can also be overridden for each + * series, which makes it a good hook for displaying units. + * + * @default '\u25CF {series.name}: {point.y}
' + * @since 2.2 + */ + pointFormat?: string; + /** + * A callback function for formatting the HTML output for a single point in the tooltip. Like the pointFormat + * string, but with more flexibility. + * + * The this keyword refers to the Point object. + * @since 4.1.0 + */ + pointFormatter?: () => string; + /** + * How many decimals to show in each series' y value. This is overridable in each series' tooltip options object. + * The default is to preserve all decimals. + * @since 2.2 + */ + valueDecimals?: number; + /** + * A string to prepend to each series' y value. Overridable in each series' tooltip options object. + * @since 2.2 + */ + valuePrefix?: string; + /** + * A string to append to each series' y value. Overridable in each series' tooltip options object. + * @since 2.2 + */ + valueSuffix?: string; + /** + * The format for the date in the tooltip header if the X axis is a datetime axis. The default is a best guess based + * on the smallest distance between points in the chart. + */ + xDateFormat?: string; + } + + interface Options { + /** + * Options regarding the chart area and plot area as well as general chart options. + */ + chart?: ChartOptions; + colorAxis?: ColorAxisOptions | ColorAxisOptions[]; + /** + * An array containing the default colors for the chart's series. When all colors are used, new colors are pulled + * from the start again. + * + * Default colors can also be set on a series or series.type basis, see column.colors, pie.colors. + * + * @default ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'] + */ + colors?: string[]; + /** + * Highchart by default puts a credits label in the lower right corner of the chart. This can be changed using these options. + */ + credits?: CreditsOptions; + /** + * The Data module provides a simplified interface for adding data to a chart from sources like CVS, HTML tables or + * grid views. See also the tutorial article on the Data module. + * + * It requires the modules/data.js file to be loaded. + * + * Please note that the default way of adding data in Highcharts, without the need of a module, is through the + * series.data option. + */ + data?: DataOptions; + /** + * Options for drill down, the concept of inspecting increasingly high resolution data through clicking on chart + * items like columns or pie slices. + * + * The drilldown feature requires the drilldown.js file to be loaded, found in the modules directory of the download + * package, or online at code.highcharts.com/modules/drilldown.js. + */ + drilldown?: DrilldownOptions; + /** + * Options for the exporting module. + */ + exporting?: ExportingOptions; + /** + * HTML labels that can be positioned anywhere in the chart area. + */ + labels?: LabelsOptions; + lang?: LangObject; + /** + * The legend is a box containing a symbol and name for each series item or point item in the chart. + */ + legend?: LegendOptions; + /** + * The loading options control the appearance of the loading screen that covers the plot area on chart operations. + * This screen only appears after an explicit call to chart.showLoading(). It is a utility for developers to + * communicate to the end user that something is going on, for example while retrieving new data via an XHR + * connection. The 'Loading...' text itself is not part of this configuration object, but part of the lang object. + */ + loading?: LoadingOptions; + /** + * A collection of options for buttons and menus appearing in the exporting module. + */ + navigation?: NavigationOptions; + /** + * Options for displaying a message like 'No data to display'. This feature requires the file no-data-to-display.js + * to be loaded in the page. The actual text to display is set in the lang.noData option. + */ + noData?: NoDataOptions; + /** + * Applies only to polar charts and angular gauges. This configuration object holds general options for the combined + * X and Y axes set. Each xAxis or yAxis can reference the pane by index. + */ + pane?: PaneOptions; + /** + * The plotOptions is a wrapper object for config objects for each series type. The config objects for each series + * can also be overridden for each series item as given in the series array. + * + * Configuration options for the series are given in three levels. Options for all series in a chart are given in + * the plotOptions.series object. Then options for all series of a specific type are given in the plotOptions of + * that type, for example plotOptions.line. Next, options for one single series are given in the series array. + */ + plotOptions?: PlotOptions; + /** + * The actual series to append to the chart. In addition to the members listed below, any member of the plotOptions + * for that specific type of plot can be added to a series individually. For example, even though a general + * lineWidth is specified in plotOptions.series, an individual lineWidth can be specified for each series. + */ + series?: IndividualSeriesOptions[]; + /** + * The chart's subtitle + */ + subtitle?: SubtitleOptions; + /** + * The chart's main title. + */ + title?: TitleOptions; + /** + * Options for the tooltip that appears when the user hovers over a series or point. + */ + tooltip?: TooltipOptions; + /** + * The X axis or category axis. Normally this is the horizontal axis, though if the chart is inverted this is the + * vertical axis. In case of multiple axes, the xAxis node is an array of configuration objects. + */ + xAxis?: AxisOptions[] | AxisOptions; + /** + * The Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the + * horizontal axis. In case of multiple axes, the yAxis node is an array of configuration objects. + */ + yAxis?: AxisOptions[] | AxisOptions; + } + + interface GlobalOptions extends Options { + /** + * Global options that don't apply to each chart. These options, like the lang options, must be set using the + * Highcharts.setOptions method. + */ + global?: GlobalObject; + /** + * Language object. The language object is global and it can't be set on each chart initiation. Instead, use + * Highcharts.setOptions to set it before any chart is initiated. + */ + lang?: LangObject; + } + + interface DateFormatSpecifiers { + [index: string]: (timestamp: number) => string; + } + + /** + * A chart can have from 0 axes (pie chart) to multiples. In a normal, single series cartesian chart, there is one X + * axis and one Y axis. * - * Attributes frequently used in Highcharts are fill, stroke, stroke-width. - * @param {any} hash A set of attributes to apply. - * @return {HighchartsElementObject} - * @since 2.0 + * The X axis or axes are referenced by chart.xAxis, which is an array of Axis objects. If there is only one axis, it + * can be referenced through chart.xAxis[0], and multiple axes have increasing indices. The same pattern goes for Y + * axes. + * + * If you need to get the axes from a series object, use the series.xAxis andseries.yAxis properties. These are not + * arrays, as one series can only be associated to one X and one Y axis. + * + * A third way to reference the axis programmatically is by id. Add an id in the axis configuration options, and get the + * axis by chart.get(id). + * + * Configuration options for the axes are given in options.xAxis and options.yAxis. */ - attr(hash: any): HighchartsElementObject; + interface AxisObject { + /** + * Add a plot band after render time. + * @param {PlotBands} options A configuration object consisting of the same members as options.xAxis.plotBands + * @since 1.2.0 + */ + addPlotBand(options: PlotBands): void; + /** + * Add a plot line after render time. + * @param {PlotLines} options A configuration object consisting of the same members as options.xAxis.plotLines + * @since 1.2.0 + */ + addPlotLine(options: PlotLines): void; + /** + * Get the current extremes for the axis. + * @since 1.2.0 + */ + getExtremes(): Extremes; + /** + * Remove an axis from the chart. + * @param [boolean] redraw Defaults to true. Whether to redraw the chart following the remove. + * @since 3.0 + */ + remove(redraw?: boolean): void; + /** + * Remove a plot band by its id. + * @param {string} id The plot band's id as given in the original configuration object or in the addPlotBand method. + * @since 1.2.0 + */ + removePlotBand(id: string): void; + /** + * Remove a plot line by its id. + * @param {string} id The plot line's id as given in the original configuration object or in the addPlotLine method. + * @since 1.2.0 + */ + removePlotLine(id: string): void; + /** + * Set new categories for the axis. Redraws. + * @param {string[]} categories The new category names. + * @since 1.2.0 + */ + setCategories(categories: string[]): void; + /** + * Set new categories for the axis. + * @param {string[]} categories The new category names. + * @param {boolean} redraw Whether to redraw the axis or wait for an explicit call to chart.redraw(). + * @since 1.2.0 + */ + setCategories(categories: string[], redraw: boolean): void; + /** + * Set the minimum and maximum of the axes after render time. If the startOnTick and endOnTick options are true, the + * minimum and maximum values are rounded off to the nearest tick. To prevent this, these options can be set to + * false before calling setExtremes. Also, setExtremes will not allow a range lower than the minRange option, which + * by default is the range of five points. + * @param {number} min The new minimum value + * @param {number} max The new maximum value + * @param {boolean} redraw Whether to redraw the chart or wait for an explicit call to chart.redraw(). + * @param {boolean | Animation} animation When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. + * @since 1.2.0 + */ + setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | Animation, eventArguments?: any): void; + /** + * Update the title of the axis after render time. + * @param {AxisTitle} title The new title options on the same format as given in xAxis.title. + * @param {boolean} redraw Whether to redraw the chart now or hold until the next chart.redraw() + * @since 2.2 + */ + setTitle(title: AxisTitle, redraw?: boolean): void; + /** + * Translates a value in terms of axis units in to pixels within the chart. + * @param {number} value A value in terms of axis units. + * @param {boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart or just the axis/pane itself. + * @return {number} + * @since 3.0 + */ + toPixels(value: number, paneCoordinates?: boolean): number; + /** + * Translate a pixel position along the axis to a value in terms of axis units. + * @param {number} pixel A pixel position along the axis. + * @param {boolean} paneCoordinates Whether the input pixel position is relative to the chart or just the axis/pane itself. + * @return {number} + * @since 3.0 + */ + toValue(pixel: number, paneCoordinates?: boolean): number; + /** + * Update an axis object with a new set of options. The options are merged with the existing options, so only new or + * altered options need to be specified. + * @param {AxisOptions} options The new options that will be merged in with existing options on the axis. + * @param {boolean} redraw Defaults to true. Whether to redraw the chart after the new options are set. + * @since 3.0 + */ + update(options: AxisOptions, redraw?: boolean): void; + } + /** - * Apply some CSS properties to the element - * @param {Object} hash The object literal of CSS properties to apply. Properties should be hyphenated, not camelCased. - * @return {HighchartsElementObject} - * @since 2.0 + * The chart object is the JavaScript object representing a single chart in the web page.The pointer to your chart + * object is returned when a chart is created using the Highcharts.Chart() constructor: + * var chart1 = new Highcharts.Chart(options); */ - css(hash: Object): HighchartsElementObject; + interface ChartObject { + /** + * Add an axis to the chart after render time. Note that this method should never be used when adding data + * synchronously at chart render time, as it adds expense to the calculations and rendering. When adding data at the + * same time as the chart is initiated, add the axis as a configuration option instead. + * @param {AxisOptions} options The Axis options, as documented under xAxis and yAxis. + * @param [boolean] isX Whether it is an X axis or Y axis + * @param [boolean] redraw Defaults to true. Whether to redraw the chart after the series is added. See the redraw() method. + * @param [boolean | Animation] animation Defaults to true. When true, the series' updating will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. + * @return {AxisObject} + * @since 3.0 + */ + addAxis(options: AxisOptions, isX?: boolean, redraw?: boolean, animation?: boolean | Animation): AxisObject; + /** + * Add a series to the chart after render time. Note that this method should never be used when adding data + * synchronously at chart render time, as it adds expense to the calculations and rendering. When adding data at the + * same time as the chart is initiated, add the series as a configuration option instead. + * @param {T} options The series options, as documented under plotOptions.series and under the plotOptions for each series type. + * @param [boolean] redraw + * @since 1.2.0 + */ + addSeries(options: T, redraw?: boolean, animation?: boolean | Animation): SeriesObject; + /** + * Add a series to the chart as drilldown from a specific point in the parent series. This method is used for async + * drilldown, when clicking a point in a series should result in loading and displaying a more high-resolution + * series. When not async, the setup is simpler using the drilldown.series options structure. + * @param {PointObject} point The existing Point object from which the drilldown will start. + * @param {IndividualSeriesOptions} seriesOptions The series options, as documented under plotOptions.series and under the plotOptions for each series type. + * @since 3.0.8 + */ + addSeriesAsDrilldown(point: PointObject, seriesOptions: IndividualSeriesOptions): void; + /** + * A reference to the containing HTML element, dynamically inserted into the element given in chart.renderTo. + * @since 1.2.5 + */ + container: HTMLElement; + /** + * Removes the chart and purges memory. This method should be called before writing a new chart into the same + * container. It is called internally on window unload to prevent leaks. + * @since 1.2.2 + */ + destroy(): void; + /** + * When the chart is drilled down to a child series, calling chart.drillUp() will drill up to the parent series. + * @since 3.0.8 + */ + drillUp(): void; + /** + * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for + * conversion. + * @since 2.0 + */ + exportChart(): void; + /** + * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for + * conversion. + * @param {ExportingOptions} options Exporting options. Out of the exporting options, the following options can be given as parameters to the exportChart method. All options default to the values given in the exporting config options. filename: the filename for the export without extension, url: the URL for the server module to do the conversion, width: the width of the PNG or JPEG image generated on the server, type: the MIME type of the converted image, sourceWidth: the width of the source (in-page) chart, sourceHeight: the height of the source chart. + * @since 2.0 + */ + exportChart(options: ExportingOptions): void; + /** + * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for + * conversion. + * @param {ExportingOptions} options Exporting options. Out of the exporting options, the following options can be given as parameters to the exportChart method. All options default to the values given in the exporting config options. filename: the filename for the export without extension, url: the URL for the server module to do the conversion, width: the width of the PNG or JPEG image generated on the server, type: the MIME type of the converted image, sourceWidth: the width of the source (in-page) chart, sourceHeight: the height of the source chart. + * @param {Options} chartOptions Additional chart options for the exported chart. For example a different background color can be added here. + * @since 2.0 + */ + exportChart(options: ExportingOptions, chartOptions: Options): void; + /** + * Export the chart to a PNG or SVG without sending it to a server. Requires + * modules/exporting.js and modules/offline-exporting.js. + * @since 2.0 + */ + exportChartLocal(): void; + /** + * Export the chart to a PNG or SVG without sending it to a server. Requires + * modules/exporting.js and modules/offline-exporting.js. + * @param {ExportingOptions} options Exporting options. Same as + * the exportChart params. + * @since 2.0 + */ + exportChartLocal(options: ExportingOptions): void; + /** + * Export the chart to a PNG or SVG without sending it to a server. + * Requires modules/exporting.js and modules/offline-exporting.js. + * @param {ExportingOptions} options Exporting options. Same as + * the exportChart params. + * @param {Options} chartOptions Additional chart options for the + * exported chart. Same as the exportChart params. + * @since 2.0 + */ + exportChartLocal(options: ExportingOptions, chartOptions: Options): void; + /** + * Get an axis, series or point by its id as given in the configuration options. + * @param {string} id The id of the axis, series or point to get. + * @return {AxisObject|SeriesObject|PointObject} + * @since 1.2.0 + */ + get(id: string): AxisObject | SeriesObject | PointObject; + /** + * Exporting module required. Get an SVG string representing the chart. + * @param {Options} additionalOptions Chart options to add to the exported chart in addition to the options given for the original chart. For example if series.lineWidth should be greater in the exported chart than in the original, or the chart should have a different background color, this is added here. + * @return {string} + * @since 2.0 + */ + getSVG(additionalOptions?: Options): string; + /** + * Returns an array of all currently selected points in the chart. Points can be selected either programmatically by + * the point.select() method or by clicking. + * @return {PointObject[]} An array of the selected points. + * @since 1.2.0 + */ + getSelectedPoints(): PointObject[]; + /** + * Returns an array of all currently selected series in the chart. Series can be selected either programmatically by + * the series.select() method or by checking the checkbox next to the legend item if series.showCheckBox is true. + * @return {SeriesObject[]} An array of the selected Series items. + * @since 1.2.0 + */ + getSelectedSeries(): SeriesObject[]; + /** + * Hide the loading screen. Options for the loading screen are defined at options.loading. + * @since 1.2.0 + */ + hideLoading(): void; + /** + * The options structure for the chart. + * @since 1.2.0 + */ + options: Options; + /** + * Exporting module required. Clears away other elements in the page and prints the chart as it is displayed. By + * default, when the exporting module is enabled, a button at the upper left calls this method. + * @since 2.0 + */ + print(): void; + /** + * Redraw the chart after changes have been done to the data or axis extremes. All methods for updating axes, series + * or points have a parameter for redrawing the chart. This is true by default. But in many cases you want to do + * more than one operation on the chart before redrawing, for example add a number of points. In those cases it is a + * waste of resources to redraw the chart for each new point added. So you add the points and call chart.redraw() + * after. + * @param [boolean | Animation] animation Defaults to true. When true, the update will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. + * @since 1.2.0 + */ + redraw(animation?: boolean | Animation): void; + /** + * Reflows the chart to its container. By default, the chart reflows automatically to its container following a + * window.resize event, as per the chart.reflow option. However, there are no reliable events for div resize, so if + * the container is resized without a window resize event, this must be called explicitly. + */ + reflow(): void; + /** + * An array of all the chart's series. + * @type {SeriesObject[]} + * @since 1.2.0 + */ + series: SeriesObject[]; + /** + * Resize the chart to a given width and height. + * @param {number} width The new pixel width of the chart. + * @param {number} height The new pixel height of the chart. + * @param {boolean | Animation} animation Defaults to true. When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. + */ + setSize(width: number, height: number, animation?: boolean | Animation): void; + /** + * Set a new title or subtitle for the chart + * @param {TitleOptions} title A configuration object for the new title as defined at #title. + * @param [SubtitleOptions] subtitle A configuration object for the new subtitle as defined at #subtitle. + * @param [boolean] redraw Whether to redraw the chart. Defaults to true. + * @since 2.1.0 + */ + setTitle(title: TitleOptions, subtitle?: SubtitleOptions, redraw?: boolean): void; + /** + * Dim the chart's plot area and show a loading label text. Options for the loading screen are defined at + * options.loading. A custom text can be given as a parameter for loading. + * @since 2.0.5 + */ + showLoading(str?: string): void; + /** + * A generic function to update any element of the chart. Elements can be enabled and disabled, moved, re-styled, + * re-formatted etc. + * A special case is configuration objects that take arrays, for example xAxis, yAxis or series. For these collections, + * an id option is used to map the new option set to an existing object. If an existing object of the same id is not + * found, the first item is updated. So for example, running chart.update with a series item without an id, will cause + * the existing chart's first series to be updated. + * See also the responsive option set. Switching between responsive.rules basically runs chart.update under the hood. + * @param {ChartOptions} option A configuration object for the new chart options as defined in the options section of the API. + * @param [boolean] redraw Whether to redraw the chart. Defaults to true. + * @since 5.0.0 + */ + update(options: ChartOptions, redraw?: boolean): void; + /** + * This method is deprecated as of 2.0.1. Updating the chart position after a move operation is no longer necessary. + * @since 1.2.5 + * @deprecated + */ + updatePosition(): void; + /** + * An array of the chart's x axes. If only one x axis, it is referenced by chart.xAxis[0]. + * @since 1.2.0 + */ + xAxis: AxisObject[]; + /** + * An array of the chart's y axes. If only one y axis, it is referenced by chart.yAxis[0]. + * @since 1.2.0 + */ + yAxis: AxisObject[]; + + renderer: RendererObject; + } + + interface Chart { + /** + * This is the constructor for creating a new chart object. + * @param {Options} options The chart options + * @return {ChartObject} + */ + new (options: Options): ChartObject; + /** + * This is the constructor for creating a new chart object. + * @param {Options} options The chart options + * @param callback A function to execute when the chart object is finished loading and rendering. In most cases the chart is built in one thread, but in Internet Explorer version 8 or less the chart is sometimes initiated before the document is ready, and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). As a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. + * @return {ChartObject} + */ + new (options: Options, callback: (chart: ChartObject) => void): ChartObject; + /** + * This is the constructor for creating a new chart object. + * @param {string|HTMLElement} renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). + * @param {Options} options The chart options + * @return {ChartObject} + */ + new (renderTo: string | HTMLElement, options: Options): ChartObject; + /** + * This is the constructor for creating a new chart object. + * @param {string|HTMLElement} renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). + * @param {Options} options The chart options + * @param callback A function to execute when the chart object is finished loading and rendering. In most cases the chart is built in one thread, but in Internet Explorer version 8 or less the chart is sometimes initiated before the document is ready, and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). As a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. + * @return {ChartObject} + */ + new (renderTo: string | HTMLElement, options: Options, callback: (chart: ChartObject) => void): ChartObject; + } + /** - * Destroy the element and free up memory - * @since 2.0 + * The Element class is a JavaScript wrapper for SVG elements used in the rendering layer of Highchart. Combined with + * the Renderer object, these elements allows freeform annotation in the charts or even in your HTML pages without + * creating a chart at all. */ - destroy(): void; - fadeOut(duration?: number): void; + interface ElementObject { + /** + * Add the element to the renderer canvas. + * @param {ElementObject} parent The element can be added to a g (group) element. + * @return {ElementObject} + * @since 2.0 + */ + add(parent?: ElementObject): ElementObject; + /** + * Apply numeric attributes to the SVG/VML element by animation. See Element.attr() for more information on setting + * attributes. + * @param {any} attributes A set of attributes to apply. + * @param {any} animation Optional animation parameters that are passed over to jQuery or other framework. Valid properties depend on the library, but options like duration, easing and complete are supported by jQuery. + * @return {ElementObject} + * @since 2.0 + */ + animate(attributes: any, animation?: any): ElementObject; + /** + * Apply attributes to the SVG/VML elements. These attributes for the most parts correspond to SVG, but some are + * specific to Highcharts, like zIndex and rotation. + * + * In order to set the rotation center for rotation, set x and y to 0 and use translateX and translateY attributes + * to position the element instead. + * + * Attributes frequently used in Highcharts are fill, stroke, stroke-width. + * @param {any} hash A set of attributes to apply. + * @return {ElementObject} + * @since 2.0 + */ + attr(hash: any): ElementObject; + /** + * Apply some CSS properties to the element + * @param {Object} hash The object literal of CSS properties to apply. Properties should be hyphenated, not camelCased. + * @return {ElementObject} + * @since 2.0 + */ + css(hash: Object): ElementObject; + /** + * Destroy the element and free up memory + * @since 2.0 + */ + destroy(): void; + fadeOut(duration?: number): void; + /** + * Get the bounding box of the element + * @return An object containing x, y, width and height values for the element. + * @since 2.0 + */ + getBBox(): { x: number; y: number; height: number; width: number; }; + /** + * Apply an event handler to the element + * @param {string} eventType The event type to attach, for example 'click', 'mouseover', 'touch'. + * @param handler The event handler function. + * @return {ElementObject} + * @since 2.0 + */ + on(eventType: string, handler: () => void): ElementObject; + /** + * Bring the element to the front. Alternatively, a zIndex attribute can be given. + * @return {ElementObject} The element object + * @since 2.0 + */ + toFront(): ElementObject; + } + /** - * Get the bounding box of the element - * @return An object containing x, y, width and height values for the element. - * @since 2.0 + * Allows direct access to the Highcharts rendering layer in order to draw primitive shapes like circles, + * rectangles,paths or text directly on a chart, or independent from any chart. The Renderer represents a wrapper object + * for SVGin modern browsers and VML in IE < 8. + * + * An existing chart's renderer can be accessed through chart.renderer. To create a renderer independent from a chart, + * use var renderer = new Highcharts.Renderer(parentNode, width, height); where parentNode is the HTML element where you + * want to add it. + * + * The Renderer's methods are chained wherever possible, so you can initiate an element then call for example attr and + * css and add on that element in one statement. */ - getBBox(): { x: number; y: number; height: number; width: number; }; + interface RendererObject { + /** + * Draw an arc on the renderer canvas. + * @param {number} centerX The x position of the arc's center in the SVG element. + * @param {number} centerY The y position of the arc's center in the SVG element. + * @param {number} outerRadius The outer radius of the arc. + * @param {number} innerRadius The inner radius of the arc. + * @param {number} start The starting angle of the arc in radians, where 0 is to the right and -Math.PI/2 is up. + * @param {number} end The ending angle of the arc in radians, where 0 is to the right and -Math.PI/2 is up. + * @return {ElementObject} + * @since 2.0 + */ + arc(centerX: number, centerY: number, outerRadius: number, innerRadius: number, start: number, end: number): ElementObject; + /** + * Draw circle on the renderer canvas. + * @param {number} centerX The x position of the circle's center in the SVG element. + * @param {number} centerY The y position of the circle's center in the SVG element. + * @param {number} radius [description] + * @return {ElementObject} + * @since 2.0 + */ + circle(centerX: number, centerY: number, radius: number): ElementObject; + /** + * Add an SVG/VML group. + * @param [string] name The name of the group. This will be used in the class name, which will be 'highcharts-'+ name. Other Element objects are added to the group by using the group as the first parameter in .add() for the wrappers + * @return {ElementObject} + * @since 2.0 + */ + g(name?: string): ElementObject; + /** + * Add an image from an external resource. + * @param {string} source The URL of the image. + * @param {number} x The x position of the image's upper left corner. + * @param {number} y The y position of the image's upper left corner. + * @param {number} width The width of the image. + * @param {number} height The height of the image. + * @return {ElementObject} + * @since 2.0 + */ + image(source: string, x: number, y: number, width: number, height: number): ElementObject; + /** + * Draw a label, which is an extended text element with support for border and background. Highcharts creates a g + * element with a text and a path or rect inside, to make it behave somewhat like a HTML div. Border and background + * are set through stroke, stroke-width and fill attributes using the attr method. This must be done before calling + * add. + * @param {string} str The text or HTML to draw + * @param {number} x The x position of the label's left side. + * @param {number} y The y position of the label's top side or baseline, depending on the baseline parameter. + * @param [string] shape The shape of the label's border/background, if any. Defaults to rect. + * @param [number] anchorX If the shape has a pointer, like the chevron on a callout shape, anchorX is the x position to point to. + * @param [number] anchorY If the shape has a pointer, like the chevron on a callout shape, anchorY is the y position to point to. + * @param [boolean] useHTML Use HTML to render the text of the label. + * @param [boolean] baseline Whether the label should be vertically aligned by the text baseline, which makes it behave like the text element, or by the top left side, which makes it behave like a HTML div. + * @param [string] className A class name for the g element surrounding the label. + * @return {ElementObject} + * @since 2.0 + */ + label(str: string, x: number, y: number, shape?: string, anchorX?: number, anchorY?: number, useHTML?: boolean, baseline?: boolean, className?: string): ElementObject; + /** + * Add a path based on SVG's path commands. In SVG capable browsers all path commands are supported, but in VML only + * a subset is supported: absolute moveTo (M), absolute lineTo (L), absolute curveTo (C) and close (Z). + * @param {(string|number)[]} path An SVG path split up in array form. + * @return {ElementObject} + */ + path(path: [string | number]): ElementObject; + /** + * Add a rectangle. + * @param {number} x The x position of the rectangle's upper left corner. + * @param {number} y The y position of the rectangle's upper left corner. + * @param {number} width The width of the rectangle. + * @param {number} height The height of the rectangle. + * @param {number} cornerRadius The corner radius of all the rectangle's corners. + * @return {ElementObject} + * @since 2.0 + */ + rect(x: number, y: number, width: number, height: number, cornerRadius: number): ElementObject; + /** + * Draw text. The text can contain a subset of HTML, like spans and anchors and some basic text styling of these. + * For more advanced features like border and background, use label instead. + * @param {string} str The text or HTML to draw + * @param {number} x The x position of the text's lower left corner. + * @param {number} y The y position of the text's lower left corner. + * @return {ElementObject} + * @since 2.0 + */ + text(str: string, x: number, y: number): ElementObject; + } + + interface Renderer { + new (parentNode: HTMLElement, width: number, height: number): RendererObject; + } + + interface Static { + Chart: Chart; + Renderer: Renderer; + Color(color: string | Gradient): string | Gradient; + + /** + * As Highcharts.Chart, but without need for the new keyword. + * @since 4.2.0 + */ + chart(options: Options, callback?: (chart: ChartObject) => void): ChartObject; + /** + * As Highcharts.Chart, but without need for the new keyword. + * @since 4.2.0 + */ + chart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; + /** + * An array containing the current chart objects in the page. A chart's position in the array is preserved + * throughout the page's lifetime. When a chart is destroyed, the array item becomes undefined. + * @since 2.3.4 + */ + charts: ChartObject[]; + /** + * Formats a JavaScript date timestamp (milliseconds since Jan 1st 1970) into a human readable date string. The + * format is a subset of the formats for PHP's strftime function. Additional formats can be given in the + * Highcharts.dateFormats hook, see below. + * @param {string} format A string containing some of the formats. + * @param [number] time The JavaScript time to format. + * @param [boolean] capitalize Whether to capitalize words in the return string. + * @return {string} + */ + dateFormat(format: string, time?: number, capitalize?: boolean): string; + /** + * A hook for defining additional date format specifiers. New specifiers are defined as key-value pairs by using the + * specifier as key, and a function which takes the timestamp as value. This function returns the formatted portion + * of the date. + */ + dateFormats: DateFormatSpecifiers; + /** + * Formats a JavaScript number with grouped thousands, a fixed amount of decimals and an optional decimal point. It + * is a port of PHP's function with the same name. See PHP number_format for a full explanation of the parameters. + * @param {number} value The raw number to format. + * @param {number} decimals The desired number of decimals. + * @param {string} decimalPoint The decimal point. Defaults to '.' or to the string specified globally in options.lang.decimalPoint. + * @param {string} thousandsSep The thousands separator. Defaults to ' ' or to the string specified globally in options.lang.thousandsSep. + * @return {string} + */ + numberFormat(value: number, decimals?: number, decimalPoint?: string, thousandsSep?: string): string; + /** + * Sets the options globally for all charts created after this has been called. Takes an options JavaScript object + * structure as the argument. These options are merged with the default options and the result is returned. + * @param options The chart configuration object. + * @return {Options} + */ + setOptions(options: GlobalOptions): Options; + /** + * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules + * wasn't enough because the setOptions method created a new object. + */ + getOptions(): Options; + + map(array: any[], fn: Function): any[]; + } + /** - * Apply an event handler to the element - * @param {string} eventType The event type to attach, for example 'click', 'mouseover', 'touch'. - * @param handler The event handler function. - * @return {HighchartsElementObject} - * @since 2.0 + * The Point object is the JavaScript representation of each data point + * + * The object can be accessed in a number of ways. In all point event handlers the point object is this. In the series + * object all the points are accessed by the series.data array. + * + * Another way to reference the point programmatically is by id. Add an id in the point configuration options, and get + * the point object by chart.get(id). */ - on(eventType: string, handler: () => void): HighchartsElementObject; + interface PointObject { + /** + * For categorized axes this property holds the category name for the point. For other axis it holds the x value. + * @since 1.2.0 + */ + category: string | number; + name: string; + index: number; + /** + * The percentage for points in a stacked series or pies. + * @since 1.2.0 + */ + percentage: number; + /** + * Remove the point from the series. + * @param [boolean] redraw Defaults to true. Whether to redraw the chart after the point is removed.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. + * @param [boolean|Animation] animation Defaults to true. When true, the graph's updating will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. + * @since 1.2.0 + */ + remove(redraw?: boolean, animation?: boolean | Animation): void; + /** + * Select or unselect the point. + * @param [boolean] select When true, the point is selected. When false, the point is unselected. When null or undefined, the selection state is toggled. + * @param [boolean] accumulate When true, the selection is added to other selected points. When false, other selected points are deselected. Internally in Highcharts,selected points are accumulated on Control, Shift or Cmd clicking the point. + * @since 1.2.0 + */ + select(select?: boolean, accumulate?: boolean): void; + /** + * Whether the point is selected or not. + * @since 1.2.0 + */ + selected: boolean; + /** + * The series object associated with the point. + * @since 1.2.0 + */ + series: SeriesObject; + /** + * Slice out or set back in a pie chart slice. This is the default way of Highcharts to visualize that a pie point + * is selected. + * @param [boolean] sliced When true, the point is sliced out. When false, the point is set in. When null or undefined, the sliced state is toggled. + * @param [boolean] redraw Defaults to true. Whether to redraw the chart after the point is altered. + * @param [boolean|Animation] animation Defaults to true. When true, the move will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. + * @since 1.2.0 + */ + slice(sliced?: boolean, redraw?: boolean, animation?: boolean | Animation): void; + /** + * The total of a stack for stacked series, or pie in pie charts. + */ + total: number; + /** + * Update the point with new values. + * @param {number|[number,number]|DataPoint} options The point options. Point options are handled as described under the series.data item for each series type. For example for a line series, if options is a single number, the point will be given that number as the main y value. If it is an array, it will be interpreted as x and y values respectively. If it is an object, advanced options are applied. + * @param [boolean] redraw Defaults to true. Whether to redraw the chart after the point is updated.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. + * @param {boolean|Animation} animation Defaults to true. When true, the update will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. + * @since 1.2.0 + */ + update(options: number | [number, number] | DataPoint, redraw?: boolean, animation?: boolean | Animation): void; + /** + * The x value for the point. + * @since 1.2.0 + */ + x: number; + /** + * The y value for the point. + * @since 1.2.0 + */ + y: number; + } + /** - * Bring the element to the front. Alternatively, a zIndex attribute can be given. - * @return {HighchartsElementObject} The element object - * @since 2.0 + * The Series object is the JavaScript representation of each line, area series, pie etc. + * + * The object can be accessed in a number of ways. All series and point event handlers give a reference to the series + * object. The chart object has a series property that is a collection of all the chart's series. The point objects also + * have the same reference. + * + * Another way to reference the series programmatically is by id. Add an id in the series configuration options, and get + * the series object by chart.get(id). + * + * Configuration options for the series are given in three levels. Options for all series in a chart are given in the + * plotOptions.series object. Then options for all series of a specific type are given in the plotOptions of that type, + * for example plotOptions.line. Next, options for one single series are given in the series array. */ - toFront(): HighchartsElementObject; + interface SeriesObject { + /** + * Add a point to the series after render time. The point can be added at the end, or by giving it an X value, to + * the start or in the middle of the series. + * @param {number|[number,number]|DataPoint} The point options. If options is a single number, a point with that y value is appended to the series.If it is an array, it will be interpreted as x and y values respectively. If it is an object, advanced options as outlined under series.data are applied. + * @param [boolean=true] redraw - Whether to redraw the chart after the point is added. When adding more than one point, it is highly recommended that the redraw option be set to false, and instead chart.redraw() is explicitly called after the adding of points is finished. + * @param [boolean=false] shift - When shift is true, one point is shifted off the start of the series as one is appended to the end. Use this option for live charts monitoring a value over time. + * @param [(boolean|Animation)=false] animation - When shift is true, one point is shifted off the start of the series as one is appended to the end. Use this option for live charts monitoring a value over time. + * @since 1.2.0 + */ + addPoint(options: number | [number, number] | DataPoint, redraw?: boolean, shift?: boolean, animation?: boolean | Animation): void; + /** + * Read only. The chart that the series belongs to. + * @since 1.2.0 + */ + chart: ChartObject; + /** + * Read only. An array with the series' data point objects. + * @since 1.2.0 + */ + data: PointObject[]; + /** + * Hides the series if visible. If the chart.ignoreHiddenSeries option is true,the chart is redrawn without this + * series. + * @since 1.2.0 + */ + hide(): void; + /** + * The series' name as given in the options. + * @since 1.2.0 + */ + name: string; + /** + * Read only. The series' options. + * @since 1.2.0 + */ + options: IndividualSeriesOptions; + /** + * Remove the series from the chart. + * @param [boolean=true] redraw - Whether to redraw the chart after the series is removed.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. + * @since 1.2.0 + */ + remove(redraw?: boolean): void; + /** + * Remove a point from the series. Unlike the Point.remove method, this can also be done on a point that is not + * instanciated because it is outside the view or subject to data grouping. + * @param {number} index - The index of the point in the data array. + * @param [boolean=true] redraw - Whether to redraw the chart after the point is added. When adding more than one point, it is highly recommended that the redraw option be set to false, and instead chart.redraw() is explicitly called after the adding of points is finished. + * @param [boolean|Animation=true] animation - When true, the graph will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. + * @since 4.1.0 + */ + removePoint(index: number, redraw?: boolean, animation?: boolean | Animation): void; + /** + * Select or unselect the series. This means its selected property is set,the checkbox in the legend is toggled and + * when selected, the series is returned in the chart.getSelectedSeries() method. + * @param [boolean] selected - When true, the series is selected. When false it is unselected. When null or undefined, the series' selection state is toggled. + * @since 1.2.0 + */ + select(selected?: boolean): void; + /** + * Read only. The series' selected state as set by series.select(). + * @since 1.2.0 + */ + selected: boolean; + /** + * Apply a new set of data to the series and optionally redraw it. Note that this method throws away all points and + * creates new ones. For updating the values of existing points, use Point.update() instead. + * @param {number[]|number[][]|DataPoint[]} data - Takes an array of data in the same format as described under seriesdata for the given series type. + * @param [boolean=true] redraw - Whether to redraw the chart after the series is altered.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. + * @param [boolean|Animation] animation - When the updated data is the same length as the existing data, points will be updated by default, and animation visualizes how the points are changed. Set false to disable animation, or a configuration object to set duration or easing. + * @param [boolean] updatePoints - When the updated data is the same length as the existing data, points will be updated instead of replace. This option prevents this, and makes setData behave like it did prior to Highcharts 3.0.10. + * @since 1.2.0 + */ + setData(data: number[] | number[][] | DataPoint[], redraw?: boolean, animation?: boolean | Animation, updatePoints?: boolean): void; + /** + * A utility function to show or hide the series with an optional redraw. + * @param [boolean] visible - Whether to show or hide the series. If undefined, the visibility is toggled. + * @param [boolean=true] redraw - Whether to redraw the chart after the series is altered.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. + * @since 1.2.0 + */ + setVisible(visible?: boolean, redraw?: boolean): void; + /** + * Shows the series if hidden. + * @since 1.2.0 + */ + show(): void; + /** + * Read only. The series' type, like 'line', 'area' etc. + * @since 1.2.0 + */ + type: string; + /** + * Update the series with a new set of options. For a clean and precise handling of new options, all methods and + * elements from the series is removed, and it is initiated from scratch. Therefore, this method is more performance + * expensive than some other utility methods like setData or setVisible. + * @param {IndividualSeriesOptions} options New options that will be merged into the series' existing options. + * @param [boolean] redraw - Whether to redraw the chart after the series is altered. If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. + * @since 1.2.0 + */ + update(options: IndividualSeriesOptions, redraw?: boolean): void; + /** + * Read only. The series' visibility state as set by series.show(), series.hide(), or the initial configuration. + * @since 1.2.0 + */ + visible: boolean; + /** + * Read only. The unique xAxis object associated with the series. + * @since 1.2.0 + */ + xAxis: AxisObject; + /** + * Read only. The unique yAxis object associated with the series. + * @since 1.2.0 + */ + yAxis: AxisObject; + } } -/** - * Allows direct access to the Highcharts rendering layer in order to draw primitive shapes like circles, - * rectangles,paths or text directly on a chart, or independent from any chart. The Renderer represents a wrapper object - * for SVGin modern browsers and VML in IE < 8. - * - * An existing chart's renderer can be accessed through chart.renderer. To create a renderer independent from a chart, - * use var renderer = new Highcharts.Renderer(parentNode, width, height); where parentNode is the HTML element where you - * want to add it. - * - * The Renderer's methods are chained wherever possible, so you can initiate an element then call for example attr and - * css and add on that element in one statement. - */ -interface HighchartsRendererObject { - /** - * Draw an arc on the renderer canvas. - * @param {number} centerX The x position of the arc's center in the SVG element. - * @param {number} centerY The y position of the arc's center in the SVG element. - * @param {number} outerRadius The outer radius of the arc. - * @param {number} innerRadius The inner radius of the arc. - * @param {number} start The starting angle of the arc in radians, where 0 is to the right and -Math.PI/2 is up. - * @param {number} end The ending angle of the arc in radians, where 0 is to the right and -Math.PI/2 is up. - * @return {HighchartsElementObject} - * @since 2.0 - */ - arc(centerX: number, centerY: number, outerRadius: number, innerRadius: number, start: number, end: number): HighchartsElementObject; - /** - * Draw circle on the renderer canvas. - * @param {number} centerX The x position of the circle's center in the SVG element. - * @param {number} centerY The y position of the circle's center in the SVG element. - * @param {number} radius [description] - * @return {HighchartsElementObject} - * @since 2.0 - */ - circle(centerX: number, centerY: number, radius: number): HighchartsElementObject; - /** - * Add an SVG/VML group. - * @param [string] name The name of the group. This will be used in the class name, which will be 'highcharts-'+ name. Other Element objects are added to the group by using the group as the first parameter in .add() for the wrappers - * @return {HighchartsElementObject} - * @since 2.0 - */ - g(name?: string): HighchartsElementObject; - /** - * Add an image from an external resource. - * @param {string} source The URL of the image. - * @param {number} x The x position of the image's upper left corner. - * @param {number} y The y position of the image's upper left corner. - * @param {number} width The width of the image. - * @param {number} height The height of the image. - * @return {HighchartsElementObject} - * @since 2.0 - */ - image(source: string, x: number, y: number, width: number, height: number): HighchartsElementObject; - /** - * Draw a label, which is an extended text element with support for border and background. Highcharts creates a g - * element with a text and a path or rect inside, to make it behave somewhat like a HTML div. Border and background - * are set through stroke, stroke-width and fill attributes using the attr method. This must be done before calling - * add. - * @param {string} str The text or HTML to draw - * @param {number} x The x position of the label's left side. - * @param {number} y The y position of the label's top side or baseline, depending on the baseline parameter. - * @param [string] shape The shape of the label's border/background, if any. Defaults to rect. - * @param [number] anchorX If the shape has a pointer, like the chevron on a callout shape, anchorX is the x position to point to. - * @param [number] anchorY If the shape has a pointer, like the chevron on a callout shape, anchorY is the y position to point to. - * @param [boolean] useHTML Use HTML to render the text of the label. - * @param [boolean] baseline Whether the label should be vertically aligned by the text baseline, which makes it behave like the text element, or by the top left side, which makes it behave like a HTML div. - * @param [string] className A class name for the g element surrounding the label. - * @return {HighchartsElementObject} - * @since 2.0 - */ - label(str: string, x: number, y: number, shape?: string, anchorX?: number, anchorY?: number, useHTML?: boolean, baseline?: boolean, className?: string): HighchartsElementObject; - /** - * Add a path based on SVG's path commands. In SVG capable browsers all path commands are supported, but in VML only - * a subset is supported: absolute moveTo (M), absolute lineTo (L), absolute curveTo (C) and close (Z). - * @param {(string|number)[]} path An SVG path split up in array form. - * @return {HighchartsElementObject} - */ - path(path: [string|number]): HighchartsElementObject; - /** - * Add a rectangle. - * @param {number} x The x position of the rectangle's upper left corner. - * @param {number} y The y position of the rectangle's upper left corner. - * @param {number} width The width of the rectangle. - * @param {number} height The height of the rectangle. - * @param {number} cornerRadius The corner radius of all the rectangle's corners. - * @return {HighchartsElementObject} - * @since 2.0 - */ - rect(x: number, y: number, width: number, height: number, cornerRadius: number): HighchartsElementObject; - /** - * Draw text. The text can contain a subset of HTML, like spans and anchors and some basic text styling of these. - * For more advanced features like border and background, use label instead. - * @param {string} str The text or HTML to draw - * @param {number} x The x position of the text's lower left corner. - * @param {number} y The y position of the text's lower left corner. - * @return {HighchartsElementObject} - * @since 2.0 - */ - text(str: string, x: number, y: number): HighchartsElementObject; -} - -interface HighchartsRenderer { - new (parentNode: HTMLElement, width: number, height: number): HighchartsRendererObject; -} - -interface HighchartsStatic { - Chart: HighchartsChart; - Renderer: HighchartsRenderer; - Color(color: string | HighchartsGradient): string | HighchartsGradient; - - /** - * As Highcharts.Chart, but without need for the new keyword. - * @since 4.2.0 - */ - chart(options: HighchartsOptions, callback?: (chart: HighchartsChartObject) => void): HighchartsChartObject; - /** - * As Highcharts.Chart, but without need for the new keyword. - * @since 4.2.0 - */ - chart(renderTo: string | HTMLElement, options: HighchartsOptions, callback?: (chart: HighchartsChartObject) => void): HighchartsChartObject; - /** - * An array containing the current chart objects in the page. A chart's position in the array is preserved - * throughout the page's lifetime. When a chart is destroyed, the array item becomes undefined. - * @since 2.3.4 - */ - charts: HighchartsChartObject[]; - /** - * Formats a JavaScript date timestamp (milliseconds since Jan 1st 1970) into a human readable date string. The - * format is a subset of the formats for PHP's strftime function. Additional formats can be given in the - * Highcharts.dateFormats hook, see below. - * @param {string} format A string containing some of the formats. - * @param [number] time The JavaScript time to format. - * @param [boolean] capitalize Whether to capitalize words in the return string. - * @return {string} - */ - dateFormat(format: string, time?: number, capitalize?: boolean): string; - /** - * A hook for defining additional date format specifiers. New specifiers are defined as key-value pairs by using the - * specifier as key, and a function which takes the timestamp as value. This function returns the formatted portion - * of the date. - */ - dateFormats: HighchartsDateFormatSpecifiers; - /** - * Formats a JavaScript number with grouped thousands, a fixed amount of decimals and an optional decimal point. It - * is a port of PHP's function with the same name. See PHP number_format for a full explanation of the parameters. - * @param {number} value The raw number to format. - * @param {number} decimals The desired number of decimals. - * @param {string} decimalPoint The decimal point. Defaults to '.' or to the string specified globally in options.lang.decimalPoint. - * @param {string} thousandsSep The thousands separator. Defaults to ' ' or to the string specified globally in options.lang.thousandsSep. - * @return {string} - */ - numberFormat(value: number, decimals?: number, decimalPoint?: string, thousandsSep?: string): string; - /** - * Sets the options globally for all charts created after this has been called. Takes an options JavaScript object - * structure as the argument. These options are merged with the default options and the result is returned. - * @param options The chart configuration object. - * @return {HighchartsOptions} - */ - setOptions(options: HighchartsGlobalOptions): HighchartsOptions; - /** - * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules - * wasn't enough because the setOptions method created a new object. - */ - getOptions(): HighchartsOptions; - - map(array: any[], fn: Function): any[]; -} - -declare var Highcharts: HighchartsStatic; - -/** - * The Point object is the JavaScript representation of each data point - * - * The object can be accessed in a number of ways. In all point event handlers the point object is this. In the series - * object all the points are accessed by the series.data array. - * - * Another way to reference the point programmatically is by id. Add an id in the point configuration options, and get - * the point object by chart.get(id). - */ -interface HighchartsPointObject { - /** - * For categorized axes this property holds the category name for the point. For other axis it holds the x value. - * @since 1.2.0 - */ - category: string | number; - name: string; - index: number; - /** - * The percentage for points in a stacked series or pies. - * @since 1.2.0 - */ - percentage: number; - /** - * Remove the point from the series. - * @param [boolean] redraw Defaults to true. Whether to redraw the chart after the point is removed.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. - * @param [boolean|HighchartsAnimation] animation Defaults to true. When true, the graph's updating will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. - * @since 1.2.0 - */ - remove(redraw?: boolean, animation?: boolean|HighchartsAnimation): void; - /** - * Select or unselect the point. - * @param [boolean] select When true, the point is selected. When false, the point is unselected. When null or undefined, the selection state is toggled. - * @param [boolean] accumulate When true, the selection is added to other selected points. When false, other selected points are deselected. Internally in Highcharts,selected points are accumulated on Control, Shift or Cmd clicking the point. - * @since 1.2.0 - */ - select(select?: boolean, accumulate?: boolean): void; - /** - * Whether the point is selected or not. - * @since 1.2.0 - */ - selected: boolean; - /** - * The series object associated with the point. - * @since 1.2.0 - */ - series: HighchartsSeriesObject; - /** - * Slice out or set back in a pie chart slice. This is the default way of Highcharts to visualize that a pie point - * is selected. - * @param [boolean] sliced When true, the point is sliced out. When false, the point is set in. When null or undefined, the sliced state is toggled. - * @param [boolean] redraw Defaults to true. Whether to redraw the chart after the point is altered. - * @param [boolean|HighchartsAnimation] animation Defaults to true. When true, the move will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. - * @since 1.2.0 - */ - slice(sliced?: boolean, redraw?: boolean, animation?: boolean|HighchartsAnimation): void; - /** - * The total of a stack for stacked series, or pie in pie charts. - */ - total: number; - /** - * Update the point with new values. - * @param {number|[number,number]|HighchartsDataPoint} options The point options. Point options are handled as described under the series.data item for each series type. For example for a line series, if options is a single number, the point will be given that number as the main y value. If it is an array, it will be interpreted as x and y values respectively. If it is an object, advanced options are applied. - * @param [boolean] redraw Defaults to true. Whether to redraw the chart after the point is updated.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. - * @param {boolean|HighchartsAnimation} animation Defaults to true. When true, the update will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. - * @since 1.2.0 - */ - update(options: number | [number, number] | HighchartsDataPoint, redraw?: boolean, animation?: boolean | HighchartsAnimation): void; - /** - * The x value for the point. - * @since 1.2.0 - */ - x: number; - /** - * The y value for the point. - * @since 1.2.0 - */ - y: number; -} - -/** - * The Series object is the JavaScript representation of each line, area series, pie etc. - * - * The object can be accessed in a number of ways. All series and point event handlers give a reference to the series - * object. The chart object has a series property that is a collection of all the chart's series. The point objects also - * have the same reference. - * - * Another way to reference the series programmatically is by id. Add an id in the series configuration options, and get - * the series object by chart.get(id). - * - * Configuration options for the series are given in three levels. Options for all series in a chart are given in the - * plotOptions.series object. Then options for all series of a specific type are given in the plotOptions of that type, - * for example plotOptions.line. Next, options for one single series are given in the series array. - */ -interface HighchartsSeriesObject { - /** - * Add a point to the series after render time. The point can be added at the end, or by giving it an X value, to - * the start or in the middle of the series. - * @param {number|[number,number]|HighchartsDataPoint} The point options. If options is a single number, a point with that y value is appended to the series.If it is an array, it will be interpreted as x and y values respectively. If it is an object, advanced options as outlined under series.data are applied. - * @param [boolean=true] redraw - Whether to redraw the chart after the point is added. When adding more than one point, it is highly recommended that the redraw option be set to false, and instead chart.redraw() is explicitly called after the adding of points is finished. - * @param [boolean=false] shift - When shift is true, one point is shifted off the start of the series as one is appended to the end. Use this option for live charts monitoring a value over time. - * @param [(boolean|HighchartsAnimation)=false] animation - When shift is true, one point is shifted off the start of the series as one is appended to the end. Use this option for live charts monitoring a value over time. - * @since 1.2.0 - */ - addPoint(options: number |[number, number]| HighchartsDataPoint, redraw?: boolean, shift?: boolean, animation?: boolean | HighchartsAnimation): void; - /** - * Read only. The chart that the series belongs to. - * @since 1.2.0 - */ - chart: HighchartsChartObject; - /** - * Read only. An array with the series' data point objects. - * @since 1.2.0 - */ - data: HighchartsPointObject[]; - /** - * Hides the series if visible. If the chart.ignoreHiddenSeries option is true,the chart is redrawn without this - * series. - * @since 1.2.0 - */ - hide(): void; - /** - * The series' name as given in the options. - * @since 1.2.0 - */ - name: string; - /** - * Read only. The series' options. - * @since 1.2.0 - */ - options: HighchartsIndividualSeriesOptions; - /** - * Remove the series from the chart. - * @param [boolean=true] redraw - Whether to redraw the chart after the series is removed.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. - * @since 1.2.0 - */ - remove(redraw?: boolean): void; - /** - * Remove a point from the series. Unlike the Point.remove method, this can also be done on a point that is not - * instanciated because it is outside the view or subject to data grouping. - * @param {number} index - The index of the point in the data array. - * @param [boolean=true] redraw - Whether to redraw the chart after the point is added. When adding more than one point, it is highly recommended that the redraw option be set to false, and instead chart.redraw() is explicitly called after the adding of points is finished. - * @param [boolean|HighchartsAnimation=true] animation - When true, the graph will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. - * @since 4.1.0 - */ - removePoint(index: number, redraw?: boolean, animation?: boolean|HighchartsAnimation): void; - /** - * Select or unselect the series. This means its selected property is set,the checkbox in the legend is toggled and - * when selected, the series is returned in the chart.getSelectedSeries() method. - * @param [boolean] selected - When true, the series is selected. When false it is unselected. When null or undefined, the series' selection state is toggled. - * @since 1.2.0 - */ - select(selected?: boolean): void; - /** - * Read only. The series' selected state as set by series.select(). - * @since 1.2.0 - */ - selected: boolean; - /** - * Apply a new set of data to the series and optionally redraw it. Note that this method throws away all points and - * creates new ones. For updating the values of existing points, use Point.update() instead. - * @param {number[]|number[][]|HighchartsDataPoint[]} data - Takes an array of data in the same format as described under seriesdata for the given series type. - * @param [boolean=true] redraw - Whether to redraw the chart after the series is altered.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. - * @param [boolean|HighchartsAnimation] animation - When the updated data is the same length as the existing data, points will be updated by default, and animation visualizes how the points are changed. Set false to disable animation, or a configuration object to set duration or easing. - * @param [boolean] updatePoints - When the updated data is the same length as the existing data, points will be updated instead of replace. This option prevents this, and makes setData behave like it did prior to Highcharts 3.0.10. - * @since 1.2.0 - */ - setData(data: number[] | number[][] | HighchartsDataPoint[], redraw?: boolean, animation?: boolean | HighchartsAnimation, updatePoints?: boolean): void; - /** - * A utility function to show or hide the series with an optional redraw. - * @param [boolean] visible - Whether to show or hide the series. If undefined, the visibility is toggled. - * @param [boolean=true] redraw - Whether to redraw the chart after the series is altered.If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. - * @since 1.2.0 - */ - setVisible(visible?: boolean, redraw?: boolean): void; - /** - * Shows the series if hidden. - * @since 1.2.0 - */ - show(): void; - /** - * Read only. The series' type, like 'line', 'area' etc. - * @since 1.2.0 - */ - type: string; - /** - * Update the series with a new set of options. For a clean and precise handling of new options, all methods and - * elements from the series is removed, and it is initiated from scratch. Therefore, this method is more performance - * expensive than some other utility methods like setData or setVisible. - * @param {HighchartsIndividualSeriesOptions} options New options that will be merged into the series' existing options. - * @param [boolean] redraw - Whether to redraw the chart after the series is altered. If doing more operations on the chart, it is a good idea to set redraw to false and call chart.redraw() after. - * @since 1.2.0 - */ - update(options: HighchartsIndividualSeriesOptions, redraw?: boolean): void; - /** - * Read only. The series' visibility state as set by series.show(), series.hide(), or the initial configuration. - * @since 1.2.0 - */ - visible: boolean; - /** - * Read only. The unique xAxis object associated with the series. - * @since 1.2.0 - */ - xAxis: HighchartsAxisObject; - /** - * Read only. The unique yAxis object associated with the series. - * @since 1.2.0 - */ - yAxis: HighchartsAxisObject; -} - -interface JQuery { - highcharts(): HighchartsChartObject; - /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param {HighchartsOptions} options Options for this chart - * @return current {JQuery} selector the current JQuery selector - **/ - highcharts(options: HighchartsOptions): JQuery; - /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param {HighchartsOptions} options Options for this chart - * @param callback Callback function used to manipulate the constructed chart instance - * @return current {JQuery} selector the current JQuery selector - **/ - highcharts(options: HighchartsOptions, callback: (chart: HighchartsChartObject) => void): JQuery; -} - -/** - * Enabling the usage of ES6 module loading. - */ -declare var Highcharts: HighchartsStatic; - -/** - * Declaration for ES6 module loading. - */ -declare module "highcharts" { - export = Highcharts; +declare global { + interface JQuery { + highcharts(): Highcharts.ChartObject; + /** + * Creates a new Highcharts.Chart for the current JQuery selector; usually + * a div selected by $('#container') + * @param {Options} options Options for this chart + * @return current {JQuery} selector the current JQuery selector + **/ + highcharts(options: Highcharts.Options): JQuery; + /** + * Creates a new Highcharts.Chart for the current JQuery selector; usually + * a div selected by $('#container') + * @param {Options} options Options for this chart + * @param callback Callback function used to manipulate the constructed chart instance + * @return current {JQuery} selector the current JQuery selector + **/ + highcharts(options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; + } } +declare var Highcharts: Highcharts.Static; +export = Highcharts; +export as namespace Highcharts; diff --git a/highcharts/modules/boost-tests.ts b/highcharts/modules/boost-tests.ts new file mode 100644 index 0000000000..98202a2129 --- /dev/null +++ b/highcharts/modules/boost-tests.ts @@ -0,0 +1 @@ +HighchartsBoost(Highcharts); diff --git a/highcharts/highcharts-modules-boost.d.ts b/highcharts/modules/boost.d.ts similarity index 54% rename from highcharts/highcharts-modules-boost.d.ts rename to highcharts/modules/boost.d.ts index 3f85bb887a..9b62dab1c7 100644 --- a/highcharts/highcharts-modules-boost.d.ts +++ b/highcharts/modules/boost.d.ts @@ -3,10 +3,8 @@ // Definitions by: Daniel Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Static } from "highcharts"; -declare var HighchartsBoost: (H: HighchartsStatic) => HighchartsStatic; - -declare module "highcharts/modules/boost" { - export = HighchartsBoost; -} +declare var HighchartsBoost: (H: Static) => Static; +export = HighchartsBoost; +export as namespace HighchartsBoost; diff --git a/highcharts/modules/exporting-tests.ts b/highcharts/modules/exporting-tests.ts new file mode 100644 index 0000000000..22bced1b24 --- /dev/null +++ b/highcharts/modules/exporting-tests.ts @@ -0,0 +1 @@ +HighchartsExporting(Highcharts); diff --git a/highcharts/highcharts-modules-exporting.d.ts b/highcharts/modules/exporting.d.ts similarity index 53% rename from highcharts/highcharts-modules-exporting.d.ts rename to highcharts/modules/exporting.d.ts index 4d3bdaa648..877ef3d0c1 100644 --- a/highcharts/highcharts-modules-exporting.d.ts +++ b/highcharts/modules/exporting.d.ts @@ -3,10 +3,8 @@ // Definitions by: Maciej Suchecki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Static } from "highcharts"; -declare var HighchartsExporting: (H: HighchartsStatic) => HighchartsStatic; - -declare module "highcharts/modules/exporting" { - export = HighchartsExporting; -} +declare var HighchartsExporting: (H: Static) => Static; +export = HighchartsExporting; +export as namespace HighchartsExporting; diff --git a/highcharts/highcharts-modules-no-data-to-display-tests.ts b/highcharts/modules/no-data-to-display-tests.ts similarity index 57% rename from highcharts/highcharts-modules-no-data-to-display-tests.ts rename to highcharts/modules/no-data-to-display-tests.ts index 6c7b12e105..84392c3bf4 100644 --- a/highcharts/highcharts-modules-no-data-to-display-tests.ts +++ b/highcharts/modules/no-data-to-display-tests.ts @@ -1,7 +1,3 @@ -/// -/// -/// - function test_NoDataToDisplay() { var chart = $("#container").highcharts(); var chartHasData = chart.hasData(); diff --git a/highcharts/modules/no-data-to-display.d.ts b/highcharts/modules/no-data-to-display.d.ts new file mode 100644 index 0000000000..0da068c413 --- /dev/null +++ b/highcharts/modules/no-data-to-display.d.ts @@ -0,0 +1,30 @@ +// Type definitions for Highcharts No Data to Display +// Project: http://www.highcharts.com/ +// Definitions by: Andrey Zolotin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Hc from "highcharts"; + +declare module "highcharts" { + interface ChartObject { + /** + * Returns true if there are data points within the plot area now + * @return {boolean} If chart has any data. + * @since 3.0.8 + */ + hasData(): boolean; + + /** + * Hide the 'No data to display' message added by the no-data-to-display plugin. + * @since 3.0.8 + */ + hideNoData(): void; + + /** + * Display a no-data message. + * @param {String} message An optional message to show in place of the default one + * @since 3.0.8 + */ + showNoData(message?: string): void; + } +} diff --git a/highcharts/modules/offline-exporting-tests.ts b/highcharts/modules/offline-exporting-tests.ts new file mode 100644 index 0000000000..22bced1b24 --- /dev/null +++ b/highcharts/modules/offline-exporting-tests.ts @@ -0,0 +1 @@ +HighchartsExporting(Highcharts); diff --git a/highcharts/highcharts-modules-offline-exporting.d.ts b/highcharts/modules/offline-exporting.d.ts similarity index 51% rename from highcharts/highcharts-modules-offline-exporting.d.ts rename to highcharts/modules/offline-exporting.d.ts index 61c7c76eeb..94ecf53485 100644 --- a/highcharts/highcharts-modules-offline-exporting.d.ts +++ b/highcharts/modules/offline-exporting.d.ts @@ -3,10 +3,8 @@ // Definitions by: Daniel Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import { Static } from "highcharts"; -declare var HighchartsOfflineExporting: (H: HighchartsStatic) => HighchartsStatic; - -declare module "highcharts/modules/offline-exporting" { - export = HighchartsOfflineExporting; -} +declare var HighchartsOfflineExporting: (H: Static) => Static; +export = HighchartsOfflineExporting; +export as namespace HighchartsOfflineExporting; diff --git a/highcharts/tsconfig.json b/highcharts/tsconfig.json index 735490820e..8082640c3b 100644 --- a/highcharts/tsconfig.json +++ b/highcharts/tsconfig.json @@ -14,8 +14,18 @@ }, "files": [ "index.d.ts", - "highstock.d.ts", "highcharts-tests.ts", + "modules/boost.d.ts", + "modules/boost-tests.ts", + "modules/exporting.d.ts", + "modules/exporting-tests.ts", + "modules/no-data-to-display.d.ts", + "modules/no-data-to-display-tests.ts", + "modules/offline-exporting.d.ts", + "modules/offline-exporting-tests.ts", + "highcharts-more.d.ts", + "highcharts-more-tests.ts", + "highstock.d.ts", "highstock-tests.ts" ] } \ No newline at end of file diff --git a/howler/howler-tests.ts b/howler/howler-tests.ts index bdd3a575bd..7b47b73abb 100644 --- a/howler/howler-tests.ts +++ b/howler/howler-tests.ts @@ -1,19 +1,13 @@ -/** - * howler-tests.ts - * Created by xperiments on 02/09/14. - */ - import * as howler from "howler"; -Howler.codecs('ogg'); -Howler.iOSAutoEnable = true; var sound = new Howl({ - urls: ['sound.mp3'] -}).play(); + src: ['sound.mp3'] +}); +sound.play(); var sound = new Howl({ - urls: ['sound.mp3', 'sound.ogg', 'sound.wav'], + src: ['sound.webm', 'sound.mp3', 'sound.wav'], autoplay: true, loop: true, volume: 0.5, @@ -23,7 +17,7 @@ var sound = new Howl({ }); var sound = new Howl({ - urls: ['sounds.mp3', 'sounds.ogg'], + src: ['sounds.webm', 'sounds.mp3'], sprite: { blast: [0, 1000], laser: [2000, 3000], @@ -31,5 +25,32 @@ var sound = new Howl({ } }); -// shoot the laser! +// Shoot the laser! sound.play('laser'); + +var sound = new Howl({ + src: ['sound.webm', 'sound.mp3'] +}); + +// Clear listener after first call. +sound.once('load', function(){ + sound.play(); +}); + +// Fires when the sound finishes playing. +sound.on('end', function(){ + console.log('Finished!'); +}); + +var sound = new Howl({ + src: ['sound.webm', 'sound.mp3'] +}); + +// Play returns a uniqe Sound ID that can be passed +// into any method on Howl to control that specific sound. +var id1 = sound.play(); +var id2 = sound.play(); + +// Fade out the first sound and speed up the second. +sound.fade(1, 0, 1000, id1); +sound.rate(1.5, id2); diff --git a/howler/index.d.ts b/howler/index.d.ts index 9e245a8058..1b6604b1aa 100644 --- a/howler/index.d.ts +++ b/howler/index.d.ts @@ -1,75 +1,107 @@ -// Type definitions for howler.js v1.1.29 +// Type definitions for howler.js v2.0.0 // Project: https://github.com/goldfire/howler.js -// Definitions by: Pedro Casaubon +// Definitions by: Pedro Casaubon , Todd Dukart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare class HowlerGlobal { - mute(): HowlerGlobal; - unmute(): HowlerGlobal; +interface HowlerGlobal { + mute(muted: boolean): void; volume(): number; - volume(volume: number): HowlerGlobal; - codecs(extension: string): boolean; - iOSAutoEnable: boolean; + volume(volume: number): this; + codecs(ext: string): boolean; + unload(): void; + usingWebAudio: boolean; + noAudio: boolean; + mobileAudioEnable: boolean; + autoSuspend: boolean; + ctx: AudioContext; + masterGain: GainNode; } -declare var Howler: HowlerGlobal; +declare let Howler: HowlerGlobal; interface IHowlSoundSpriteDefinition { - [name: string]: number[]; + [name: string]: [number, number]|[number, number, boolean] } -declare type HowlPos3d = [number, number, number]|[number, number, number, number]; - interface IHowlProperties { - autoplay?: boolean; - buffer?: boolean; - duration?: number; - format?: string; - loop?: boolean; - sprite?: IHowlSoundSpriteDefinition; - src?: string; - pos3d?: HowlPos3d; + src: string|string[]; volume?: number; - urls?: string[]; + html5?: boolean; + loop?: boolean; + preload?: boolean; + autoplay?: boolean; + mute?: boolean; + sprite?: IHowlSoundSpriteDefinition; rate?: number; - model?: 'equalpower'|'HRTF'; - onend?: Function; - onload?: Function; - onloaderror?: Function; - onpause?: Function; - onplay?: Function; + pool?: number; + format?: string[] | string; + onload?: () => void; + onloaderror?: (soundId: number, error: any) => void; + onplay?: (soundId: number) => void; + onend?: (soundId: number) => void; + onpause?: (soundId: number) => void; + onstop?: (soundId: number) => void; + onmute?: (soundId: number) => void; + onvolume?: (soundId: number) => void; + onrate?: (soundId: number) => void; + onseek?: (soundId: number) => void; + onfade?: (soundId: number) => void; } interface Howl { - autoplay: Boolean; - buffer: Boolean; - format: string; - rate: number; - model: string; - onend: Function; - onload: Function; - onloaderror: Function; - onpause: Function; - onplay: Function; - load(): Howl; - play(sprite?: string, callback?: (soundId: string) => void): Howl; - play(callback?: (soundId: string) => void): Howl; - pause(soundId?: string): Howl; - stop(soundId?: string): Howl; - mute(soundId?: string): Howl; - unmute(soundId?: string): Howl; - fade(from: number, to: number, duration: number, callback?: Function, soundId?: string): Howl; - loop(): boolean; - loop(loop: boolean): Howl; - pos(position?: number, soundId?: string): number; - pos3d(x: number, y: number, z: number, soundId?: string): any; - sprite(definition?: IHowlSoundSpriteDefinition): IHowlSoundSpriteDefinition; + play(spriteOrId?: string|number): number; // .play() is not chainable; the other methods are + pause(id?: number): this; + stop(id?: number): this; + + mute(): boolean; + mute(muted: boolean, id?: number): this; + volume(): number; - volume(volume?: number, soundId?: string): Howl; - urls(): string[]; - urls(urls: string[]): Howl; - on(event: string, listener?: Function): Howl; - off(event: string, listener?: Function): Howl; + volume(idOrSetVolume: number): this | number; + volume(volume: number, id: number): this; + + fade(from: number, to: number, duration: number, id?: number): this; + + rate(): number; + rate(idOrSetRate: number): this | number; + rate(rate: number, id: number): this; + + seek(seek?: number, id?: number): this; + loop(loop?: boolean, id?: number): this; + playing(id?: number): boolean; + duration(id?: number): number; + + + on(event: 'load', callback: () => void, id?: number): this; + on(event: 'loaderror', callback: (soundId: number, error: any) => void, id?: number): this; + on(event: 'play', callback: (soundId: number) => void, id?: number): this; + on(event: 'end', callback: (soundId: number) => void, id?: number): this; + on(event: 'pause', callback: (soundId: number) => void, id?: number): this; + on(event: 'stop', callback: (soundId: number) => void, id?: number): this; + on(event: 'mute', callback: (soundId: number) => void, id?: number): this; + on(event: 'volume', callback: (soundId: number) => void, id?: number): this; + on(event: 'rate', callback: (soundId: number) => void, id?: number): this; + on(event: 'seek', callback: (soundId: number) => void, id?: number): this; + on(event: 'fade', callback: (soundId: number) => void, id?: number): this; + on(event: string, callback: Function, id?: number): this; + + once(event: 'load', callback: () => void, id?: number): this; + once(event: 'loaderror', callback: (soundId: number, error: any) => void, id?: number): this; + once(event: 'play', callback: (soundId: number) => void, id?: number): this; + once(event: 'end', callback: (soundId: number) => void, id?: number): this; + once(event: 'pause', callback: (soundId: number) => void, id?: number): this; + once(event: 'stop', callback: (soundId: number) => void, id?: number): this; + once(event: 'mute', callback: (soundId: number) => void, id?: number): this; + once(event: 'volume', callback: (soundId: number) => void, id?: number): this; + once(event: 'rate', callback: (soundId: number) => void, id?: number): this; + once(event: 'seek', callback: (soundId: number) => void, id?: number): this; + once(event: 'fade', callback: (soundId: number) => void, id?: number): this; + once(event: string, callback: Function, id?: number): this; + + off(event: string, callback?: Function, id?: number): this; + + state(): 'unloaded' | 'loading' | 'loaded'; + load(): void; unload(): void; } diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index d7440fbc16..d8d3a880dc 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -73,4 +73,11 @@ var err = new createError['404'](); //createError['404'](); // TypeScript should fail with "Did you mean to include 'new'?" //new createError(); // TypeScript should fail with "Only a void function can be called with the 'new' keyword" +// Error messages can have custom messages +var err = new createError.NotFound('This might be a problem'); + +// 1.5.0 supports 421 - Misdirected Request +var err = new createError.MisdirectedRequest(); +var err = new createError.MisdirectedRequest('Where should this go?'); + let error: createError.HttpError; diff --git a/http-errors/index.d.ts b/http-errors/index.d.ts index 199a521b06..7766aa3508 100644 --- a/http-errors/index.d.ts +++ b/http-errors/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for http-errors v1.3.1 +// Type definitions for http-errors v1.5.0 // Project: https://github.com/jshttp/http-errors // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,6 +12,8 @@ declare namespace createHttpError { statusCode: number; expose: boolean; } + + type HttpErrorConstructor = new(msg?: string) => HttpError; interface CreateHttpError { // See https://github.com/Microsoft/TypeScript/issues/227#issuecomment-50092674 @@ -19,68 +21,69 @@ declare namespace createHttpError { (...args: Array): HttpError; - Continue: new () => HttpError; - SwitchingProtocols: new () => HttpError; - Processing: new () => HttpError; - OK: new () => HttpError; - Created: new () => HttpError; - Accepted: new () => HttpError; - NonAuthoritativeInformation: new () => HttpError; - NoContent: new () => HttpError; - ResetContent: new () => HttpError; - PartialContent: new () => HttpError; - MultiStatus: new () => HttpError; - AlreadyReported: new () => HttpError; - IMUsed: new () => HttpError; - MultipleChoices: new () => HttpError; - MovedPermanently: new () => HttpError; - Found: new () => HttpError; - SeeOther: new () => HttpError; - NotModified: new () => HttpError; - UseProxy: new () => HttpError; - Unused: new () => HttpError; - TemporaryRedirect: new () => HttpError; - PermanentRedirect: new () => HttpError; - BadRequest: new () => HttpError; - Unauthorized: new () => HttpError; - PaymentRequired: new () => HttpError; - Forbidden: new () => HttpError; - NotFound: new () => HttpError; - MethodNotAllowed: new () => HttpError; - NotAcceptable: new () => HttpError; - ProxyAuthenticationRequired: new () => HttpError; - RequestTimeout: new () => HttpError; - Conflict: new () => HttpError; - Gone: new () => HttpError; - LengthRequired: new () => HttpError; - PreconditionFailed: new () => HttpError; - PayloadTooLarge: new () => HttpError; - URITooLong: new () => HttpError; - UnsupportedMediaType: new () => HttpError; - RangeNotSatisfiable: new () => HttpError; - ExpectationFailed: new () => HttpError; - ImATeapot: new () => HttpError; - UnprocessableEntity: new () => HttpError; - Locked: new () => HttpError; - FailedDependency: new () => HttpError; - UnorderedCollection: new () => HttpError; - UpgradeRequired: new () => HttpError; - PreconditionRequired: new () => HttpError; - TooManyRequests: new () => HttpError; - RequestHeaderFieldsTooLarge: new () => HttpError; - UnavailableForLegalReasons: new () => HttpError; - InternalServerError: new () => HttpError; - NotImplemented: new () => HttpError; - BadGateway: new () => HttpError; - ServiceUnavailable: new () => HttpError; - GatewayTimeout: new () => HttpError; - HTTPVersionNotSupported: new () => HttpError; - VariantAlsoNegotiates: new () => HttpError; - InsufficientStorage: new () => HttpError; - LoopDetected: new () => HttpError; - BandwidthLimitExceeded: new () => HttpError; - NotExtended: new () => HttpError; - NetworkAuthenticationRequired: new () => HttpError; + Continue: HttpErrorConstructor; + SwitchingProtocols: HttpErrorConstructor; + Processing: HttpErrorConstructor; + OK: HttpErrorConstructor; + Created: HttpErrorConstructor; + Accepted: HttpErrorConstructor; + NonAuthoritativeInformation: HttpErrorConstructor; + NoContent: HttpErrorConstructor; + ResetContent: HttpErrorConstructor; + PartialContent: HttpErrorConstructor; + MultiStatus: HttpErrorConstructor; + AlreadyReported: HttpErrorConstructor; + IMUsed: HttpErrorConstructor; + MultipleChoices: HttpErrorConstructor; + MovedPermanently: HttpErrorConstructor; + Found: HttpErrorConstructor; + SeeOther: HttpErrorConstructor; + NotModified: HttpErrorConstructor; + UseProxy: HttpErrorConstructor; + Unused: HttpErrorConstructor; + TemporaryRedirect: HttpErrorConstructor; + PermanentRedirect: HttpErrorConstructor; + BadRequest: HttpErrorConstructor; + Unauthorized: HttpErrorConstructor; + PaymentRequired: HttpErrorConstructor; + Forbidden: HttpErrorConstructor; + NotFound: HttpErrorConstructor; + MethodNotAllowed: HttpErrorConstructor; + NotAcceptable: HttpErrorConstructor; + ProxyAuthenticationRequired: HttpErrorConstructor; + RequestTimeout: HttpErrorConstructor; + Conflict: HttpErrorConstructor; + Gone: HttpErrorConstructor; + LengthRequired: HttpErrorConstructor; + PreconditionFailed: HttpErrorConstructor; + PayloadTooLarge: HttpErrorConstructor; + URITooLong: HttpErrorConstructor; + UnsupportedMediaType: HttpErrorConstructor; + RangeNotSatisfiable: HttpErrorConstructor; + ExpectationFailed: HttpErrorConstructor; + ImATeapot: HttpErrorConstructor; + MisdirectedRequest: HttpErrorConstructor; + UnprocessableEntity: HttpErrorConstructor; + Locked: HttpErrorConstructor; + FailedDependency: HttpErrorConstructor; + UnorderedCollection: HttpErrorConstructor; + UpgradeRequired: HttpErrorConstructor; + PreconditionRequired: HttpErrorConstructor; + TooManyRequests: HttpErrorConstructor; + RequestHeaderFieldsTooLarge: HttpErrorConstructor; + UnavailableForLegalReasons: HttpErrorConstructor; + InternalServerError: HttpErrorConstructor; + NotImplemented: HttpErrorConstructor; + BadGateway: HttpErrorConstructor; + ServiceUnavailable: HttpErrorConstructor; + GatewayTimeout: HttpErrorConstructor; + HTTPVersionNotSupported: HttpErrorConstructor; + VariantAlsoNegotiates: HttpErrorConstructor; + InsufficientStorage: HttpErrorConstructor; + LoopDetected: HttpErrorConstructor; + BandwidthLimitExceeded: HttpErrorConstructor; + NotExtended: HttpErrorConstructor; + NetworkAuthenticationRequired: HttpErrorConstructor; } } diff --git a/humanparser/humanparser-tests.ts b/humanparser/humanparser-tests.ts new file mode 100644 index 0000000000..0abe741554 --- /dev/null +++ b/humanparser/humanparser-tests.ts @@ -0,0 +1,19 @@ +import human = require('humanparser'); + +let parsedName = human.parseName("Mr. William R. Hearst, III"); +parsedName.firstName; +parsedName.lastName; +parsedName.fullName; +parsedName.suffix; +parsedName.middleName; +parsedName.salutation; + +let parsedAddress = human.parseAddress("123 Happy Street, Honolulu, HI 65780"); +parsedAddress.address; +parsedAddress.state; +parsedAddress.fullAddress; +parsedAddress.zip; +parsedAddress.city; + +let parsedFullName = human.getFullestName("John & Peggy Sue"); +parsedFullName.fullName; diff --git a/humanparser/index.d.ts b/humanparser/index.d.ts new file mode 100644 index 0000000000..37209a60f3 --- /dev/null +++ b/humanparser/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for humanparser 1.1.1 +// Project: https://github.com/chovy/humanparser +// Definitions by: Michał Podeszwa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace humanparser { + interface NameOutput { + firstName: string; + lastName: string; + fullName: string; + suffix?: string; + middleName?: string; + salutation?: string; + } + + interface FullerNameOutput { + fullName: string; + } + + interface AddressOutput { + address: string; + state: string; + fullAddress: string; + zip: string; + city: string; + } + + interface HumanparserStatic { + parseName (name: string): NameOutput; + getFullestName (name: string): FullerNameOutput; + parseAddress (address: string): AddressOutput; + } + +} + +declare const humanparser: humanparser.HumanparserStatic; +export = humanparser; diff --git a/humanparser/tsconfig.json b/humanparser/tsconfig.json new file mode 100644 index 0000000000..17b129eba5 --- /dev/null +++ b/humanparser/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "humanparser-tests.ts" + ] +} diff --git a/i2c-bus/i2c-bus-tests.ts b/i2c-bus/i2c-bus-tests.ts new file mode 100644 index 0000000000..1e4c6c8bcb --- /dev/null +++ b/i2c-bus/i2c-bus-tests.ts @@ -0,0 +1,153 @@ +// Tests for i2c-bus/index.d.ts +// Project: https://github.com/fivdi/i2c-bus +// Definitions by: Jason Heard + +// Tests taken from documentation samples. + +import { I2cBus, open, openSync } from "i2c-bus"; +import * as asnc from "async"; + + +function toCelsius(rawTemp: number): number { + const halfDegrees = ((rawTemp & 0xff) << 1) + (rawTemp >> 15); + + if ((halfDegrees & 0x100) === 0) { + return halfDegrees / 2; // Temp +ve + } + + return -((~halfDegrees & 0xff) / 2); // Temp -ve +} + + +/** + * Example 1 from the i2c-bus README file. + */ +function example1(): void { + const i2c1 = openSync(1); + + const DS1621_ADDR = 0x48, + CMD_ACCESS_CONFIG = 0xac, + CMD_READ_TEMP = 0xaa, + CMD_START_CONVERT = 0xee; + + // Enter one shot mode (this is a non volatile setting) + i2c1.writeByteSync(DS1621_ADDR, CMD_ACCESS_CONFIG, 0x01); + + // Wait while non volatile memory busy + while (i2c1.readByteSync(DS1621_ADDR, CMD_ACCESS_CONFIG) & 0x10) { + } + + // Start temperature conversion + i2c1.sendByteSync(DS1621_ADDR, CMD_START_CONVERT); + + // Wait for temperature conversion to complete + while ((i2c1.readByteSync(DS1621_ADDR, CMD_ACCESS_CONFIG) & 0x80) === 0) { + } + + // Display temperature + const rawTemp = i2c1.readWordSync(DS1621_ADDR, CMD_READ_TEMP); + console.log("temp: " + toCelsius(rawTemp)); + + i2c1.closeSync(); +} + + +/** + * Example 2 from the i2c-bus README file. + */ +function example2(): void { + let i2c1: I2cBus; + + const DS1621_ADDR = 0x48, + CMD_ACCESS_CONFIG = 0xac, + CMD_READ_TEMP = 0xaa, + CMD_START_CONVERT = 0xee; + + async.series([ + cb => { + i2c1 = open(1, cb); + }, + cb => { + // Enter one shot mode (this is a non volatile setting) + i2c1.writeByte(DS1621_ADDR, CMD_ACCESS_CONFIG, 0x01, cb); + }, + cb => { + // Wait while non volatile memory busy + (function read(): void { + i2c1.readByte(DS1621_ADDR, CMD_ACCESS_CONFIG, (err, config) => { + if (err) return cb(err); + if (config & 0x10) return read(); + cb(undefined); + }); + }()); + }, + cb => { + // Start temperature conversion + i2c1.sendByte(DS1621_ADDR, CMD_START_CONVERT, cb); + }, + cb => { + // Wait for temperature conversion to complete + (function read(): void { + i2c1.readByte(DS1621_ADDR, CMD_ACCESS_CONFIG, (err, config) => { + if (err) return cb(err); + if ((config & 0x80) === 0) return read(); + cb(undefined); + }); + }()); + }, + cb => { + // Display temperature + i2c1.readWord(DS1621_ADDR, CMD_READ_TEMP, (err, rawTemp) => { + if (err) return cb(err); + console.log("temp: " + toCelsius(rawTemp)); + cb(undefined); + }); + }, + cb => { + i2c1.close(cb); + } + ], err => { + if (err) throw err; + }); +} + + +/** + * Example 3 from the i2c-bus README file. + */ +function example3(): void { + let i2c1: I2cBus; + + const DS1621_ADDR = 0x48, + DS1621_CMD_ACCESS_TH = 0xa1; + + const TSL2561_ADDR = 0x39, + TSL2561_CMD = 0x80, + TSL2561_REG_ID = 0x0a; + + i2c1 = open(1, err => { + if (err) throw err; + + function readTempHigh(): void { + i2c1.readWord(DS1621_ADDR, DS1621_CMD_ACCESS_TH, (err, tempHigh) => { + if (err) throw err; + console.log("temp: " + tempHigh); + // read another temperature + readTempHigh(); + }); + } + + readTempHigh(); + + function readId(): void { + i2c1.readByte(TSL2561_ADDR, TSL2561_CMD | TSL2561_REG_ID, (err, id) => { + if (err) throw err; + console.log("id: " + id); + // read another ID + readId(); + }); + } + + readId(); + }); +} diff --git a/i2c-bus/index.d.ts b/i2c-bus/index.d.ts new file mode 100644 index 0000000000..e03432b75d --- /dev/null +++ b/i2c-bus/index.d.ts @@ -0,0 +1,396 @@ +// Type definitions for i2c-bus v1.0.0 +// Project: https://github.com/fivdi/i2c-bus +// Definitions by: Jason Heard +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +type CompletionCallback = (error: any) => any; + +type BufferCallback = (error: any, bytesReadOrWritten: number, buffer: Buffer) => any; + +type ResultCallback = (error: any, result: T) => any; + +export interface I2cBusFuncs { + i2c: boolean; + tenBitAddr: boolean; + protocolMangling: boolean; + smbusPec: boolean; + smbusBlockProcCall: boolean; + smbusQuick: boolean; + smbusReceiveByte: boolean; + smbusSendByte: boolean; + smbusReadByte: boolean; + smbusWriteByte: boolean; + smbusReadWord: boolean; + smbusWriteWord: boolean; + smbusProcCall: boolean; + smbusReadBlock: boolean; + smbusWriteBlock: boolean; + smbusReadI2cBlock: boolean; + smbusWriteI2cBlock: boolean; +} + +export interface I2cBus { + + /** + * Asynchronous close. + * + * @param {CompletionCallback} callback + * Completion callback + */ + close(callback: CompletionCallback): void; + + /** + * Synchronous close. + */ + closeSync(): void; + + /** + * Determine functionality of the bus/adapter asynchronously. + * + * @param {ResultCallback} callback + * Callback that will recieve a frozen I2cFuncs object describing the I2C functionality available. + */ + i2cFuncs(callback: ResultCallback): void; + + /** + * Determine functionality of the bus/adapter synchronously. + * + * @return {I2cBusFuncs} + * A frozen I2cFuncs object describing the I2C functionality available. + */ + i2cFuncsSync(): I2cBusFuncs; + + /** + * Scans the I2C bus asynchronously for devices the same way i2cdetect -y -r would. + * + * @param {ResultCallback} callback + * Callback that will recieve an array of numbers where each number represents the I2C address of a device which was detected. + */ + scan(callback: ResultCallback): void; + + /** + * Scans the I2C bus synchronously for devices the same way i2cdetect -y -r would. + * + * @return {number[]} + * An array of numbers where each number represents the I2C address of a device which was detected. + */ + scanSync(): number[]; + + /** + * Asynchronous plain I2C read. + * + * @param {number} address + * I2C device address. + * @param {number} length + * The number of bytes to read. + * @param {Buffer} buffer + * The buffer that the data will be written to (must be at least {length} bytes long). + * @param {BufferCallback} callback + * Callback that will recieve the number of bytes read and the given buffer. + */ + i2cRead(address: number, length: number, buffer: Buffer, callback: BufferCallback): void; + + /** + * Synchronous plain I2C read. + * + * @param {number} address + * I2C device address. + * @param {number} length + * The number of bytes to read. + * @param {Buffer} buffer + * The buffer that the data will be written to (must be at least {length} bytes long). + * @return {number} + * The number of bytes read. + */ + i2cReadSync(address: number, length: number, buffer: Buffer): number; + + /** + * Asynchronous plain I2C write. + * + * @param {number} address + * I2C device address. + * @param {number} length + * The number of bytes to write. + * @param {Buffer} buffer + * The buffer that the data to write (must contain at least {length} bytes). + * @param {BufferCallback} callback + * Callback that will recieve the number of bytes written and the given buffer. + */ + i2cWrite(address: number, length: number, buffer: Buffer, callback: BufferCallback): void; + + /** + * Synchronous plain I2C write. + * + * @param {number} address + * I2C device address. + * @param {number} length + * The number of bytes to write. + * @param {Buffer} buffer + * The buffer that the data will to write (must contain at least {length} bytes). + * @return {number} + * The number of bytes written. + */ + i2cWriteSync(address: number, length: number, buffer: Buffer): number; + + /** + * Asynchronous SMBus read byte. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {ResultCallback} callback + * Callback that will recieve the byte read. + */ + readByte(address: number, command: number, callback: ResultCallback): void; + + /** + * Synchronous SMBus read byte. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @return {number} + * The byte read. + */ + readByteSync(address: number, command: number): number; + + /** + * Asynchronous SMBus read word. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {ResultCallback} callback + * Callback that will recieve the word read. + */ + readWord(address: number, command: number, callback: ResultCallback): void; + + /** + * Synchronous SMBus read word. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @return {number} + * The word read. + */ + readWordSync(address: number, command: number): number; + + /** + * Asynchronous I2C block read (not defined by the SMBus + * specification). Reads a block of bytes from a device, from a + * designated register that is specified by cmd. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {number} length + * The number of bytes to read (max 32). + * @param {Buffer} buffer + * The buffer that the data will be written to (must be at least {length} bytes long). + * @param {BufferCallback} callback + * Callback that will recieve the number of bytes read and the given buffer. + */ + readI2cBlock(address: number, command: number, length: number, buffer: Buffer, callback: BufferCallback): void; + + /** + * Synchronous I2C block read (not defined by the SMBus + * specification). Reads a block of bytes from a device, from a + * designated register that is specified by cmd. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {number} length + * The number of bytes to read (max 32). + * @param {Buffer} buffer + * The buffer that the data will be written to (must be at least {length} bytes long). + * @return {number} + * The number of bytes read. + */ + readI2cBlockSync(address: number, command: number, length: number, buffer: Buffer): number; + + /** + * Asynchronous SMBus receive byte. + * + * @param {number} address + * I2C device address. + * @param {ResultCallback} callback + * Callback that will recieve the byte received. + */ + receiveByte(address: number, callback: ResultCallback): void; + + /** + * Synchronous SMBus receive byte. + * + * @param {number} address + * I2C device address. + * @return {number} + * The byte received. + */ + receiveByteSync(address: number): number; + + /** + * Asynchronous SMBus send byte. + * + * @param {number} address + * I2C device address. + * @param {number} byte + * The data byte to send. + * @param {CompletionCallback} callback + * Completion callback + */ + sendByte(address: number, byte: number, callback: CompletionCallback): void; + + /** + * Synchronous SMBus send byte. + * + * @param {number} address + * I2C device address. + * @param {number} byte + * The data byte to send. + */ + sendByteSync(address: number, byte: number): void; + + /** + * Asynchronous SMBus write byte. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {number} byte + * The data byte to write. + * @param {CompletionCallback} callback + * Completion callback + */ + writeByte(address: number, command: number, byte: number, callback: CompletionCallback): void; + + /** + * Synchronous SMBus write byte. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {number} byte + * The data byte to write. + */ + writeByteSync(address: number, command: number, byte: number): void; + + /** + * Asynchronous SMBus write word. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {number} word + * The data word to write. + * @param {CompletionCallback} callback + * Completion callback + */ + writeWord(address: number, command: number, word: number, callback: CompletionCallback): void; + + /** + * Synchronous SMBus write word. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {number} word + * The data word to write. + */ + writeWordSync(address: number, command: number, word: number): void; + + /** + * Asynchronous SMBus quick command. Writes a single bit to the device. + * + * @param {number} address + * I2C device address. + * @param {number} bit + * The data bit to write (0 or 1). + * @param {CompletionCallback} callback + * Completion callback + */ + writeQuick(address: number, command: number, bit: number, callback: CompletionCallback): void; + + /** + * Synchronous SMBus quick command. Writes a single bit to the device. + * + * @param {number} address + * I2C device address. + * @param {number} bit + * The data bit to write (0 or 1). + */ + writeQuickSync(address: number, command: number, bit: number): void; + + /** + * Asynchronous I2C block write (not defined by the SMBus + * specification). Writes a block of bytes to a device, to a designated + * register that is specified by {command}. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {number} length + * The number of bytes to write (max 32). + * @param {Buffer} buffer + * The buffer that the data to write (must contain at least {length} bytes). + * @param {BufferCallback} callback + * Callback that will recieve the number of bytes written and the given buffer. + */ + writeI2cBlock(address: number, command: number, length: number, buffer: Buffer, callback: BufferCallback): void; + + /** + * Synchronous I2C block write (not defined by the SMBus + * specification). Writes a block of bytes to a device, to a designated + * register that is specified by {command}. + * + * @param {number} address + * I2C device address. + * @param {number} command + * The command code. + * @param {number} length + * The number of bytes to write (max 32). + * @param {Buffer} buffer + * The buffer that the data will to write (must contain at least {length} bytes). + * @return {number} + * The number of bytes written. + */ + writeI2cBlockSync(address: number, command: number, length: number, buffer: Buffer): number; + +} + +/** + * Asynchronous open. + * + * @param {number} busNumber + * The number of the I2C bus/adapter to open, 0 for {/dev/i2c-0}, 1 for {/dev/i2c-1}, etc. + * @param {CompletionCallback} callback + * Completion callback. + * @return {I2cBus} + * A new I2cBus object. + */ +export function open(busNumber: number, calback: CompletionCallback): I2cBus; + +/** + * Synchronous open. + * + * @param {number} busNumber + * The number of the I2C bus/adapter to open, 0 for {/dev/i2c-0}, 1 for {/dev/i2c-1}, etc. + * @return {I2cBus} + * A new I2cBus object. + */ +export function openSync(busNumber: number): I2cBus; diff --git a/i2c-bus/tsconfig.json b/i2c-bus/tsconfig.json new file mode 100644 index 0000000000..174a0be030 --- /dev/null +++ b/i2c-bus/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "../async/index.d.ts", + "index.d.ts", + "i2c-bus-tests.ts" + ] +} diff --git a/ids/tsconfig.json b/ids/tsconfig.json index 822ef6cd32..85fbd7f361 100644 --- a/ids/tsconfig.json +++ b/ids/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "target": "es5", + "target": "es6", "noImplicitAny": true, "strictNullChecks": false, "baseUrl": "../", diff --git a/immutable/index.d.ts b/immutable/index.d.ts index cbc27ab300..9cadb3c29e 100644 --- a/immutable/index.d.ts +++ b/immutable/index.d.ts @@ -260,11 +260,11 @@ declare namespace Immutable { * @see `Map#mergeWith` */ mergeWith( - merger: (previous?: T, next?: T, key?: number) => T, + merger: (previous: T, next: T, key: number) => T, ...iterables: Iterable.Indexed[] ): List; mergeWith( - merger: (previous?: T, next?: T, key?: number) => T, + merger: (previous: T, next: T, key: number) => T, ...iterables: Array[] ): List; @@ -278,11 +278,11 @@ declare namespace Immutable { * @see `Map#mergeDeepWith` */ mergeDeepWith( - merger: (previous?: T, next?: T, key?: number) => T, + merger: (previous: T, next: T, key: number) => T, ...iterables: Iterable.Indexed[] ): List; mergeDeepWith( - merger: (previous?: T, next?: T, key?: number) => T, + merger: (previous: T, next: T, key: number) => T, ...iterables: Array[] ): List; @@ -541,11 +541,11 @@ declare namespace Immutable { * */ mergeWith( - merger: (previous?: V, next?: V, key?: K) => V, + merger: (previous: V, next: V, key: K) => V, ...iterables: Iterable[] ): Map; mergeWith( - merger: (previous?: V, next?: V, key?: K) => V, + merger: (previous: V, next: V, key: K) => V, ...iterables: {[key: string]: V}[] ): Map; @@ -572,11 +572,11 @@ declare namespace Immutable { * */ mergeDeepWith( - merger: (previous?: V, next?: V, key?: K) => V, + merger: (previous: V, next: V, key: K) => V, ...iterables: Iterable[] ): Map; mergeDeepWith( - merger: (previous?: V, next?: V, key?: K) => V, + merger: (previous: V, next: V, key: K) => V, ...iterables: {[key: string]: V}[] ): Map; @@ -1459,7 +1459,7 @@ declare namespace Immutable { * */ mapKeys( - mapper: (key?: K, value?: V, iter?: this) => M, + mapper: (key: K, value: V, iter: this) => M, context?: any ): /*this*/Iterable.Keyed; @@ -1474,9 +1474,9 @@ declare namespace Immutable { */ mapEntries( mapper: ( - entry?: [K, V], - index?: number, - iter?: this + entry: [K, V], + index: number, + iter: this ) => [KM, VM], context?: any ): /*this*/Iterable.Keyed; @@ -1641,7 +1641,7 @@ declare namespace Immutable { * provided predicate function. Otherwise -1 is returned. */ findIndex( - predicate: (value?: T, index?: number, iter?: this) => boolean, + predicate: (value: T, index: number, iter: this) => boolean, context?: any ): number; @@ -1650,7 +1650,7 @@ declare namespace Immutable { * provided predicate function. Otherwise -1 is returned. */ findLastIndex( - predicate: (value?: T, index?: number, iter?: this) => boolean, + predicate: (value: T, index: number, iter: this) => boolean, context?: any ): number; } @@ -1971,7 +1971,7 @@ declare namespace Immutable { * */ map( - mapper: (value?: V, key?: K, iter?: this) => M, + mapper: (value: V, key: K, iter: this) => M, context?: any ): /*this*/Iterable; @@ -1984,7 +1984,7 @@ declare namespace Immutable { * */ filter( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -1997,7 +1997,7 @@ declare namespace Immutable { * */ filterNot( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2033,7 +2033,7 @@ declare namespace Immutable { * */ sortBy( - comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: (valueA: C, valueB: C) => number ): this; @@ -2044,7 +2044,7 @@ declare namespace Immutable { * Note: This is always an eager operation. */ groupBy( - grouper: (value?: V, key?: K, iter?: this) => G, + grouper: (value: V, key: K, iter: this) => G, context?: any ): Seq.Keyed; @@ -2059,7 +2059,7 @@ declare namespace Immutable { * (including the last iteration which returned false). */ forEach( - sideEffect: (value?: V, key?: K, iter?: this) => any, + sideEffect: (value: V, key: K, iter: this) => any, context?: any ): number; @@ -2118,7 +2118,7 @@ declare namespace Immutable { * */ skipWhile( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2132,7 +2132,7 @@ declare namespace Immutable { * */ skipUntil( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2158,7 +2158,7 @@ declare namespace Immutable { * */ takeWhile( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2171,7 +2171,7 @@ declare namespace Immutable { * */ takeUntil( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): this; @@ -2209,11 +2209,11 @@ declare namespace Immutable { * Similar to `iter.map(...).flatten(true)`. */ flatMap( - mapper: (value?: V, key?: K, iter?: this) => Iterable, + mapper: (value: V, key: K, iter: this) => Iterable, context?: any ): /*this*/Iterable; flatMap( - mapper: (value?: V, key?: K, iter?: this) => /*iterable-like*/any, + mapper: (value: V, key: K, iter: this) => /*iterable-like*/any, context?: any ): /*this*/Iterable; @@ -2230,7 +2230,7 @@ declare namespace Immutable { * @see `Array#reduce`. */ reduce( - reducer: (reduction?: R, value?: V, key?: K, iter?: this) => R, + reducer: (reduction: R, value: V, key: K, iter: this) => R, initialReduction?: R, context?: any ): R; @@ -2242,7 +2242,7 @@ declare namespace Immutable { * with `Array#reduceRight`. */ reduceRight( - reducer: (reduction?: R, value?: V, key?: K, iter?: this) => R, + reducer: (reduction: R, value: V, key: K, iter: this) => R, initialReduction?: R, context?: any ): R; @@ -2251,7 +2251,7 @@ declare namespace Immutable { * True if `predicate` returns true for all entries in the Iterable. */ every( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): boolean; @@ -2259,7 +2259,7 @@ declare namespace Immutable { * True if `predicate` returns true for any entry in the Iterable. */ some( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): boolean; @@ -2289,7 +2289,7 @@ declare namespace Immutable { */ count(): number; count( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): number; @@ -2300,7 +2300,7 @@ declare namespace Immutable { * Note: This is not a lazy operation. */ countBy( - grouper: (value?: V, key?: K, iter?: this) => G, + grouper: (value: V, key: K, iter: this) => G, context?: any ): Seq.Keyed; @@ -2311,7 +2311,7 @@ declare namespace Immutable { * Returns the first value for which the `predicate` returns true. */ find( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any, notSetValue?: V ): V; @@ -2322,7 +2322,7 @@ declare namespace Immutable { * Note: `predicate` will be called for each entry in reverse. */ findLast( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any, notSetValue?: V ): V; @@ -2331,7 +2331,7 @@ declare namespace Immutable { * Returns the first [key, value] entry for which the `predicate` returns true. */ findEntry( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any, notSetValue?: V ): [K, V]; @@ -2343,7 +2343,7 @@ declare namespace Immutable { * Note: `predicate` will be called for each entry in reverse. */ findLastEntry( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any, notSetValue?: V ): [K, V]; @@ -2352,7 +2352,7 @@ declare namespace Immutable { * Returns the key for which the `predicate` returns true. */ findKey( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): K; @@ -2362,7 +2362,7 @@ declare namespace Immutable { * Note: `predicate` will be called for each entry in reverse. */ findLastKey( - predicate: (value?: V, key?: K, iter?: this) => boolean, + predicate: (value: V, key: K, iter: this) => boolean, context?: any ): K; @@ -2401,7 +2401,7 @@ declare namespace Immutable { * */ maxBy( - comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: (valueA: C, valueB: C) => number ): V; @@ -2430,7 +2430,7 @@ declare namespace Immutable { * */ minBy( - comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparatorValueMapper: (value: V, key: K, iter: this) => C, comparator?: (valueA: C, valueB: C) => number ): V; diff --git a/inquirer/index.d.ts b/inquirer/index.d.ts index 9ff36e3098..b60dfef00d 100644 --- a/inquirer/index.d.ts +++ b/inquirer/index.d.ts @@ -30,7 +30,8 @@ declare namespace inquirer { * @param cb Callback being passed the user answers * @return */ - prompt(questions: Questions, cb?: (answers: Answers) => any): ui.Prompt; + prompt(questions: Questions, cb: (answers: Answers) => any): ui.Prompt; + prompt(questions: Questions): Promise; prompts: Prompts; Separator: objects.SeparatorStatic; ui: { @@ -110,7 +111,7 @@ declare namespace inquirer { * A key/value hash containing the client answers in each prompt. */ interface Answers { - [key: string]: string | boolean; + [key: string]: any; } namespace ui { diff --git a/inquirer/inquirer-tests.ts b/inquirer/inquirer-tests.ts index 2f2ac7079b..a8610aca8a 100644 --- a/inquirer/inquirer-tests.ts +++ b/inquirer/inquirer-tests.ts @@ -57,7 +57,7 @@ inquirer.prompt([ choices: [ new inquirer.Separator("The usual:"), { - name: "Peperonni" + name: "Pepperoni" }, { name: "Cheese", @@ -202,7 +202,7 @@ inquirer.prompt([ "Make a reservation", new inquirer.Separator(), "Ask opening hours", - "Talk to the receptionnist" + "Talk to the receptionist" ] }, { @@ -356,8 +356,8 @@ var questions2 = [ choices: [ { key: "p", - name: "Peperonni and chesse", - value: "PeperonniChesse" + name: "Pepperoni and cheese", + value: "PepperoniCheese" }, { key: "a", @@ -420,7 +420,7 @@ inquirer.prompt([ "Make a reservation", new inquirer.Separator(), "Ask opening hours", - "Talk to the receptionnist" + "Talk to the receptionist" ] }, { diff --git a/ioredis/index.d.ts b/ioredis/index.d.ts index 714e34cddf..9fa66ad2b6 100644 --- a/ioredis/index.d.ts +++ b/ioredis/index.d.ts @@ -277,6 +277,8 @@ declare module IORedis { sort(...args: any[]): any; info(args: any[], callback?: ResCallbackT): any; info(...args: any[]): any; + time(args: any[], callback?: ResCallbackT): any; + time(...args: any[]): any; monitor(args: any[], callback?: ResCallbackT): any; monitor(...args: any[]): any; ttl(args: any[], callback?: ResCallbackT): any; @@ -562,6 +564,8 @@ declare module IORedis { sort(...args: any[]): Pipeline; info(args: any[], callback?: ResCallbackT): Pipeline; info(...args: any[]): Pipeline; + time(args: any[], callback?: ResCallbackT): Pipeline; + time(...args: any[]): Pipeline; monitor(args: any[], callback?: ResCallbackT): Pipeline; monitor(...args: any[]): Pipeline; ttl(args: any[], callback?: ResCallbackT): Pipeline; diff --git a/jasmine-es6-promise-matchers/jasmine-es6-promise-matchers-tests.ts b/jasmine-es6-promise-matchers/jasmine-es6-promise-matchers-tests.ts index 148725ca29..9d76049de8 100644 --- a/jasmine-es6-promise-matchers/jasmine-es6-promise-matchers-tests.ts +++ b/jasmine-es6-promise-matchers/jasmine-es6-promise-matchers-tests.ts @@ -4,15 +4,15 @@ describe('specs', () => { beforeEach(() => { JasminePromiseMatchers.install }); - + afterEach(() => { JasminePromiseMatchers.uninstall }); - + it('should have correct syntax', (done) => { var foo = {}; var bar = {}; - + expect(foo).toBeResolvedWith(bar, done); expect(foo).toBeRejectedWith(bar, done); expect(foo).toBeResolved(done); diff --git a/jasmine/index.d.ts b/jasmine/index.d.ts index 180b3ef5ba..abf8ed4f82 100644 --- a/jasmine/index.d.ts +++ b/jasmine/index.d.ts @@ -155,6 +155,7 @@ declare namespace jasmine { versionString(): string; nextSpecId(): number; addReporter(reporter: Reporter): void; + addReporter(reporter: CustomReporter): void; execute(): void; describe(description: string, specDefinitions: () => void): Suite; // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these @@ -347,6 +348,45 @@ declare namespace jasmine { addReporter(reporter: Reporter): void; } + interface SuiteInfo { + totalSpecsDefined: number; + } + + interface CustomReportExpectation { + matcherName: string; + message: string; + passed: boolean; + stack: string; + } + + interface FailedExpectation extends CustomReportExpectation { + actual: string; + expected: string; + } + + interface PassedExpectation extends CustomReportExpectation { + + } + + interface CustomReporterResult { + description: string, + failedExpectations?: FailedExpectation[], + fullName: string, + id: string; + passedExpectations?: PassedExpectation[], + pendingReason?: string; + status?: string; + } + + interface CustomReporter { + jasmineStarted?(suiteInfo: SuiteInfo): void; + suiteStarted?(result: CustomReporterResult): void; + specStarted?(result: CustomReporterResult): void; + specDone?(result: CustomReporterResult): void; + suiteDone?(result: CustomReporterResult): void; + jasmineDone?(): any; + } + interface Runner { new (env: Env): any; diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index ca2b2808cc..87497e90c2 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -902,6 +902,62 @@ describe("Custom matcher: 'toBeGoofy'", function () { }); }); +// test based on http://jasmine.github.io/2.5/custom_reporter.html +var myReporter: jasmine.CustomReporter = { + jasmineStarted: function (suiteInfo: jasmine.SuiteInfo ) { + console.log("Running suite with " + suiteInfo.totalSpecsDefined); + }, + + suiteStarted: function (result: jasmine.CustomReporterResult) { + console.log("Suite started: " + result.description + " whose full description is: " + result.fullName); + }, + + specStarted: function (result: jasmine.CustomReporterResult) { + console.log("Spec started: " + result.description + " whose full description is: " + result.fullName); + }, + + specDone: function (result: jasmine.CustomReporterResult) { + console.log("Spec: " + result.description + " was " + result.status); + for (var i = 0; i < result.failedExpectations.length; i++) { + console.log("Failure: " + result.failedExpectations[i].message); + console.log("Actual: " + result.failedExpectations[i].actual); + console.log("Expected: " + result.failedExpectations[i].expected); + console.log(result.failedExpectations[i].stack); + } + console.log(result.passedExpectations.length); + }, + + suiteDone: function (result: jasmine.CustomReporterResult) { + console.log('Suite: ' + result.description + ' was ' + result.status); + for (var i = 0; i < result.failedExpectations.length; i++) { + console.log('AfterAll ' + result.failedExpectations[i].message); + console.log(result.failedExpectations[i].stack); + } + }, + + jasmineDone: function() { + console.log('Finished suite'); + } +}; + +jasmine.getEnv().addReporter(myReporter); + +// test for custom reporter which return ES6 Promise in jasmineDone(): +var myShortReporter: jasmine.CustomReporter = { + jasmineDone: function() { + return new Promise(function(resolve, reject) { + setTimeout(() => resolve(), 10000); + }); + } +} + +var jasmineDoneResolved: Promise = myShortReporter.jasmineDone(); +jasmineDoneResolved.then(() => { + console.log("[ShortReporter] : jasmineDone Resolved"); +}); + +jasmine.getEnv().addReporter(myShortReporter); + describe("Randomize Tests", function() { it("should allow randomization of the order of tests", function() { expect(function() { diff --git a/jdenticon/index.d.ts b/jdenticon/index.d.ts new file mode 100644 index 0000000000..87d8609551 --- /dev/null +++ b/jdenticon/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for Jdenticon 1.3.2 +// Project: http://jdenticon.com/ +// Definitions by: Martin Thorsen Ranang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface JdenticonConfig { + lightness?: { + color?: number[]; + grayscale?: number[]; + }; + saturation?: number; +} + +export var jdenticon_config: JdenticonConfig; + +export namespace jdenticon { + export function drawIcon(ctx: CanvasRenderingContext2D, hash: string, size: number): void; + + export function toSvg(hash: string, size: number, padding?: number): string; + + export function update(el: Element|string, hash?: string, padding?: number): void; + + export let config: JdenticonConfig; + + export const version: string; +} diff --git a/jdenticon/jdenticon-tests.ts b/jdenticon/jdenticon-tests.ts new file mode 100644 index 0000000000..b26a01696b --- /dev/null +++ b/jdenticon/jdenticon-tests.ts @@ -0,0 +1,11 @@ +import {jdenticon} from "jdenticon"; + +function testJdenticon() { + if (typeof jdenticon.version !== 'string') { + throw '.version should be of string type.'; + } + + jdenticon.update('#jdenticon', 'd6d7705392bc7af633328bea8c4c6904', 8); +} + +testJdenticon(); diff --git a/jdenticon/tsconfig.json b/jdenticon/tsconfig.json new file mode 100644 index 0000000000..50e496b1a1 --- /dev/null +++ b/jdenticon/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jdenticon-tests.ts" + ] +} diff --git a/jest/index.d.ts b/jest/index.d.ts index d0660193f6..dc0260cebb 100644 --- a/jest/index.d.ts +++ b/jest/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Jest 15.1.1 +// Type definitions for Jest 16.0.0 // Project: http://facebook.github.io/jest/ // Definitions by: Asana , Ivo Stratev , jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,23 +26,25 @@ interface NodeRequire { } declare namespace jest { - function addMatchers(matchers: jasmine.CustomMatcherFactories): void; + function addMatchers(matchers: jasmine.CustomMatcherFactories): typeof jest; /** Disables automatic mocking in the module loader. */ - function autoMockOff(): void; + function autoMockOff(): typeof jest; /** Enables automatic mocking in the module loader. */ - function autoMockOn(): void; + function autoMockOn(): typeof jest; + /** Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function. */ + function clearAllMocks(): typeof jest; /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */ - function clearAllTimers(): void; + function clearAllTimers(): typeof jest; /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ - function deepUnmock(moduleName: string): void; + function deepUnmock(moduleName: string): typeof jest; /** Disables automatic mocking in the module loader. */ - function disableAutomock(): void; + function disableAutomock(): typeof jest; /** Mocks a module with an auto-mocked version when it is being required. */ - function doMock(moduleName: string): void; + function doMock(moduleName: string): typeof jest; /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ - function dontMock(moduleName: string): void; + function dontMock(moduleName: string): typeof jest; /** Enables automatic mocking in the module loader. */ - function enableAutomock(): void; + function enableAutomock(): typeof jest; /** Creates a mock function. Optionally takes a mock implementation. */ function fn(implementation?: Function): Mock; /** Use the automatic mocking system to generate a mocked version of the given module. */ @@ -50,28 +52,30 @@ declare namespace jest { /** Returns whether the given function is a mock function. */ function isMockFunction(fn: any): fn is Mock; /** Mocks a module with an auto-mocked version when it is being required. */ - function mock(moduleName: string, factory?: any, options?: MockOptions): void; + function mock(moduleName: string, factory?: any, options?: MockOptions): typeof jest; /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ - function resetModuleRegistry(): void; + function resetModuleRegistry(): typeof jest; /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ - function resetModules(): void; + function resetModules(): typeof jest; /** Exhausts tasks queued by setImmediate(). */ - function runAllImmediates(): void; + function runAllImmediates(): typeof jest; /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */ - function runAllTicks(): void; + function runAllTicks(): typeof jest; /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */ - function runAllTimers(): void; + function runAllTimers(): typeof jest; /** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). * If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */ - function runOnlyPendingTimers(): void; + function runOnlyPendingTimers(): typeof jest; + /** Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). */ + function runTimersToTime(msToRun: number): typeof jest; /** Explicitly supplies the mock object that the module system should return for the specified module. */ - function setMock(moduleName: string, moduleExports: T): void; + function setMock(moduleName: string, moduleExports: T): typeof jest; /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ - function unmock(moduleName: string): void; + function unmock(moduleName: string): typeof jest; /** Instructs Jest to use fake versions of the standard timer functions. */ - function useFakeTimers(): void; + function useFakeTimers(): typeof jest; /** Instructs Jest to use the real versions of the standard timer functions. */ - function useRealTimers(): void; + function useRealTimers(): typeof jest; interface MockOptions { virtual?: boolean; @@ -98,6 +102,7 @@ declare namespace jest { (name: string, fn: ProvidesCallback): void; only: It; skip: It; + concurrent: It; } interface Describe { @@ -124,6 +129,7 @@ declare namespace jest { toBeTruthy(): void; toBeUndefined(): void; toContain(expected: any): void; + toContainEqual(expected: any): void; toEqual(expected: any): void; toHaveBeenCalled(): boolean; toHaveBeenCalledTimes(expected: number): boolean; @@ -132,6 +138,7 @@ declare namespace jest { toMatchSnapshot(): void; toThrow(): void; toThrowError(error?: string | Constructable | RegExp): void; + toThrowErrorMatchingSnapshot(): void; } interface Constructable { diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index e774ad1fb5..4b81f6282c 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -208,6 +208,8 @@ describe('missing tests', function () { expect(getFruits()).toContain('Orange'); mock.mockReturnValueOnce(['Apple', 'Plum']); expect(mock()).not.toContain('Orange'); + const myBeverage: any = {delicious: true, sour: false}; + expect(myBeverage).toContainEqual({delicious: true, sour: false}); mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. mock.mockClear(); let thisMock: jest.Mock = jest.fn().mockReturnThis(); @@ -215,8 +217,7 @@ describe('missing tests', function () { }); it('creates snapshoter', function () { - jest.disableAutomock(); - jest.mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); + jest.disableAutomock().mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); const render: () => string = require('./render'); expect(render()).toMatch(/Link/); jest.enableAutomock(); @@ -225,7 +226,7 @@ describe('missing tests', function () { it('runs only pending timers', function () { jest.useRealTimers(); setTimeout(() => expect(1).not.toEqual(0), 3000); - jest.runOnlyPendingTimers(); + jest.runOnlyPendingTimers().runTimersToTime(300); }); it('runs all timers', function () { @@ -249,6 +250,12 @@ describe('toMatchSnapshot', function () { }); }); +describe('toThrowErrorMatchingSnapshot', function () { + it('compares snapshots', function () { + expect(() => { throw new Error('descriptiton') }).toThrowErrorMatchingSnapshot(); + }); +}); + function testInstances() { var mockFn = jest.fn(); var a = new mockFn(); diff --git a/joi/index.d.ts b/joi/index.d.ts index ece6bb6d62..2f803cdf7d 100644 --- a/joi/index.d.ts +++ b/joi/index.d.ts @@ -40,6 +40,10 @@ export interface ValidationOptions { * provides an external data set to be used in references */ context?: Object; + /** + * when true, do not apply default values. Defaults to false. + */ + noDefaults?: boolean; } export interface RenameOptions { @@ -121,10 +125,10 @@ export interface IPOptions { } export interface ValidationError extends Error { - message: string; + isJoi: boolean; details: ValidationErrorItem[]; - simple(): string; - annotated(): string; + annotate(): string; + _object: any; } export interface ValidationErrorItem { @@ -132,6 +136,7 @@ export interface ValidationErrorItem { type: string; path: string; options?: ValidationOptions; + context?: any; } export interface ValidationResult { @@ -287,6 +292,16 @@ export interface AnySchema> { * @param schema - any object or joi schema to match. An undefined schema unsets that rule. */ empty(schema?: any): T; + /** + * Overrides the default joi error with a custom error if the rule fails where: + * @param err - the override error. + * + * Note that the provided error will be returned as-is, unmodified and undecorated + * with any of the normal joi error properties. If validation fails and another + * error is found before the error override, that error will be returned and the + * override will be ignored (unless the abortEarly option has been set to false). + */ + error?(err: Error): T; } export interface BooleanSchema extends AnySchema { @@ -827,10 +842,18 @@ export declare function lazy(cb: () => Schema): Schema; /** * Validates a value using the given schema and options. */ -export declare function validate(value: T, schema: Schema, callback: (err: ValidationError, value: T) => void): void; -export declare function validate(value: T, schema: Object, callback: (err: ValidationError, value: T) => void): void; -export declare function validate(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): ValidationResult; +export function validate(value: T): ValidationResult; +export function validate(value: T, callback: (err: ValidationError, value: T) => R): R; +export function validate(value: T, schema: Schema): ValidationResult; +export function validate(value: T, schema: Object): ValidationResult; +export function validate(value: T, schema: Schema, callback: (err: ValidationError, value: T) => R): R; +export function validate(value: T, schema: Object, callback: (err: ValidationError, value: T) => R): R; + +export function validate(value: T, schema: Schema, options: ValidationOptions): ValidationResult; +export function validate(value: T, schema: Object, options: ValidationOptions): ValidationResult; +export function validate(value: T, schema: Schema, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; +export function validate(value: T, schema: Object, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; /** * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). */ @@ -878,3 +901,118 @@ export function reach(schema: Schema, path: string): Schema; * Creates a new Joi instance customized with the extension(s) you provide included. */ export function extend(extention: Extension): any; + +/** + * Whitelists a value + */ +export function allow(value: any, ...values: any[]): Schema; +export function allow(values: any[]): Schema; + +/** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ +export function valid(value: any, ...values: any[]): Schema; +export function valid(values: any[]): Schema; +export function only(value: any, ...values : any[]): Schema; +export function only(values: any[]): Schema; +export function equal(value: any, ...values : any[]): Schema; +export function equal(values: any[]): Schema; + +/** + * Blacklists a value + */ +export function invalid(value: any, ...values: any[]): Schema; +export function invalid(values: any[]): Schema; +export function disallow(value: any, ...values : any[]): Schema; +export function disallow(values: any[]): Schema; +export function not(value: any, ...values : any[]): Schema; +export function not(values: any[]): Schema; + +/** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ +export function required(): Schema; + +/** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ +export function optional(): Schema; + +/** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ +export function forbidden(): Schema; + +/** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ +export function strip(): Schema; + +/** + * Annotates the key + */ +export function description(desc: string): Schema; + +/** + * Annotates the key + */ +export function notes(notes: string): Schema; +export function notes(notes: string[]): Schema; + +/** + * Annotates the key + */ +export function tags(notes: string): Schema; +export function tags(notes: string[]): Schema; + +/** + * Attaches metadata to the key. + */ +export function meta(meta: Object): Schema; + +/** + * Annotates the key with an example value, must be valid. + */ +export function example(value: any): Schema; + +/** + * Annotates the key with an unit name. + */ +export function unit(name: string): Schema; + +/** + * Overrides the global validate() options for the current key and any sub-key. + */ +export function options(options: ValidationOptions): Schema; + +/** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ +export function strict(isStrict?: boolean): Schema; + +/** + * Returns a new type that is the result of adding the rules of one type to another. + */ +export function concat(schema: T): T; + +/** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ +export function when(ref: string, options: WhenOptions): AlternativesSchema; +export function when(ref: Reference, options: WhenOptions): AlternativesSchema; + +/** + * Overrides the key name in error messages. + */ +export function label(name: string): Schema; + +/** + * Outputs the original untouched value instead of the casted value. + */ +export function raw(isRaw?: boolean): Schema; + +/** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ +export function empty(schema?: any) : Schema; diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index eb0f147f78..d50db6eedd 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -58,6 +58,7 @@ validOpts = {stripUnknown: bool}; validOpts = {language: bool}; validOpts = {presence: str}; validOpts = {context: obj}; +validOpts = {noDefaults: bool}; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -125,7 +126,8 @@ validErrItem = { message: str, type: str, path: str, - options: validOpts + options: validOpts, + context: obj }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -221,6 +223,8 @@ namespace common { anySchema = anySchema.empty(); anySchema = anySchema.empty(str); anySchema = anySchema.empty(anySchema); + + anySchema = anySchema.error(err); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -756,30 +760,57 @@ schema = Joi.lazy(() => schema) // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- -Joi.validate(value, obj); -Joi.validate(value, schema); -Joi.validate(value, schema, validOpts); -Joi.validate(value, schema, validOpts, (err, value) => { +namespace validate_tests { + { + Joi.validate(value, obj); + Joi.validate(value, schema); + Joi.validate(value, schema, validOpts); + Joi.validate(value, schema, validOpts, (err, value) => { x = value; str = err.message; str = err.details[0].path; str = err.details[0].message; str = err.details[0].type; -}); -Joi.validate(value, schema, (err, value) => { + }); + Joi.validate(value, schema, (err, value) => { x = value; str = err.message; str = err.details[0].path; str = err.details[0].message; str = err.details[0].type; -}); -// variant -Joi.validate(num, schema, validOpts, (err, value) => { + }); + // variant + Joi.validate(num, schema, validOpts, (err, value) => { num = value; -}); + }); + + // plain opts + Joi.validate(value, {}); + } + + { + let value = { username: 'example', password: 'example' }; + let schema = Joi.object().keys({ + username: Joi.string().max(255).required(), + password: Joi.string().regex(/^[a-zA-Z0-9]{3,255}$/).required(), + }); + let returnValue: Joi.ValidationResult; + + returnValue = Joi.validate(value); + value = Joi.validate(value, (err, value) => value); + + returnValue = Joi.validate(value, schema); + returnValue = Joi.validate(value, obj); + value = Joi.validate(value, obj, (err, value) => value); + value = Joi.validate(value, schema, (err, value) => value); + + returnValue = Joi.validate(value, schema, validOpts); + returnValue = Joi.validate(value, obj, validOpts); + value = Joi.validate(value, obj, validOpts, (err, value) => value); + value = Joi.validate(value, schema, validOpts, (err, value) => value); + } +} -// plain opts -Joi.validate(value, {}); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -801,3 +832,56 @@ Joi.isRef(ref); schema = Joi.reach(schema, ''); const Joi2 = Joi.extend({ name: '', base: schema }); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.allow(x, x); +schema = Joi.allow([x, x, x]); +schema = Joi.valid(x); +schema = Joi.valid(x, x); +schema = Joi.valid([x, x, x]); +schema = Joi.only(x); +schema = Joi.only(x, x); +schema = Joi.only([x, x, x]); +schema = Joi.equal(x); +schema = Joi.equal(x, x); +schema = Joi.equal([x, x, x]); +schema = Joi.invalid(x); +schema = Joi.invalid(x, x); +schema = Joi.invalid([x, x, x]); +schema = Joi.disallow(x); +schema = Joi.disallow(x, x); +schema = Joi.disallow([x, x, x]); +schema = Joi.not(x); +schema = Joi.not(x, x); +schema = Joi.not([x, x, x]); + +schema = Joi.required(); +schema = Joi.optional(); +schema = Joi.forbidden(); +schema = Joi.strip(); + +schema = Joi.description(str); +schema = Joi.notes(str); +schema = Joi.notes(strArr); +schema = Joi.tags(str); +schema = Joi.tags(strArr); + +schema = Joi.meta(obj); +schema = Joi.example(obj); +schema = Joi.unit(str); + +schema = Joi.options(validOpts); +schema = Joi.strict(); +schema = Joi.strict(bool); +schema = Joi.concat(x); + +schema = Joi.when(str, whenOpts); +schema = Joi.when(ref, whenOpts); + +schema = Joi.label(str); +schema = Joi.raw(); +schema = Joi.raw(bool); +schema = Joi.empty(); +schema = Joi.empty(str); +schema = Joi.empty(anySchema); diff --git a/jointjs/index.d.ts b/jointjs/index.d.ts index 9af669fdea..aec9f1237d 100644 --- a/jointjs/index.d.ts +++ b/jointjs/index.d.ts @@ -1,135 +1,559 @@ -// Type definitions for Joint JS 0.9.3 +// Type definitions for Joint JS 1.0.1 // Project: http://www.jointjs.com/ -// Definitions by: Aidan Reel , David Durman , Ewout Van Gossum +// Definitions by: Aidan Reel , David Durman , Ewout Van Gossum , Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// typings: https://github.com/CaselIT/typings-jointjs /// + declare namespace joint { + export var g: any; + export var V: any; namespace dia { - - interface IElementSize { + interface Size { width: number; height: number; } + interface Point { + x: number; + y: number; + } + + interface BBox extends Point, Size { } + + interface TranslateOptions { + restrictedArea?: BBox; + transition?: TransitionOptions; + } + + interface TransitionOptions { + delay?: number; + duration?: number; + timingFunction?: (t: number) => number; + valueFunction?: (a: any, b: any) => (t: number) => any; + } + + interface DfsBfsOptions { + inbound?: boolean; + outbound?: boolean; + deep?: boolean; + } + + interface ExploreOptions { + breadthFirst?: boolean; + deep?: boolean; + } + class Graph extends Backbone.Model { - addCell(cell:Cell) : void; - addCells(cells:Cell[]) : void; - initialize() : void; - fromJSON(json:any) : void; - toJSON() : Object; - clear() : void; - getConnectedLinks(cell:Cell, opt?:any):Link[]; - disconnectLinks(cell:Cell) : void; - removeLinks(cell:Cell) : void; - findModelsFromPoint(point:{x : number; y: number}):Element[]; + constructor(attributes?: any, options?: { cellNamespace: any }); + addCell(cell: Cell | Cell[]): this; + addCells(cells: Cell[]): this; + resetCells(cells: Cell[], options?: any): this; + getCell(id: string): Cell; + getElements(): Element[]; + getLinks(): Link[]; + getCells(): Cell[]; + getFirstCell(): Cell; + getLastCell(): Cell; + getConnectedLinks(element: Cell, options?: { inbound?: boolean, outbound?: boolean, deep?: boolean }): Link[]; + disconnectLinks(cell: Cell, options?: any): void; + removeLinks(cell: Cell, options?: any): void; + translate(tx: number, ty?: number, options?: TranslateOptions): void; + cloneCells(cells: Cell[]): { [id: string]: Cell }; + getSubgraph(cells: Cell[], options?: { deep?: boolean }): Cell[]; + cloneSubgraph(cells: Cell[], options?: { deep?: boolean }): { [id: string]: Cell }; + dfs(element: Element, iteratee: (element: Element, distance: number) => boolean, options?: DfsBfsOptions, visited?: Object, distance?: number): void; + bfs(element: Element, iteratee: (element: Element, distance: number) => boolean, options?: DfsBfsOptions): void; + search(element: Element, iteratee: (element: Element, distance: number) => boolean, options?: { breadthFirst?: boolean }): void; + getSuccessors(element: Element, options?: ExploreOptions): Element[]; + getPredecessors(element: Element, options?: ExploreOptions): Element[]; + isSuccessor(elementA: Element, elementB: Element): boolean; + isPredecessor(elementA: Element, elementB: Element): boolean; + isSource(element: Element): boolean; + isSink(element: Element): boolean; + getSources(): Element[]; + getSinks(): Element[]; + getNeighbors(element: Element, options?: DfsBfsOptions): Element[]; + isNeighbor(elementA: Element, elementB: Element, options?: { inbound?: boolean, outbound?: boolean; }): boolean; + getCommonAncestor(...cells: Cell[]): Element; + toJSON(): any; + fromJSON(json: any, options?: any): this; + clear(options?: any): this; + findModelsFromPoint(rect: BBox): Element[]; + findModelsUnderElement(element: Element, options?: { searchBy?: 'bbox' | 'center' | 'origin' | 'corner' | 'topRight' | 'bottomLeft' }): Element[]; + getBBox(elements: Element[], options?: any): BBox; + toGraphLib(): any; // graphlib graph object + findModelsInArea(rect: BBox, options?: any): BBox | boolean; + getCellsBBox(cells: Cell[], options?: any): BBox; + getInboundEdges(node: string): Object; + getOutboundEdges(node: string): Object; + hasActiveBatch(name?: string): number | boolean; + maxZIndex(): number; + removeCells(cells: Cell[], options?: any): this; + resize(width: number, height: number, options?: number): this; + resizeCells(width: number, height: number, cells: Cell[], options?: number): this; + set(key: Object | string, value: any, options?: any): this; + startBatch(name: string, data?: Object): any; + stopBatch(name: string, data?: Object): any; } class Cell extends Backbone.Model { - toJSON() : Object; - remove(options?:any) : void; - toFront() : void; - toBack() : void; - embed(cell:Cell) : void; - unembed(cell:Cell) : void; - getEmbeddedCells():Cell[]; - clone(opt?:any):Backbone.Model; // @todo: return can either be Cell or Cell[]. - attr(attrs:any):Cell; + id: string; + toJSON(): any; + remove(options?: { disconnectLinks?: boolean }): this; + toFront(options?: { deep?: boolean }): this; + toBack(options?: { deep?: boolean }): this; + getAncestors(): Cell[]; + isEmbeddedIn(element: Element, options?: { deep: boolean }): boolean; + prop(key: string): any; + prop(object: any): this; + prop(key: string, value: any, options?: any): this; + removeProp(path: string, options?: any): this; + attr(key: string): any; + attr(object: SVGAttributes): this; + attr(key: string, value: any): this; + clone(): Cell; + clone(opt: { deep?: boolean }): Cell | Cell[]; + removeAttr(path: string | string[], options?: any): this; + transition(path: string, value?: any, options?: TransitionOptions, delim?: string): number; + getTransitions(): string[]; + stopTransitions(path?: string, delim?: string): this; + addTo(graph: Graph, options?: any): this; + isLink(): boolean; + embed(cell: Cell, options?: any): this; + findView(paper: Paper): CellView; + getEmbeddedCells(options?: any): Cell[]; + initialize(options?: any): void; + isElement(): boolean; + isEmbedded(): boolean; + processPorts(): void; + startBatch(name: string, options?: any): this; + stopBatch(name: string, options?: any): this; + unembed(cell: Cell, options?: any): this; } + type Padding = number | { + top?: number; + right?: number; + bottom?: number; + left?: number + }; + class Element extends Cell { - position(x:number, y:number):Element; - position(): {x:number, y:number}; - translate(tx:number, ty?:number):Element; - resize(width:number, height:number):Element; - rotate(angle:number, options : {absolute : boolean; origin: {x:number;y:number}}):Element; - remove(): void; + translate(tx: number, ty?: number, options?: TranslateOptions): this; + position(options?: { parentRelative: boolean }): Point; + position(x: number, y: number, options?: { parentRelative?: boolean }): this; + resize(width: number, height: number, options?: { direction?: 'left' | 'right' | 'top' | 'bottom' | 'top-right' | 'top-left' | 'bottom-left' | 'bottom-right' }): this; + rotate(deg: number, absolute?: boolean, origin?: Point): this; + embed(cell: Cell): this; + unembed(cell: Cell): this; + getEmbeddedCells(options?: ExploreOptions): Cell[]; + fitEmbeds(options?: { deep?: boolean, padding?: Padding }): this; + getBBox(options?: any): BBox; + findView(paper: Paper): ElementView; + isElement(): boolean; + scale(scaleX: number, scaleY: number, origin?: Point, options?: any): this; } - interface IDefaults { - type: string; + interface CSSSelector { + [key: string]: string | number | Object; // Object added to support special attributes like filter http://jointjs.com/api#SpecialAttributes:filter + } + + interface SVGAttributes { + [selector: string]: CSSSelector; + } + + interface CellAttributes { + [key: string]: any; + } + + interface TextAttrs extends SVGAttributes { + text?: { + [key: string]: string | number; + text?: string; + }; + } + + interface Label { + position: number; + attrs?: TextAttrs; + } + interface LinkAttributes extends CellAttributes { + source?: Point | { id: string, selector?: string, port?: string }; + target?: Point | { id: string, selector?: string, port?: string }; + labels?: Label[]; + vertices?: Point[]; + smooth?: boolean; + attrs?: TextAttrs; } class Link extends Cell { - defaults():IDefaults; - disconnect():Link; - label(idx?:number, value?:any):any; // @todo: returns either a label under idx or Link if both idx and value were passed - remove(): void; + markup: string; + labelMarkup: string; + toolMakup: string; + vertexMarkup: string; + arrowHeadMarkup: string; + + constructor(attributes?: LinkAttributes, options?: Object); + disconnect(): this; + label(index?: number): any; + label(index: number, value: Label): this; + reparent(options?: any): Element; + findView(paper: Paper): LinkView; + getSourceElement(): Element; + getTargetElement(): Element; + hasLoop(options?: { deep?: boolean }): boolean; + applyToPoints(fn: Function, options?: any): this; + getRelationshipAncestor(): Element; + isLink(): boolean; + isRelationshipEmbeddedIn(element: Element): boolean; + scale(sx: number, sy: number, origin: Point, optionts?: any): this; + translate(tx: number, ty: number, options?: any): this; } - interface IOptions { + interface ManhattanRouterArgs { + excludeTypes?: string[]; + excludeEnds?: 'source' | 'target'; + startDirections?: ['left' | 'right' | 'top' | 'bottom']; + endDirections?: ['left' | 'right' | 'top' | 'bottom']; + } + + interface PaperOptions extends Backbone.ViewOptions { + el?: string | JQuery | HTMLElement; width?: number; height?: number; + origin?: Point; gridSize?: number; perpendicularLinks?: boolean; - elementView?: ElementView; - linkView?: LinkView; + elementView?: (element: Element) => ElementView | ElementView; + linkView?: (link: Link) => LinkView | LinkView; + defaultLink?: ((cellView: CellView, magnet: SVGElement) => Link) | Link; + defaultRouter?: ((vertices: Point[], args: Object, linkView: LinkView) => Point[]) | { name: string, args?: ManhattanRouterArgs }; + defaultConnector?: ((sourcePoint: Point, targetPoint: Point, vertices: Point[], args: Object, linkView: LinkView) => string) | { name: string, args?: { radius?: number } }; + interactive?: ((cellView: CellView, event: string) => boolean) | boolean | { vertexAdd?: boolean, vertexMove?: boolean, vertexRemove?: boolean, arrowheadMove?: boolean }; + validateMagnet?: (cellView: CellView, magnet: SVGElement) => boolean; + validateConnection?: (cellViewS: CellView, magnetS: SVGElement, cellViewT: CellView, magnetT: SVGElement, end: 'source' | 'target', linkView: LinkView) => boolean; + linkConnectionPoint?: (linkView: LinkView, view: ElementView, magnet: SVGElement, reference: Point) => Point; + snapLinks?: boolean | { radius: number }; + linkPinning?: boolean; + markAvailable?: boolean; + async?: boolean | { batchZise: number }; + embeddingMode?: boolean; + validateEmbedding?: (childView: ElementView, parentView: ElementView) => boolean; + restrictTranslate?: ((elementView: ElementView) => BBox) | boolean; + guard?: (evt: Event, view: CellView) => boolean; + multiLinks?: boolean; + cellViewNamespace?: Object; + /** useful undocumented option */ + clickThreshold?: number; } - class Paper extends Backbone.View { - options:IOptions; - - setDimensions(width:number, height:number) : void; - scale(sx:number, sy?:number, ox?:number, oy?:number):Paper; - rotate(deg:number, ox?:number, oy?:number):Paper; // @todo not released yet though it's in the source code already - findView(el:any):CellView; - findViewByModel(modelOrId:any):CellView; - findViewsFromPoint(p:{ x: number; y: number; }):CellView[]; - findViewsInArea(r:{ x: number; y: number; width: number; height: number; }):CellView[]; - fitToContent(opt?:any): void; + interface ScaleContentOptions { + padding?: number; + preserveAspectRatio?: boolean; + minScale?: number; + minScaleX?: number; + minScaleY?: number; + maxScale?: number; + maxScaleX?: number; + maxScaleY?: number; + scaleGrid?: number; + fittingBBox?: BBox; } - class ElementView extends CellView { - scale(sx:number, sy:number) : void; + interface FitToContentOptions { + gridWidth?: number; + gridHeight?: number; + padding?: Padding; + allowNewOrigin?: 'negative' | 'positive' | 'any'; + minWidth?: number; + minHeight?: number; + maxWidth?: number; + maxHeight?: number; } - class CellView extends Backbone.View { - getBBox():{ x: number; y: number; width: number; height: number; }; - highlight(el?:any): void; - unhighlight(el?:any): void; - findMagnet(el:any): void; - getSelector(el:any): void; + class Paper extends Backbone.View { + constructor(options?: PaperOptions); + options: PaperOptions; + svg: SVGElement; + viewport: SVGGElement; + defs: SVGDefsElement; + setDimensions(width: number, height: number): void; + setOrigin(x: number, y: number): void; + scale(sx: number, sy?: number, ox?: number, oy?: number): this; + findView(element: any): CellView; + findViewByModel(model: Cell | string): CellView; + findViewsFromPoint(point: Point): ElementView[]; + findViewsInArea(rect: BBox, options?: { strict?: boolean }): CellView[]; + fitToContent(options?: FitToContentOptions): void; + scaleContentToFit(options?: ScaleContentOptions): void; + getContentBBox(): BBox; + clientToLocalPoint(p: Point): Point; - pointerdblclick(evt:any, x:number, y:number):void; - pointerclick(evt:any, x:number, y:number):void; - pointerdown(evt:any, x:number, y:number):void; - pointermove(evt:any, x:number, y:number):void; - pointerup(evt:any, x:number, y:number):void; + rotate(deg: number, ox?: number, oy?: number): Paper; // @todo not released yet though it's in the source code already + + afterRenderViews(): void; + asyncRenderViews(cells: Cell[], options?: any): void; + beforeRenderViews(cells: Cell[]): Cell[]; + cellMouseout(evt: Event): void; + cellMouseover(evt: Event): void; + clearGrid(): this; + contextmenu(evt: Event): void; + createViewForModel(cell: Cell): CellView; + drawGrid(options?: any): this; + fitToContent(gridWidth?: number, gridHeight?: number, padding?: number, options?: any): void; + getArea(): BBox; + getDefaultLink(cellView: CellView, magnet: HTMLElement): Link; + getModelById(id: string): Cell; + getRestrictedArea(): BBox; + guard(evt: Event, view: CellView): boolean; + linkAllowed(linkViewOrModel: LinkView | Link): boolean; + mouseclick(evt: Event): void; + mousedblclick(evt: Event): void; + mousewheel(evt: Event): void; + onCellAdded(cell: Cell, graph: Graph, options: Object): void; + onCellHighlight(cellView: CellView, magnetEl: HTMLElement, options?: any): void; + onCellUnhighlight(cellView: CellView, magnetEl: HTMLElement, options?: any): void; + onRemove(): void; + pointerdown(evt: Event): void; + pointermove(evt: Event): void; + pointerup(evt: Event): void; + remove(): this; + removeView(cell: Cell): CellView; + removeViews(): void; + renderView(cell: Cell): CellView; + resetViews(cellsCollection: Cell[], options: any): void; + resolveHighlighter(options?: any): boolean | Object; + setGridSize(gridSize: number): this; + setInteractivity(value: any): void; + snapToGrid(p: Point): Point; + sortViews(): void; } - class LinkView extends CellView { - getConnectionLength():number; - getPointAtLength(length:number):{ x: number; y: number; }; + + interface GradientOptions { + type: 'linearGradient' | 'radialGradient'; + stops: Array<{ + offset: string; + color: string; + opacity?: number; + }>; + } + class CellViewGeneric extends Backbone.View { + getBBox(options?: { useModelGeometry?: boolean }): BBox; + highlight(el?: any, options?: any): this; + unhighlight(el?: any, options?: any): this; + applyFilter(selector: string | HTMLElement, filter: Object): void; + applyGradient(selector: string | HTMLElement, attr: 'fill' | 'stroke', gradient: GradientOptions): void; + can(feature: string): boolean; + findBySelector(selector: string): JQuery; + findMagnet(el: any): HTMLElement; + getSelector(el: HTMLElement, prevSelector: string): string; + getStrokeBBox(el: any): BBox; // string|HTMLElement|Vectorizer + mouseout(evt: Event): void; + mouseover(evt: Event): void; + mousewheel(evt: Event, x: number, y: number, delta: number): void + notify(eventName: string): void; + onChangeAttrs(cell: Cell, attrs: Backbone.ViewOptions, options?: any): this; + onSetTheme(oldTheme: string, newTheme: string): void; + pointerclick(evt: Event, x: number, y: number): void; + pointerdblclick(evt: Event, x: number, y: number): void; + pointerdown(evt: Event, x: number, y: number): void; + pointermove(evt: Event, x: number, y: number): void; + pointerup(evt: Event, x: number, y: number): void; + remove(): this; + setInteractivity(value: any): void; + setTheme(theme: string, options?: any): this; } + class CellView extends CellViewGeneric { } + + interface ElementViewAttributes { + style?: string; + text?: string; + html?: string; + "ref-x"?: string | number; + "ref-y"?: string | number; + "ref-dx"?: number; + "ref-dy"?: number; + "ref-width"?: string | number; + "ref-height"?: string | number; + ref?: string; + "x-alignment"?: 'middle' | 'right' | number; + "y-alignment"?: 'middle' | 'bottom' | number; + port?: string; + } + class ElementView extends CellViewGeneric { + scale(sx: number, sy: number): void; // @todo Documented in source but not released + finalizeEmbedding(options?: any): void; + getBBox(options?: any): BBox; + pointerdown(evt: Event, x: number, y: number): void; + pointermove(evt: Event, x: number, y: number): void; + pointerup(evt: Event, x: number, y: number): void; + positionRelative(vel: any, bbox: BBox, attributes: ElementViewAttributes, nodesBySelector?: Object): void; // Vectorizer + prepareEmbedding(options?: any): void; + processEmbedding(options?: any): void; + render(): this; + renderMarkup(): void; + resize(): void; + rotate(): void; + translate(model: Backbone.Model, changes?: any, options?: any): void; + update(cell: Cell, renderingOnlyAttrs?: Object): void; + } + + class LinkView extends CellViewGeneric { + options: { + shortLinkLength?: number, + doubleLinkTools?: boolean, + longLinkLength?: number, + linkToolsOffset?: number, + doubleLinkToolsOffset?: number, + sampleInterval: number + }; + getConnectionLength(): number; + sendToken(token: SVGElement, duration?: number, callback?: () => void): void; + addVertex(vertex: Point): number; + getPointAtLength(length: number): Point; // Marked as public api in source but not in the documents + createWatcher(endType: { id: string }): Function; + findRoute(oldVertices: Point[]): Point[]; + getConnectionPoint(end: 'source' | 'target', selectorOrPoint: Element | Point, referenceSelectorOrPoint: Element | Point): Point; + getPathData(vertices: Point[]): any; + onEndModelChange(endType: 'source' | 'target', endModel?: Element, opt?: any): void; + onLabelsChange(): void; + onSourceChange(cell: Cell, sourceEnd: { id: string }, options: any): void; + onTargetChange(cell: Cell, targetEnd: { id: string }, options: any): void; + onToolsChange(): void; + onVerticesChange(cell: Cell, changed: any, options: any): void; + pointerdown(evt: Event, x: number, y: number): void; + pointermove(evt: Event, x: number, y: number): void; + pointerup(evt: Event, x: number, y: number): void; + removeVertex(idx: number): this; + render(): this; + renderArrowheadMarkers(): this; + renderLabels(): this; + renderTools(): this; + renderVertexMarkers(): this; + startArrowheadMove(end: 'source' | 'target', options?: any): void; + startListening(): void; + update(model: any, attributes: any, options?: any): this; + updateArrowheadMarkers(): this; + updateAttributes(): void; + updateConnection(options?: any): void; + updateLabelPositions(): this; + updateToolsPosition(): this; + } } - namespace ui {} + namespace ui { } namespace shapes { + interface GenericAttributes extends dia.CellAttributes { + position?: dia.Point; + size?: dia.Size; + angle?: number; + attrs?: T; + } + interface ShapeAttrs extends dia.CSSSelector { + fill?: string; + stroke?: string; + r?: string | number; + rx?: string | number; + ry?: string | number; + cx?: string | number; + cy?: string | number; + height?: string | number; + width?: string | number; + } namespace basic { class Generic extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object) + } + interface RectAttrs extends dia.TextAttrs { + rect?: ShapeAttrs; } class Rect extends Generic { + constructor(attributes?: GenericAttributes, options?: Object) } class Text extends Generic { + constructor(attributes?: GenericAttributes, options?: Object) + } + interface CircleAttrs extends dia.TextAttrs { + circle?: ShapeAttrs; } class Circle extends Generic { + constructor(attributes?: GenericAttributes, options?: Object) + } + interface EllipseAttrs extends dia.TextAttrs { + ellipse?: ShapeAttrs; + } + class Ellipse extends Generic { + constructor(attributes?: GenericAttributes, options?: Object) } class Image extends Generic { } + class Path extends Generic { + } + class Polygon extends Generic { + } + class Polyline extends Generic { + } } } namespace util { - function uuid():string; - function guid(obj:any):string; - function mixin(objects:any[]):any; - function supplement(objects:any[]):any; - function deepMixin(objects:any[]):any; - function deepSupplement(objects:any[], defaultIndicator?:any):any; + + namespace format { + export function number(specifier: string, value: number): string; + } + + export function uuid(): string; + export function guid(obj?: Object): string; + export function nextFrame(callback: () => void, context?: Object): number; + export function cancelFrame(requestId: number): void; + export function flattenObject(object: Object, delim: string, stop: (node: any) => boolean): any; + export function getByPath(object: Object, path: string, delim: string): any; + export function setByPath(object: Object, path: string, value: Object, delim: string): any; + export function unsetByPath(object: Object, path: string, delim: string): any; + export function breakText(text: string, size: dia.Size, attrs?: dia.SVGAttributes, options?: { svgDocument?: SVGElement }): string; + export function normalizeSides(box: number | { x?: number, y?: number, height?: number, width?: number }): dia.BBox; + export function getElementBBox(el: Element): dia.BBox; + export function setAttributesBySelector(el: Element, attrs: dia.SVGAttributes): void; + export function sortElements(elements: Element[] | string | JQuery, comparator: (a: Element, b: Element) => number): Element[]; + export function shapePerimeterConnectionPoint(linkView: dia.LinkView, view: dia.ElementView, magnet: SVGElement, ref: dia.Point): dia.Point; + export function imageToDataUri(url: string, callback: (err: Error, dataUri: string) => void): void; + + // Not documented but used in examples + /** @deprecated use lodash _.defaultsDeep */ + export function deepSupplement(objects: any, defaultIndicator?: any): any; + + // Private functions + /** @deprecated use lodash _.assign */ + export function mixin(objects: any[]): any; + /** @deprecated use lodash _.defaults */ + export function supplement(objects: any[]): any; + /** @deprecated use lodash _.mixin */ + export function deepMixin(objects: any[]): any; } -} + namespace layout { + + interface LayoutOptions { + nodeSep?: number; + edgeSep?: number; + rankSep?: number; + rankDir?: 'TB' | 'BT' | 'LR' | 'RL'; + marginX?: number; + marginY?: number; + resizeCluster?: boolean; + setPosition?: (element: dia.Element, position: dia.BBox) => void; + setLinkVertices?: (link: dia.Link, vertices: Position[]) => void; + } + + class DirectedGraph { + static layout(graph: dia.Graph, options?: LayoutOptions): dia.BBox; + } + } +} \ No newline at end of file diff --git a/jqrangeslider/index.d.ts b/jqrangeslider/index.d.ts index 9e65d7fa5d..36bb5a16d2 100644 --- a/jqrangeslider/index.d.ts +++ b/jqrangeslider/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQRangeSlider 4.2.8 +// Type definitions for jQRangeSlider 5.7.2 // Project: http://ghusse.github.com/jQRangeSlider // Definitions by: Dániel Tar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -31,6 +31,15 @@ interface JQRangeSliderDateSteps { seconds?: number; } +interface jQRangeSliderScale { + first?: (min:number, max:number) => number; // compute the ruler first value. + next: (value:any) => any; // compute the next value. + label?: (value:any, nextValue:any) => string; // compute displayed text for a given internal + stop?: (value:any) => boolean; // 'true' to stop scale generating ticks from a given value + format?: (tickContainer:any, tickStartValue:any, tickEndValue:any) => void; // customise the tick container DOM element (passed as jQuery object) + // doco example mentions 'end' function in example but it's not supported: https://github.com/ghusse/jQRangeSlider/blob/master/jQRuler.js#L12 +} + interface JQRangeSliderOptions { wheelMode?: string; // function of the wheel, "zoom", "scroll" or null wheelSpeed?: number; // speed of the wheel scrolling @@ -40,6 +49,9 @@ interface JQRangeSliderOptions { durationOut?: number; // fade out length when displaying value labels (only when valueLabels = "change") delayOut?: number; // duration labels are shown after the user changed its values (only when valueLabels = "change") range?: JQRangeSliderRangeLength; // lets you specify minimum and/or maximum range length + symmetricPositionning?: boolean; // show handles and make them clearly select the range. Warning: must be used with 'minimum' and must not be used with 'scale' + enabled?: boolean; // configure a read-only slider + scales?: jQRangeSliderScale[]; // TODO support scales } interface JQNumericRangeSliderOptions extends JQRangeSliderOptions { @@ -49,6 +61,10 @@ interface JQNumericRangeSliderOptions extends JQRangeSliderOptions { step?: number; // allows to customize values rounding, and graphically render this rounding } +interface JQEditRangeSliderOptions extends JQNumericRangeSliderOptions { + type?: string; // specify input types in edit slider. Possible values are text (default) and number +} + interface JQDateRangeSliderOptions extends JQRangeSliderOptions { bounds?: JQRangeSliderDateRange; // min and max values of the slider defaultValues?: JQRangeSliderDateRange; // values selected by default on construction @@ -65,7 +81,7 @@ interface JQuery { editRangeSlider(method: string): any; editRangeSlider(method: string, value: number): JQuery; editRangeSlider(method: string, min: number, max: number): JQuery - editRangeSlider(options?: JQNumericRangeSliderOptions): JQuery; + editRangeSlider(options?: JQEditRangeSliderOptions): JQuery; dateRangeSlider(method: string): any; dateRangeSlider(method: string, value: Date): JQuery; diff --git a/jqrangeslider/jqrangeslider-tests.ts b/jqrangeslider/jqrangeslider-tests.ts index 0e8d600559..1af815806f 100644 --- a/jqrangeslider/jqrangeslider-tests.ts +++ b/jqrangeslider/jqrangeslider-tests.ts @@ -51,6 +51,16 @@ $("#defaultValuesExample").dateRangeSlider({ durationIn: 1000, durationOut: 1000 }); +// Enabled +$("#disabledExample").rangeSlider({ + enabled: false +}); +$("#disabledExample").editRangeSlider({ + enabled: false +}); +$("#disabledExample").dateRangeSlider({ + enabled: false +}); // Formatter - JS-way $("#formatterExample").rangeSlider({ formatter: function (val) { @@ -114,6 +124,51 @@ $("#rangeExample").rangeSlider({range: {min: 10, max: false}}); $("#rangeExample").rangeSlider({range: false}); $("#rangeExample").rangeSlider({range: {min: false, max: false}}); $("#rangeExample").rangeSlider({range: {min: false}}); +// Scales +$("#rulersExample").rangeSlider({ + scales: [ + // Primary scale + { + first: function(val){ return val; }, + next: function(val){ return val + 10; }, + stop: function(val){ return false; }, + label: function(val){ return val; }, + format: function(tickContainer, tickStart, tickEnd){ + tickContainer.addClass("myCustomClass"); + } + }, + // Secondary scale + { + first: function(val){ return val; }, + next: function(val){ + if (val % 10 === 9){ + return val + 2; + } + return val + 1; + }, + stop: function(val){ return false; }, + label: function(){ return null; } + }] +}); +var monthsForScales = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]; +$("#dateRulersExample").dateRangeSlider({ + bounds: {min: new Date(2012, 0, 1), max: new Date(2012, 11, 31, 12, 59, 59)}, + defaultValues: {min: new Date(2012, 1, 10), max: new Date(2012, 4, 22)}, + scales: [{ + first: function(value){ return value; }, + stop: function(value) {return false; }, // changed from original example which had 'end' because that's a typo + next: function(value){ + var next = new Date(value); + return new Date(next.setMonth(value.getMonth() + 1)); + }, + label: function(value){ + return monthsForScales[value.getMonth()]; + }, + format: function(tickContainer, tickStart, tickEnd){ + tickContainer.addClass("myCustomClass"); + } + }] +}); // Step $("#stepExample").rangeSlider({step: 10}); $("#rangeExample").dateRangeSlider({ @@ -121,6 +176,13 @@ $("#rangeExample").dateRangeSlider({ days: 2 } }); +// Symmetric Positionning +$("#symmetricExample").rangeSlider({ + symmetricPositionning: true, + range: {min: 0} +}); +// Type +$("#typeExample").editRangeSlider({type: "number"}); // Value labels $("#valueLabelsExample").rangeSlider({valueLabels: "change"}); $("#valueLabelsExample").dateRangeSlider({valueLabels: "change"}); diff --git a/jquery.ajaxfile/jquery.ajaxFile-tests.ts b/jquery.ajaxfile/jquery.ajaxfile-tests.ts similarity index 100% rename from jquery.ajaxfile/jquery.ajaxFile-tests.ts rename to jquery.ajaxfile/jquery.ajaxfile-tests.ts diff --git a/jquery.bbq/jquery.bbq-tests.ts b/jquery.bbq/jquery.bbq-tests.ts index baa6c7f42f..8f3ab25aea 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 673b81b480..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.7 +// 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,11 @@ 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. @@ -374,6 +374,7 @@ declare namespace DataTables { length: number; recordsTotal: number; recordsDisplay: number; + serverSide: boolean } //#endregion "page-methods" @@ -436,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. * @@ -910,6 +916,15 @@ declare namespace DataTables { */ 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. */ @@ -970,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. */ @@ -1057,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 @@ -1100,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" @@ -1257,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; @@ -1271,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 */ @@ -1643,7 +1685,7 @@ declare namespace DataTables { } interface FunctionRowCallback { - (row: Node, data: any[] | Object): void; + (row: Node, data: any[] | Object, index: number): void; } interface FunctionStateLoadCallback { @@ -1685,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 f9f6209871..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,8 +306,9 @@ $(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(); @@ -343,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(); @@ -401,7 +404,7 @@ $(document).ready(function () { .cache('search') .sort() .unique() - .each(function (d) { + .each(function (d: any) { select.append($('')); }); @@ -520,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( @@ -707,7 +710,7 @@ $(document).ready(function () { .cache('search') .sort() .unique() - .each(function (d) { + .each(function (d: any) { select.append($('')); }); }); @@ -751,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(); @@ -767,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({ @@ -831,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( @@ -881,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(); @@ -905,6 +926,7 @@ $(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.rateit/index.d.ts b/jquery.rateit/index.d.ts new file mode 100644 index 0000000000..be62f3b3da --- /dev/null +++ b/jquery.rateit/index.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.rateit/jquery.rateit-tests.ts b/jquery.rateit/jquery.rateit-tests.ts new file mode 100644 index 0000000000..d2127cbaa0 --- /dev/null +++ b/jquery.rateit/jquery.rateit-tests.ts @@ -0,0 +1,46 @@ +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/tsconfig.json b/jquery.rateit/tsconfig.json new file mode 100644 index 0000000000..0f7906596e --- /dev/null +++ b/jquery.rateit/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery.rateit-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.slimscroll/jquery.SlimScroll-tests.ts b/jquery.slimscroll/jquery.slimscroll-tests.ts similarity index 100% rename from jquery.slimscroll/jquery.SlimScroll-tests.ts rename to jquery.slimscroll/jquery.slimscroll-tests.ts diff --git a/jquery.slimscroll/tsconfig.json b/jquery.slimscroll/tsconfig.json index 910f07039e..524b9a8740 100644 --- a/jquery.slimscroll/tsconfig.json +++ b/jquery.slimscroll/tsconfig.json @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "jquery.slimScroll-tests.ts" + "jquery.slimscroll-tests.ts" ] } \ No newline at end of file diff --git a/jquery/index.d.ts b/jquery/index.d.ts index f8af62caba..fa22a1599b 100644 --- a/jquery/index.d.ts +++ b/jquery/index.d.ts @@ -180,7 +180,7 @@ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { /** * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. */ - then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => R, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; + then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => R|JQueryPromise, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; /** * Property containing the parsed response if the response Content-Type is json */ diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index 479081c477..b64fdc43cf 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -169,6 +169,12 @@ function test_ajax() { console.log(data, textStatus, jqXHR); }); + // then method can change promise type through promise chaining + var chainedValuePromise : JQueryPromise; + chainedValuePromise = $.ajax({ + url: "test.js" + }).then(() => $.when(1)); + // fail method $.ajax({ url: "test.js" @@ -209,9 +215,9 @@ 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" @@ -239,7 +245,7 @@ function test_ajax() { }).promise().always((jqXHR, textStatus, errorThrown) => { console.log(jqXHR, textStatus, errorThrown); }); - + // then method (as of 1.8) $.ajax({ url: "test.js" @@ -252,7 +258,7 @@ function test_ajax() { // generic then method var p: JQueryPromise = $.ajax({ url: "test.js" }).promise() .then(() => "Hello") - .then((x) => x.length); + .then((x) => x.length); } function test_ajaxComplete() { diff --git a/js-base64/index.d.ts b/js-base64/index.d.ts index a26d24ea54..bd195e3885 100644 --- a/js-base64/index.d.ts +++ b/js-base64/index.d.ts @@ -19,37 +19,36 @@ add methods: - [ ] noConflict */ -declare namespace Base64 { - 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 - } -} - declare module 'js-base64' { - export = 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/jsonminify/index.d.ts b/jsonminify/index.d.ts new file mode 100644 index 0000000000..613ac9a9ab --- /dev/null +++ b/jsonminify/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for jsonminify 0.4.1 +// Project: https://github.com/fkei/JSON.minify +// Definitions by: Dan Homola +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function minify(json: string): string; + +export = minify; diff --git a/jsonminify/jsonminify-tests.ts b/jsonminify/jsonminify-tests.ts new file mode 100644 index 0000000000..fdb6150768 --- /dev/null +++ b/jsonminify/jsonminify-tests.ts @@ -0,0 +1,3 @@ +import jsonminify = require("jsonminify"); + +const minified: string = jsonminify('{ "foo": "bar" }'); diff --git a/jsonminify/tsconfig.json b/jsonminify/tsconfig.json new file mode 100644 index 0000000000..3fe847d334 --- /dev/null +++ b/jsonminify/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jsonminify-tests.ts" + ] +} diff --git a/jsonstream/JSONStream-tests.ts b/jsonstream/jsonstream-tests.ts similarity index 100% rename from jsonstream/JSONStream-tests.ts rename to jsonstream/jsonstream-tests.ts diff --git a/jsonstream/tsconfig.json b/jsonstream/tsconfig.json index 2be61cf00e..bdaba2cde8 100644 --- a/jsonstream/tsconfig.json +++ b/jsonstream/tsconfig.json @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "JSONStream-tests.ts" + "jsonstream-tests.ts" ] -} \ No newline at end of file +} diff --git a/jstimezonedetect/index.d.ts b/jstimezonedetect/index.d.ts new file mode 100644 index 0000000000..9709f52724 --- /dev/null +++ b/jstimezonedetect/index.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/jstimezonedetect/jstimezonedetect-tests.ts b/jstimezonedetect/jstimezonedetect-tests.ts new file mode 100644 index 0000000000..9baf0f4aa5 --- /dev/null +++ b/jstimezonedetect/jstimezonedetect-tests.ts @@ -0,0 +1,3 @@ +import * as jstz from 'jstimezonedetect'; + +jstz.determine().name() === 'America/Montreal'; diff --git a/jstimezonedetect/tsconfig.json b/jstimezonedetect/tsconfig.json new file mode 100644 index 0000000000..d036a843d1 --- /dev/null +++ b/jstimezonedetect/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jstimezonedetect-tests.ts" + ] +} \ No newline at end of file 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..347cc066f0 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 { diff --git a/kefir/index.d.ts b/kefir/index.d.ts index 12afaad5e2..d445be74ad 100644 --- a/kefir/index.d.ts +++ b/kefir/index.d.ts @@ -1,11 +1,20 @@ -// Type definitions for Kefir 3.2.0 +// Type definitions for Kefir 3.3.0 // Project: http://rpominov.github.io/kefir/ // Definitions by: Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +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 @@ -22,6 +31,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 bf3db2f9b5..43af9f8305 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 @@ -90,8 +90,39 @@ declare namespace kendo { }; var cultures: {[culture: string] : { - name?: string; - calendar?: { + name?: string; + calendar?: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + calendars?: { + standard: { AM: string[]; PM: string[]; days: { @@ -121,55 +152,24 @@ declare namespace kendo { }; twoDigitYearMax: number; }; - calendars?: { - standard: { - AM: string[]; - PM: string[]; - days: { - names: string[]; - namesAbbr: string[]; - namesShort: string[]; - firstDay: number; - }; - months: { - names: string[]; - namesAbbr: string[]; - }; - patterns: { - D: string; - F: string; - G: string; - M: string; - T: string; - Y: string; - d: string; - g: string; - m: string; - s: string; - t: string; - u: string; - y: string; - }; - twoDigitYearMax: number; - }; - }; - numberFormat?: { - currency: { - decimals: number; - groupSize: number[]; - pattern: string[]; - symbol: string; - }; + }; + numberFormat?: { + currency: { decimals: number; groupSize: number[]; pattern: string[]; - percent: { - decimals: number; - groupSize: number[]; - pattern: string[]; - symbol: string; - }; + symbol: string; }; + decimals: number; + groupSize: number[]; + pattern: string[]; + percent: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; + }; }}; function format(format: string, ...values: any[]): string; @@ -1112,7 +1112,7 @@ declare namespace kendo.data { } interface DataSourceFilterItem extends DataSourceFilter { - operator?: string; + operator?: string|Function; field?: string; value?: any; } @@ -1245,6 +1245,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 +1275,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 +1487,7 @@ declare namespace kendo.mobile { statusBarStyle?: string; transition?: string; useNativeScrolling?: boolean; + init?(e: ApplicationEvent): void; } interface ApplicationEvent { @@ -1538,7 +1546,7 @@ declare namespace kendo.ui { static extend(proto: Object): AgendaView; } - class Alert extends kendo.ui.Widget { + class Alert extends kendo.ui.Dialog { static fn: Alert; @@ -2043,12 +2051,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; @@ -2809,66 +2818,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 { @@ -5141,12 +5179,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; @@ -5542,6 +5581,7 @@ declare namespace kendo.ui { minorTimeHeaderTemplate?: string|Function; selected?: boolean; selectedDateFormat?: string; + selectedShortDateFormat?: string; showWorkHours?: boolean; slotTemplate?: string|Function; startTime?: Date; @@ -6068,6 +6108,7 @@ declare namespace kendo.ui { comparerType?: string; dataType?: string; from?: string; + showButton?: boolean; to?: string; allowNulls?: boolean; messageTemplate?: string; @@ -6102,6 +6143,7 @@ declare namespace kendo.ui { cells?: SpreadsheetSheetRowCell[]; height?: number; index?: number; + type?: string; } interface SpreadsheetSheetSortColumn { @@ -7291,7 +7333,7 @@ declare namespace kendo.ui { destroy(): void; disable(): void; enable(enable?: boolean): void; - getFiles(): void; + getFiles(): any; removeAllFiles(): void; removeFile(): void; removeFileByUid(): void; @@ -7470,6 +7512,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; @@ -11017,7 +11061,6 @@ declare namespace kendo.dataviz.ui { autoBind?: boolean; axisDefaults?: ChartAxisDefaults; categoryAxis?: ChartCategoryAxisItem[]; - valueAxis?: ChartValueAxisItem[]; chartArea?: ChartChartArea; dataSource?: any|any|kendo.data.DataSource; legend?: ChartLegend; @@ -11033,6 +11076,7 @@ declare namespace kendo.dataviz.ui { title?: ChartTitle; tooltip?: ChartTooltip; transitions?: boolean; + valueAxis?: ChartValueAxisItem[]; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; zoomable?: boolean|ChartZoomable; @@ -16928,7 +16972,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; @@ -16939,7 +16983,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; @@ -16947,7 +16991,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; @@ -17032,6 +17076,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/keymirror/index.d.ts b/keymirror/index.d.ts new file mode 100644 index 0000000000..1f2b6c01da --- /dev/null +++ b/keymirror/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for keymirror 0.1.1 +// Project: https://github.com/STRML/keyMirror +// Definitions by: Johannes Fahrenkrug +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function KeyMirror(obj: {}): { [key: string]: string }; +export = KeyMirror; diff --git a/keymirror/keymirror-tests.ts b/keymirror/keymirror-tests.ts new file mode 100644 index 0000000000..ace29f9947 --- /dev/null +++ b/keymirror/keymirror-tests.ts @@ -0,0 +1,3 @@ +import keyMirror = require('keymirror'); + +keyMirror({key1: null, key2: null}); diff --git a/keymirror/tsconfig.json b/keymirror/tsconfig.json new file mode 100644 index 0000000000..ce57da7581 --- /dev/null +++ b/keymirror/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "keymirror-tests.ts" + ] +} diff --git a/koa-passport/index.d.ts b/koa-passport/index.d.ts new file mode 100644 index 0000000000..f17bf87f39 --- /dev/null +++ b/koa-passport/index.d.ts @@ -0,0 +1,63 @@ +// 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()); + + =============================================== */ + +import * as Koa from "koa"; +declare 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; +} +declare const koaPassport: KoaPassport; + +declare namespace KoaPassport { + interface Profile extends passport.Profile { } + interface Framework extends passport.Framework { } +} + +export = koaPassport; diff --git a/koa-passport/koa-passport-tests.ts b/koa-passport/koa-passport-tests.ts new file mode 100644 index 0000000000..eebb67a3b1 --- /dev/null +++ b/koa-passport/koa-passport-tests.ts @@ -0,0 +1,38 @@ +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/tsconfig.json b/koa-passport/tsconfig.json new file mode 100644 index 0000000000..8e0b10ae18 --- /dev/null +++ b/koa-passport/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-passport-tests.ts" + ] +} \ No newline at end of file diff --git a/koa-session-minimal/index.d.ts b/koa-session-minimal/index.d.ts new file mode 100644 index 0000000000..1c55660dc9 --- /dev/null +++ b/koa-session-minimal/index.d.ts @@ -0,0 +1,44 @@ +// 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()); + + =============================================== */ + +import * as Koa from "koa"; +import * as cookies from "cookies"; + +declare module "koa" { + interface Request { + session: any; + sessionHandler: { regenerateId: () => void }; + } +} + +declare 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 }; + +declare namespace session {} +export = session; 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..b58f441d8e --- /dev/null +++ b/koa-session-minimal/koa-session-minimal-tests.ts @@ -0,0 +1,28 @@ +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/tsconfig.json b/koa-session-minimal/tsconfig.json new file mode 100644 index 0000000000..d269751272 --- /dev/null +++ b/koa-session-minimal/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-session-minimal-tests.ts" + ] +} \ No newline at end of file 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/lab/index.d.ts b/lab/index.d.ts new file mode 100644 index 0000000000..2b4c036bde --- /dev/null +++ b/lab/index.d.ts @@ -0,0 +1,187 @@ +// Type definitions for lab 11.1.0 +// Project: https://github.com/hapijs/lab +// Definitions by: Prashant Tiwari +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** The test script. */ +export function script(options?: ScriptOptions): Lab & ExperimentAlt & TestAlt; +/** Access the configured assertion library. */ +export const assertions: any; + +interface Lab { + /** Organise tests into an experiment */ + experiment(desc: string, cb: EmptyCallback): void; + + /** Organise tests into an experiment with options */ + experiment(desc: string, options: ExperimentOptions, cb: EmptyCallback): void; + + /** Create a test suite */ + describe(desc: string, cb: EmptyCallback): void; + + /** Create a test suite with options */ + describe(desc: string, options: ExperimentOptions, cb: EmptyCallback): void; + + /** Create a test suite */ + suite(desc: string, cb: EmptyCallback): void; + + /** Create a test suite with options */ + suite(desc: string, options: ExperimentOptions, cb: EmptyCallback): void; + + /** The test spec */ + test(desc: string, cb: TestCallback): void; + + /** The test spec using a promise */ + test(desc: string, promise: TestPromise): void; + + /** The test spec with options */ + test(desc: string, options: TestOptions, cb: TestCallback): void; + + /** The test spec using a promise with options */ + test(desc: string, options: TestOptions, promise: TestPromise): void; + + /** The test spec */ + it(desc: string, cb: TestCallback): void; + + /** The test spec using a promise */ + it(desc: string, promise: TestPromise): void; + + /** The test spec with options */ + it(desc: string, options: TestOptions, cb: TestCallback): void; + + /** The test spec using a promise with options */ + it(desc: string, options: TestOptions, promise: TestPromise): void; + + /** Perform async actions before the test suite */ + before(cb: AsyncCallback): void; + + /** Perform async actions before the test suite using a promise */ + before(promise: AsyncPromise): void; + + /** Perform async actions before the test suite with options */ + before(options: AsyncOptions, cb: AsyncCallback): void; + + /** Perform async actions before the test suite with otions, using a promise */ + before(options: AsyncOptions, promise: AsyncPromise): void; + + /** Perform async actions before each test */ + beforeEach(cb: AsyncCallback): void; + + /** Perform async actions before each test using a promise */ + beforeEach(promise: AsyncPromise): void; + + /** Perform async actions before each test with options */ + beforeEach(options: AsyncOptions, cb: AsyncCallback): void; + + /** Perform async actions before each test with options, using a promise */ + beforeEach(options: AsyncOptions, promise: AsyncPromise): void; + + /** Perform async actions after the test suite */ + after(cb: AsyncCallback): void; + + /** Perform async actions after the test suite using a promise */ + after(promise: AsyncPromise): void; + + /** Perform async actions after the test suite with options */ + after(options: AsyncOptions, cb: AsyncCallback): void; + + /** Perform async actions after the test suite with options, using a promise */ + after(options: AsyncOptions, promise: AsyncPromise): void; + + /** Perform async actions after each test */ + afterEach(cb: AsyncCallback): void; + + /** Perform async actions after each test using a promise */ + afterEach(promise: AsyncPromise): void; + + /** Perform async actions after each test with options */ + afterEach(options: AsyncOptions, cb: AsyncCallback): void; + + /** Perform async actions after each test with options, using a promise */ + afterEach(options: AsyncOptions, promise: AsyncPromise): void; +} + +interface ExperimentAlt { + experiment: SkipOnlyExperiment; + suite: SkipOnlyExperiment; + describe: SkipOnlyExperiment; +} + +interface TestAlt { + test: SkipOnlyTest; + it: SkipOnlyTest; +} + +interface SkipOnlyExperiment { + /** Skip this test suite */ + skip: ExperimentArgs & ExperimentWithOptionsArgs; + + /** Only execute this test suite */ + only: ExperimentArgs & ExperimentWithOptionsArgs; +} + +interface SkipOnlyTest { + /** Skip this test */ + skip: TestArgs & TestWithOptionsArgs; + + /** Only execute this test */ + only: TestArgs & TestWithOptionsArgs; +} + +interface ScriptOptions { + /** Enable auto-execution of the script? (true) */ + schedule?: boolean; + + /** Pass Lab CLI options */ + cli?: any; +} + +interface ExperimentOptions { + /** Set a specific timeout in milliseconds (2000) */ + timeout?: number; + + /** Execute tests in parallel? (false) */ + parallel?: boolean; + + /** Skip execution? (false) */ + skip?: boolean; + + /** Execute only this test/experiment? (false) */ + only?: boolean; +} + +interface TestOptions extends ExperimentOptions { + /** The expected number of assertions to execute */ + plan?: number; +} + +interface AsyncOptions { + /** Set a specific timeout in milliseconds (disabled) */ + timeout?: number; +} + +interface DoneNote { + /** Attach a note to the test case */ + note: (text: string) => void; +} + +type EmptyCallback = () => void; + +type DoneFunction = (err?: Error) => void; + +type CleanupFunction = (func: (next: Function) => void) => void; + +type TestCallback = (done: DoneFunction & DoneNote, onCleanup?: CleanupFunction) => void; + +type TestPromise = () => Promise; + +type AsyncCallback = (done: DoneFunction) => void; + +type AsyncPromise = () => Promise; + +type ExperimentArgs = (desc: string, cb: EmptyCallback) => {}; + +type ExperimentWithOptionsArgs = (desc: string, options: ExperimentOptions, cb: EmptyCallback) => {}; + +type TestArgs = (desc: string, cb: TestCallback) => {}; + +type TestWithOptionsArgs = (desc: string, options: TestOptions, cb: TestCallback) => {} diff --git a/lab/lab-tests.ts b/lab/lab-tests.ts new file mode 100644 index 0000000000..ae77ab242f --- /dev/null +++ b/lab/lab-tests.ts @@ -0,0 +1,169 @@ +import { script, assertions } from "lab"; + +const { experiment, describe, suite, test, it, before, beforeEach, after, afterEach } = script(); +const expect = assertions.expect; +const fail = assertions.fail; + +experiment('math', () => { + + before((done) => { + + setTimeout(() => { + + done(); + }, 1000); + }); + + beforeEach((done) => { + + done(); + }); + + test('returns true when 1 + 1 equals 2', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +experiment('math', () => { + + before(() => { + + return Promise.resolve(); + }); + + test('returns true when 1 + 1 equals 2', () => { + + return Promise.resolve() + .then((aValue) => { + + const expectedValue = aValue; + expect(aValue).to.equal(expectedValue); + }); + }); +}); + +experiment.only('with only experiment', () => { + + test('this test will run', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); + + test('another test that will run', (done) => { + + expect(true).to.equal(true); + done(); + }); +}); + +experiment('with only test', () => { + + test.only('only this test will run', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); + + test('another test that will not be executed', (done) => { + + done(); + }); +}); + +test('attaches notes', (done) => { + + expect(1 + 1).to.equal(2); + done.note(`The current time is ${Date.now()}`); + done(); +}); + +test('cleanups after test', (done, onCleanup) => { + + if (onCleanup) { + + onCleanup((next) => { + + return next(); + }); + } + + expect(1 + 1).to.equal(2); + done(); +}); + +experiment('my plan', () => { + + test('only a single assertion executes', { plan: 1 }, (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +experiment('math', { timeout: 1000 }, () => { + + before({ timeout: 500 }, (done) => { + + done(); + }); + + test('returns true when 1 + 1 equals 2', { parallel: true }, (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +describe('math', () => { + + before((done) => { + + done(); + }); + + after((done) => { + + done(); + }); + + afterEach((done) => { + + done(); + }); + + it('returns true when 1 + 1 equals 2', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +suite('math', () => { + + test('returns true when 1 + 1 equals 2', (done) => { + + expect(1 + 1).to.equal(2); + done(); + }); +}); + +describe('expectation', () => { + + it('should be able to expect', (done) => { + + expect(true).to.be.true(); + + done(); + }); + + it('should be able to fail (This test should fail)', (done) => { + + fail('Should fail'); + + done(); + }); + +}); diff --git a/lab/tsconfig.json b/lab/tsconfig.json new file mode 100644 index 0000000000..5562163523 --- /dev/null +++ b/lab/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lab-tests.ts" + ] +} \ No newline at end of file diff --git a/ldclient-js/index.d.ts b/ldclient-js/index.d.ts new file mode 100644 index 0000000000..47792db29a --- /dev/null +++ b/ldclient-js/index.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/ldclient-js/ldclient-js-tests.ts b/ldclient-js/ldclient-js-tests.ts new file mode 100644 index 0000000000..3b7ea30125 --- /dev/null +++ b/ldclient-js/ldclient-js-tests.ts @@ -0,0 +1,30 @@ +// 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/tsconfig.json b/ldclient-js/tsconfig.json new file mode 100644 index 0000000000..37c3af1f5a --- /dev/null +++ b/ldclient-js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ldclient-js-tests.ts" + ] +} \ No newline at end of file diff --git a/leadfoot/index.d.ts b/leadfoot/index.d.ts new file mode 100644 index 0000000000..eb93321c28 --- /dev/null +++ b/leadfoot/index.d.ts @@ -0,0 +1,3275 @@ +// Type definitions for leadfoot +// Project: https://github.com/theintern/leadfoot +// Definitions by: theintern +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module leadfoot { + + /** + * An error from the remote WebDriver server. + */ + interface WebDriverError extends Error { + /** + * The human-readable error type returned by the WebDriver server. See {@link module:leadfoot/lib/statusCodes} for a + * list of error types. + */ + name: string; + + /** + * A human-readable message describing the error. + */ + message: string; + + /** + * The raw error status code returned by the WebDriver server. + */ + status: number; + + /** + * The raw detail of the error returned by the WebDriver server. + */ + detail: any; + + /** + * The parameters for the request. + */ + request: { + url: string; + method: string; + requestData: {}; + }; + + /** + * The response object for the request. + */ +// response: request.IResponse; + response: any; + + /** + * The stack trace for the request. + */ + stack: string; + } + + /** + * An object that describes an HTTP cookie. + */ + interface WebDriverCookie { + /** + * The name of the cookie. + */ + name: string; + + /** + * The value of the cookie. + */ + value: string; + + /** + * The registered path for the cookie. + */ + path: string; + + /** + * The registered domain for the cookie. + */ + domain: string; + + /** + * True if the cookie should only be transmitted over HTTPS. + */ + secure: boolean; + + /** + * True if the cookie should be inaccessible to client-side scripting. + */ + httpOnly: boolean; + + /** + * The expiration date of the cookie. + */ + expiry: Date; + } + + /** + * An object that describes a geographical location. + */ + interface Geolocation { + /** + * Latitude in WGS84 decimal coordinate system. + */ + latitude: number; + + /** + * Longitude in WGS84 decimal coordinate system. + */ + longitude: number; + + /** + * Altitude in meters above the WGS84 ellipsoid. + */ + altitude: number; + } + + /** + * A remote log entry. + */ + interface LogEntry { + /** + * The timestamp of the entry in seconds since unix epoch. + */ + timestamp: number; + + /** + * The severity level of the entry. This level is not currently normalised. + */ + level: string; + + /** + * The log entry message. + */ + message: string; + } + + /** + * A list of possible capabilities for a remote WebDriver environment. + */ + interface Capabilities { + /** + * Environments with this capability expose the state of the browser’s offline application cache via the WebDriver API. + */ + applicationCacheEnabled?: boolean; + + /** + * Environments with this capability are incapable of clearing or deleting cookies. This issue cannot be worked around. + */ + brokenCookies?: boolean; + + /** + * Environments with this capability do not correctly retrieve the size of a CSS transformed element. This issue is + * automatically corrected. + */ + brokenCssTransformedSize?: boolean; + + /** + * Environments with this capability do not correctly delete cookies. This issue is automatically corrected for cookies + * that are accessible via JavaScript. + */ + brokenDeleteCookie?: boolean; + + /** + * Environments with this capability do not follow the correct event order when double-clicking. This issue is + * automatically corrected. + */ + brokenDoubleClick?: boolean; + + /** + * Environments with this capability return invalid element handles from execute functions. This issue cannot be worked + * around. + */ + brokenExecuteElementReturn?: boolean; + + /** + * Environments with this capability claim fully transparent elements are non-hidden. This issue is automatically + * corrected. + */ + brokenElementDisplayedOpacity?: boolean; + + /** + * Environments with this capability claim elements positioned offscreen to the top/left of the page are non-hidden. + * This issue is automatically corrected. + */ + brokenElementDisplayedOffscreen?: boolean; + + /** + * Environments with this capability do not correctly retrieve the position of a CSS transformed element. This issue is + * automatically corrected. + */ + brokenElementPosition?: boolean; + + /** + * Environments with this capability do not operate correctly when the `flickFinger` method is called. This issue cannot + * be corrected. + */ + brokenFlickFinger?: boolean; + + /** + * Environments with this capability return HTML tag names with the incorrect case. This issue is automatically + * corrected. + */ + brokenHtmlTagName?: boolean; + + /** + * Environments with this capability fail to perform long tap gestures. This issue is not currently corrected. + */ + brokenLongTap?: boolean; + + /** + * Environments with this capability have broken mouse event APIs. This issue is automatically corrected as much as + * possible through JavaScript-based event emulation. + */ + brokenMouseEvents?: boolean; + + /** + * Environments with this capability do not support dragging fingers across the page. This issue is not currently + * corrected. + */ + brokenMoveFinger?: boolean; + + /** + * Environments with this capability do not support browser navigation functions (back, forward, refresh). This issue + * cannot be corrected. + */ + brokenNavigation?: boolean; + + /** + * Environments with this capability incorrectly return an empty string instead of `null` for attributes that do not + * exist when using the `getSpecAttribute` retrieval method. This issue is automatically corrected. + */ + brokenNullGetSpecAttribute?: boolean; + + /** + * Environments with this capability fail to complete calls to refresh a page through the standard WebDriver API. This + * issue is automatically corrected. + */ + brokenRefresh?: boolean; + + /** + * Environments with this capability have broken keyboard event APIs. This issue is automatically corrected as much as + * possible through JavaScript-based event emulation. + */ + brokenSendKeys?: boolean; + + /** + * Environments with this capability incorrectly omit the key/value of the button being submitted. This issue is + * automatically corrected. + */ + brokenSubmitElement?: boolean; + + /** + * Environments with this capability do not operate correctly when the `touchScroll` method is called. This issue is + * automatically corrected. + */ + brokenTouchScroll?: boolean; + + /** + * Environments with this capability cannot switch between windows. This issue cannot be corrected. + */ + brokenWindowSwitch?: boolean; + + /** + * Environments with this capability break when `setWindowPosition` is called. This issue cannot be corrected. + */ + brokenWindowPosition?: boolean; + + /** + * The name of the current environment. + */ + browserName: string; + + /** + * Environments with this capability can use CSS selectors to find elements. + */ + cssSelectorsEnabled?: boolean; + + /** + * Environments with this capability have viewports that can be resized. + */ + dynamicViewport?: boolean; + + /** + * Environments with this capability break when the `getLogTypes` method is called. The list of log types provided here + * are used in lieu of the values provided by the server when calling `getLogTypes`. + */ + fixedLogTypes?: boolean | string[]; + + /** + * Environments with this capability have JavaScript enabled. Leadfoot does not operate in environments without + * JavaScript. + */ + javascriptEnabled?: boolean; + + /** + * Environments with this capability allow the geographic location of the browser to be set and retrieved using the + * WebDriver API. + */ + locationContextEnabled?: boolean; + + /** + * Environments with this capability support interaction via mouse commands. + */ + mouseEnabled?: boolean; + + /** + * Environments with this capability use platform native events instead of emulated events. + */ + nativeEvents?: boolean; + + /** + * The name of the platform on which the current environment is running. + */ + platform: string; + + /** + * Environments with this capability allow files to be uploaded from a remote client. + */ + remoteFiles?: boolean; + + /** + * Environments with this capability allow the rotation of the device to be set and retrieved using the WebDriver API. + */ + rotatable?: boolean; + + /** + * The special key that is used by default on the given platform to perform keyboard shortcuts. + */ + shortcutKey?: string; + + /** + * Environments with this capability support CSS transforms. + */ + supportsCssTransforms?: boolean; + + /** + * Environments with this capability support asynchronous JavaScript execution. + */ + supportsExecuteAsync?: boolean; + + /** + * Environments with this capability support navigation to `data:` URIs. + */ + supportsNavigationDataUris?: boolean; + + /** {boolean} takesScreenshot + * Environments with this capability allow screenshots of the current screen to be taken. + */ + takesScreenshot?: boolean; + + /** + * Environments with this capability support interaction via touch commands. + */ + touchEnabled?: boolean; + + /** + * The version number of the current environment. + */ + version: string; + + /** + * Environments with this capability allow local storage and session storage to be set and retrieved using the + * WebDriver API. + */ + webStorageEnabled?: boolean; + } +} + +declare module 'leadfoot/helpers/pollUntil' { + import Promise = require('dojo/promise/Promise'); + + namespace pollUntil { } + + /** + * A {@link module:leadfoot/Command} helper that polls for a value within the client environment until the value exists + * or a timeout is reached. + * + * @param poller + * The poller function to execute on an interval. The function should return `null` or `undefined` if there is not a + * result. If the poller function throws, polling will halt. + * + * @param args + * An array of arguments to pass to the poller function when it is invoked. Only values that can be serialised to JSON, + * plus {@link module:leadfoot/Element} objects, can be specified as arguments. + * + * @param timeout + * The maximum amount of time to wait for a successful result, in milliseconds. If not specified, the current + * `executeAsync` maximum timeout for the session will be used. + * + * @param pollInterval + * The amount of time to wait between calls to the poller function, in milliseconds. If not specified, defaults to 67ms. + * + * @returns + * A {@link module:leadfoot/Command#then} callback function that, when called, returns a promise that resolves to the + * value returned by the poller function on success and rejects on failure. + * + * @example + * var Command = require('leadfoot/Command'); + * var pollUntil = require('leadfoot/helpers/pollUntil'); + * + * new Command(session) + * .get('http://example.com') + * .then(pollUntil('return document.getElementById("a");', 1000)) + * .then(function (elementA) { + * // element was found + * }, function (error) { + * // element was not found + * }); + * + * @example + * var Command = require('leadfoot/Command'); + * var pollUntil = require('leadfoot/helpers/pollUntil'); + * + * new Command(session) + * .get('http://example.com') + * .then(pollUntil(function (value) { + * var element = document.getElementById('a'); + * return element && element.value === value ? true : null; + * }, [ 'foo' ], 1000)) + * .then(function () { + * // value was set to 'foo' + * }, function (error) { + * // value was never set + * }); + */ + function pollUntil(poller: Function | string, args?: any[], timeout?: number, pollInterval?: number): (value: any) => Promise; + function pollUntil(poller: Function | string, timeout?: number, pollInterval?: number): (value: any) => Promise; + + export = pollUntil; +} + +declare module 'leadfoot/Command' { + import Element = require('leadfoot/Element'); + import Promise = require('dojo/promise/Promise'); + import Thenable = require('dojo/promise/Thenable'); + import Session = require('leadfoot/Session'); + + /** + * The Command class is a chainable, subclassable object type that can be used to execute commands serially against a + * remote WebDriver environment. The standard Command class includes methods from the {@link module:leadfoot/Session} + * and {@link module:leadfoot/Element} classes, so you can perform all standard session and element operations that + * come with Leadfoot without being forced to author long promise chains. + * + * In order to use the Command class, you first need to pass it a {@link module:leadfoot/Session} instance for it to + * use: + * + * ```js + * var command = new Command(session); + * ``` + * + * Once you have created the Command, you can then start chaining methods, and they will execute in order one after + * another: + * + * ```js + * command.get('http://example.com') + * .findByTagName('h1') + * .getVisibleText() + * .then(function (text) { + * assert.strictEqual(text, 'Example Domain'); + * }); + * ``` + * + * Because these operations are asynchronous, you need to use a `then` callback in order to retrieve the value from the + * last method. Command objects are Thenables, which means that they can be used with any Promises/A+ or ES6-confirmant + * Promises implementation, though there are some specific differences in the arguments and context that are provided + * to callbacks; see {@link module:leadfoot/Command#then} for more details. + * + * --- + * + * Each call on a Command generates a new Command object, which means that certain operations can be parallelised: + * + * ```js + * command = command.get('http://example.com'); + * Promise.all([ + * command.getPageTitle(), + * command.findByTagName('h1').getVisibleText() + * ]).then(function (results) { + * assert.strictEqual(results[0], results[1]); + * }); + * ``` + * + * In this example, the commands on line 3 and 4 both depend upon the `get` call completing successfully but are + * otherwise independent of each other and so execute here in parallel. This is different from commands in Intern 1 + * which were always chained onto the last called method within a given test. + * + * --- + * + * Command objects actually encapsulate two different types of interaction: *session* interactions, which operate + * against the entire browser session, and *element* interactions, which operate against specific elements taken from + * the currently loaded page. Things like navigating the browser, moving the mouse cursor, and executing scripts are + * session interactions; things like getting text displayed on the page, typing into form fields, and getting element + * attributes are element interactions. + * + * Session interactions can be performed at any time, from any Command. On the other hand, to perform element + * interactions, you first need to retrieve one or more elements to interact with. This can be done using any of the + * `find` or `findAll` methods, by the `getActiveElement` method, or by returning elements from `execute` or + * `executeAsync` calls. The retrieved elements are stored internally as the *element context* of all chained + * Commands. When an element method is called on a chained Command with a single element context, the result will be + * returned as-is: + * + * ```js + * command = command.get('http://example.com') + * // finds one element -> single element context + * .findByTagName('h1') + * .getVisibleText() + * .then(function (text) { + * // `text` is the text from the element context + * assert.strictEqual(text, 'Example Domain'); + * }); + * ``` + * + * When an element method is called on a chained Command with a multiple element context, the result will be returned + * as an array: + * + * ```js + * command = command.get('http://example.com') + * // finds multiple elements -> multiple element context + * .findAllByTagName('p') + * .getVisibleText() + * .then(function (texts) { + * // `texts` is an array of text from each of the `p` elements + * assert.deepEqual(texts, [ + * 'This domain is established to be used for […]', + * 'More information...' + * ]); + * }); + * ``` + * + * The `find` and `findAll` methods are special and change their behaviour based on the current element filtering state + * of a given command. If a command has been filtered by element, the `find` and `findAll` commands will only find + * elements *within* the currently filtered set of elements. Otherwise, they will find elements throughout the page. + * + * Some method names, like `click`, are identical for both Session and Element APIs; in this case, the element APIs + * are suffixed with the word `Element` in order to identify them uniquely. + * + * --- + * + * Commands can be subclassed in order to add additional functionality without making direct modifications to the + * default Command prototype that might break other parts of the system: + * + * ```js + * function CustomCommand() { + * Command.apply(this, arguments); + * } + * CustomCommand.prototype = Object.create(Command.prototype); + * CustomCommand.prototype.constructor = CustomCommand; + * CustomCommand.prototype.login = function (username, password) { + * return new this.constructor(this, function () { + * return this.parent + * .findById('username') + * .click() + * .type(username) + * .end() + * .findById('password') + * .click() + * .type(password) + * .end() + * .findById('login') + * .click() + * .end(); + * }); + * }; + * ``` + * + * Note that returning `this`, or a command chain starting from `this`, from a callback or command initialiser will + * deadlock the Command, as it waits for itself to settle before settling. + */ + class Command implements Thenable { + /** + * @constructor module:leadfoot/Command + * @param {module:leadfoot/Command|module:leadfoot/Session} parent + * The parent command that this command is chained to, or a {@link module:leadfoot/Session} object if this is the + * first command in a command chain. + * + * @param {function(setContext:Function, value:any): (any|Promise)} initialiser + * A function that will be executed when all parent commands have completed execution. This function can create a + * new context for this command by calling the passed `setContext` function any time prior to resolving the Promise + * that it returns. If no context is explicitly provided, the context from the parent command will be used. + * + * @param {(function(setContext:Function, error:Error): (any|Promise))=} errback + * A function that will be executed if any parent commands failed to complete successfully. This function can create + * a new context for the current command by calling the passed `setContext` function any time prior to resolving the + * Promise that it returns. If no context is explicitly provided, the context from the parent command will be used. + */ + constructor( + parent: Command | Session, + initialiser?: (setContext: Command.ContextSetter, value: any) => Thenable | T, + errback?: (setContext: Command.ContextSetter, error: Error) => Thenable | T + ); + + /** + * The parent Command of the Command, if one exists. + * + * @readonly + */ + parent: Command; + + /** + * The parent Session of the Command. + * + * @readonly + */ + session: Session; + + /** + * The filtered elements that will be used if an element-specific method is invoked. Note that this property is not + * valid until the parent Command has been settled. The context array also has two additional properties: + * + * - isSingle (boolean): If true, the context will always contain a single element. This is used to differentiate + * between methods that should still return scalar values (`find`) and methods that should return arrays of + * values even if there is only one element in the context (`findAll`). + * - depth (number): The depth of the context within the command chain. This is used to prevent traversal into + * higher filtering levels by {@link module:leadfoot/Command#end}. + * + * @readonly + */ + context: Command.Context; + + /** + * The underlying Promise for the Command. + * + * @readonly + */ + promise: Promise; + + /** + * Pauses execution of the next command in the chain for `ms` milliseconds. + * + * @param {number} ms Time to delay, in milliseconds. + * @returns {module:leadfoot/Command.} + */ + sleep(ms: number): Command; + + /** + * Ends the most recent filtering operation in the current Command chain and returns the set of matched elements + * to the previous state. This is equivalent to the `jQuery#end` method. + * + * @example + * command + * .findById('parent') // sets filter to #parent + * .findByClassName('child') // sets filter to all .child inside #parent + * .getVisibleText() + * .then(function (visibleTexts) { + * // all the visible texts from the children + * }) + * .end() // resets filter to #parent + * .end(); // resets filter to nothing (the whole document) + * + * @param numCommandsToPop The number of element contexts to pop. Defaults to 1. + */ + end(numCommandsToPop?: number): Command; + + /** + * Adds a callback to be invoked once the previously chained operation has completed. + * + * This method is compatible with the `Promise#then` API, with two important differences: + * + * 1. The context (`this`) of the callback is set to the Command object, rather than being `undefined`. This allows + * promise helpers to be created that can retrieve the appropriate session and element contexts for execution. + * 2. A second non-standard `setContext` argument is passed to the callback. This `setContext` function can be + * called at any time before the callback fulfills its return value and expects either a single + * {@link module:leadfoot/Element} or an array of Elements to be provided as its only argument. The provided + * element(s) will be used as the context for subsequent element method invocations (`click`, etc.). If + * the `setContext` method is not called, the element context from the parent will be passed through unmodified. + * + * @param {Function=} callback + * @param {Function=} errback + * @returns {module:leadfoot/Command.} + */ + then( + callback: (value: T, setContext?: Command.ContextSetter) => Thenable | U, + errback?: (error: Error, setContext?: Command.ContextSetter) => Thenable | U + ): Command; + + /** + * Adds a callback to be invoked when any of the previously chained operations have failed. + */ + catch(errback: (error: Error, setContext?: Command.ContextSetter) => Thenable | U): Command; + + /** + * Adds a callback to be invoked once the previously chained operations have resolved. + */ + finally(callback: (valueOrError: T | Error, setContext?: Command.ContextSetter) => Thenable | U): Command; + + /** + * Cancels all outstanding chained operations of the Command. Calling this method will cause this command and all + * subsequent chained commands to fail with a CancelError. + */ + cancel(): Command; + + /** + * Gets the current value of a timeout for the session. + * + * @param type The type of timeout to retrieve. One of 'script', 'implicit', or 'page load'. + * @returns The timeout, in milliseconds. + */ + getTimeout(type: string): Command; + + /** + * Sets the value of a timeout for the session. + * + * @param type + * The type of timeout to set. One of 'script', 'implicit', or 'page load'. + * + * @param ms + * The length of time to use for the timeout, in milliseconds. A value of 0 will cause operations to time out + * immediately. + */ + setTimeout(type: string, ms: number): Command; + + /** + * Gets the identifier for the window that is currently focused. + * + * @returns A window handle identifier that can be used with other window handling functions. + */ + getCurrentWindowHandle(): Command; + + /** + * Gets a list of identifiers for all currently open windows. + */ + getAllWindowHandles(): Command; + + /** + * Gets the URL that is loaded in the focused window/frame. + */ + getCurrentUrl(): Command; + + /** + * Navigates the focused window/frame to a new URL. + */ + get(url: string): Command; + + /** + * Navigates the focused window/frame forward one page using the browser’s navigation history. + */ + goForward(): Command; + + /** + * Navigates the focused window/frame back one page using the browser’s navigation history. + */ + goBack(): Command; + + /** + * Reloads the current browser window/frame. + */ + refresh(): Command; + + /** + * Executes JavaScript code within the focused window/frame. The code should return a value synchronously. + * + * @see {@link module:leadfoot/Session#executeAsync} to execute code that returns values asynchronously. + * + * @param script + * The code to execute. If a string value is passed, it will be converted to a function on the remote end. + * + * @param args + * An array of arguments that will be passed to the executed code. Only values that can be serialised to JSON, plus + * {@link module:leadfoot/Element} objects, can be specified as arguments. + * + * @returns + * The value returned by the remote code. Only values that can be serialised to JSON, plus DOM elements, can be + * returned. + */ + execute(script: Function | string, args: any[]): Command; + + /** + * Executes JavaScript code within the focused window/frame. The code must invoke the provided callback in + * order to signal that it has completed execution. + * + * @see {@link module:leadfoot/Session#execute} to execute code that returns values synchronously. + * @see {@link module:leadfoot/Session#setExecuteAsyncTimeout} to set the time until an asynchronous script is + * considered timed out. + * + * @param script + * The code to execute. If a string value is passed, it will be converted to a function on the remote end. + * + * @param args + * An array of arguments that will be passed to the executed code. Only values that can be serialised to JSON, plus + * {@link module:leadfoot/Element} objects, can be specified as arguments. In addition to these arguments, a + * callback function will always be passed as the final argument to the script. This callback function must be + * invoked in order to signal that execution has completed. The return value of the script, if any, should be passed + * to this callback function. + * + * @returns + * The value returned by the remote code. Only values that can be serialised to JSON, plus DOM elements, can be + * returned. + */ + executeAsync(script: Function | string, args: any[]): Command; + + /** + * Gets a screenshot of the focused window and returns it in PNG format. + * + * @returns A buffer containing a PNG image. + */ + takeScreenshot(): Command; + + /** + * Gets a list of input method editor engines available to the remote environment. + * As of April 2014, no known remote environments support IME functions. + */ + getAvailableImeEngines(): Command; + + /** + * Gets the currently active input method editor for the remote environment. + * As of April 2014, no known remote environments support IME functions. + */ + getActiveImeEngine(): Command; + + /** + * Returns whether or not an input method editor is currently active in the remote environment. + * As of April 2014, no known remote environments support IME functions. + */ + isImeActivated(): Command; + + /** + * Deactivates any active input method editor in the remote environment. + * As of April 2014, no known remote environments support IME functions. + */ + deactivateIme(): Command; + + /** + * Activates an input method editor in the remote environment. + * As of April 2014, no known remote environments support IME functions. + * + * @param engine The type of IME to activate. + */ + activateIme(engine: string): Command; + + /** + * Switches the currently focused frame to a new frame. + * + * @param id + * The frame to switch to. In most environments, a number or string value corresponds to a key in the + * `window.frames` object of the currently active frame. If `null`, the topmost (default) frame will be used. + * If an Element is provided, it must correspond to a `` or `