diff --git a/README.md b/README.md
index b188982fbf..7da7d1530b 100644
--- a/README.md
+++ b/README.md
@@ -4,36 +4,221 @@
> 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. |
+
+`index.d.ts` should start with a header looking like:
+
+```ts
+// Type definitions for foo 1.2
+// Project: https://github.com/baz/foo
+// Definitions by: My Self
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+```
+
+The `Project` link does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.
+
+`tsconfig.json` should look like this:
+
+```json
+{
+ "compilerOptions": {
+ "module": "commonjs",
+ "target": "es6",
+ "noImplicitAny": true,
+ "strictNullChecks": false,
+ "baseUrl": "../",
+ "typeRoots": [
+ "../"
+ ],
+ "types": [],
+ "noEmit": true,
+ "forceConsistentCasingInFileNames": true
+ },
+ "files": [
+ "index.d.ts",
+ "foo-tests.ts"
+ ]
+}
+```
+
+These should be identical accross projects except that `foo-tests` will be replaced with the name of your test file,
+and you may also add the `"jsx"` compiler option if your library needs it.
+
+DefinitelyTyped members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down.
+
+
+#### 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 Foo { new(): Foo }`:
+ This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }
+* `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" }`.
+
+
+## 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 written as 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.
+
+#### 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/angular-material/index.d.ts b/angular-material/index.d.ts
index d4020a8c2a..610dcf34d7 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 {
diff --git a/angular-ui-router-default/angular-ui-router-default-tests.ts b/angular-ui-router-default/angular-ui-router-default-tests.ts
new file mode 100644
index 0000000000..2b6bfbe61e
--- /dev/null
+++ b/angular-ui-router-default/angular-ui-router-default-tests.ts
@@ -0,0 +1,39 @@
+///
+
+angular.module("test", [
+ "ui.router",
+ "ui.router.default"
+])
+ .config(function($stateProvider: angular.ui.IStateProvider) {
+ $stateProvider
+ .state('concrete', {
+ // no abstract or default
+ })
+ .state('string', {
+ abstract: true,
+ default: 'concrete'
+ })
+ .state('func_str', {
+ abstract: true,
+ default: function($rootScope): string { return $rootScope.test; }
+ })
+ .state('func_promise', {
+ abstract: true,
+ default: function($q: ng.IQService): ng.IPromise {
+ return $q.when("concrete");
+ }
+ })
+ .state('injection_str', {
+ abstract: true,
+ default: ["$rootScope", function($rootScope) {
+ return $rootScope.test;
+ }]
+ })
+ .state('injection_promise', {
+ abstract: true,
+ default: ["$q", function($q: ng.IQService) {
+ return $q.when("concrete");
+ }]
+ })
+ ;
+ });
diff --git a/angular-ui-router-default/angular-ui-router-default.d.ts b/angular-ui-router-default/angular-ui-router-default.d.ts
new file mode 100644
index 0000000000..9d102681cf
--- /dev/null
+++ b/angular-ui-router-default/angular-ui-router-default.d.ts
@@ -0,0 +1,17 @@
+// Type definitions for angular-ui-router-default 0.5+
+// Project: https://github.com/nonplus/angular-ui-router-default
+// Definitions by: Stepan Riha
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+///
+
+declare namespace angular.ui {
+ export type StateDefaultSpecifier = string
+ | ((...args: any[]) => string)
+ | ((...args: any[]) => ng.IPromise)
+ | (string | ((...args: any[]) => string))[]
+ | (string | ((...args: any[]) => ng.IPromise))[];
+ interface IState {
+ default?: StateDefaultSpecifier
+ }
+}
diff --git a/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts b/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts
new file mode 100644
index 0000000000..3f14b2a40f
--- /dev/null
+++ b/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts
@@ -0,0 +1,30 @@
+///
+
+angular.module("test", [
+ "ui.bootstrap",
+ "ui.router",
+ "ui.router.default"
+])
+ .config(function($stateProvider: angular.ui.IStateProvider) {
+ $stateProvider
+ .state('contacts', {
+ // no modal
+ resolve: {
+ a: function() {
+ return "a";
+ },
+ b: function() {
+ return ["a", "b"];
+ }
+ }
+ })
+ .state('contacts.contact', {
+ // boolean modal
+ modal: true
+ })
+ .state('contacts.contact.edit', {
+ // string[] modal
+ modal: ["a", "b"]
+ })
+ ;
+ });
diff --git a/angular-ui-router-uib-modal/angular-ui-router-uib-modal.d.ts b/angular-ui-router-uib-modal/angular-ui-router-uib-modal.d.ts
new file mode 100644
index 0000000000..598fe964fe
--- /dev/null
+++ b/angular-ui-router-uib-modal/angular-ui-router-uib-modal.d.ts
@@ -0,0 +1,12 @@
+// Type definitions for angular-ui-uib-modal 0.11+ (ui.router module)
+// Project: https://github.com/nonplus/angular-ui-router-uib-modal
+// Definitions by: Stepan Riha
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+///
+
+declare namespace angular.ui {
+ interface IState {
+ modal?: boolean | string[];
+ }
+}
diff --git a/angular/angular-tests.ts b/angular/angular-tests.ts
index 639534e8be..8e0711d6f7 100644
--- a/angular/angular-tests.ts
+++ b/angular/angular-tests.ts
@@ -278,8 +278,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 +354,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..ede4733708 100644
--- a/angular/index.d.ts
+++ b/angular/index.d.ts
@@ -1043,6 +1043,7 @@ declare namespace angular {
* @param value Value or a promise
*/
when(value: IPromise|T): IPromise;
+ when(value: IPromise|T, successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*/
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/archiver/archiver-tests.ts b/archiver/archiver-tests.ts
index 3bef66a44c..d79b29f079 100644
--- a/archiver/archiver-tests.ts
+++ b/archiver/archiver-tests.ts
@@ -11,4 +11,12 @@ var readStream = FS.createReadStream('./archiver.d.ts');
archiver.pipe(writeStream);
archiver.append(readStream, {name: 'archiver.d.ts'});
-archiver.finalize();
\ No newline at end of file
+archiver.finalize();
+
+archiver.directory('./path', './someOtherPath');
+archiver.directory('./path', { name: "testName"} );
+
+archiver.directory('./', "", {});
+archiver.directory('./', {name: 'test'}, {});
+
+archiver.bulk({ mappaing: {} });
\ No newline at end of file
diff --git a/archiver/index.d.ts b/archiver/index.d.ts
index df824c3915..d67705e2ea 100644
--- a/archiver/index.d.ts
+++ b/archiver/index.d.ts
@@ -25,6 +25,11 @@ interface nameInterface {
interface Archiver extends STREAM.Transform {
pipe(writeStream: FS.WriteStream): void;
append(source: FS.ReadStream | Buffer | string, name: nameInterface): void;
+
+ directory(dirpath: string, destpath: nameInterface | string): void;
+ directory(dirpath: string, destpath: nameInterface | string, data: any | Function): void;
+
+ bulk(mappings: any): void;
finalize(): void;
}
diff --git a/async-polling/async-polling-tests.ts b/async-polling/async-polling-tests.ts
new file mode 100644
index 0000000000..ec9e5200f2
--- /dev/null
+++ b/async-polling/async-polling-tests.ts
@@ -0,0 +1,64 @@
+///
+
+import * as AsyncPolling from "async-polling";
+
+// Tests based on examples in https://github.com/cGuille/async-polling#readme
+
+AsyncPolling(end => {
+ end();
+}, 3000).run();
+
+function someAsynchroneProcess(callback: (error?: Error, response?: any) => any): any {
+ callback();
+}
+
+let polling = AsyncPolling(end => {
+ someAsynchroneProcess(function (error, response) {
+ if (error) {
+ end(error);
+ return;
+ }
+
+ end(null, response);
+ });
+}, 3000);
+polling.on("error", (error: Error) => {});
+polling.on("result", (result: any) => {});
+polling.run();
+polling.stop();
+
+AsyncPolling(function(end) {
+ this.stop();
+ end();
+}, 3000).run();
+
+let i = 0;
+
+polling = AsyncPolling(function(end) {
+ ++i;
+ if (i === 3) {
+ return end(new Error("i is " + i));
+ }
+ if (i >= 5) {
+ this.stop();
+ return end(null, `#${i} stop`);
+ }
+ end(null, `#${i} wait a second...`);
+}, 1000);
+
+const eventNames: AsyncPolling.EventName[] = ["run", "start", "end", "schedule", "stop"];
+eventNames.forEach(eventName => {
+ polling.on(eventName, () => {
+ console.log("lifecycle:", eventName);
+ });
+});
+
+polling.on("result", (result: any) => {
+ console.log("result:", result);
+});
+
+polling.on("error", (error: Error) => {
+ console.error("error:", error);
+});
+
+polling.run();
\ No newline at end of file
diff --git a/async-polling/async-polling.d.ts b/async-polling/async-polling.d.ts
new file mode 100644
index 0000000000..579d041e37
--- /dev/null
+++ b/async-polling/async-polling.d.ts
@@ -0,0 +1,18 @@
+// Type definitions for AsyncPolling
+// Project: https://github.com/cGuille/async-polling
+// Definitions by: Zlatko Andonovski
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare module "async-polling" {
+ module AsyncPolling {
+ export type EventName = "run"|"start"|"error"|"result"|"end"|"schedule"|"stop";
+ }
+
+ function AsyncPolling(pollingFunc: (end: (err?: Error, result?: Result) => any) => any, delay: number): {
+ run: () => any;
+ stop: () => any;
+ on: (eventName: AsyncPolling.EventName, listener: Function) => any;
+ }
+
+ export = AsyncPolling;
+}
\ No newline at end of file
diff --git a/awesomplete/awesomplete-tests.ts b/awesomplete/awesomplete-tests.ts
new file mode 100644
index 0000000000..8132ad4555
--- /dev/null
+++ b/awesomplete/awesomplete-tests.ts
@@ -0,0 +1,57 @@
+///
+
+var input = document.getElementById("myinput");
+new Awesomplete(input, {list: "#mylist"});
+
+new Awesomplete(input, {list: document.querySelector("#mylist")});
+
+new Awesomplete(input, {
+ list: ["Ada", "Java", "JavaScript", "LOLCODE", "Node.js", "Ruby on Rails"]
+});
+
+var awesomplete = new Awesomplete(input);
+awesomplete.list = ["Ada", "Java", "JavaScript", "LOLCODE", "Node.js", "Ruby on Rails"];
+
+new Awesomplete(input, {
+ list: [
+ { label: "Belarus", value: "BY" },
+ { label: "China", value: "CN" },
+ { label: "United States", value: "US" }
+ ]
+});
+
+// Same with arrays:
+new Awesomplete(input, {
+ list: [
+ [ "Belarus", "BY" ],
+ [ "China", "CN" ],
+ [ "United States", "US" ]
+ ]
+});
+
+new Awesomplete('input[type="email"]', {
+ list: ["aol.com", "att.net", "comcast.net", "facebook.com", "gmail.com", "gmx.com", "googlemail.com", "google.com", "hotmail.com", "hotmail.co.uk", "mac.com", "me.com", "mail.com", "msn.com", "live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk"],
+ data: function (text: string, input: any) {
+ return input.slice(0, input.indexOf("@")) + "@" + text;
+ },
+ filter: Awesomplete.FILTER_STARTSWITH
+});
+
+new Awesomplete('input[data-multiple]', {
+ filter: function(text: string, input: any) {
+ return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]);
+ },
+
+ replace: function(text: string) {
+ var before = this.input.value.match(/^.+,\s*|/)[0];
+ this.input.value = before + text + ", ";
+ }
+});
+
+var ajax = new XMLHttpRequest();
+ajax.open("GET", "https://restcountries.eu/rest/v1/lang/fr", true);
+ajax.onload = function() {
+ var list = JSON.parse(ajax.responseText).map(function(i: any) { return i.name; });
+ new Awesomplete(document.querySelector("#ajax-example input"),{ list: list });
+};
+ajax.send();
\ No newline at end of file
diff --git a/awesomplete/awesomplete.d.ts b/awesomplete/awesomplete.d.ts
new file mode 100644
index 0000000000..d39389f008
--- /dev/null
+++ b/awesomplete/awesomplete.d.ts
@@ -0,0 +1,49 @@
+// Type definitions for Awesomplete v1.1.0
+// Project: https://leaverou.github.io/awesomplete/
+// Definitions by: webbiesdk , Ben Dixon
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare class Awesomplete {
+ constructor(input: Element | HTMLElement | string, o?: AwesompleteOptions);
+ static all: Array;
+ static $$: (expr: string | NodeSelector, con?: any) => NodeList;
+ static ITEM: (text: string, input: string) => HTMLElement;
+ static $: {
+ (expr: string|Element, con?: NodeSelector): string | Element;
+ regExpEscape: (s: { replace: (arg0: RegExp, arg1: string) => void }) => any;
+ create: (tag: string, o: any) => HTMLElement;
+ fire: (target: EventTarget, type: string, properties: any) => any;
+ siblingIndex: (el: Element) => number;
+ };
+ static FILTER_STARTSWITH: (text: string, input: string) => boolean;
+ static FILTER_CONTAINS: (text: string, input: string) => boolean;
+ static SORT_BYLENGTH: (a: number | any[], b: number | any[]) => number;
+ static REPLACE: (text: any) => void;
+ next: () => void;
+ container: HTMLElement;
+ select: (selected?: HTMLElement, originalTarget?: HTMLElement) => void;
+ previous: () => void;
+ index: number;
+ opened: number;
+ list: string | string[] | Element | { label: string, value: any }[] | [string, string][];
+ input: HTMLElement | string;
+ goto: (i: number) => void;
+ ul: HTMLElement;
+ close: () => void;
+ evaluate: () => void;
+ selected: boolean;
+ open: () => void;
+ status: HTMLElement;
+}
+
+interface AwesompleteOptions {
+ list?: string | string[] | Element | { label: string, value: any }[] | [string, string][];
+ minChars?: Number;
+ maxItems?: Number;
+ autoFirst?: boolean;
+ data?: Function;
+ filter?: Function;
+ sort?: Function;
+ item?: Function;
+ replace?: Function;
+}
diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts
index ea695d728d..f54c3cc2d4 100644
--- a/aws-lambda/aws-lambda-tests.ts
+++ b/aws-lambda/aws-lambda-tests.ts
@@ -54,7 +54,6 @@ function callback(cb: AWSLambda.Callback) {
cb(error);
cb(null, anyObj);
}
-
/* Compatibility functions */
context.done();
context.done(error);
diff --git a/aws-sdk/index.d.ts b/aws-sdk/index.d.ts
index 83ecb93f53..7d70edf939 100644
--- a/aws-sdk/index.d.ts
+++ b/aws-sdk/index.d.ts
@@ -522,7 +522,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
diff --git a/aws-serverless-express/aws-serverless-express-tests.ts b/aws-serverless-express/aws-serverless-express-tests.ts
new file mode 100644
index 0000000000..6a0d7694d9
--- /dev/null
+++ b/aws-serverless-express/aws-serverless-express-tests.ts
@@ -0,0 +1,29 @@
+///
+///
+
+import * as awsServerlessExpress from 'aws-serverless-express';
+import * as express from 'express';
+
+const app = express();
+const server = awsServerlessExpress.createServer(app, () => {});
+
+const mockEvent = {
+ key: 'value'
+};
+
+const mockContext = {
+ callbackWaitsForEmptyEventLoop: true,
+ functionName: 'testFunction',
+ functionVersion: '1',
+ invokedFunctionArn: 'arn',
+ memoryLimitInMB: 128,
+ awsRequestId: 'id',
+ logGroupName: 'group',
+ logStreamName: 'stream',
+ getRemainingTimeInMillis: () => 2000,
+ done: () => false,
+ fail: (error: any) => false,
+ succeed: (message: string) => false
+};
+
+awsServerlessExpress.proxy(server, mockEvent, mockContext);
diff --git a/aws-serverless-express/aws-serverless-express.d.ts b/aws-serverless-express/aws-serverless-express.d.ts
new file mode 100644
index 0000000000..50aa0e1a0b
--- /dev/null
+++ b/aws-serverless-express/aws-serverless-express.d.ts
@@ -0,0 +1,24 @@
+// Type definitions for aws-serverless-express
+// Project: https://github.com/awslabs/aws-serverless-express
+// Definitions by: Ben Speakman
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+///
+///
+
+declare module 'aws-serverless-express' {
+
+ import * as http from 'http';
+ import * as lambda from 'aws-lambda';
+
+ export function createServer(
+ requestListener: (request: http.IncomingMessage, response: http.ServerResponse) => http.Server,
+ serverListenCallback?: () => any
+ ): http.Server;
+
+ export function proxy(
+ server: http.Server,
+ event: any,
+ context: lambda.Context
+ ): void;
+}
diff --git a/axios/axios-tests.ts b/axios/axios-tests.ts
index 1f05653229..a321e97f19 100644
--- a/axios/axios-tests.ts
+++ b/axios/axios-tests.ts
@@ -69,6 +69,10 @@ axios.post("http://example.com/", {
]
});
+var config: Axios.AxiosXHRConfigBase = {headers: {}};
+config.headers['X-Custom-Header'] = 'baz';
+axios.post("http://example.com/", config);
+
var getRepoIssue = axios.get("https://api.github.com/repos/mzabriskie/axios/issues/1");
var axiosInstance = axios.create({
diff --git a/axios/index.d.ts b/axios/index.d.ts
index 9c4705d093..a2c5bfbd45 100644
--- a/axios/index.d.ts
+++ b/axios/index.d.ts
@@ -39,7 +39,7 @@ declare namespace Axios {
/**
* custom headers to be sent
*/
- headers?: Object;
+ headers?: {[key: string]: any};
/**
* URL parameters to be sent with the request
diff --git a/bases/bases-tests.ts b/bases/bases-tests.ts
new file mode 100644
index 0000000000..5414b18764
--- /dev/null
+++ b/bases/bases-tests.ts
@@ -0,0 +1,10 @@
+///
+import * as bases from 'bases';
+
+let bs16String: string = bases.toBase(200, 16); // => 'c8'
+let bs62String: string = bases.toBase(99999, 62); // => 'q0T'
+let customBaseString: string = bases.toAlphabet(300, 'aAbBcC'); // => 'Abba'
+
+let frombs16Int: number = bases.fromBase('c8', 16); // => 200
+let frombs62Int: number = bases.fromBase('q0T', 62); // => 99999
+let customBaseInt: number = bases.fromAlphabet('Abba', 'aAbBcC'); // => 300
diff --git a/bases/bases.d.ts b/bases/bases.d.ts
new file mode 100644
index 0000000000..2e62cf685a
--- /dev/null
+++ b/bases/bases.d.ts
@@ -0,0 +1,22 @@
+// Type definitions for bases 0.2.1
+// Project: https://github.com/aseemk/bases.js
+// Definitions by: Hari Krishna
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare module "bases" {
+ export function toAlphabet(num: number, alphabet: string): string;
+
+ export function fromAlphabet(str: string, alphabet: string): number;
+
+ export function toBase(num: number, base: number): string;
+
+ export function fromBase(str: string, base:number): number;
+
+ export let KNOWN_ALPHABETS: any;
+
+ export let NUMERALS: string;
+
+ export let LETTERS_LOWERCASE: string;
+
+ export let LETTERS_UPPERCASE: string;
+}
diff --git a/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..b97794b071
--- /dev/null
+++ b/bonjour/bonjour-tests.ts
@@ -0,0 +1,21 @@
+///
+import * as bonjour from 'bonjour';
+
+var bonjourOptions: bonjour.BonjourOptions;
+var bonjourInstance: bonjour.Bonjour;
+
+var serviceOptions: bonjour.ServiceOptions;
+var service: bonjour.Service;
+
+var browserOptions: bonjour.BrowserOptions;
+var browser: bonjour.Browser;
+
+bonjourOptions = { interface: '192.168.1.1', port: 5353 };
+bonjourInstance = new bonjour.Bonjour(bonjourOptions);
+
+serviceOptions = { name: 'My Web Server', type: 'http', port: 3000 };
+service = bonjourInstance.publish(serviceOptions);
+
+browserOptions = { protocol: 'tcp', type: 'http' };
+browser = bonjour.find(browserOptions);
+
diff --git a/bonjour/bonjour.d.ts b/bonjour/bonjour.d.ts
new file mode 100644
index 0000000000..0ffd9f1171
--- /dev/null
+++ b/bonjour/bonjour.d.ts
@@ -0,0 +1,71 @@
+// Type definitions for bonjour v3.5.0
+// Project: https://github.com/watson/bonjour
+// Definitions by: Quentin Lampin
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare module "bonjour" {
+ export interface BonjourOptions {
+ multicast?: boolean;
+ interface?: string;
+ port?: number;
+ ip?: string;
+ ttl?: number;
+ loopback?: boolean;
+ reuseAddr?: boolean;
+ }
+
+ export interface BrowserOptions {
+ type?: string;
+ subtypes?: string[];
+ protocol?: string;
+ txt?: Object;
+ }
+
+ export interface ServiceOptions {
+ name: string;
+ host?: string;
+ port: number;
+ type: string;
+ subtypes?: string[];
+ protocol?: 'udp'|'tcp';
+ txt?: Object;
+ }
+
+ export interface Service {
+ name: string;
+ type: string;
+ subtypes: string[];
+ protocol: string;
+ host: string;
+ port: number;
+ fqdn: string;
+ rawTxt: Object;
+ txt: Object;
+ published: boolean;
+
+ stop: (cb: ()=>any) => void;
+ start: () => void;
+ }
+
+ export class Bonjour {
+
+ constructor(opts: BonjourOptions);
+ publish(options: ServiceOptions):Service;
+ unpublishAll(cb: ()=>any): void;
+ find(options:BrowserOptions, onUp: ()=>any): Browser;
+ findOne(options:any, cb: (service: Service)=>any): Browser;
+ destroy():void;
+ }
+
+ export class Browser {
+ services: Service[];
+
+ start():void;
+ update():void;
+ stop():void;
+ }
+
+ export function find(options: BrowserOptions, onUp?: ()=>any): Browser;
+ export function findOne(options: BrowserOptions): Browser;
+
+}
diff --git a/bootbox/index.d.ts b/bootbox/index.d.ts
index ea6d4d9664..40494d5ca5 100644
--- a/bootbox/index.d.ts
+++ b/bootbox/index.d.ts
@@ -40,6 +40,7 @@ interface BootboxConfirmOptions extends BootboxDialogOptions {
interface BootboxPromptOptions extends BootboxBaseOptions {
title: string;
value?: string;
+ inputType?: string;
callback: (result: string) => any;
buttons?: BootboxConfirmPromptButtonMap;
}
diff --git a/bootstrap-datepicker/index.d.ts b/bootstrap-datepicker/index.d.ts
index 39b8846cd0..1f9fd065d2 100644
--- a/bootstrap-datepicker/index.d.ts
+++ b/bootstrap-datepicker/index.d.ts
@@ -36,6 +36,7 @@ interface DatepickerOptions {
multidateSeparator?: string;
orientation?: string;
assumeNearbyYear?: any;
+ viewMode?: string;
}
interface DatepickerCustomFormatOptions {
diff --git a/bootstrap-table/bootstrap-table.d.ts b/bootstrap-table/bootstrap-table.d.ts
new file mode 100644
index 0000000000..d0356dff84
--- /dev/null
+++ b/bootstrap-table/bootstrap-table.d.ts
@@ -0,0 +1,12 @@
+// Type definitions for Bootstrap Table v1.11.0
+// Project: http://bootstrap-table.wenzhixin.net.cn/
+// Definitions by: Talat Baig
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+///
+
+interface JQuery {
+ bootstrapTable(options?: any): JQuery;
+}
+
+declare var bootstrapTable: JQueryStatic;
diff --git a/braintree-web/braintree-web-tests.ts b/braintree-web/braintree-web-tests.ts
index 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 `` dropdown list. This can only be used for `expirationMonth` and `expirationYear` fields.
+ * @property {string[]} [select.options] An array of 12 strings, one per month. This can only be used for the `expirationMonth` field. For example, the array can look like `['01 - January', '02 - February', ...]`.
*/
interface HostedFieldsField {
selector: string;
placeholder?: string;
+ type?: string;
formatInput?: boolean;
+ select?: boolean | { options: string[] };
}
/**
diff --git a/bull/index.d.ts b/bull/index.d.ts
index 8a8de1870d..c604fe25d6 100644
--- a/bull/index.d.ts
+++ b/bull/index.d.ts
@@ -1,4 +1,4 @@
-// Type definitions for bull 0.7.0
+// Type definitions for bull 1.0.0
// Project: https://github.com/OptimalBits/bull
// Definitions by: Bruno Grieder
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -24,7 +24,7 @@ declare module "bull" {
export interface Job {
- id: string
+ jobId: string
/**
* The custom data passed when the job was created
diff --git a/bunyan/bunyan-tests.ts b/bunyan/bunyan-tests.ts
index 86a24f6bef..c609901b0a 100644
--- a/bunyan/bunyan-tests.ts
+++ b/bunyan/bunyan-tests.ts
@@ -55,7 +55,20 @@ var options:bunyan.LoggerOptions = {
var log = bunyan.createLogger(options);
+var customSerializer = function(anything: any) {
+ return { obj: anything};
+};
+
+log.addSerializers({anything: customSerializer});
log.addSerializers(bunyan.stdSerializers);
+log.addSerializers(
+ {
+ err: bunyan.stdSerializers.err,
+ req: bunyan.stdSerializers.req,
+ res: bunyan.stdSerializers.res
+ }
+);
+
var child = log.child({name: 'child'});
child.reopenFileStreams();
log.addStream({path: '/dev/null'});
diff --git a/bunyan/index.d.ts b/bunyan/index.d.ts
index ade8577847..79aa9e5f20 100644
--- a/bunyan/index.d.ts
+++ b/bunyan/index.d.ts
@@ -11,7 +11,7 @@ import { EventEmitter } from 'events';
declare class Logger extends EventEmitter {
constructor(options: LoggerOptions);
addStream(stream: Stream): void;
- addSerializers(serializers: Serializers): void;
+ addSerializers(serializers:Serializers | StdSerializers):void;
child(options: LoggerOptions, simple?: boolean): Logger;
child(obj: Object, simple?: boolean): Logger;
reopenFileStreams(): void;
@@ -21,7 +21,7 @@ declare class Logger extends EventEmitter {
levels(name: number | string, value: number | string): void;
fields: any;
- src: boolean;
+ src:boolean;
trace(error: Error, format?: any, ...params: any[]): void;
trace(buffer: Buffer, format?: any, ...params: any[]): void;
@@ -58,8 +58,18 @@ interface LoggerOptions {
src?: boolean;
}
+ interface Serializer {
+ (input:any): any;
+ }
+
interface Serializers {
- [key: string]: (input: any) => string;
+ [key:string]: Serializer;
+ }
+
+ interface StdSerializers {
+ err: Serializer;
+ res: Serializer;
+ req: Serializer;
}
interface Stream {
@@ -72,7 +82,7 @@ interface Stream {
count?: number;
}
-export declare var stdSerializers: Serializers;
+ export var stdSerializers:StdSerializers;
export declare var TRACE: number;
export declare var DEBUG: number;
diff --git a/bwip-js/bwip-js-tests.ts b/bwip-js/bwip-js-tests.ts
new file mode 100644
index 0000000000..71601f111a
--- /dev/null
+++ b/bwip-js/bwip-js-tests.ts
@@ -0,0 +1,43 @@
+///
+///
+'use strict';
+
+import * as bwipjs from 'bwip-js';
+import * as http from 'http';
+import * as fs from 'fs';
+
+bwipjs.loadFont('Inconsolata', 108,
+ fs.readFileSync('fonts/Inconsolata.otf', 'binary'));
+
+
+http.createServer(function(req, res) {
+ // If the url does not begin /?bcid= then 404. Otherwise, we end up
+ // returning 400 on requests like favicon.ico.
+ if (req.url.indexOf('/?bcid=') != 0) {
+ res.writeHead(404, { 'Content-Type':'text/plain' });
+ res.end('BWIPJS: Unknown request format.', 'utf8');
+ } else {
+ bwipjs(req, res);
+ }
+
+}).listen(3030);
+
+bwipjs.toBuffer({
+ bcid: 'code128', // Barcode type
+ text: '0123456789', // Text to encode
+ scale: 3, // 3x scaling factor
+ height: 10, // Bar height, in millimeters
+ includetext: true, // Show human-readable text
+ textxalign: 'center', // Always good to set this
+ textfont: 'Inconsolata', // Use your custom font
+ textsize: 13 // Font size, in points
+}, function (err:string|Error, png: Buffer) {
+ if (err) {
+ console.log(err);
+ } else {
+ // `png` is a Buffer
+ // png.length : PNG file length
+ // png.readUInt32BE(16) : PNG image width
+ // png.readUInt32BE(20) : PNG image height
+ }
+});
diff --git a/bwip-js/bwip-js.d.ts b/bwip-js/bwip-js.d.ts
new file mode 100644
index 0000000000..0f40b5771e
--- /dev/null
+++ b/bwip-js/bwip-js.d.ts
@@ -0,0 +1,86 @@
+// Type definitions for bwip-js 1.1.1
+// Project: https://github.com/metafloor/bwip-js
+// Definitions by: TANAKA Koichi
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+///
+
+declare module 'bwip-js' {
+ import {IncomingMessage as Request, ServerResponse as Response} from 'http';
+
+ module BwipJs {
+ export function loadFont(fontName:string, sizeMulti: number, fontFile: string): void;
+ export function toBuffer(opts: ToBufferOptions, callback:(err: string|Error, png: Buffer) => void): void;
+ interface ToBufferOptions {
+ bcid: string;
+ text: string;
+
+ parse?: boolean;
+ parsefunc?: boolean;
+
+ height?: number;
+ width?: number;
+
+ scaleX?: number;
+ scaleY?: number;
+ scale?: number;
+
+ rotate?: 'N'|'R'|'L'|'I';
+
+ paddingwidth?: number;
+ paddingheight?: number;
+
+ monochrome?: boolean;
+ alttext?: boolean;
+
+ includetext?: boolean;
+ textfont?: string;
+ textsize?: number;
+ textgaps?: number;
+
+ textxalign?:'offleft'|'left'|'center'|'right'|'offright'|'justify';
+ textyalign?:'below'|'center'|'above';
+ textxoffset?: number;
+ textyoffset?: number;
+
+ showborder?: boolean;
+ borderwidth?: number;
+ borderleft?: number;
+ borderright?: number;
+ bordertop?: number;
+ boraderbottom?: number;
+
+ barcolor?: string;
+ backgroundcolor?: string;
+ bordercolor?: string;
+ textcolor?: string;
+
+ addontextxoffset?: number;
+ addontextyoffset?: number;
+ addontextfont?: string;
+ addontextsize?: number;
+
+ guardwhitespace?: boolean;
+ guardwidth?: number;
+ guardheight?: number;
+ guardleftpos?: number;
+ guardrightpos?: number;
+ guardleftypos?: number;
+ guardrightypos?: number;
+
+ sizelimit?: number;
+
+ includecheck?: boolean;
+ includecheckintext?: boolean;
+
+ inkspread?: number;
+ inkspreadh?: number;
+ inkspreadv?: number;
+ }
+ }
+
+
+ function BwipJs(req: Request, res: Response, opts?:BwipJs.ToBufferOptions): void;
+
+ export = BwipJs;
+}
diff --git a/byline/byline-tests.ts b/byline/byline-tests.ts
index d21b8a196c..a2c0edd56c 100644
--- a/byline/byline-tests.ts
+++ b/byline/byline-tests.ts
@@ -6,8 +6,9 @@
import fs = require( 'fs' );
import byline = require( 'byline' );
-//TODO can this be typed in an ambient way?
-//var stream = byline( fs.createReadStream( 'sample.txt', {encoding: 'utf8'} ) );
+var stream = byline();
+
+var stream = byline( fs.createReadStream( 'sample.txt', {encoding: 'utf8'} ) );
var stream = byline.createStream( fs.createReadStream( 'sample.txt', {encoding: 'utf8'} ) );
diff --git a/byline/index.d.ts b/byline/index.d.ts
index 243db166cd..785a799a98 100644
--- a/byline/index.d.ts
+++ b/byline/index.d.ts
@@ -7,31 +7,38 @@
import stream = require("stream");
+declare function bl(): bl.LineStream;
+declare function bl(stream: NodeJS.ReadableStream, options?: bl.LineStreamOptions): bl.LineStream;
-export interface LineStreamOptions extends stream.TransformOptions {
- keepEmptyLines?: boolean;
+declare namespace bl {
+
+ export interface LineStreamOptions extends stream.TransformOptions {
+ keepEmptyLines?: boolean;
+ }
+
+ export interface LineStream extends stream.Transform {
+ }
+
+ export interface LineStreamCreatable extends LineStream {
+ new (options?: LineStreamOptions): LineStream
+ }
+
+ //TODO is it possible to declare static factory functions without name (directly on the module)
+ //
+ // JS:
+ // // convinience API
+ // module.exports = function(readStream, options) {
+ // return module.exports.createStream(readStream, options);
+ // };
+ //
+ // TS:
+ // ():LineStream; // same as createStream():LineStream
+ // (stream:stream.Stream, options?:LineStreamOptions):LineStream; // same as createStream(stream, options?):LineStream
+
+ export function createStream(): LineStream;
+ export function createStream(stream: NodeJS.ReadableStream, options?: LineStreamOptions): LineStream;
+
+ export var LineStream: LineStreamCreatable;
}
-export interface LineStream extends stream.Transform {
-}
-
-export interface LineStreamCreatable extends LineStream {
- new (options?: LineStreamOptions): LineStream
-}
-
-//TODO is it possible to declare static factory functions without name (directly on the module)
-//
-// JS:
-// // convinience API
-// module.exports = function(readStream, options) {
-// return module.exports.createStream(readStream, options);
-// };
-//
-// TS:
-// ():LineStream; // same as createStream():LineStream
-// (stream:stream.Stream, options?:LineStreamOptions):LineStream; // same as createStream(stream, options?):LineStream
-
-export declare function createStream(): LineStream;
-export declare function createStream(stream: NodeJS.ReadableStream, options?: LineStreamOptions): LineStream;
-
-export declare var LineStream: LineStreamCreatable;
+export = bl;
\ No newline at end of file
diff --git a/c3/index.d.ts b/c3/index.d.ts
index c8484bffb9..90b670c73c 100644
--- a/c3/index.d.ts
+++ b/c3/index.d.ts
@@ -1,10 +1,13 @@
-// Type definitions for C3js
+// Type definitions for C3js v0.4
// Project: http://c3js.org/
// Definitions by: Marc Climent
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///
+export = c3;
+export as namespace c3;
+
declare namespace c3 {
type PrimitiveArray = Array;
@@ -385,10 +388,10 @@ declare namespace c3 {
* - d is the data where mouse cursor moves out. In this callback, this will be the Chart object.
*/
onmouseout?: (d: any, element?: any) => void;
-
+
onselected?: (d: any, element?: any) => void;
- onunselected?: (d: any, element?: any) => void;
+ onunselected?: (d: any, element?: any) => void;
}
interface Axis {
diff --git a/c3/package.json b/c3/package.json
new file mode 100644
index 0000000000..5e771f4dcd
--- /dev/null
+++ b/c3/package.json
@@ -0,0 +1,5 @@
+{
+ "dependencies": {
+ "@types/d3": "^3.5.36"
+ }
+}
diff --git a/c3/tsconfig.json b/c3/tsconfig.json
index beb374a8ea..dd50256240 100644
--- a/c3/tsconfig.json
+++ b/c3/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",
"c3-tests.ts"
]
-}
\ No newline at end of file
+}
diff --git a/cal-heatmap/package.json b/cal-heatmap/package.json
new file mode 100644
index 0000000000..5e771f4dcd
--- /dev/null
+++ b/cal-heatmap/package.json
@@ -0,0 +1,5 @@
+{
+ "dependencies": {
+ "@types/d3": "^3.5.36"
+ }
+}
diff --git a/cal-heatmap/tsconfig.json b/cal-heatmap/tsconfig.json
index 69a3fe2a25..6b19258ef7 100644
--- a/cal-heatmap/tsconfig.json
+++ b/cal-heatmap/tsconfig.json
@@ -6,6 +6,7 @@
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
+ "node_modules/@types",
"../"
],
"types": [],
@@ -16,4 +17,4 @@
"index.d.ts",
"cal-heatmap-tests.ts"
]
-}
\ No newline at end of file
+}
diff --git a/camljs/index.d.ts b/camljs/index.d.ts
index b49337621d..73bbe03767 100644
--- a/camljs/index.d.ts
+++ b/camljs/index.d.ts
@@ -7,19 +7,20 @@
declare class CamlBuilder {
constructor();
/** Generate CAML Query, starting from tag */
- public Where(): CamlBuilder.IFieldExpression;
+ Where(): CamlBuilder.IFieldExpression;
/** Generate tag for SP.CamlQuery
- @param viewFields If omitted, default view fields are requested; otherwise, only values for the fields with the specified internal names are returned.
- Specifying view fields is a good practice, as it decreases traffic between server and client. */
- public View(viewFields?: string[]): CamlBuilder.IView;
+ @param viewFields If omitted, default view fields are requested; otherwise, only values for the fields with the specified internal names are returned.
+ Specifying view fields is a good practice, as it decreases traffic between server and client. */
+ View(viewFields?: string[]): CamlBuilder.IView;
/** Generate tag for SPServices */
- public ViewFields(viewFields: string[]): CamlBuilder.IFinalizableToString;
+ ViewFields(viewFields: string[]): CamlBuilder.IFinalizableToString;
/** Use for:
- 1. SPServices CAMLQuery attribute
- 2. Creating partial expressions
- 3. In conjunction with Any & All clauses
- */
+ 1. SPServices CAMLQuery attribute
+ 2. Creating partial expressions
+ 3. In conjunction with Any & All clauses
+ */
static Expression(): CamlBuilder.IFieldExpression;
+ static FromXml(xml: string): CamlBuilder.IRawQuery;
}
declare namespace CamlBuilder {
interface IView extends IJoinable, IFinalizable {
@@ -29,24 +30,24 @@ declare namespace CamlBuilder {
}
interface IJoinable {
/** Join the list you're querying with another list.
- Joins are only allowed through a lookup field relation.
- @param lookupFieldInternalName Internal name of the lookup field, that points to the list you're going to join in.
- @alias alias for the joined list */
+ Joins are only allowed through a lookup field relation.
+ @param lookupFieldInternalName Internal name of the lookup field, that points to the list you're going to join in.
+ @alias alias for the joined list */
InnerJoin(lookupFieldInternalName: string, alias: string): IJoin;
/** Join the list you're querying with another list.
- Joins are only allowed through a lookup field relation.
- @param lookupFieldInternalName Internal name of the lookup field, that points to the list you're going to join in.
- @alias alias for the joined list */
+ Joins are only allowed through a lookup field relation.
+ @param lookupFieldInternalName Internal name of the lookup field, that points to the list you're going to join in.
+ @alias alias for the joined list */
LeftJoin(lookupFieldInternalName: string, alias: string): IJoin;
}
interface IJoin extends IJoinable {
/** Select projected field for using in the main Query body
- @param remoteFieldAlias By this alias, the field can be used in the main Query body. */
+ @param remoteFieldAlias By this alias, the field can be used in the main Query body. */
Select(remoteFieldInternalName: string, remoteFieldAlias: string): IProjectableView;
}
interface IProjectableView extends IView {
/** Select projected field for using in the main Query body
- @param remoteFieldAlias By this alias, the field can be used in the main Query body. */
+ @param remoteFieldAlias By this alias, the field can be used in the main Query body. */
Select(remoteFieldInternalName: string, remoteFieldAlias: string): IProjectableView;
}
enum ViewScope {
@@ -57,7 +58,7 @@ declare namespace CamlBuilder {
/** */
FilesOnly = 2,
}
- interface IQuery {
+ interface IQuery extends IGroupable {
Where(): IFieldExpression;
}
interface IFinalizableToString {
@@ -70,21 +71,21 @@ declare namespace CamlBuilder {
}
interface ISortable extends IFinalizable {
/** Adds OrderBy clause to the query
- @param fieldInternalName Internal field of the first field by that the data will be sorted (ascending)
- @param override This is only necessary for large lists. DON'T use it unless you know what it is for!
- @param useIndexForOrderBy This is only necessary for large lists. DON'T use it unless you know what it is for!
+ @param fieldInternalName Internal field of the first field by that the data will be sorted (ascending)
+ @param override This is only necessary for large lists. DON'T use it unless you know what it is for!
+ @param useIndexForOrderBy This is only necessary for large lists. DON'T use it unless you know what it is for!
*/
OrderBy(fieldInternalName: string, override?: boolean, useIndexForOrderBy?: boolean): ISortedQuery;
/** Adds OrderBy clause to the query (using descending order for the first field).
- @param fieldInternalName Internal field of the first field by that the data will be sorted (descending)
- @param override This is only necessary for large lists. DON'T use it unless you know what it is for!
- @param useIndexForOrderBy This is only necessary for large lists. DON'T use it unless you know what it is for!
+ @param fieldInternalName Internal field of the first field by that the data will be sorted (descending)
+ @param override This is only necessary for large lists. DON'T use it unless you know what it is for!
+ @param useIndexForOrderBy This is only necessary for large lists. DON'T use it unless you know what it is for!
*/
OrderByDesc(fieldInternalName: string, override?: boolean, useIndexForOrderBy?: boolean): ISortedQuery;
}
interface IGroupable extends ISortable {
/** Adds GroupBy clause to the query.
- @param collapse If true, only information about the groups is retrieved, otherwise items are also retrieved. */
+ @param collapse If true, only information about the groups is retrieved, otherwise items are also retrieved. */
GroupBy(fieldInternalName: any): IGroupedQuery;
}
interface IExpression extends IGroupable {
@@ -134,17 +135,19 @@ declare namespace CamlBuilder {
DateField(internalName: string): IDateTimeFieldExpression;
/** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is DateTime */
DateTimeField(internalName: string): IDateTimeFieldExpression;
+ /** Specifies that a condition will be tested against the field with the specified internal name, and the type of this field is ModStat (moderation status) */
+ ModStatField(internalName: string): IModStatFieldExpression;
/** Used in queries for retrieving recurring calendar events.
- NOTICE: DateRangesOverlap with overlapType other than Now cannot be used with SP.CamlQuery, because it doesn't support
- CalendarDate and ExpandRecurrence query options. Lists.asmx, however, supports them, so you can still use DateRangesOverlap
- with SPServices.
- @param overlapType Defines type of overlap: return all events for a day, for a week, for a month or for a year
- @param calendarDate Defines date that will be used for determining events for which exactly day/week/month/year will be returned.
- This value is ignored for overlapType=Now, but for the other overlap types it is mandatory.
- @param eventDateField Internal name of "Start Time" field (default: "EventDate" - all OOTB Calendar lists use this name)
- @param endDateField Internal name of "End Time" field (default: "EndDate" - all OOTB Calendar lists use this name)
- @param recurrenceIDField Internal name of "Recurrence ID" field (default: "RecurrenceID" - all OOTB Calendar lists use this name)
- */
+ NOTICE: DateRangesOverlap with overlapType other than Now cannot be used with SP.CamlQuery, because it doesn't support
+ CalendarDate and ExpandRecurrence query options. Lists.asmx, however, supports them, so you can still use DateRangesOverlap
+ with SPServices.
+ @param overlapType Defines type of overlap: return all events for a day, for a week, for a month or for a year
+ @param calendarDate Defines date that will be used for determining events for which exactly day/week/month/year will be returned.
+ This value is ignored for overlapType=Now, but for the other overlap types it is mandatory.
+ @param eventDateField Internal name of "Start Time" field (default: "EventDate" - all OOTB Calendar lists use this name)
+ @param endDateField Internal name of "End Time" field (default: "EndDate" - all OOTB Calendar lists use this name)
+ @param recurrenceIDField Internal name of "Recurrence ID" field (default: "RecurrenceID" - all OOTB Calendar lists use this name)
+ */
DateRangesOverlap(overlapType: DateRangesOverlapType, calendarDate: string, eventDateField?: string, endDateField?: string, recurrenceIDField?: string): IExpression;
}
interface IBooleanFieldExpression {
@@ -201,25 +204,25 @@ declare namespace CamlBuilder {
/** Checks whether the value of the field is equal to one of the specified values */
In(arrayOfValues: Date[]): IExpression;
/** Checks whether the value of the field is equal to the specified value.
- The datetime value should be defined in ISO 8601 format! */
+ The datetime value should be defined in ISO 8601 format! */
EqualTo(value: string): IExpression;
/** Checks whether the value of the field is not equal to the specified value.
- The datetime value should be defined in ISO 8601 format! */
+ The datetime value should be defined in ISO 8601 format! */
NotEqualTo(value: string): IExpression;
/** Checks whether the value of the field is greater than the specified value.
- The datetime value should be defined in ISO 8601 format! */
+ The datetime value should be defined in ISO 8601 format! */
GreaterThan(value: string): IExpression;
/** Checks whether the value of the field is less than the specified value.
- The datetime value should be defined in ISO 8601 format! */
+ The datetime value should be defined in ISO 8601 format! */
LessThan(value: string): IExpression;
/** Checks whether the value of the field is greater than or equal to the specified value.
- The datetime value should be defined in ISO 8601 format! */
+ The datetime value should be defined in ISO 8601 format! */
GreaterThanOrEqualTo(value: string): IExpression;
/** Checks whether the value of the field is less than or equal to the specified value.
- The datetime value should be defined in ISO 8601 format! */
+ The datetime value should be defined in ISO 8601 format! */
LessThanOrEqualTo(value: string): IExpression;
/** Checks whether the value of the field is equal to one of the specified values.
- The datetime value should be defined in ISO 8601 format! */
+ The datetime value should be defined in ISO 8601 format! */
In(arrayOfValues: string[]): IExpression;
}
interface ITextFieldExpression {
@@ -322,6 +325,27 @@ declare namespace CamlBuilder {
/** DEPRECATED: "Neq" operation in CAML works exactly the same as "NotIncludes". To avoid confusion, please use NotIncludes. */
NotEqualTo(value: any): IExpression;
}
+ interface IModStatFieldExpression {
+ /** Represents moderation status ID. */
+ ModStatId(): INumberFieldExpression;
+ /** Checks whether the value of the field is Approved - same as ModStatId.EqualTo(0) */
+ IsApproved(): IExpression;
+ /** Checks whether the value of the field is Rejected - same as ModStatId.EqualTo(1) */
+ IsRejected(): IExpression;
+ /** Checks whether the value of the field is Pending - same as ModStatId.EqualTo(2) */
+ IsPending(): IExpression;
+ /** Represents moderation status as localized text. In most cases it is better to use ModStatId in the queries instead of ValueAsText. */
+ ValueAsText(): ITextFieldExpression;
+ }
+ interface IRawQuery {
+ /** Change Where clause */
+ ReplaceWhere(): IFieldExpression;
+ ModifyWhere(): IRawQueryModify;
+ }
+ interface IRawQueryModify {
+ AppendOr(): IFieldExpression;
+ AppendAnd(): IFieldExpression;
+ }
enum DateRangesOverlapType {
/** Returns events for today */
Now = 0,
@@ -330,7 +354,7 @@ declare namespace CamlBuilder {
/** Returns events for one week, specified by CalendarDate in QueryOptions */
Week = 2,
/** Returns events for one month, specified by CalendarDate in QueryOptions.
- Caution: usually also returns few days from previous and next months */
+ Caution: usually also returns few days from previous and next months */
Month = 3,
/** Returns events for one year, specified by CalendarDate in QueryOptions */
Year = 4,
@@ -340,6 +364,7 @@ declare namespace CamlBuilder {
static createViewFields(viewFields: string[]): IFinalizableToString;
static createWhere(): IFieldExpression;
static createExpression(): IFieldExpression;
+ static createRawQuery(xml: string): IRawQuery;
}
class CamlValues {
/** Dynamic value that represents Id of the current user */
diff --git a/canvas-gauges/index.d.ts b/canvas-gauges/index.d.ts
index 5dbd361872..6ba360a7ea 100644
--- a/canvas-gauges/index.d.ts
+++ b/canvas-gauges/index.d.ts
@@ -1,4 +1,4 @@
-// Type definitions for canvas-gauges
+// Type definitions for canvas-gauges v2.0.8
// Project: https://github.com/Mikhus/canvas-gauges
// Definitions by: Mikhus
// Definitions: https://github.com/Mikhus/DefinitelyTyped
diff --git a/cassandra-driver/cassandra-driver.tests.ts b/cassandra-driver/cassandra-driver-tests.ts
similarity index 67%
rename from cassandra-driver/cassandra-driver.tests.ts
rename to cassandra-driver/cassandra-driver-tests.ts
index 514514b059..9feee249ac 100644
--- a/cassandra-driver/cassandra-driver.tests.ts
+++ b/cassandra-driver/cassandra-driver-tests.ts
@@ -6,6 +6,6 @@ import * as util from 'util';
var client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1'});
var query = 'SELECT email, last_name FROM user_profiles WHERE key=?';
-client.execute(query, ['guy'], {}, function(err, result) {
- console.log('got user profile with email ' + result.rows[0].get("email"));
+client.execute(query, ['guy'], function(err: any, result: any) {
+ console.log('got user profile with email ' + result.rows[0].email);
});
\ No newline at end of file
diff --git a/cassandra-driver/index.d.ts b/cassandra-driver/index.d.ts
index 55a67e11f9..041f9f84e2 100644
--- a/cassandra-driver/index.d.ts
+++ b/cassandra-driver/index.d.ts
@@ -134,7 +134,7 @@ export namespace types {
var LocalTime: LocalTimeStatic;
var Long: _Long;
var ResultSet: ResultSetStatic;
- var ResultStream: ResultStreamStatic;
+ // var ResultStream: ResultStreamStatic;
var Row: RowStatic;
var TimeUuid: TimeUuidStatic;
var Tuple: TupleStatic;
@@ -365,7 +365,6 @@ export namespace types {
buffer: Buffer;
paused: boolean;
- _read(): void;
_valve(readNext: Function): void;
add(chunk: Buffer): void;
}
diff --git a/chart.js/index.d.ts b/chart.js/index.d.ts
index 57389ee4ea..9bf41eeaae 100644
--- a/chart.js/index.d.ts
+++ b/chart.js/index.d.ts
@@ -345,6 +345,7 @@ interface ChartXAxe {
stacked?: boolean;
categoryPercentage?: number;
barPercentage?: number;
+ barThickness?: number;
gridLines?: GridLineOptions;
position?: string;
ticks?: TickOptions;
@@ -379,7 +380,7 @@ interface TimeScale extends ChartScales {
parser?: string | ((arg: any) => any);
round?: string;
tooltipFormat?: string;
- unit?: TimeUnit;
+ unit?: string | TimeUnit;
unitStepSize?: number;
}
@@ -390,11 +391,12 @@ interface RadialLinearScale {
ticks?: TickOptions;
}
-declare var Chart: {
- new (context: CanvasRenderingContext2D, options: ChartConfiguration): {};
+declare class Chart {
+ constructor (context: CanvasRenderingContext2D, options: ChartConfiguration);
+ config: ChartConfiguration;
destroy: () => {};
- update: (duration: any, lazy: any) => {};
- render: (duration: any, lazy: any) => {};
+ update: (duration?: any, lazy?: any) => {};
+ render: (duration?: any, lazy?: any) => {};
stop: () => {};
resize: () => {};
clear: () => {};
@@ -407,4 +409,4 @@ declare var Chart: {
defaults: {
global: ChartOptions;
}
-};
+}
diff --git a/chunked-dc/chunked-dc-tests.ts b/chunked-dc/chunked-dc-tests.ts
new file mode 100644
index 0000000000..304d26e952
--- /dev/null
+++ b/chunked-dc/chunked-dc-tests.ts
@@ -0,0 +1,21 @@
+///
+
+// Chunker
+
+let chunker = new Chunker(1337, Uint8Array.of(1,2,3), 2);
+for (let chunk of chunker) {
+ // Do smoething with chunk
+}
+while (chunker.hasNext) {
+ let chunk = chunker.next().value;
+}
+
+// Unchunker
+
+let unchunker = new Unchunker();
+unchunker.onMessage = (message: Uint8Array, context: any[]) => {
+ // Do something with the received message
+};
+let chunk = Uint8Array.of(1,2).buffer;
+unchunker.add(chunk);
+unchunker.gc(1024);
diff --git a/chunked-dc/chunked-dc.d.ts b/chunked-dc/chunked-dc.d.ts
new file mode 100644
index 0000000000..2b38bef438
--- /dev/null
+++ b/chunked-dc/chunked-dc.d.ts
@@ -0,0 +1,55 @@
+// Type definitions for chunked-dc v0.1.2
+// Project: https://github.com/saltyrtc/chunked-dc-js
+// Definitions by: Danilo Bargen
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+// Interfaces
+declare namespace chunkedDc {
+
+ /** common.ts **/
+
+ interface CommonStatic {
+ HEADER_LENGTH: number;
+ }
+
+ /** chunker.ts **/
+
+ interface Chunker extends IterableIterator {
+ hasNext: boolean;
+ next(): IteratorResult;
+ [Symbol.iterator](): IterableIterator;
+ }
+
+ interface ChunkerStatic {
+ new(id: number, message: Uint8Array, chunkSize: number): Chunker
+ }
+
+ /** unchunker.ts **/
+
+ type MessageListener = (message: Uint8Array, context?: any) => void;
+
+ interface Unchunker {
+ onMessage: MessageListener;
+ add(chunk: ArrayBuffer, context?: any): void;
+ gc(maxAge: number): number;
+ }
+
+ interface UnchunkerStatic {
+ new(): Unchunker
+ }
+
+ /** main.ts **/
+
+ interface Standalone {
+ Chunker: ChunkerStatic,
+ Unchunker: UnchunkerStatic,
+ }
+
+}
+
+// Entry point for the packed ES5 version:
+declare var chunkedDc: chunkedDc.Standalone;
+
+// Entry point for the ES2015 version:
+declare var Chunker: chunkedDc.ChunkerStatic;
+declare var Unchunker: chunkedDc.UnchunkerStatic;
diff --git a/chunked-dc/chunked-dc.tscparams b/chunked-dc/chunked-dc.tscparams
new file mode 100644
index 0000000000..ed262d8039
--- /dev/null
+++ b/chunked-dc/chunked-dc.tscparams
@@ -0,0 +1 @@
+--target es2015 --noImplicitAny
diff --git a/ckeditor/ckeditor-tests.ts b/ckeditor/ckeditor-tests.ts
index 10b6e31375..f0aa64cc07 100644
--- a/ckeditor/ckeditor-tests.ts
+++ b/ckeditor/ckeditor-tests.ts
@@ -37,6 +37,23 @@ function test_CKEDITOR() {
CKEDITOR.replaceAll((textarea, config) => false);
}
+function test_config() {
+ var config1: CKEDITOR.config = {
+ toolbar: 'basic',
+ };
+ var config2: CKEDITOR.config = {
+ toolbar: [
+ [ 'mode', 'document', 'doctools' ],
+ [ 'clipboard', 'undo' ],
+ '/',
+ [ 'find', 'selection', 'spellchecker' ],
+ [ 'basicstyles', 'cleanup' ],
+ '/',
+ [ 'list', 'indent', 'blocks', 'align', 'bidi' ],
+ ],
+ };
+}
+
function test_dom_comment() {
var type = CKEDITOR.NODE_COMMENT;
var nativeNode = document.createComment('Example');
@@ -319,3 +336,30 @@ function test_focusManager() {
var object: CKEDITOR.dom.domObject = focusManager.currentActive;
var bool: boolean = focusManager.hasFocus;
}
+
+function test_basicWriter() {
+ var writer = new CKEDITOR.htmlParser.basicWriter();
+ writer.openTag('p', {});
+ writer.attribute('class', 'MyClass');
+ writer.openTagClose('p', false);
+ writer.text('Hello');
+ writer.closeTag('p');
+ alert(writer.getHtml(true)); // 'Hello
'
+}
+
+function test_htmlWriter() {
+ var writer = new CKEDITOR.htmlWriter();
+ writer.openTag('p', {});
+ writer.attribute('class', 'MyClass');
+ writer.openTagClose('p', false);
+ writer.text('Hello');
+ writer.closeTag('p');
+ alert(writer.getHtml(true)); // 'Hello
'
+
+ writer.indentationChars = '\t';
+ writer.lineBreakChars = '\r\n';
+ writer.selfClosingEnd = '>';
+ writer.indentation();
+ writer.lineBreak();
+ writer.setRules('img', {breakBeforeOpen: true, breakAfterOpen: true});
+}
diff --git a/ckeditor/index.d.ts b/ckeditor/index.d.ts
index b5009fa031..72e56cd253 100644
--- a/ckeditor/index.d.ts
+++ b/ckeditor/index.d.ts
@@ -807,7 +807,7 @@ declare namespace CKEDITOR {
templates_files?: Object;
templates_replaceContent?: boolean;
title?: string | boolean;
- toolbar?: string | (string[])[];
+ toolbar?: string | (string | string[])[];
toolbarCanCollapse?: boolean;
toolbarGroupCycling?: boolean;
toolbarGroups?: toolbarGroups[];
@@ -1270,6 +1270,16 @@ declare namespace CKEDITOR {
toHtml(data: string, fixForBody?: string): void;
}
+ class htmlDataProcessor {
+ dataFilter: htmlParser.filter;
+ htmlFilter: htmlParser.filter;
+ writer: htmlParser.basicWriter;
+
+ constructor(editor: editor);
+ toDataFormat(html: string, options?: Object): string;
+ toHtml(data: string, options?: Object): string;
+ }
+
class event {
constructor();
@@ -1803,6 +1813,16 @@ declare namespace CKEDITOR {
}
+ class htmlWriter extends htmlParser.basicWriter {
+ indentationChars: string;
+ lineBreakChars: string;
+ selfClosingEnd: string;
+
+ indentation(): void;
+ lineBreak(): void;
+ setRules(tagName: string, rules: Object): void;
+ }
+
namespace tools {
var callFunction: Function;
diff --git a/clipboard-js/clipboard-js-tests.ts b/clipboard-js/clipboard-js-tests.ts
new file mode 100644
index 0000000000..93adfda3a5
--- /dev/null
+++ b/clipboard-js/clipboard-js-tests.ts
@@ -0,0 +1,6 @@
+///
+
+clipboard.copy("Hello World");
+clipboard.copy(document.body).then(() => console.log("success"));
+
+clipboard.paste().then(val => console.log(val));
diff --git a/clipboard-js/clipboard-js.d.ts b/clipboard-js/clipboard-js.d.ts
new file mode 100644
index 0000000000..fafc44ef36
--- /dev/null
+++ b/clipboard-js/clipboard-js.d.ts
@@ -0,0 +1,18 @@
+// Type definitions for clipboard-js 0.3.1
+// Project: https://github.com/lgarron/clipboard.js
+// Definitions by: Mark Wong Siang Kai
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare namespace clipboard {
+
+ interface IClipboardJsStatic {
+ copy(val: string | Element): Promise;
+ paste(): Promise;
+ }
+}
+
+declare var clipboard: clipboard.IClipboardJsStatic;
+
+declare module 'clipboard-js' {
+ export = clipboard;
+}
diff --git a/codemirror/index.d.ts b/codemirror/index.d.ts
index fbbf2d84fd..708b32812e 100644
--- a/codemirror/index.d.ts
+++ b/codemirror/index.d.ts
@@ -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;
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/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-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-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/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-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..67a32d6cc5 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..e2e14a6724 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-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.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