From 1d1db373db08b243fcd5ee2cbcd4647e5ac81a8a Mon Sep 17 00:00:00 2001 From: Derek Finlinson Date: Tue, 24 Jul 2018 10:36:11 -0600 Subject: [PATCH 001/200] Change Xrm.Utility.lookupObjects to return array --- types/xrm/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/xrm/index.d.ts b/types/xrm/index.d.ts index fdb6504e96..1b688c1e59 100644 --- a/types/xrm/index.d.ts +++ b/types/xrm/index.d.ts @@ -970,7 +970,7 @@ declare namespace Xrm { * Opens a lookup control to select one or more items. * @param lookupOptions Defines the options for opening the lookup dialog */ - lookupObjects(lookupOptions: LookupOptions): Async.PromiseLike; + lookupObjects(lookupOptions: LookupOptions): Async.PromiseLike; /** * Refreshes the parent grid containing the specified record. From 8a7c70eb95d7727b712acab61e02dbdf3705afde Mon Sep 17 00:00:00 2001 From: Justin Grant Date: Wed, 21 Nov 2018 19:14:37 -0800 Subject: [PATCH 002/200] Updated to clarify versioning behavior Fixed a few things with version-related documentation: * clarified the relationship of typings package version vs. library versions * explained how package versions and library versions can get out of sync * fixed broken links in major-version-upgrade section * clarified major-version-upgrade section See #25677 for more discussion and background for these changes. --- README.md | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9a31d73da1..8663bbb140 100644 --- a/README.md +++ b/README.md @@ -256,14 +256,43 @@ If the standard is still a draft, it belongs here. Use a name beginning with `dom-` and include a link to the standard as the "Project" link in the header. When it graduates draft mode, we may remove it from DefinitelyTyped and deprecate the associated `@types` package. -#### I want to update a package to a new major version +#### How do DefinitelyTyped package versions relate to versions of the corresponding library? -If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to: +_NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ + +Each DefinitelyTyped package is versioned when published to NPM. The [automated tools](https://github.com/Microsoft/types-publisher) that publish typings packages to NPM will set the typings package's version using the version number listed in the first line of the typings file. For example, below is the first few lines of the latest (as of late 2018) [node.js typings file](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library version `10.12`. Because this version is included in the typings file, the NPM version of the `@types/node` package will also be `10.12`: + +```javascript +// Type definitions for Node.js 10.12 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +``` + +Sometimes typings versions and library versions can get out of sync. Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. + +* The patch version of the typings package is incremented every time an updated typings file is published for the same major and minor version. For example, a library may have only published `2.3.0` but the typings package might have gone through several revisions so its version would be `2.3.4`. If the library is later updated to `2.3.6` without any type updates needed, then the typings version would remain `2.3.4`. +* If a minor release adds new features that don't impact the type system, then there's no need to publish an updated typings file. In cases like this, updates are often skipped to the typings file. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the typings version might remain `2.1.3` even as the library goes to `2.2.0`. +* Users who are updating typings for a library sometimes forget to increment the typings version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest typings version, although it may be confusing for users because they might assume that a library update is missing types that are really present. +* It's common for typings to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the typings for a new library release. + +:exclamation:If you're updating the typings for a library version, always set the major/minor version in the first line of the typings file to match the library version that you're documenting!:exclamation: + +#### If a library is updated to a new major version with breaking changes, how should I update its typings package? + +[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped typings should also be updated to `4.0.0`, including any breaking changes to the library's API. + +Many libraries have a large installed base of developers (including mainatiners of other packages using that library as a dependency) who who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to udpate typings for older versions. + +If you intend to continue updating the older version of the typings package, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. + +Because the root folder should always contain the typings for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root. 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. -For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. Therefore, there's a `v2` folder inside the history repository that contains typings for the older version. The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: ```json { @@ -281,10 +310,9 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi } ``` -If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version. +If there are other packages in DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this recursively for packages depending on packages depending on the old version. -For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`; -transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). +For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`. Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was udpated to the latest version. Also, `/// ` will not work with path mapping, so dependencies must use `import`. From 30c8898e6866fd6820a75998616de91e88fa9207 Mon Sep 17 00:00:00 2001 From: Justin Grant Date: Fri, 23 Nov 2018 18:17:19 -0800 Subject: [PATCH 003/200] Changes in response to @Flarna review --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8663bbb140..aee5a1d07e 100644 --- a/README.md +++ b/README.md @@ -260,7 +260,7 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat _NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ -Each DefinitelyTyped package is versioned when published to NPM. The [automated tools](https://github.com/Microsoft/types-publisher) that publish typings packages to NPM will set the typings package's version using the version number listed in the first line of the typings file. For example, below is the first few lines of the latest (as of late 2018) [node.js typings file](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library version `10.12`. Because this version is included in the typings file, the NPM version of the `@types/node` package will also be `10.12`: +Each DefinitelyTyped package is versioned when published to NPM. The [automated tools](https://github.com/Microsoft/types-publisher) that publish typings packages to NPM will set the typings package's version using the version number listed in the first line of the typings file. For example, below are the first few lines of the latest (as of late 2018) [node.js typings file](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library versions `10.12.x`. ```javascript // Type definitions for Node.js 10.12 @@ -270,11 +270,13 @@ Each DefinitelyTyped package is versioned when published to NPM. The [automated // Alberto Schiabel ``` +Because `10.12` is at the end the first line, the NPM version of the `@types/node` package will also be `10.12.x`. Note that the first-line comment in the typings file should only contaiin major/minor versions (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). This is because only the major and minor release numbers are aligned between library packages and typings packages. The patch release number of the typings package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. + Sometimes typings versions and library versions can get out of sync. Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. -* The patch version of the typings package is incremented every time an updated typings file is published for the same major and minor version. For example, a library may have only published `2.3.0` but the typings package might have gone through several revisions so its version would be `2.3.4`. If the library is later updated to `2.3.6` without any type updates needed, then the typings version would remain `2.3.4`. -* If a minor release adds new features that don't impact the type system, then there's no need to publish an updated typings file. In cases like this, updates are often skipped to the typings file. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the typings version might remain `2.1.3` even as the library goes to `2.2.0`. -* Users who are updating typings for a library sometimes forget to increment the typings version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest typings version, although it may be confusing for users because they might assume that a library update is missing types that are really present. +* As noted above, the patch version of the typings package is unrelated to the library patch version. This allows DefinitelyTyped to safely update typings for the same major/minor version of a library. +* If a minor release adds new features that don't impact the type system, then there's no need to publish an updated typings file. In cases like this, updates are often skipped to the typings file. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the typings version might remain `2.0.3` even as the library goes to `2.1.0`. +* Users who are updating typings for a library sometimes forget to increment the typings version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest typings version, although it may be confusing for users because they might assume that a library update is missing types that are really present. It will also cause problems when libraries are (see below) updated to a new major release with breaking changes, because users won't know which typings version is the right one to use for older versions of the library. * It's common for typings to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the typings for a new library release. :exclamation:If you're updating the typings for a library version, always set the major/minor version in the first line of the typings file to match the library version that you're documenting!:exclamation: @@ -283,7 +285,7 @@ Sometimes typings versions and library versions can get out of sync. Below are a [Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped typings should also be updated to `4.0.0`, including any breaking changes to the library's API. -Many libraries have a large installed base of developers (including mainatiners of other packages using that library as a dependency) who who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to udpate typings for older versions. +Many libraries have a large installed base of developers (including mainatiners of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to udpate typings for older versions. If you intend to continue updating the older version of the typings package, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. @@ -292,7 +294,7 @@ Because the root folder should always contain the typings for the latest ("new") 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. -For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. Therefore, there's a `v2` folder inside the history repository that contains typings for the older version. The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. Therefore, a maintainer of the typings for this library added a `v2` folder inside the history repository that contains typings for the older version. The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: ```json { From 60a7ec20eebfbe1c0c98100a718e1422dfdeb685 Mon Sep 17 00:00:00 2001 From: Justin Grant Date: Tue, 4 Dec 2018 12:26:57 -0800 Subject: [PATCH 004/200] Updated in response to @DanielRosenwasser feedback Thanks @DanielRosenwasser for feedback! Here's what's different: * Updated typos: contaiin, udpated, udpate, mainatiners * One sentence per line, except bullet points where adding a newline will show up in user-visible text (GitHub markdown doesn't ignore line breaks in bullet points) * Removed "typings", replaced with either "type definition(s)" or "type definition package" depending on context Happy to make more edits, just let me know. --- README.md | 47 +++++++++++++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index aee5a1d07e..650cecd1d5 100644 --- a/README.md +++ b/README.md @@ -260,7 +260,9 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat _NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ -Each DefinitelyTyped package is versioned when published to NPM. The [automated tools](https://github.com/Microsoft/types-publisher) that publish typings packages to NPM will set the typings package's version using the version number listed in the first line of the typings file. For example, below are the first few lines of the latest (as of late 2018) [node.js typings file](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library versions `10.12.x`. +Each DefinitelyTyped package is versioned when published to NPM. +The [automated tools](https://github.com/Microsoft/types-publisher) that publish type declaration packages to NPM will set the type declaration package's version using the version number listed in the first line of its `index.d.ts` file. +For example, below are the first few lines of the latest (as of late 2018) [node.js type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library versions `10.12.x`. ```javascript // Type definitions for Node.js 10.12 @@ -270,31 +272,42 @@ Each DefinitelyTyped package is versioned when published to NPM. The [automated // Alberto Schiabel ``` -Because `10.12` is at the end the first line, the NPM version of the `@types/node` package will also be `10.12.x`. Note that the first-line comment in the typings file should only contaiin major/minor versions (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). This is because only the major and minor release numbers are aligned between library packages and typings packages. The patch release number of the typings package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. +Because `10.12` is at the end the first line, the NPM version of the `@types/node` package will also be `10.12.x`. +Note that the first-line comment in the `index.d.ts` file should only contain major/minor versions (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). +This is because only the major and minor release numbers are aligned between library packages and type declaration packages. +The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. -Sometimes typings versions and library versions can get out of sync. Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. +Sometimes type declaration package versions and library package versions can get out of sync. +Below are a few common reasons why, in order of how much they inconvenience users of a library. +Only the last case is typically problematic. -* As noted above, the patch version of the typings package is unrelated to the library patch version. This allows DefinitelyTyped to safely update typings for the same major/minor version of a library. -* If a minor release adds new features that don't impact the type system, then there's no need to publish an updated typings file. In cases like this, updates are often skipped to the typings file. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the typings version might remain `2.0.3` even as the library goes to `2.1.0`. -* Users who are updating typings for a library sometimes forget to increment the typings version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest typings version, although it may be confusing for users because they might assume that a library update is missing types that are really present. It will also cause problems when libraries are (see below) updated to a new major release with breaking changes, because users won't know which typings version is the right one to use for older versions of the library. -* It's common for typings to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the typings for a new library release. +* As noted above, the patch version of the type declaration package is unrelated to the library patch version. This allows DefinitelyTyped to safely update type declarations for the same major/minor version of a library. +* If a minor release adds new features that don't impact the type system, then there's no need to publish updated type declarations. In cases like this, updates are often skipped to the type declaration package. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the type declaration package version might remain `2.0.3` even as the library goes to `2.1.0`. +* Users who are updating type declarations for a library sometimes forget to increment the type declaration package's version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest type declaration package version, although it may be confusing for users because they might assume that a library update is missing types that are really present. It will also cause problems when libraries are (see below) updated to a new major release with breaking changes, because users won't know which type declaration package version is the right one to use for older versions of the library. +* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release. -:exclamation:If you're updating the typings for a library version, always set the major/minor version in the first line of the typings file to match the library version that you're documenting!:exclamation: +:exclamation:If you're updating type declarations for a library, always set the major/minor version in the first line of `index.d.ts` to match the library version that you're documenting!:exclamation: -#### If a library is updated to a new major version with breaking changes, how should I update its typings package? +#### If a library is updated to a new major version with breaking changes, how should I update its type declaration package? -[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped typings should also be updated to `4.0.0`, including any breaking changes to the library's API. +[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. +For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. +Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped type declaration package should also be updated to `4.0.0`, including any breaking changes to the library's API. -Many libraries have a large installed base of developers (including mainatiners of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to udpate typings for older versions. +Many libraries have a large installed base of developers (including maintainers of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. +In the meantime, users of old library versions still may want to update type declarations for older versions. -If you intend to continue updating the older version of the typings package, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. +If you intend to continue updating the older version of a library's type declarations, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. -Because the root folder should always contain the typings for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root. +Because the root folder should always contain the type declarations for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root. 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. -For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. Therefore, a maintainer of the typings for this library added a `v2` folder inside the history repository that contains typings for the older version. The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. +Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. +Therefore, a maintainer of the type declarations for this library added a `v2` folder inside the history repository that contains type declarations for the older version. +The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: ```json { @@ -312,9 +325,11 @@ For example, the [`history`](https://github.com/ReactTraining/history/) library } ``` -If there are other packages in DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this recursively for packages depending on packages depending on the old version. +If there are other packages in DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. +You will also need to do this recursively for packages depending on packages depending on the old version. -For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`. Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was udpated to the latest version. +For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`. +Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was updated to the latest version. Also, `/// ` will not work with path mapping, so dependencies must use `import`. From c4e76c862663d7d6646cd24068cbdc05d6161101 Mon Sep 17 00:00:00 2001 From: Nicolas Penin Date: Sun, 6 Jan 2019 19:41:15 +0100 Subject: [PATCH 005/200] Update index.d.ts fixed typescript compilation issue --- types/debug/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 2eca1c8fb8..a03d5cd988 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -6,7 +6,7 @@ // Brasten Sager // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var debug: debug.IDebug; +declare var debug: debug.IDebug & {debug:debug.IDebug, default:debug.IDebug}; export = debug; export as namespace debug; From 43f9cfc7f19576a637561ca27eb7e0aaa6f74125 Mon Sep 17 00:00:00 2001 From: Nicolas Penin Date: Mon, 7 Jan 2019 10:51:47 +0100 Subject: [PATCH 006/200] fixed coding convention --- types/debug/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index a03d5cd988..e8cfac264b 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -6,7 +6,7 @@ // Brasten Sager // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var debug: debug.IDebug & {debug:debug.IDebug, default:debug.IDebug}; +declare var debug: debug.IDebug & {debug: debug.IDebug, default: debug.IDebug}; export = debug; export as namespace debug; From 4657145fda72194ffe641ac0042acfd884190a5a Mon Sep 17 00:00:00 2001 From: Nicolas Penin Date: Wed, 16 Jan 2019 10:37:51 +0100 Subject: [PATCH 007/200] fixed header --- types/debug/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index e8cfac264b..ad37e702a0 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for debug +// Type definitions for debug 4.1 // Project: https://github.com/visionmedia/debug // Definitions by: Seon-Wook Park // Gal Talmor // John McLaughlin // Brasten Sager +// Nicolas Penin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var debug: debug.IDebug & {debug: debug.IDebug, default: debug.IDebug}; From f88076efc7f0ac3290bb7075a6ed1c6a2f4bedf2 Mon Sep 17 00:00:00 2001 From: Nicolas Penin Date: Wed, 16 Jan 2019 10:39:08 +0100 Subject: [PATCH 008/200] disabled rules --- types/debug/tslint.json | 78 +---------------------------------------- 1 file changed, 1 insertion(+), 77 deletions(-) diff --git a/types/debug/tslint.json b/types/debug/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/debug/tslint.json +++ b/types/debug/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From afb8bca54a8982b435cb5fae2a509abd8b75ce69 Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Mon, 21 Jan 2019 22:16:15 +0200 Subject: [PATCH 009/200] [@types/feathersjs__errors] Added typings for the missing "code", "className", "data" and "errors" property members of the FeathersError object. --- types/feathersjs__errors/index.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 056acff676..9adcdc6dbf 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -5,7 +5,11 @@ // TypeScript Version: 2.2 export class FeathersError extends Error { - constructor(msg: string | Error, name: string, code: number, className: string, data: any) + code: number; + className: string; + data: any; + errors: any; + constructor(msg: string | Error, name: string, code: number, className: string, data: any); } export class BadRequest extends FeathersError { From 3c55900c9c6c09ca616377e4a66d0fb62f85314a Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Mon, 21 Jan 2019 22:16:46 +0200 Subject: [PATCH 010/200] [@types/feathersjs__errors] Added "RazzM13" to "Definitions by" section as per the contribution guidelines. --- types/feathersjs__errors/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 9adcdc6dbf..01969de8a3 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for @feathersjs/errors 3.2 // Project: http://feathersjs.com/ // Definitions by: Jan Lohage +// RazzM13 // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.2 From 2328852a4c1dc673fc93c4b0434eae81ce2d4cca Mon Sep 17 00:00:00 2001 From: James Lismore Date: Thu, 24 Jan 2019 08:56:57 -0500 Subject: [PATCH 011/200] Props for components now extend HtmlElements --- types/react-tabs/index.d.ts | 32 +++++++++++++++++----------- types/react-tabs/react-tabs-tests.ts | 2 +- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/types/react-tabs/index.d.ts b/types/react-tabs/index.d.ts index 013973e8df..e6793ebb4e 100644 --- a/types/react-tabs/index.d.ts +++ b/types/react-tabs/index.d.ts @@ -4,10 +4,13 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from 'react'; +import * as React from "react"; -export interface TabsProps { - className?: string | Array | { [name: string]: boolean; }; +type Omit = Pick>; + +export interface TabsProps + extends Omit, "className" | "onSelect"> { + className?: string | Array | { [name: string]: boolean }; defaultFocus?: boolean; defaultIndex?: number; disabledTabClassName?: string; @@ -19,27 +22,30 @@ export interface TabsProps { selectedTabPanelClassName?: string; } -export interface TabListProps { - className?: string | Array | { [name: string]: boolean; }; +export interface TabListProps + extends Omit, "className"> { + className?: string | Array | { [name: string]: boolean }; } -export interface TabProps { - className?: string | Array | { [name: string]: boolean; }; +export interface TabProps + extends Omit, "className" | "tabIndex"> { + className?: string | Array | { [name: string]: boolean }; disabled?: boolean; disabledClassName?: string; selectedClassName?: string; tabIndex?: string; } -export interface TabPanelProps { - className?: string | Array | { [name: string]: boolean; }; +export interface TabPanelProps + extends Omit, "className"> { + className?: string | Array | { [name: string]: boolean }; forceRender?: boolean; selectedClassName?: string; } -export declare class Tabs extends React.Component { } -export declare class TabList extends React.Component { } -export declare class Tab extends React.Component { } -export declare class TabPanel extends React.Component { } +export declare class Tabs extends React.Component {} +export declare class TabList extends React.Component {} +export declare class Tab extends React.Component {} +export declare class TabPanel extends React.Component {} export declare function resetIdCounter(): void; diff --git a/types/react-tabs/react-tabs-tests.ts b/types/react-tabs/react-tabs-tests.ts index a7b86de6e0..ec9a88c11e 100644 --- a/types/react-tabs/react-tabs-tests.ts +++ b/types/react-tabs/react-tabs-tests.ts @@ -26,7 +26,7 @@ class TestApp extends React.Component { } render() { - return React.createElement(Tabs, {onSelect: this.onSelect, selectedIndex: 1}, + return React.createElement(Tabs, {onSelect: this.onSelect, selectedIndex: 1, defaultFocus:true, name:'Tabs', autoFocus:true}, React.createElement(TabList, {className: "test-class"}, React.createElement(Tab, {disabled: true}, "Tab1"), React.createElement(Tab, {selectedClassName: "active"}, "Tab2"), From e44c615c7086bab0479fa4e401712e942223c430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sat, 26 Jan 2019 20:03:10 +0900 Subject: [PATCH 012/200] Added type definition for hexo --- types/hexo/hexo-tests.ts | 462 ++++++++++++++++++ types/hexo/index.d.ts | 976 +++++++++++++++++++++++++++++++++++++++ types/hexo/tsconfig.json | 23 + types/hexo/tslint.json | 7 + 4 files changed, 1468 insertions(+) create mode 100644 types/hexo/hexo-tests.ts create mode 100644 types/hexo/index.d.ts create mode 100644 types/hexo/tsconfig.json create mode 100644 types/hexo/tslint.json diff --git a/types/hexo/hexo-tests.ts b/types/hexo/hexo-tests.ts new file mode 100644 index 0000000000..3c00489c3a --- /dev/null +++ b/types/hexo/hexo-tests.ts @@ -0,0 +1,462 @@ +import Hexo = require('hexo'); +import fs = require('fs'); +import Bunyan = require('bunyan'); +import { ParsedArgs } from 'minimist'; +import util = require('hexo-util'); +import http = require('http'); + +const config: Hexo.InstanceOptions = {}; +config.debug = false; +config.safe = false; +config.silent = false; +config.config = '_config.yml'; + +let h: Hexo; +h = hexo; +h = new Hexo(); +h = new Hexo('./'); +h = new Hexo('./', config); + +const logger: Bunyan = h.log; +console.log(h.base_dir); +console.log(h.public_dir); +console.log(h.source_dir); +console.log(h.plugin_dir); +console.log(h.script_dir); +console.log(h.scaffold_dir); +console.log(h.theme_dir); +console.log(h.theme_script_dir); +console.log(h.config_path); +console.log(h.env.args); +console.log(h.env.debug); +console.log(h.env.safe); +console.log(h.env.silent); +console.log(h.env.env); +console.log(h.env.version); +console.log(h.env.init); +console.log(h.config.title); +console.log(h.config.subtitle); +console.log(h.config.description); +console.log(h.config.author); +console.log(h.config.language); +console.log(h.config.timezone); +console.log(h.config.url); +console.log(h.config.root); +console.log(h.config.permalink); +console.log(h.config.permalink_defaults); +console.log(h.config.source_dir); +console.log(h.config.public_dir); +console.log(h.config.tag_dir); +console.log(h.config.archive_dir); +console.log(h.config.category_dir); +console.log(h.config.code_dir); +console.log(h.config.i18n_dir); +console.log(h.config.skip_render); +console.log(h.config.new_post_name); +console.log(h.config.default_layout); +console.log(h.config.titlecase); +console.log(h.config.external_link); +console.log(h.config.filename_case); +console.log(h.config.render_drafts); +console.log(h.config.post_asset_folder); +console.log(h.config.relative_link); +console.log(h.config.future); +console.log(h.config.highlight.enable); +console.log(h.config.highlight.line_number); +console.log(h.config.highlight.auto_detect); +console.log(h.config.highlight.tab_replace); +console.log(h.config.default_category); +console.log(h.config.category_map); +console.log(h.config.tag_map); +console.log(h.config.time_format); +console.log(h.config.per_page); +console.log(h.config.pagination_dir); +console.log(h.config.theme); +console.log(h.config.theme_config); +console.log(h.config.deploy); +console.log(h.config.include); +console.log(h.config.exclude); +console.log(h.config.ignore); + +h.init().then(async () => { + await h.watch(); + h.unwatch(); + + await h.theme.watch(); + h.theme.unwatch(); + + await h.source.watch(); + h.source.unwatch(); + + await h.load(); + h.call('config', {_: ['arg1']}, (err, value) => {}); + + await h.exit(); +}); + +h.on('ready', () => { + h.on('deployBefore', () => {}); + h.on('deployAfter', () => {}); + h.on('exit', err => { + console.log(err); + }); + h.on('generateBefore', () => {}); + h.on('generateAfter', () => {}); + h.on('new', param => { + const path: string = param.path; + const content: string = param.content; + }); + h.on('processBefore', (type, path) => { + const t: Hexo.Box.File['type'] = type; + const p: string = path; + }); + h.on('processAfter', (type, path) => { + const t: Hexo.Box.File['type'] = type; + const p: string = path; + }); + h.on('ready', () => {}); + + { + let local: Hexo.Locals.Post[] = []; + const model = hexo.locals.get('posts'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Page[] = []; + const model = hexo.locals.get('pages'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Category[] = []; + const model = hexo.locals.get('categories'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Tag[] = []; + const model = hexo.locals.get('tags'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + h.locals.set('some-data', () => 'some vlue'); + h.locals.remove('some-data'); + h.locals.toObject(); + h.locals.invalidate(); + } + + { + const route = h.route.get('index.html'); + if (route) { + console.log(route.modified); + console.log(route.read()); + } + + const data: Hexo.Router.Data = { + data: 'some data', + modified: true, + }; + data.data = new Buffer([]); + data.data = () => 'return'; + + let router: Hexo.Router; + router = h.route; + router = h.route.set('index.html', 'content'); + router = h.route.set('index.html', new Buffer([])); + router = h.route.set('index.html', new util.Pattern(() => false)); + router = h.route.set('index.html', { data: 'index', modified: false }); + + router = h.route.remove('index.html'); + + const list: string[] = h.route.list(); + const format: string = h.route.format('/'); + } + + { + h.source.process(() => {}); + h.source.addProcessor('path', file => { + console.log(file.source); + console.log(file.path); + console.log(file.type); + console.log(file.params); + + file.read((err, content) => { + console.log(err, content.toString()); + console.log(content); + }); + + file.read({encoding: 'utf8', flag: 'r'}, (err, content) => { + console.log(err, content.toString()); + console.log(content); + }); + + file.readSync({encoding: 'utf8', flag: 'r'}); + + file.stat((err, stat) => { + console.log(err); + console.log(stat.mtime); + console.log(stat.ctime); + console.log(stat.atime); + }); + + file.stat().then(stat => { + console.log(stat.mtime); + console.log(stat.ctime); + console.log(stat.atime); + }); + + const stat: fs.Stats = file.statSync(); + + let render = ''; + file.render({}, (err, result) => { + render = result; + }); + file.render((err, result) => { + render = result; + }); + file.render().then(result => { + render = result; + }); + render = file.renderSync(); + }); + } + + { + let _bool = true; + _bool = h.render.isRenderable('path'); + _bool = h.render.isRenderableSync('path'); + + const option: Hexo.Render.Data = { + engine: 'ejs', + text: 'test', + path: __filename, + }; + + let _string = ''; + h.render.render({text: 'example', engine: 'swig'}).then(result => { + _string = result; + }); + h.render.render({path: __filename}).then(result => { + _string = result; + }); + h.render.render({text: ''}, {foo: 'foo'}).then(result => { + _string = result; + }); + _string = h.render.renderSync({text: 'example'}); + + _string = h.render.getOutput('ejs'); + } + + { + const data: Hexo.Post.Data = {}; + data.title = 'Title'; + data.slug = 'URL'; + data.layout = 'layout_name'; + data.path = 'path'; + data.date = new Date(); + + h.post.create(data, false, () => {}); + h.post.create(data, () => {}); + + h.post.publish(data, false, () => {}); + h.post.publish(data, () => {}); + + const renderData: Hexo.Post.RenderData = {}; + renderData.content = 'content'; + renderData.engine = 'ejs'; + h.post.render(null, renderData, () => {}); + } + + { + h.scaffold.get('post').then(result => ''); + h.scaffold.set('post', '').then(() => {}); + h.scaffold.remove('post').then(() => {}); + } + + { + const themeConfig: Hexo['config'] = h.theme.config; + let v: Hexo.View | undefined; + h.theme.setView('path-name', {}); + v = h.theme.getView('post'); + if (v) { + console.log(v.path); + console.log(v.source); + + v.render().then(result => {}); + v.renderSync(); + } + + h.theme.removeView('path-name'); + h.theme.process(() => {}); + } + + { + const options: Hexo.extend.Console.Options = {}; + options.usage = '[layout] '; + options.arguments = [ + {name: 'layout', desc: 'Post layout'}, + {name: 'title', desc: 'Post title'}, + ]; + options.options = [ + {name: '-r, --replace', desc: 'Replace existing files'}, + ]; + options.desc = 'desc'; + + h.extend.console.register('name', 'description', options, args => { + const a: ParsedArgs = args; + }); + h.extend.console.register('name', options, args => {}); + h.extend.console.register('name', 'description', args => {}); + h.extend.console.register('name', args => {}); + } + + { + h.extend.deployer.register('name', args => { + console.log(args.type); + console.log(args.someExtraArg); + }); + } + + { + h.extend.filter.register('before_post_render', data => data); + h.extend.filter.register('before_post_render', data => undefined); + h.extend.filter.register('before_post_render', data => undefined, 1); + + h.extend.filter.register('after_post_render', data => data); + h.extend.filter.register('after_post_render', data => undefined); + h.extend.filter.register('after_post_render', data => undefined, 1); + + h.extend.filter.register('before_exit', () => {}); + h.extend.filter.register('before_exit', () => {}, 1); + + h.extend.filter.register('before_generate', data => data); + h.extend.filter.register('before_generate', data => undefined); + h.extend.filter.register('before_generate', data => undefined, 1); + + h.extend.filter.register('after_generate', () => {}); + h.extend.filter.register('after_generate', () => {}, 1); + + h.extend.filter.register('template_locals', locals => locals); + h.extend.filter.register('template_locals', locals => undefined); + h.extend.filter.register('template_locals', locals => undefined, 1); + + h.extend.filter.register('after_init', () => {}); + h.extend.filter.register('after_init', () => {}, 1); + + h.extend.filter.register('new_post_path', (data, replace) => undefined); + h.extend.filter.register('new_post_path', (data, replace) => undefined, 1); + + h.extend.filter.register('post_permalink', permalink => permalink); + h.extend.filter.register('post_permalink', permalink => permalink, 1); + + h.extend.filter.register('after_render:html', (result, data) => result); + h.extend.filter.register('after_render:html', (result, data) => result, 1); + + h.extend.filter.register('after_clean', () => {}); + h.extend.filter.register('after_clean', () => {}, 1); + + h.extend.filter.register('server_middleware', app => { + app.use((req: http.IncomingMessage, res: http.ServerResponse) => { + res.setHeader('X-Powered-By', 'Hexo'); + }); + }); + + const filter = (data: any) => data; + h.extend.filter.register('custom_filter', filter); + h.extend.filter.unregister('custom_filter', filter); + + const options: Hexo.extend.Filter.Options = {}; + options.args = ['foo', 'bar']; + options.context = h; + h.extend.filter.exec('custom_filter', options); + h.extend.filter.exec('custom_filter'); + h.extend.filter.execSync('custom_filter', options); + h.extend.filter.execSync('custom_filter'); + } + + { + const ret: Hexo.extend.Generator.Return = { + data: {}, + layout: 'layout-name', + path: '/', + }; + h.extend.generator.register('name', local => ret); + h.extend.generator.register('name', local => [ret]); + h.extend.generator.register('name', local => { + console.log(local.data); + const categories: Hexo.Locals.Category[] = local.categories.toArray(); + const pages: Hexo.Locals.Page[] = local.pages.toArray(); + const posts: Hexo.Locals.Post[] = local.posts.toArray(); + const tags: Hexo.Locals.Tag[] = local.tags.toArray(); + + return ret; + }); + } + + { + h.extend.helper.register('name', (...args) => { + return 'ret'; + }); + } + + { + h.extend.migrator.register('name', args => { + const a: ParsedArgs = args; + }); + } + + { + let f: Hexo.Box.File; + h.extend.processor.register('pattern', file => f = file); + h.extend.processor.register(/pattern/, file => f = file); + h.extend.processor.register((str) => true , file => f = file); + h.extend.processor.register(file => f = file); + } + + { + h.extend.renderer.register('ts', 'js', (data, options) => { + console.log(data.path); + console.log(data.text); + return 'result'; + }, true); + + h.extend.renderer.register('ts', 'js', (data, options) => Promise.resolve('result'), false); + h.extend.renderer.register('ts', 'js', (data, options) => Promise.resolve('result')); + } + + { + const option: Hexo.extend.Tag.Options = {}; + option.async = true; + option.ends = true; + + h.extend.tag.register('name', (args, content) => { + if (content) { + const c: string = content; + } + const a: string[] = args; + return 'content'; + }); + } +}); diff --git a/types/hexo/index.d.ts b/types/hexo/index.d.ts new file mode 100644 index 0000000000..0688b1631a --- /dev/null +++ b/types/hexo/index.d.ts @@ -0,0 +1,976 @@ +// Type definitions for hexo 3.8 +// Project: https://hexo.io/ +// Definitions by: KentarouTakeda <https://github.com/kentarouTakeda> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import EventEmitter = require('events'); +import moment = require('moment'); +import { ParsedArgs } from 'minimist'; +import Logger = require('bunyan'); +import underscore = require('underscore'); +import connect = require('connect'); +import Stream = require('stream'); +import util = require('hexo-util'); +import fs = require('fs'); + +declare global { + const hexo: Hexo; +} + +interface HexoConfig { + [key: string]: any; + /** + * The title of your website + */ + readonly title: string; + + /** + * The subtitle of your website + */ + readonly subtitle: string; + + /** + * The description of your website + */ + readonly description: string; + + /* + * Your name + */ + readonly author: string; + + /** + * The language of your website. Use a 2-lettter ISO-639-1 code. Default is en. + */ + readonly language: string; + + /** + * The timezone of your website. Hexo uses the setting on your computer by default. + * You can find the list of available timezones [here]{@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones} . + * Some examples are `America/New_York` , `Japan` , and `UTC` . + */ + readonly timezone: string; + + /* + * The URL of your website + */ + readonly url: string; + + /** + * The root directory of your website + */ + readonly root: string; + + /** + * The permalink format of articles + */ + readonly permalink: string; + + /** + * Default values of each segment in permalink + */ + readonly permalink_defaults: string|null; + + /** + * Source folder. Where your content is stored + */ + readonly source_dir: string; + + /** + * Public folder. Where the static site will be generated + */ + readonly public_dir: string; + + /** + * Tag directory + */ + readonly tag_dir: string; + + /** + * Archive directory + */ + readonly archive_dir: string; + + /** + * Category directory + */ + readonly category_dir: string; + + /** + * Include code directory (subdirectory of source_dir) + */ + readonly code_dir: string; + + /** + * i18n directory + */ + readonly i18n_dir: string; + + /** + * Paths that will be copied to public raw, without being rendered. You can use glob expressions for path matching. + */ + readonly skip_render: string|string[]|null; + + /** + * The filename format for new posts + */ + readonly new_post_name: string; + + /** + * Default layout + */ + readonly default_layout: string; + + /** + * Transform titles into title case? + */ + readonly titlecase: boolean; + + /** + * Open external links in a new tab? + */ + readonly external_link: boolean; + + /** + * Transform filenames to 1 lower case; 2 upper case + */ + readonly filename_case: number; + + /** + * Display drafts? + */ + readonly render_drafts: boolean; + + /** + * Enable the Asset Folder? + */ + readonly post_asset_folder: boolean; + + /** + * Make links relative to the root folder? + */ + readonly relative_link: boolean; + + /** + * Display future posts? + */ + readonly future: boolean; + + /** + * Code block settings + */ + readonly highlight: { + readonly enable: boolean; + readonly line_number: boolean; + readonly auto_detect: boolean; + readonly tab_replace: string|null; + }; + + /** + * Default category + */ + readonly default_category: string; + + /** + * Category slugs + */ + readonly category_map: {[key: string]: string|number}; + + /** + * Tag slugs + */ + readonly tag_map: {[key: string]: string|number}; + + /** + * Date format + * https://momentjs.com/ + */ + readonly date_format: string; + + /** + * Time format + * https://momentjs.com/ + */ + readonly time_format: string; + + /** + * The amount of posts displayed on a single page. 0 disables pagination + */ + readonly per_page: number; + + /** + * Pagination directory + */ + readonly pagination_dir: string; + + /** + * Theme name. false disables theming + */ + readonly theme: string|false; + + /** + * Theme configuration. Include any custom theme settings under this key to override theme defaults. + */ + readonly theme_config: {[key: string]: string|number}; + + /** + * Deployment settings + */ + readonly deploy: Hexo.extend.Deployer.Config | Hexo.extend.Deployer.Config | null; + + /** + * Hexo by default ignores hidden files and folders, but setting this field will make Hexo process them + */ + readonly include ?: string[]; + + /** + * Hexo process will ignore files list under this field + */ + readonly exclude ?: string[]; + readonly ignore: string[]; +} + +interface Model<T> { + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + toArray(): T[]; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + count(): number; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + forEach(fn: (v: T, i: number) => void): void; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + filter(fn: (v: T, i: number) => boolean): Model<T>; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + map<U>(fn: (v: T, i: number) => U): U[]; +} + +interface Site { + posts: Model<Hexo.Locals.Post>; + pages: Model<Hexo.Locals.Page>; + categories: Model<Hexo.Locals.Category>; + tags: Model<Hexo.Locals.Tag>; + data: {[key: string]: any}; +} + +declare class Hexo extends EventEmitter { + /** + * Create a Hexo instance. + * @param base the root directory of the website, `base_dir` . + * @param args an object containing the initialization options. + */ + constructor(base?: string, args?: Hexo.InstanceOptions); + + /** + * Load configuration and plugins. + */ + init(): Promise<void>; + + /** + * Loading all files in the `source` folder as well as the theme data. + */ + load(fn?: (err: any, value: any) => void): Promise<any>; + + /** + * The same things `load` does, but will also start watching for file changes continuously. + */ + watch(fn?: (err: any, value: any) => void): Promise<any>; + + unwatch(): void; + + /** + * Any console command can be called explicitly using the call method on the Hexo instance. + */ + call(name: string, args?: any, fn?: (err: any, value: any) => void): Promise<any>; + call(name: string, fn?: (err: any, value: any) => void): Promise<any>; + + /** + * You should call the `exit` method upon successful or unsuccessful completion of a console command. + * This allows Hexo to exit gracefully and finish up important things such as saving the database. + */ + exit(err?: any): Promise<void>; + + /** + * Site settings in `_config.yml` + */ + readonly config: HexoConfig; + + readonly theme: Hexo.Theme; + readonly source: Hexo.Box; + readonly post: Hexo.Post; + readonly render: Hexo.Render; + + /** + * Local variables are used for template rendering, which is the `site` variable in templates. + * https://hexo.io/api/locals + */ + readonly locals: Hexo.Locals; + + readonly base_dir: string; + + /** + * Public folder. Where the static site will be generated + */ + readonly public_dir: string; + + /** + * Source folder. Where your content is stored + */ + readonly source_dir: string; + + readonly plugin_dir: string; + readonly script_dir: string; + readonly scaffold_dir: string; + readonly theme_dir: string; + readonly theme_script_dir: string; + readonly config_path: string; + readonly env: { + readonly args: ParsedArgs; + readonly debug: boolean; + readonly safe: boolean; + readonly silent: boolean; + readonly env: string; + readonly version: string; + readonly init: boolean; + }; + + /** + * Logger object + * https://www.npmjs.com/package/bunyan + */ + readonly log: Logger; + + readonly extend: { + /** + * The console forms the bridge between Hexo and its users. It registers and describes the available console commands. + */ + readonly console: Hexo.extend.Console; + /** + * A deployer helps users quickly deploy their site to a remote server without complicated commands. + */ + readonly deployer: Hexo.extend.Deployer; + /** + * A filter is used to modify some specified data. Hexo passes data to filters in sequence and the filters then modify the data one after the other. + */ + readonly filter: Hexo.extend.Filter; + /** + * A generator builds routes based on processed files. + */ + readonly generator: Hexo.extend.Generator; + /** + * A helper makes it easy to quickly add snippets to your templates. We recommend using helpers instead of templates when you’re dealing with more complicated code. + */ + readonly helper: Hexo.extend.Helper; + /** + * A migrator helps users migrate from other systems to Hexo. + */ + readonly migrator: Hexo.extend.Migrator; + /** + * A processor is used to process source files in the source folder. + */ + readonly processor: Hexo.extend.Processor; + /** + * A renderer is used to render content. + */ + readonly renderer: Hexo.extend.Renderer; + /** + * A tag allows users to quickly and easily insert snippets into their posts. + */ + readonly tag: Hexo.extend.Tag; + }; + + readonly route: Hexo.Router; + readonly scaffold: Hexo.Scaffold; + + /** + * Emitted before deployment begins. + */ + on(ev: 'deployBefore', fn: () => void): this; + + /** + * Emitted after deployment finishes. + */ + on(ev: 'deployAfter', fn: () => void): this; + + /** + * Emitted before Hexo exits. + */ + on(ev: 'exit', fn: (err: any) => void): this; + + /** + * Emitted before generation begins. + */ + on(ev: 'generateBefore', fn: () => void): this; + + /** + * Emitted after generation finishes. + */ + on(ev: 'generateAfter', fn: () => void): this; + + /** + * Emitted after a new post has been created. This event returns the post data: + */ + on(ev: 'new', fn: (post: {path: string, content: string}) => void): this; + + /** + * Emitted before processing begins. This event returns a path representing the root directory of the box. + */ + on(ev: 'processBefore', fn: (type: Hexo.Box.File['type'], path: string) => void): this; + + /** + * Emitted after processing finishes. This event returns a path representing the root directory of the box. + */ + on(ev: 'processAfter', fn: (type: Hexo.Box.File['type'], path: string) => void): this; + + /** + * Emitted after initialization finishes. + */ + on(ev: 'ready', fn: () => void): this; +} + +declare namespace Hexo { + interface InstanceOptions { + debug?: boolean; + safe?: boolean; + silent?: boolean; + config?: string; + } + + interface Locals { + get(type: 'posts'): Model<Locals.Post>; + get(type: 'pages'): Model<Locals.Page>; + get(type: 'categories'): Model<Locals.Category>; + get(type: 'tags'): Model<Locals.Tag>; + /** + * Get a Variable + */ + get(type: string): any; + + /** + * Set a Variable + */ + set(type: string, fn: () => any): this; + + /** + * Remove a Variable + */ + remove(type: string): this; + + /** + * Get All Variable + */ + toObject(): any; + + /** + * Invalidate the cache + */ + invalidate(): this; + } + namespace Locals { + interface Page { + title: string; + date: moment.Moment; + updated?: moment.Moment; + comments: boolean; + layout: string; + content: string; + excerpt?: string; + more?: string; + source: string; + full_source: string; + path: string; + permalink: string; + prev?: null|Page; + next?: null|Page; + raw?: string; + photos?: string[]; + link?: string; + [key: string]: any; + } + + interface Post extends Page { + published?: boolean; + categories?: string[]; + tags: string[]; + } + + interface Tag { + name: string; + slug: string; + path: string; + permalink: string; + posts: Model<Post>; + length: number; + } + interface Category extends Tag { + parent: string; + } + } + + namespace extend { + interface Console { + register(name: string, desc: string, options: Console.Options, fn: (args: ParsedArgs) => void): void; + register(name: string, options: Console.Options, fn: (args: ParsedArgs) => void): void; + register(name: string, desc: string, fn: (args: ParsedArgs) => void): void; + register(name: string, fn: (args: ParsedArgs) => void): void; + } + namespace Console { + interface Options { + /** + * The usage of a console command. + */ + usage?: string; + + /** + * The description of each argument of a console command. + */ + arguments?: Array<{name: string, desc: string}>; + + /** + * The description of each option of a console command. + */ + options?: Array<{name: string, desc: string}>; + + /** + * More detailed information about a console command. + */ + desc?: string; + } + } + + interface Deployer { + register(name: string, fn: (args: Deployer.Config) => void): void; + } + namespace Deployer { + interface Config { + readonly type: string|undefined; + readonly [key: string]: any; + } + } + + interface Filter { + register(type: string, fn: (data: any, ...args: any[]) => any, priority?: number): void; + + /** + * Executed before a post is rendered. Refer to post rendering to learn the execution steps. + */ + register(type: 'before_post_render', fn: (data: { content: string, [key: string]: any }) => { content: string, [key: string]: any }|void, priority?: number): void; + + /** + * Executed after a post is rendered. Refer to post rendering to learn the execution steps. + */ + register(type: 'after_post_render', fn: (data: { content: string, [key: string]: any }) => { content: string, [key: string]: any }|void, priority?: number): void; + + /** + * Executed before Hexo is about to exit – this will run right after `hexo.exit` is called. + */ + register(type: 'before_exit', fn: () => void, priority?: number): void; + + /** + * Executed before generation begins. + */ + register(type: 'before_generate', fn: (data: any) => any, priority?: number): void; + + /** + * Executed after generation finishes. + */ + register(type: 'after_generate', fn: () => void, priority?: number): void; + + /** + * Modify [local variables](https://hexo.io/docs/variables) in templates. + */ + register(type: 'template_locals', fn: (locals: TemplateLocals) => TemplateLocals|void, priority?: number): void; + + /** + * Executed after Hexo is initialized – this will run right after `hexo.init` completes. + */ + register(type: 'after_init', fn: () => void, priority?: number): void; + + /** + * Executed when creating a post to determine the path of new posts. + */ + register(type: 'new_post_path', fn: (data: Post.Data, replace?: boolean) => void, priority?: number): void; + + /** + * Used to determine the permalink of posts. + */ + register(type: 'post_permalink', fn: (permalink: string) => string, priority?: number): void; + + /** + * Executed after rendering finishes. You can see rendering for more info. + */ + register(type: 'after_render:html', fn: (result: string, data: {path: string, text: string, [key: string]: any}) => string|void, priority?: number): void; + + /** + * Executed after generated files and cache are removed with hexo clean command. + */ + register(type: 'after_clean', fn: () => void, priority?: number): void; + + /** + * Add middleware to the server. app is a Connect instance. + */ + register(type: 'server_middleware', fn: (app: connect.Server) => connect.Server|void, priority?: number): void; + + unregister(type: string, fn: (...args: any[]) => any): void; + exec(type: string, data?: any, options?: Filter.Options): any; + execSync(type: string, data?: any, options?: Filter.Options): any; + } + namespace Filter { + interface Options { + /** + * `hexo` object. + */ + context?: Hexo; + /** + * Arguments. This must be an array. + */ + args?: any[]; + } + } + + interface Generator { + register(name: string, fn: (locals: Site) => Generator.Return| Generator.Return[]): void; + } + namespace Generator { + interface Return { + /** + * Path not including the prefixing `/` . + */ + path: string; + + /** + * Layout. Specify the layouts for rendering. The value can be a string or an array. If it’s ignored then the route will return data directly. + */ + layout: string|string[]; + + data: any; + } + } + + interface Helper { + register(name: string, fn: (...args: any[]) => any): void; + } + + interface Migrator { + register(name: string, fn: (args: ParsedArgs, fn: (err: any) => void) => void): void; + } + + interface Processor { + register(pattern: RegExp | string | ((str: string) => any), fn: (file: Box.File) => void): void; + register(fn: (file: Box.File) => void): void; + } + + interface Renderer { + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => string, sync: true): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => Promise<string>, sync: false): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => Promise<string>): void; + } + + interface Tag { + register(name: string, fn: (args: string[], content?: string) => string, options?: Tag.Options): void; + } + namespace Tag { + interface Options { + ends?: boolean; + async?: boolean; + } + } + } + + interface Router { + /** + * The `get` method returns a `Stream`. + */ + get(path: string): Router.RouteStream|undefined; + + /** + * The `set` method takes a string, a `Buffer` or a function. + */ + set(path: string, data: string|Buffer|util.Pattern<boolean>|Router.Data): this; + + /** + * Remove a Path + */ + remove(path: string): this; + + /** + * Get the List of Routes + */ + list(): string[]; + + /** + * The `format` method transforms a string to a valid path. + */ + format(path: string): string; + } + namespace Router { + interface Data { + data: string | Buffer | Callback; + modified: boolean; + } + + interface RouteStream extends Stream.Readable { + readonly modified: boolean; + } + + type Callback = ((err: any, result: string) => void) | (() => Promise<string>); + } + + interface Scaffold { + /** + * Get a Scaffold + */ + get(name: string, fn?: (err: any, result: string) => void): Promise<string>; + /** + * Set a Scaffold + */ + set(name: string, content: string, fn?: (err: any) => void): Promise<void>; + /** + * Remove a Scaffold + */ + remove(name: string, fn?: (err: any) => void): Promise<void>; + } + + interface Box extends EventEmitter { + /** + * Loads all files in the folder. + */ + process(fn: (err: any) => void): Promise<void>; + /** + * Loads all files in the folder and start watching for file changes. + */ + watch(fn?: (err: any) => void): Promise<void>; + /** + * Stop watching. + */ + unwatch(): void; + + /** + * A processor is an essential element of `Box` and is used to process files. + * You can use path matching as described above to restrict what exactly the processor should process. + * Register a new processor with the `addProcessor` method. + */ + addProcessor(pattern: string|RegExp|util.Pattern<boolean>, fn: (file: Box.File) => void): void; + } + namespace Box { + interface File { + /** + * Full path of the file + */ + readonly source: string; + + /** + * Relative path to the box of the file + */ + readonly path: string; + + /** + * File type. The value can be `create` , `update` , `skip`, `delete` . + */ + readonly type: 'create' | 'update' | 'skip' | 'delete'; + + /** + * The information from path matching. + */ + readonly params: any; + + /** + * Read a file + */ + read(option?: {encoding?: string|null, flag?: string}, fn?: (err: any, result: string|Buffer) => void): Promise<string|Buffer>; + read(fn?: (err: any, result: string|Buffer) => void): Promise<string|Buffer>; + + /** + * Read a file synchronously + */ + readSync(option?: {encoding?: string|null, flag?: string}): string|Buffer; + + /** + * Read the status of a file + */ + stat(fn?: (err: any, result: fs.Stats) => void): Promise<fs.Stats>; + + /** + * Read the status of a file synchronously + */ + statSync(): fs.Stats; + + /** + * Render a file + */ + render(fn?: (err: any, result: string) => void): Promise<string>; + render(option?: any, fn?: (err: any, result: string) => void): Promise<string>; + + /** + * Render a file synchronously + */ + renderSync(option?: any): string; + } + } + + interface Render { + render(data: Render.Data, option?: any, fn?: (err: any, result: string) => void): Promise<string>; + render(data: Render.Data, fn?: (err: any, result: string) => void): Promise<string>; + renderSync(data: Render.Data, option?: any): string; + + /** + * Check whether a file is renderable synchronously. + */ + isRenderable(path: string): boolean; + + /** + * Check whether a file is renderable. + */ + isRenderableSync(path: string): boolean; + + /** + * Get the Output Extension + */ + getOutput(path: string): string; + } + namespace Render { + interface Data { + text?: string; + engine?: string; + path?: string; + } + } + + interface Post { + /** + * Create a Post + */ + create(data: Post.Data, replace?: boolean, fn?: (err: any) => void): Promise<void>; + create(data: Post.Data, fn?: (err: any) => void): Promise<void>; + + /** + * Publish a Draft + */ + publish(data: Post.Data, replace?: boolean, fn?: (err: any) => void): Promise<void>; + publish(data: Post.Data, fn?: (err: any) => void): Promise<void>; + + render(source: string|null|undefined, data: Post.RenderData, fn: (err: any) => void): Promise<void>; + } + namespace Post { + interface Data { + title?: string; + slug?: string; + layout?: string; + path?: string; + date?: moment.MomentInput; + } + interface RenderData { + engine?: string; + content?: string; + } + } + + interface Theme extends Box { + config: HexoConfig; + + /** + * Get a View + */ + getView(path: string): View|undefined; + + /** + * Set a View + */ + setView(path: string, data: any): void; + + /** + * Remove a View + */ + removeView(path: string): void; + } + + interface View { + readonly path: string; + readonly source: string; + + /** + * Remove a View + */ + render(options?: any, fn?: (err: any, result: string) => void): Promise<string>; + render(fn: (err: any, result: string) => void): Promise<any>; + + /** + * Remove a View synchronously. + */ + renderSync(options?: any): string; + } +} + +interface TemplateLocals { + /** + * Underscore object + */ + _: underscore.UnderscoreStatic; + page: Hexo.Locals.Post | Hexo.Locals.Page | Hexo.Locals.Category | Hexo.Locals.Tag | IndexPage | ArchivePage | CategoryPage | TagPage; + path: string; + url: string; + + /** + * Site settings in `_config.yml` + */ + config: HexoConfig; + theme: HexoConfig; + env: Hexo['env']; + layout: string; + view_dir: string; + site: any; +} + +interface IndexPage { + per_page?: number; + total?: number; + current?: number; + current_url?: string; + posts?: object; + prev?: number; + prev_link?: string; + next?: number; + next_link?: string; + path?: string; +} + +interface ArchivePage extends IndexPage { + archive?: boolean; + year?: number; + month?: number; +} + +interface CategoryPage extends IndexPage { + category: string; +} + +interface TagPage extends IndexPage { + tag: string; +} + +interface HexoRendererData { + /** + * File content. + */ + readonly text: string; + /** + * File path. + */ + readonly path?: string; +} + +export = Hexo; diff --git a/types/hexo/tsconfig.json b/types/hexo/tsconfig.json new file mode 100644 index 0000000000..6e37a832a0 --- /dev/null +++ b/types/hexo/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hexo-tests.ts" + ] +} diff --git a/types/hexo/tslint.json b/types/hexo/tslint.json new file mode 100644 index 0000000000..d2e0e4cec1 --- /dev/null +++ b/types/hexo/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } + +} From bfa613e355a7bb485348a32318a9d3c81e273d51 Mon Sep 17 00:00:00 2001 From: Unknown <rkarilka@campus.haifa.ac.il> Date: Sat, 26 Jan 2019 14:34:11 +0200 Subject: [PATCH 013/200] @types/leaflet: Add VideoOverlay --- types/leaflet/index.d.ts | 27 ++++++++ types/leaflet/leaflet-tests.ts | 120 +++++++++++++++++++-------------- 2 files changed, 97 insertions(+), 50 deletions(-) diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 96bcb3277a..c88a505b8b 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Alejandro Sánchez <https://github.com/alejo90> // Arne Schubert <https://github.com/atd-schubert> // Michael Auer <https://github.com/mcauer> +// Roni Karilkar <https://github.com/ronikar> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -579,6 +580,32 @@ export class ImageOverlay extends Layer { export function imageOverlay(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions): ImageOverlay; +export interface VideoOverlayOptions extends ImageOverlayOptions { + autoplay?: boolean; + loop?: boolean; +} + +export class VideoOverlay extends Layer { + constructor(video: string | string[] | HTMLVideoElement, bounds: LatLngBoundsExpression, options?: VideoOverlayOptions); + setOpacity(opacity: number): this; + bringToFront(): this; + bringToBack(): this; + setUrl(url: string): this; + + /** Update the bounds that this VideoOverlay covers */ + setBounds(bounds: LatLngBounds): this; + + /** Get the bounds that this VideoOverlay covers */ + getBounds(): LatLngBounds; + + /** Get the video element that represents the VideoOverlay on the map */ + getElement(): HTMLVideoElement | undefined; + + options: VideoOverlayOptions; +} + +export function videoOverlay(video: string | string[] | HTMLVideoElement, bounds: LatLngBoundsExpression, options?: VideoOverlayOptions): VideoOverlay; + export type LineCapShape = 'butt' | 'round' | 'square' | 'inherit'; export type LineJoinShape = 'miter' | 'round' | 'bevel' | 'inherit'; diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index a6c9b6ccc3..8b024d790e 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -1,13 +1,13 @@ import * as L from 'leaflet'; -const latLngLiteral: L.LatLngLiteral = {lat: 12, lng: 13}; +const latLngLiteral: L.LatLngLiteral = { lat: 12, lng: 13 }; const latLngTuple: L.LatLngTuple = [12, 13]; let latLng: L.LatLng; latLng = L.latLng(12, 13); latLng = L.latLng(12, 13, 0); latLng = L.latLng(latLngLiteral); -latLng = L.latLng({lat: 12, lng: 13, alt: 0}); +latLng = L.latLng({ lat: 12, lng: 13, alt: 0 }); latLng = L.latLng(latLngTuple); latLng = L.latLng([12, 13, 0]); @@ -34,7 +34,7 @@ let point: L.Point; point = L.point(12, 13); point = L.point(12, 13, true); point = L.point(pointTuple); -point = L.point({x: 12, y: 13}); +point = L.point({ x: 12, y: 13 }); point = new L.Point(12, 13); point = new L.Point(12, 13, true); @@ -171,7 +171,7 @@ map.removeEventListener('moveend'); map.removeEventListener('moveend', () => {}); map.removeEventListener('moveend', () => {}, {}); -map.panInside(latLng, {padding: [50, 50], paddingBottomRight: point, paddingTopLeft: [100, 100]}); +map.panInside(latLng, { padding: [50, 50], paddingBottomRight: point, paddingTopLeft: [100, 100] }); // map.getRenderer @@ -218,25 +218,25 @@ mapPixelBounds = map.getPixelWorldBounds(12); let tileLayerOptions: L.TileLayerOptions = {}; tileLayerOptions = { - minZoom: 0, - maxZoom: 18, - maxNativeZoom: 2, - errorTileUrl: '', - zoomOffset: 0, - tms: true, - zoomReverse: true, - detectRetina: true, - crossOrigin: false, - opacity: 1, - updateWhenIdle: true, - updateWhenZooming: true, - updateInterval: 500, - attribution: '', - zIndex: 1, - noWrap: true, - pane: '', - className: '', - keepBuffer: 1, + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 2, + errorTileUrl: '', + zoomOffset: 0, + tms: true, + zoomReverse: true, + detectRetina: true, + crossOrigin: false, + opacity: 1, + updateWhenIdle: true, + updateWhenZooming: true, + updateInterval: 500, + attribution: '', + zIndex: 1, + noWrap: true, + pane: '', + className: '', + keepBuffer: 1, }; tileLayerOptions.subdomains = 'a'; @@ -259,14 +259,14 @@ tileLayer = new L.TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', tileLayer // imageOverlay let imageOverlayOptions: L.ImageOverlayOptions; imageOverlayOptions = { - opacity: 100, - alt: 'alt', - interactive: true, - attribution: 'attribution', - crossOrigin: true, - className: 'className', - bubblingMouseEvents: false, - pane: 'pane' + opacity: 100, + alt: 'alt', + interactive: true, + attribution: 'attribution', + crossOrigin: true, + className: 'className', + bubblingMouseEvents: false, + pane: 'pane' }; const imageOverlayBounds = latLngBounds; @@ -274,22 +274,42 @@ let imageOverlay: L.ImageOverlay; imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds); imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds, imageOverlayOptions); imageOverlay = L.imageOverlay('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png', imageOverlayBounds, { - opacity: 100, - alt: 'alt', - className: 'className', + opacity: 100, + alt: 'alt', + className: 'className', }); -const eventHandler = () => {}; +// videoOverlay +let videoOverlayOptions: L.VideoOverlayOptions; +videoOverlayOptions = { + interactive: true, + opacity: 100, + autoplay: true, + loop: false +}; + +const videoOverlayBounds = latLngBounds; +const videoOverlayUrls = ['https://www.mapbox.com/bites/00188/patricia_nasa.webm']; +const videoElement = document.createElement('video'); + +let videoOverlay: L.VideoOverlay; +videoOverlay = L.videoOverlay('https://www.mapbox.com/bites/00188/patricia_nasa.webm', videoOverlayBounds); +videoOverlay = L.videoOverlay(videoOverlayUrls, videoOverlayBounds, videoOverlayOptions); +videoOverlay = L.videoOverlay(videoElement, videoOverlayBounds, { + autoplay: true +}); + +const eventHandler = () => { }; const domEvent: Event = {} as Event; L.DomEvent .on(htmlElement, 'click', eventHandler) .addListener(htmlElement, 'click', eventHandler) .off(htmlElement, 'click', eventHandler) .removeListener(htmlElement, 'click', eventHandler) - .on(htmlElement, {click: eventHandler}) - .addListener(htmlElement, {click: eventHandler}) - .off(htmlElement, {click: eventHandler}, eventHandler) - .removeListener(htmlElement, {click: eventHandler}, eventHandler) + .on(htmlElement, { click: eventHandler }) + .addListener(htmlElement, { click: eventHandler }) + .off(htmlElement, { click: eventHandler }, eventHandler) + .removeListener(htmlElement, { click: eventHandler }, eventHandler) .stopPropagation(domEvent) .disableScrollPropagation(htmlElement) .disableClickPropagation(htmlElement) @@ -415,13 +435,13 @@ let threeCoords: [number, number, number] = [1, 2, 3]; latLng = L.GeoJSON.coordsToLatLng(threeCoords); threeCoords = L.GeoJSON.latLngToCoords(latLng) as [number, number, number]; -let nestedTwoCoords = [ [12, 13], [13, 14], [14, 15] ]; +let nestedTwoCoords = [[12, 13], [13, 14], [14, 15]]; const nestedLatLngs: L.LatLng[] = L.GeoJSON.coordsToLatLngs(nestedTwoCoords, 1); nestedTwoCoords = L.GeoJSON.latLngsToCoords(nestedLatLngs, 1); const geojson = new L.GeoJSON(); const style: L.PathOptions = { - className: "string", + className: "string", }; const styler: L.StyleFunction<MyProperties> = () => style; geojson.setStyle(style); @@ -441,7 +461,7 @@ class MyLayer extends L.Layer { class MyIcon extends L.Icon { constructor() { - super({iconUrl: 'icon.png'}); + super({ iconUrl: 'icon.png' }); } } @@ -451,9 +471,9 @@ class MyDivIcon extends L.DivIcon { } } -const divIcon = L.divIcon({html: ''}); +const divIcon = L.divIcon({ html: '' }); let defaultIcon = new L.Icon.Default(); -defaultIcon = new L.Icon.Default({imagePath: 'apath'}); +defaultIcon = new L.Icon.Default({ imagePath: 'apath' }); const myControlClass = L.Control.extend({}); const myControl = new myControlClass(); @@ -511,11 +531,11 @@ const complexPolygonLatLngs2: L.LatLng[][] = polygon.getLatLngs() as L.LatLng[][ // multi polygon const multiPolygonLatLngs: L.LatLngExpression[][][] = [ [ // first polygon - [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring - [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole + [[37, -109.05], [41, -109.03], [41, -102.05], [37, -102.04]], // outer ring + [[37.29, -108.58], [40.71, -108.58], [40.71, -102.50], [37.29, -102.50]] // hole ], [ // second polygon - [[41, -111.03], [45, -111.04], [45, -104.05], [41, -104.05]] + [[41, -111.03], [45, -111.04], [45, -104.05], [41, -104.05]] ] ]; polygon = L.polygon(multiPolygonLatLngs); @@ -534,8 +554,8 @@ const simplePolylineLatLngs2: L.LatLng[] = polyline.getLatLngs() as L.LatLng[]; // multi polyline const multiPolylineLatLngs: L.LatLngExpression[][] = [ - [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], - [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]] + [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], + [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]] ]; polyline = L.polyline(multiPolylineLatLngs); polyline = new L.Polyline(multiPolylineLatLngs); @@ -569,7 +589,7 @@ const extended3: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 = L.Util. const extended4: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 & typeof obj5 = L.Util.extend(obj1, obj2, obj3, obj4, obj5); L.Util.create({}); -L.Util.create(null, {foo: {writable: true, value: 'bar'}}); +L.Util.create(null, { foo: { writable: true, value: 'bar' } }); L.Util.bind(() => {}, {}); L.Util.stamp({}); From 5493a2aed147071f6f52e5429cebca1d05b69038 Mon Sep 17 00:00:00 2001 From: Joao Peixoto <joao.hartimer@gmail.com> Date: Sat, 26 Jan 2019 22:21:51 -0800 Subject: [PATCH 014/200] Make userHandle optional --- types/webappsec-credential-management/index.d.ts | 3 ++- .../webappsec-credential-management-tests.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index 4c47ee7cc8..c8fbf8ec60 100644 --- a/types/webappsec-credential-management/index.d.ts +++ b/types/webappsec-credential-management/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for W3C (WebAppSec) Credential Management API Level 1, 0.3 // Project: https://github.com/w3c/webappsec-credential-management // Definitions by: Iain McGinniss <https://github.com/iainmcgin> +// Joao Peixoto <https://github.com/Hartimer> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 @@ -493,7 +494,7 @@ interface AuthenticatorAttestationResponse extends AuthenticatorResponse { interface AuthenticatorAssertionResponse extends AuthenticatorResponse { readonly authenticatorData: ArrayBuffer; readonly signature: ArrayBuffer; - readonly userHandle: ArrayBuffer; + readonly userHandle?: ArrayBuffer; } /** diff --git a/types/webappsec-credential-management/webappsec-credential-management-tests.ts b/types/webappsec-credential-management/webappsec-credential-management-tests.ts index 2afa9f8785..1e0500dfce 100644 --- a/types/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/types/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -352,3 +352,16 @@ function webauthnAuthenticate() { console.log(e.message); }); } + +function mockAuthenticatorAssertionResponse() { + if (!navigator.credentials) { + return; + } + + const sampleResponse: AuthenticatorAssertionResponse = { + clientDataJSON: new ArrayBuffer(0), + authenticatorData: new ArrayBuffer(0), + signature: new ArrayBuffer(0), + }; + sampleResponse.userHandle === undefined; +} From c2ce3512058edf773a51c0c58a1f2f777b128d2a Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 10:41:49 +0100 Subject: [PATCH 015/200] Update debug-tests.ts fixed tslint issues --- types/debug/debug-tests.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index bad51ed584..ddfd698825 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -1,11 +1,9 @@ - - import debug = require("debug"); debug.disable(); debug.enable("DefinitelyTyped:*"); -var log:debug.IDebugger = debug("DefinitelyTyped:log"); +const log: debug.IDebugger = debug("DefinitelyTyped:log"); log("Just text"); log("Formatted test (%d arg)", 1); @@ -15,12 +13,12 @@ log("Enabled?: %s", debug.enabled("DefinitelyTyped:log")); log("Name Enabled: %s", debug.names.some(name => name.test("DefinitelyTyped:log"))); log("Namespace: %s", log.namespace); -var error:debug.IDebugger = debug("DefinitelyTyped:error"); +const error: debug.IDebugger = debug("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); -var extendedLog: debug.IDebugger = log.extend('extended'); +const extendedLog: debug.IDebugger = log.extend('extended'); extendedLog("Testing this is also an IDebugger."); -var extendedWithCustomDelimiter: debug.IDebugger = log.extend('with-delim', '.'); -extendedWithCustomDelimiter("Testing this is an IDebugger, too."); \ No newline at end of file +const extendedWithCustomDelimiter: debug.IDebugger = log.extend('with-delim', '.'); +extendedWithCustomDelimiter("Testing this is an IDebugger, too."); From 99c9aff07f708e974a0e9ade9a7457682f0a13b1 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 10:50:23 +0100 Subject: [PATCH 016/200] Update index.d.ts --- types/debug/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index ad37e702a0..9d6814cf9a 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -13,29 +13,29 @@ export = debug; export as namespace debug; declare namespace debug { - export interface IDebug { - (namespace: string): debug.IDebugger, - coerce: (val: any) => any, - disable: () => void, - enable: (namespaces: string) => void, - enabled: (namespaces: string) => boolean, + interface Debug { + (namespace: string): debug.Debugger; + coerce: (val: any) => any; + disable: () => void; + enable: (namespaces: string) => void; + enabled: (namespaces: string) => boolean; - names: RegExp[], - skips: RegExp[], + names: RegExp[]; + skips: RegExp[]; - formatters: IFormatters + formatters: Formatters; } - export interface IFormatters { - [formatter: string]: Function + interface Formatters { + [formatter: string]: (v:Object)=>string; } - export interface IDebugger { + interface Debugger { (formatter: any, ...args: any[]): void; enabled: boolean; log: Function; namespace: string; - extend: (namespace: string, delimiter?: string) => debug.IDebugger; + extend: (namespace: string, delimiter?: string) => debug.Debugger; } } From 753941216112d4f4cdb0280ff6c444f1a97dd692 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:26:13 +0100 Subject: [PATCH 017/200] Update index.d.ts --- types/debug/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 9d6814cf9a..ccc2c363af 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -7,7 +7,7 @@ // Nicolas Penin <https://github.com/npenin> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var debug: debug.IDebug & {debug: debug.IDebug, default: debug.IDebug}; +declare var debug: debug.Debug & {debug: debug.Debug, default: debug.Debug}; export = debug; export as namespace debug; From 2943797f768de0d4e9a9f486e9fae11fad778f70 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:27:07 +0100 Subject: [PATCH 018/200] Update debug-tests.ts --- types/debug/debug-tests.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index ddfd698825..22ac083a14 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -3,7 +3,7 @@ import debug = require("debug"); debug.disable(); debug.enable("DefinitelyTyped:*"); -const log: debug.IDebugger = debug("DefinitelyTyped:log"); +const log: debug.Debugger = debug("DefinitelyTyped:log"); log("Just text"); log("Formatted test (%d arg)", 1); @@ -13,12 +13,12 @@ log("Enabled?: %s", debug.enabled("DefinitelyTyped:log")); log("Name Enabled: %s", debug.names.some(name => name.test("DefinitelyTyped:log"))); log("Namespace: %s", log.namespace); -const error: debug.IDebugger = debug("DefinitelyTyped:error"); +const error: debug.Debugger = debug("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); -const extendedLog: debug.IDebugger = log.extend('extended'); +const extendedLog: debug.Debugger = log.extend('extended'); extendedLog("Testing this is also an IDebugger."); -const extendedWithCustomDelimiter: debug.IDebugger = log.extend('with-delim', '.'); +const extendedWithCustomDelimiter: debug.Debugger = log.extend('with-delim', '.'); extendedWithCustomDelimiter("Testing this is an IDebugger, too."); From ca16f6f8441cfd7ac63fb7a2a1f614fbddc56f07 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:38:11 +0100 Subject: [PATCH 019/200] Update index.d.ts --- types/debug/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index ccc2c363af..7b4e44dbdd 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -14,7 +14,7 @@ export as namespace debug; declare namespace debug { interface Debug { - (namespace: string): debug.Debugger; + (namespace: string): Debugger; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; @@ -27,15 +27,15 @@ declare namespace debug { } interface Formatters { - [formatter: string]: (v:Object)=>string; + [formatter: string]: (v: any) => string; } interface Debugger { (formatter: any, ...args: any[]): void; enabled: boolean; - log: Function; + log: (v: any) => string; namespace: string; - extend: (namespace: string, delimiter?: string) => debug.Debugger; + extend: (namespace: string, delimiter?: string) => Debugger; } } From 0d2ae95d00b95dd3931255ee67d866beb67f6ccb Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:44:16 +0100 Subject: [PATCH 020/200] Update index.d.ts fixed backward compatibility --- types/debug/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 7b4e44dbdd..3dc8d32774 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -25,10 +25,14 @@ declare namespace debug { formatters: Formatters; } + + type IDebug=Debug; interface Formatters { [formatter: string]: (v: any) => string; } + + type IDebugger=Debugger; interface Debugger { (formatter: any, ...args: any[]): void; From 01925c6c8bd763e757ae3fd867a06cf21ab0a24f Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:49:04 +0100 Subject: [PATCH 021/200] Update index.d.ts --- types/debug/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 3dc8d32774..2067b27222 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -25,14 +25,14 @@ declare namespace debug { formatters: Formatters; } - - type IDebug=Debug; + + type IDebug = Debug; interface Formatters { [formatter: string]: (v: any) => string; } - - type IDebugger=Debugger; + + type IDebugger = Debugger; interface Debugger { (formatter: any, ...args: any[]): void; From a20d5543e69dd9208edc75daf38accd8467e1183 Mon Sep 17 00:00:00 2001 From: Satyajit Sahoo <satyajit.happy@gmail.com> Date: Wed, 9 Jan 2019 15:15:42 +0100 Subject: [PATCH 022/200] Update Expo APIs for SDK 31 --- types/expo/expo-tests.tsx | 29 ++++--- types/expo/index.d.ts | 176 ++++++++++++++++++++++++++++---------- 2 files changed, 148 insertions(+), 57 deletions(-) diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 62a7dcbb91..12a88703c5 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Text, AccessibilityInfo } from 'react-native'; +import { Text } from 'react-native'; import { Accelerometer, @@ -21,9 +21,6 @@ import { Constants, Contacts, DocumentPicker, - EdgeInsets, - EdgePadding, - EventUserLocation, Facebook, FacebookAds, FaceDetector, @@ -33,24 +30,29 @@ import { ImagePicker, IntentLauncherAndroid, KeepAwake, - KmlMapEvent, LinearGradient, Linking, Location, MailComposer, - MapEvent, - MapStyleElement, MapView, MediaLibrary, Permissions, PublisherBanner, - Region, registerRootComponent, ScreenOrientation, SecureStore, Svg, Updates } from 'expo'; +import { + EdgeInsets, + EdgePadding, + EventUserLocation, + KmlMapEvent, + MapEvent, + MapStyleElement, + Region +} from 'react-native-maps'; const reverseGeocode: Promise<Location.GeocodeData[]> = Location.reverseGeocodeAsync({ latitude: 0, @@ -154,7 +156,6 @@ Audio.setAudioModeAsync({ interruptionModeIOS: 2, interruptionModeAndroid: 1, allowsRecordingIOS: true, - playThroughEarpieceAndroid: false }); Audio.setIsEnabledAsync(true); @@ -233,7 +234,7 @@ Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3; Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY; Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY; async () => { - const result = await Audio.Sound.create({uri: 'uri'}, { + const result = await Audio.Sound.createAsync({uri: 'uri'}, { volume: 0.55, rate: 16.5 }, null, true); @@ -262,13 +263,13 @@ async () => { <AppLoading /> ); -const barCodeScannedCallback = () => {}; +const barcodeReadCallback = () => {}; () => ( <BarCodeScanner type="front" torchMode="off" barCodeTypes={[BarCodeScanner.Constants.BarCodeType.aztec]} - onBarCodeScanned={barCodeScannedCallback} /> + onBarCodeScanned={barcodeReadCallback} /> ); () => ( @@ -408,7 +409,7 @@ async () => { }; async () => { - const result = await ImageManipulator.manipulate('url', [ + const result = await ImageManipulator.manipulateAsync('url', [ { rotate: 90 }, { resize: { width: 300 } }, { resize: { height: 300 } }, @@ -963,7 +964,7 @@ const userLocationCallback = (event: EventUserLocation) => console.log(event); // #endregion async () => { - const updateEventListener: Updates.UpdateEventListener = ({ type, manifest, message }) => { + const updateEventListener: Updates.UpdateEventListener = ({ type }) => { switch (type) { case Updates.EventType.DOWNLOAD_STARTED: case Updates.EventType.DOWNLOAD_PROGRESS: diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 1b24c3151c..591174c6e8 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -15,18 +15,28 @@ // Pavel Ihm <https://github.com/ihmpavel> // Bartosz Dotryw <https://github.com/burtek> // Jason Killian <https://github.com/jkillian> +// Satyajit Sahoo <https://github.com/satya164> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -export * from 'react-native-maps'; +import { EventSubscription } from 'fbemitter'; +import { Component, ComponentClass, Ref, ComponentType } from 'react'; +import { + ColorPropType, + ImageRequireSource, + ImageURISource, + LinkingStatic as ReactNativeLinkingStatic, + NativeEventEmitter, + ViewProps, + ViewStyle, + Permission, + StyleProp +} from 'react-native'; + export { default as MapView } from 'react-native-maps'; -import { EventSubscription } from 'fbemitter'; -import { Component, ComponentClass, ComponentType, Ref } from 'react'; -import { ImageRequireSource, ImageURISource, LinkingStatic as ReactNativeLinkingStatic, StyleProp, ViewProps, ViewStyle } from 'react-native'; - export type Axis = number; -export type BarCodeScannedCallback = (params: { type: string; data: string; }) => void; +export type BarCodeScannedCallback = (result: { type: string; data: string; }) => void; export type Md5 = string; export type Orientation = 'portrait' | 'landscape'; export type RequireSource = ImageRequireSource; @@ -401,9 +411,6 @@ export namespace Audio { /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ interruptionModeAndroid: InterruptionModeAndroid; - - /** Boolean selecting if audio should go to earpiece (only on Android). */ - playThroughEarpieceAndroid: boolean; } function setIsEnabledAsync(value: boolean): Promise<void>; @@ -420,7 +427,7 @@ export namespace Audio { * - `sound`: The newly created and loaded Sound object. * - `status`: The PlaybackStatus of the Sound object. See the AV documentation for further information. */ - static create( + static createAsync( /** * The source of the sound. The following forms are supported: * @@ -565,7 +572,7 @@ export interface PlaybackStatusToSet { volume?: number; } -export type PlaybackSource = RequireSource | { uri: string, headers?: { [header: string]: string }, overrideFileExtensionAndroid?: string } | Asset; +export type PlaybackSource = RequireSource | { uri: string } | Asset; export class PlaybackObject { /** @@ -769,10 +776,10 @@ export namespace Brightness { * Camera */ export interface PictureOptions { - quality?: number; - base64?: boolean; - exif?: boolean; - onPictureSaved?: (data: PictureResponse) => void; + quality?: number; + base64?: boolean; + exif?: boolean; + onPictureSaved?: (data: PictureResponse) => void; } export interface PictureResponse { @@ -797,24 +804,28 @@ export class CameraObject { } export interface CameraProps extends ViewProps { - autoFocus?: string | number | boolean; - barCodeTypes?: Array<string | number>; - faceDetectionClassifications?: number; - faceDetectionLandmarks?: number; - faceDetectionMode?: number; - flashMode?: string | number; + zoom?: number; + ratio?: string; /** Distance to plane of sharpest focus. A value between `0` and `1`. `0`: infinity focus, `1`: focus as close as possible. Default: `0`. For Android this is available only for some devices and when `useCamera2Api` is set to `true`. */ focusDepth?: number; - onBarCodeScanned?: BarCodeScannedCallback; + type?: number | string; onCameraReady?: () => void; + useCamera2Api?: boolean; + flashMode?: number | string; + whiteBalance?: number | string; + autoFocus?: string | boolean | number; + pictureSize?: string; + videoStabilizationMode?: number; + onMountError?: (error: { message: string }) => void; + barCodeScannerSettings?: { barCodeTypes?: Array<string | number>; }; + onBarCodeScanned?: BarCodeScannedCallback; + faceDetectorSettings?: { + mode?: number; + runClassifications?: number; + detectLandmarks?: number; + }; onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; - onMountError?: () => void; - ratio?: string; ref?: Ref<CameraObject>; - type?: string | number; - whiteBalance?: string | number; - /** A value between `0` and `1` being a percentage of device's max zoom. `0`: not zoomed, `1`: maximum zoom. Default: `0`. */ - zoom?: number; } export interface CameraConstants { @@ -1540,15 +1551,62 @@ export namespace FacebookAds { setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; } - function withNativeAd(component: Component<{ - icon?: string; - coverImage?: string; - title?: string; - subtitle?: string; - description?: string; - callToActionText?: string; + interface NativeAd { + /** + * The headline the advertiser entered when they created their ad. This is usually the ad's main + * title. + */ + headline?: string; + + /** + * The link description which is additional information that the advertiser may have entered + */ + linkDescription?: string; + + /** + * The name of the Facebook Page or mobile app that represents the business running the ad + */ + advertiserName?: string; + + /** + * The ad's social context, such as, "Over half a million users" + */ socialContext?: string; - }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * The call-to-action phrase of the ad, such as, "Install Now" + */ + callToActionText?: string; + + /** + * The body text, truncated to 90 characters, that contains the text the advertiser entered when + * they created their ad to tell people what the ad promotes + */ + bodyText?: string; + + /** + * The word "ad", translated into the viewer's language + */ + adTranslation?: string; + + /** + * The word "promoted", translated into the viewer's language + */ + promotedTranslation?: string; + + /** + * The word "sponsored", translated into the viewer's language + */ + sponsoredTranslation?: string; + } + + function withNativeAd<P>(component: Component<P & { nativeAd: NativeAd }>): Component< + { + adsManager: NativeAdsManager, + onAdLoaded?: ((ad: NativeAd) => void) | null; + } & P, + { ad: NativeAd | null, canRequestAds: boolean } + >; /** * Banner View @@ -1564,6 +1622,16 @@ export namespace FacebookAds { class BannerView extends Component<BannerViewProps> { } + type AdTriggerViewProps<P> = { + renderInteractiveComponent?: (props: P) => React.ReactElement<P>; + } & P; + + class AdTriggerView<P> extends Component<AdTriggerViewProps<P>> { } + + class AdIconView extends Component { } + + class AdMediaView extends Component { } + /** * Ad Settings */ @@ -1657,6 +1725,8 @@ export namespace FaceDetector { * FileSystem */ export namespace FileSystem { + type EncodingType = "utf8" | "base64"; + type FileInfo = { exists: true; isDirectory: boolean; @@ -1669,6 +1739,16 @@ export namespace FileSystem { isDirectory: false; }; + interface ReadingOptions { + encoding?: EncodingType; + position?: number; + length?: number; + } + + interface WritingOptions { + encoding?: EncodingType; + } + interface DownloadResult { uri: string; status: number; @@ -1680,8 +1760,8 @@ export namespace FileSystem { const cacheDirectory: string; function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise<FileInfo>; - function readAsStringAsync(fileUri: string): Promise<string>; - function writeAsStringAsync(fileUri: string, contents: string): Promise<void>; + function readAsStringAsync(fileUri: string, options?: ReadingOptions): Promise<string>; + function writeAsStringAsync(fileUri: string, contents: string, options?: WritingOptions): Promise<void>; function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise<void>; function moveAsync(options: { from: string, to: string; }): Promise<void>; function copyAsync(options: { from: string, to: string; }): Promise<void>; @@ -1742,6 +1822,14 @@ export namespace LocalAuthentication { error: string }; + interface AuthenticationTypeType { + FINGERPRINT: number; + FACIAL_RECOGNITION: number; + } + + /** Determine the auhentication types supported on the device. */ + function supportedAuthenticationTypesAsync(): Promise<AuthenticationTypeType[]>; + /** Determine whether a face or fingerprint scanner is available on the device. */ function hasHardwareAsync(): Promise<boolean>; @@ -1887,8 +1975,6 @@ export namespace ImageManipulator { format?: 'jpeg' | 'png'; } - function manipulate(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise<ImageResult>; - function manipulateAsync(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise<ImageResult>; } @@ -2078,6 +2164,7 @@ export namespace Location { enableHighAccuracy?: boolean; timeInterval?: number; distanceInterval?: number; + timeout?: number; } interface LocationProps { @@ -2127,7 +2214,7 @@ export namespace Location { function getProviderStatusAsync(): Promise<ProviderStatus>; function getHeadingAsync(): Promise<HeadingStatus>; function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; - function geocodeAsync(address: string): Promise<Coords[]>; + function geocodeAsync(address: string): Promise<Coords>; function reverseGeocodeAsync(location: LocationProps): Promise<GeocodeData[]>; function setApiKey(key: string): void; } @@ -2198,7 +2285,7 @@ export namespace Notifications { function presentLocalNotificationAsync(localNotification: LocalNotification): Promise<LocalNotificationId>; function scheduleLocalNotificationAsync( localNotification: LocalNotification, - schedulingOptions: SchedulingOptions + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } ): Promise<LocalNotificationId>; function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise<void>; function dismissAllNotificationsAsync(): Promise<void>; @@ -2332,11 +2419,14 @@ export namespace Segment { function identify(userId: string): void; function identifyWithTraits(userId: string, traits: object): void; function track(event: string): void; + function alias(newId: string, options?: { [key: string]: any }): Promise<boolean>; function reset(): void; function trackWithProperties(event: string, properties: object): void; function screen(screenName: string): void; function screenWithProperties(screenName: string, properties: object): void; function flush(): void; + function getEnabledAsync(): void; + function setEnabledAsync(enabled: boolean): void; } /** @@ -2350,7 +2440,7 @@ export namespace Speech { onStart?: () => void; onStopped?: () => void; onDone?: () => void; - onError?: (error: string) => void; + onError?: (error: Error) => void; } function speak(text: string, options?: SpeechOptions): void; From 11e1f15fbfe39b9a7f86b68053c7fbeec501d780 Mon Sep 17 00:00:00 2001 From: Nick Zahn <nic.z@me.com> Date: Mon, 28 Jan 2019 15:15:58 +0000 Subject: [PATCH 023/200] [supercluster] Upgrade to 5.0; stricter types --- types/supercluster/index.d.ts | 188 +++++++++++++++-------- types/supercluster/supercluster-tests.ts | 128 ++++++++++----- types/supercluster/tslint.json | 8 +- 3 files changed, 214 insertions(+), 110 deletions(-) diff --git a/types/supercluster/index.d.ts b/types/supercluster/index.d.ts index 7fd487ae09..74ef517d7e 100644 --- a/types/supercluster/index.d.ts +++ b/types/supercluster/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for supercluster 3.0 +// Type definitions for supercluster 5.0 // Project: https://github.com/mapbox/supercluster // Definitions by: Denis Carriere <https://github.com/DenisCarriere> +// Nick Zahn <https://github.com/Manc> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -8,113 +9,164 @@ import * as GeoJSON from 'geojson'; export as namespace supercluster; -export interface Options { +export interface Options<P, C> { /** * Minimum zoom level at which clusters are generated. + * + * @default 0 */ minZoom?: number; + /** * Maximum zoom level at which clusters are generated. + * + * @default 16 */ maxZoom?: number; + /** * Cluster radius, in pixels. + * + * @default 40 */ radius?: number; + /** * (Tiles) Tile extent. Radius is calculated relative to this value. + * + * @default 512 */ extent?: number; + /** * Size of the KD-tree leaf node. Affects performance. + * + * @default 64 */ nodeSize?: number; + /** * Whether timing info should be logged. + * + * @default false */ log?: boolean; + /** - * a reduce function for calculating custom cluster properties + * A function that returns cluster properties corresponding to a single point. * * @example - * function (accumulated, props) { accumulated.sum += props.sum; } + * (props) => ({sum: props.myValue}) */ - reduce?: (accumulated: any, props: any) => void; + map?: (props: P) => C; + /** - * initial properties of a cluster (before running the reducer) + * A reduce function that merges properties of two clusters into one. * * @example - * function () { return {sum: 0}; } + * (accumulated, props) => { accumulated.sum += props.sum; } */ - initial?: () => any; - /** - * properties to use for individual points when running the reducer - * - * @example - * function (props) { return {sum: props.my_value}; } - */ - map?: (props: any) => any; -} - -export class Supercluster { - /** - * Loads an array of GeoJSON.Feature objects. Each feature's geometry must be a GeoJSON.Point. Once loaded, index is immutable. - */ - load(points: Points): Supercluster; - /** - * For the given bbox array ([westLng, southLat, eastLng, northLat]) and integer zoom, returns an array of clusters and points as GeoJSON.Feature objects. - */ - getClusters(bbox: BBox, zoom: number): Clusters; - - /** - * For a given zoom and x/y coordinates, returns a geojson-vt-compatible JSON tile object with cluster/point features. - */ - getTile(z: number, x: number, y: number): Tile; - - /** - * Returns the children of a cluster (on the next zoom level) given its id (cluster_id value from feature properties) and zoom the cluster was from. - */ - getChildren(clusterId: number, clusterZoom: number): Clusters; - - /** - * Returns all the points of a cluster (given its cluster_id and zoom), - * with pagination support: limit is the number of points to return (set to Infinity for all points), - * and offset is the amount of points to skip (for pagination). - */ - getLeaves(clusterId: number, clusterZoom: number, limit?: number, offset?: number): Clusters; - - /** - * Returns the zoom on which the cluster expands into several children (useful for "click to zoom" feature), given the cluster's cluster_id and zoom. - */ - getClusterExpansionZoom(clusterId: number, clusterZoom: number): number; + reduce?: (accumulated: C, props: Readonly<C>) => void; } /** - * A very fast JavaScript library for geospatial point clustering for browsers and Node. + * Default properties type, allowing any properties. + * Try to avoid this for better typesafety by using proper types. */ -export default function supercluster(options: Options): Supercluster; +export interface AnyProps { + [name: string]: any; +} + +/** + * A very fast geospatial point clustering library for browsers and Node. + */ +export default class Supercluster<P extends GeoJSON.GeoJsonProperties = AnyProps, C extends GeoJSON.GeoJsonProperties = AnyProps> { + constructor(options?: Options<P, C>); + + /** + * Loads an array of GeoJSON Feature objects. Each feature's geometry + * must be a GeoJSON Point. Once loaded, index is immutable. + * + * @param points Array of GeoJSON Features, the geometries being GeoJSON Points. + */ + load(points: Array<PointFeature<P>>): Supercluster<P, C>; + + /** + * Returns an array of clusters and points as `GeoJSON.Feature` objects + * for the given bounding box (`bbox`) and zoom level (`zoom`). + * + * @param bbox Bounding box (`[westLng, southLat, eastLng, northLat]`). + * @param zoom Zoom level. + */ + getClusters(bbox: GeoJSON.BBox, zoom: number): Array<ClusterFeature<C> | PointFeature<P>>; + + /** + * For a given zoom and x/y coordinates, returns a + * [geojson-vt](https://github.com/mapbox/geojson-vt)-compatible JSON + * tile object with cluster any point features. + */ + getTile(zoom: number, x: number, y: number): Tile<C, P> | null; + + /** + * Returns the children of a cluster (on the next zoom level). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + * @throws {Error} If `clusterId` does not exist. + */ + getChildren(clusterId: number): Array<ClusterFeature<C> | PointFeature<P>>; + + /** + * Returns all the points of a cluster (with pagination support). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + * @param limit The number of points to return (set to `Infinity` for all points). + * @param offset The amount of points to skip (for pagination). + */ + getLeaves(clusterId: number, limit?: number, offset?: number): Array<ClusterFeature<C> | PointFeature<P>>; // Cluster[]; + + /** + * Returns the zoom level on which the cluster expands into several + * children (useful for "click to zoom" feature). + * + * @param clusterId Cluster ID (`cluster_id` value from feature properties). + */ + getClusterExpansionZoom(clusterId: number): number; +} + +/** + * [GeoJSON Feature](https://tools.ietf.org/html/rfc7946#section-3.2), + * with the geometry being a + * [GeoJSON Point](https://tools.ietf.org/html/rfc7946#section-3.1.2). + */ +export type PointFeature<P> = GeoJSON.Feature<GeoJSON.Point, P>; -export type Point = GeoJSON.Feature<GeoJSON.Point>; -export type Points = Point[]; -export type Clusters = Cluster[]; -export type TileFeatures = TileFeature[]; -export type BBox = [number, number, number, number]; export interface ClusterProperties { - cluster?: boolean; - cluster_id?: number; - point_count?: number; - point_count_abbreviated?: number; - sum?: number; - [key: string]: any; + /** + * Always `true` to indicate that the Feature is a Cluster and not + * an individual point. + */ + cluster: true; + /** Cluster ID */ + cluster_id: number; + /** Number of points in the cluster. */ + point_count: number; + /** + * Abbreviated number of points in the cluster as string if the number + * is 1000 or greater (e.g. `1.3k` if the number is 1298). + * + * For less than 1000 points it is the same value as `point_count`. + */ + point_count_abbreviated: string | number; } -export interface Cluster extends Point { - properties: ClusterProperties; -} -export interface TileFeature { + +export type ClusterFeature<C> = PointFeature<ClusterProperties & C>; + +export interface TileFeature<C, P> { type: 1; geometry: Array<[number, number]>; - tags: ClusterProperties; + tags: (ClusterProperties & C) | P; } -export interface Tile { - features: TileFeatures; + +export interface Tile<C, P> { + features: Array<TileFeature<C, P>>; } diff --git a/types/supercluster/supercluster-tests.ts b/types/supercluster/supercluster-tests.ts index e3120206e9..6da89ef104 100644 --- a/types/supercluster/supercluster-tests.ts +++ b/types/supercluster/supercluster-tests.ts @@ -1,43 +1,101 @@ -import supercluster, { Point } from 'supercluster'; +import Supercluster, { PointFeature, ClusterProperties } from 'supercluster'; -const point1: Point = { - type: 'Feature', - properties: {my_value: 2}, - geometry: { type: 'Point', coordinates: [10, 20] } -}; -const point2: Point = { - type: 'Feature', - properties: {my_value: 3}, - geometry: { type: 'Point', coordinates: [20, 30] } -}; -const points = [point1, point2]; +// +// Test 1: strictly typed +// -const initialFunction = () => { - return {sum: 0}; -}; +interface TestPointProps { + myTestFeatureName: string; +} -const mapFunction = (props: any) => { - return {sum: props.my_value}; -}; +interface TestClusterProps { + myTestClusterName: string; +} -const reduceFunction = (accumulated: any, props: any) => { - accumulated.sum += props.sum; -}; +const points: Array<PointFeature<TestPointProps>> = [ + { + type: 'Feature', + properties: { myTestFeatureName: 'a' }, + geometry: { type: 'Point', coordinates: [10, 20] } + }, + { + type: 'Feature', + properties: { myTestFeatureName: 'b' }, + geometry: { type: 'Point', coordinates: [20, 30] } + } +]; -const index = supercluster({ - radius: 40, - maxZoom: 16, - extent: 256, - log: true, - initial: initialFunction, - map: mapFunction, - reduce: reduceFunction, +// construct() +new Supercluster(); +new Supercluster({}); +const index = new Supercluster({ + minZoom: 5, + maxZoom: 16, + radius: 40, + extent: 256, + nodeSize: 64, + log: true, + map: (props: TestPointProps): TestClusterProps => ({ + myTestClusterName: props.myTestFeatureName.toUpperCase() + }), + reduce: (accumulated, props) => { + accumulated.myTestClusterName += ` & ${props.myTestClusterName}`; + }, }); + +// load() index.load(points); + +// getClusters() const clusters = index.getClusters([-180, -85, 180, 85], 2); -clusters[0].properties.cluster_id; -index.getTile(0, 0, 0); -index.getChildren(0, 0); -index.getLeaves(0, 0, 10, 5); -index.getClusterExpansionZoom(0, 0); -index.getTile(0, 0, 0).features[0].tags.sum; +const firstProps = clusters[0].properties; // Either cluster or point properties +// Generic cluster properties +(<ClusterProperties> firstProps).cluster; +(<ClusterProperties> firstProps).point_count; +// Custom cluster properties +(<TestClusterProps> firstProps).myTestClusterName; +// Custom point properties +(<TestPointProps> firstProps).myTestFeatureName; + +// getTile() +const tile = index.getTile(0, 0, 0); +if (tile) { + const tileProps = tile.features[0].tags; // Either cluster or point properties + // Generic cluster properties + (<ClusterProperties> tileProps).cluster; + (<ClusterProperties> tileProps).point_count; + // Custom cluster properties + (<TestClusterProps> tileProps).myTestClusterName; + // Custom point properties + (<TestPointProps> tileProps).myTestFeatureName; +} + +// Other methods +index.getChildren(0); +index.getLeaves(0); +index.getLeaves(0, Infinity); +index.getLeaves(0, 0, 10); +index.getClusterExpansionZoom(0); + +// +// Test 2: loosely typed +// + +const index2 = new Supercluster(); +index2.load([ + { + type: 'Feature', + properties: { testPropertyA: 100 }, + geometry: { type: 'Point', coordinates: [10, 20] } + }, + { + type: 'Feature', + properties: { testPropertyB: 'test' }, + geometry: { type: 'Point', coordinates: [20, 30] } + } +]); +const clusters2 = index2.getClusters([-180, -85, 180, 85], 2); +const firstProps2 = clusters2[0].properties; +(<ClusterProperties> firstProps2).cluster_id; +firstProps2.testPropertyA; +firstProps2.testPropertyB; diff --git a/types/supercluster/tslint.json b/types/supercluster/tslint.json index 440efbd687..3db14f85ea 100644 --- a/types/supercluster/tslint.json +++ b/types/supercluster/tslint.json @@ -1,7 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // TODO - "no-duplicate-imports": false - } -} +{ "extends": "dtslint/dt.json" } From 86227dcd724cabb2458511d54f0856a9a87a7ffb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joa=CC=83o=20Vieira?= <joaoguerravieira@gmail.com> Date: Mon, 28 Jan 2019 16:05:27 +0000 Subject: [PATCH 024/200] Overload unless function. --- types/express-unless/express-unless-tests.ts | 12 ++++++------ types/express-unless/index.d.ts | 12 +++++++----- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/types/express-unless/express-unless-tests.ts b/types/express-unless/express-unless-tests.ts index 4a90728f1c..b4d579e742 100644 --- a/types/express-unless/express-unless-tests.ts +++ b/types/express-unless/express-unless-tests.ts @@ -1,11 +1,11 @@ - -import express = require('express'); -import unless = require('express-unless'); +import express = require("express"); +import unless = require("express-unless"); var app = express(); -var middleware:unless.RequestHandler = function (req, res, next) { +var middleware: unless.RequestHandler = function(req, res, next) { next(); -} +}; middleware.unless = unless; -app.use(middleware.unless({ method: 'OPTIONS' })); \ No newline at end of file +app.use(middleware.unless({ method: "OPTIONS" })); +app.use(middleware.unless(req => req.path === "test")); diff --git a/types/express-unless/index.d.ts b/types/express-unless/index.d.ts index 7d7056f766..79eb870cb3 100644 --- a/types/express-unless/index.d.ts +++ b/types/express-unless/index.d.ts @@ -1,19 +1,21 @@ -// Type definitions for express-unless +// Type definitions for express-unless 0.5 // Project: https://www.npmjs.org/package/express-unless // Definitions by: Wonshik Kim <https://github.com/wokim> +// Joao Vieira <https://github.com/joaovieira> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import express = require('express'); +import express = require("express"); declare function unless(options: unless.Options): express.RequestHandler; +declare function unless(options: unless.Options["custom"]): express.RequestHandler; declare namespace unless { export interface Options { custom?: (req: express.Request) => boolean; - path?: any; // TODO: union type 'string|string[]' is not supported yet - ext?: any; // TODO: union type 'string|string[]' is not supported yet - method?: any; // TODO: union type 'string|string[]' is not supported yet + path?: string | string[]; + ext?: string | string[]; + method?: string | string[]; } export interface RequestHandler extends express.RequestHandler { unless?: typeof unless; From 35e3d24f055795316c8d0addbcb89546c3195d31 Mon Sep 17 00:00:00 2001 From: Leo Salgueiro <leonardosalgueiro@live.com> Date: Mon, 28 Jan 2019 18:27:05 -0800 Subject: [PATCH 025/200] upgrading react-highlight-words typings to the newest version of the library 0.16.0 --- types/react-highlight-words/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-highlight-words/index.d.ts b/types/react-highlight-words/index.d.ts index 9cd72ec411..9dc19130a7 100644 --- a/types/react-highlight-words/index.d.ts +++ b/types/react-highlight-words/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-highlight-words 0.12 +// Type definitions for react-highlight-words 0.16 // Project: https://github.com/bvaughn/react-highlight-words#readme // Definitions by: Mohamed Hegazy <https://github.com/mhegazy> // Diogo Corrêa <https://github.com/diogodca> @@ -25,7 +25,7 @@ interface HighlighterProps { /** The class name to be applied to an active match. Use along with activeIndex */ activeClassName?: string; /** Specify the match index that should be actively highlighted. Use along with activeClassName */ - activeIndex?: string; + activeIndex?: number; /** The inline style to be applied to an active match. Use along with activeIndex */ activeStyle?: React.CSSProperties; /** Escape characters in searchWords which are meaningful in regular expressions */ @@ -48,7 +48,7 @@ interface HighlighterProps { * Type of tag to wrap around highlighted matches; defaults to mark but can also be a React element * (class or functional) */ - highlightTag?: string; + highlightTag?: string | React.ComponentType<any>; /** * Process each search word and text to highlight before comparing (eg remove accents); signature * (text: string): string From 4d254b9d090376b0380b20c7e44a40f93c18bbfa Mon Sep 17 00:00:00 2001 From: Leo Salgueiro <leonardosalgueiro@live.com> Date: Mon, 28 Jan 2019 18:33:37 -0800 Subject: [PATCH 026/200] fixing the test --- .../react-highlight-words/react-highlight-words-tests.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/types/react-highlight-words/react-highlight-words-tests.tsx b/types/react-highlight-words/react-highlight-words-tests.tsx index de63c6d9ec..db8389fe9f 100644 --- a/types/react-highlight-words/react-highlight-words-tests.tsx +++ b/types/react-highlight-words/react-highlight-words-tests.tsx @@ -6,17 +6,20 @@ const findChunks = ({ textToHighlight }: FindChunks) => []; +const CustomHighlight: React.FC = ({children}) => (<span>{children}</span>) + class HighlighterTest extends React.Component { render() { return ( <div> <Highlighter + highlightTag="span" searchWords={["el", "or"]} textToHighlight="Hello World" /> <Highlighter activeClassName="activeClassName" - activeIndex="activeIndex" + activeIndex={1} activeStyle={{ color: "red" }} autoEscape={true} className="className" @@ -24,7 +27,7 @@ class HighlighterTest extends React.Component { findChunks={findChunks} highlightClassName="highlightClassName" highlightStyle={{ color: "red" }} - highlightTag="span" + highlightTag={CustomHighlight} sanitize={(text: string) => text} searchWords={["el", "or"]} textToHighlight="Hello World" From 1a96cde57a30f5377f6545c1244e5934c479f0be Mon Sep 17 00:00:00 2001 From: Leo Salgueiro <leonardosalgueiro@live.com> Date: Mon, 28 Jan 2019 18:40:55 -0800 Subject: [PATCH 027/200] fixing mistake that the linting found --- types/react-highlight-words/react-highlight-words-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-highlight-words/react-highlight-words-tests.tsx b/types/react-highlight-words/react-highlight-words-tests.tsx index db8389fe9f..de1100e0de 100644 --- a/types/react-highlight-words/react-highlight-words-tests.tsx +++ b/types/react-highlight-words/react-highlight-words-tests.tsx @@ -6,7 +6,7 @@ const findChunks = ({ textToHighlight }: FindChunks) => []; -const CustomHighlight: React.FC = ({children}) => (<span>{children}</span>) +const CustomHighlight: React.FC = ({children}) => (<span>{children}</span>); class HighlighterTest extends React.Component { render() { From c24399496d98a1c0ee597569f2e7b00b77cd963b Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 15:15:47 -0800 Subject: [PATCH 028/200] [jscodeshift] Run `npx dts-gen --dt --name jscodeshift --template module` --- types/jscodeshift/index.d.ts | 39 ++++++++++++++++++++++++++ types/jscodeshift/jscodeshift-tests.ts | 0 types/jscodeshift/tsconfig.json | 22 +++++++++++++++ types/jscodeshift/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/jscodeshift/index.d.ts create mode 100644 types/jscodeshift/jscodeshift-tests.ts create mode 100644 types/jscodeshift/tsconfig.json create mode 100644 types/jscodeshift/tslint.json diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts new file mode 100644 index 0000000000..7d1fe12f72 --- /dev/null +++ b/types/jscodeshift/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for jscodeshift 0.6 +// Project: https://github.com/facebook/jscodeshift#readme +// Definitions by: My Self <https://github.com/me> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ If this module is a UMD module that exposes a global variable 'myLib' when + *~ loaded outside a module loader environment, declare that global here. + *~ Otherwise, delete this declaration. + */ +export as namespace myLib; + +/*~ If this module has methods, declare them as functions like so. + */ +export function myMethod(a: string): string; +export function myOtherMethod(a: number): number; + +/*~ You can declare types that are available via importing the module */ +export interface someType { + name: string; + length: number; + extras?: string[]; +} + +/*~ You can declare properties of the module using const, let, or var */ +export const myField: number; + +/*~ If there are types, properties, or methods inside dotted names + *~ of the module, declare them inside a 'namespace'. + */ +export namespace subProp { + /*~ For example, given this definition, someone could write: + *~ import { subProp } from 'yourModule'; + *~ subProp.foo(); + *~ or + *~ import * as yourMod from 'yourModule'; + *~ yourMod.subProp.foo(); + */ + export function foo(): void; +} \ No newline at end of file diff --git a/types/jscodeshift/jscodeshift-tests.ts b/types/jscodeshift/jscodeshift-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json new file mode 100644 index 0000000000..726b5b889f --- /dev/null +++ b/types/jscodeshift/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jscodeshift-tests.ts" + ] +} diff --git a/types/jscodeshift/tslint.json b/types/jscodeshift/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jscodeshift/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3d12a04ac4f3591d580eccbcb4e1b6bcbb14f8e1 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 15:39:35 -0800 Subject: [PATCH 029/200] [jscodeshift] Add types for jscodeshift 0.6 --- types/jscodeshift/index.d.ts | 448 +++++++++++++++++++++++-- types/jscodeshift/jscodeshift-tests.ts | 50 +++ types/jscodeshift/package.json | 7 + types/jscodeshift/tsconfig.json | 1 + 4 files changed, 477 insertions(+), 29 deletions(-) create mode 100644 types/jscodeshift/package.json diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index 7d1fe12f72..3e91d382ba 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -1,39 +1,429 @@ // Type definitions for jscodeshift 0.6 // Project: https://github.com/facebook/jscodeshift#readme -// Definitions by: My Self <https://github.com/me> +// Definitions by: Brie Bunge <https://github.com/brieb> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 -/*~ If this module is a UMD module that exposes a global variable 'myLib' when - *~ loaded outside a module loader environment, declare that global here. - *~ Otherwise, delete this declaration. - */ -export as namespace myLib; +declare module "jscodeshift" { + import { Collection, registerMethods } from "jscodeshift/src/Collection"; + import * as JSXElement from "jscodeshift/src/collections/JSXElement"; + import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; + import { Template } from "jscodeshift/src/template"; + import recast, { Builders, NamedTypes, NodePath, Options, Parser } from "recast"; + import { ASTNode } from "ast-types/gen/nodes"; -/*~ If this module has methods, declare them as functions like so. - */ -export function myMethod(a: string): string; -export function myOtherMethod(a: number): number; + export type ASTPath<N = ASTNode> = NodePath<N, N>; -/*~ You can declare types that are available via importing the module */ -export interface someType { - name: string; - length: number; - extras?: string[]; + export interface Filters { + JSXElement: JSXElement.FilterMethods; + VariableDeclarator: VariableDeclarator.FilterMethods; + } + + export interface Mappings { + JSXElement: JSXElement.MappingMethods; + } + + export interface Plugin { + (core: Core): void; + } + + export interface FileInfo { + /** The absolute path to the current file. */ + path: string; + /** The source code of the current file. */ + source: string; + } + + export interface Stats { + /** + * Helper function to collect data during --dry runs. + * This function keeps a counter for how often it was called with a specific argument. + * The result is shown in the console. Useful for finding out how many files match a criterion. + */ + (name: string, quantity?: number): void; + } + + interface Core { + (source: string, options?: Options): Collection<any>; + (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection<any>; + + registerMethods: typeof registerMethods; + + types: typeof recast.types; + + match(path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode): boolean; + + /** template, bound to default parser */ + template: Template; + + filters: Filters; + + mappings: Mappings; + + /** + * Utility function for registering plugins. + * + * Plugins are simple functions that are passed the core jscodeshift instance. + * They should extend jscodeshift by calling `registerMethods`, etc. + * This method guards against repeated registrations (the plugin callback will only be called once). + */ + use(plugin: Plugin): void; + + /** + * Returns a version of the core jscodeshift function "bound" to a specific + * parser. + */ + withParser(parser: string | Parser): JSCodeshift; + } + + type JSCodeshift = Core & NamedTypes & Builders; + + const core: JSCodeshift; + export default core; + + export interface API { + j: JSCodeshift; + jscodeshift: JSCodeshift; + stats: Stats; + report: (msg: string) => void; + } + + export interface Options { + [option: string]: any; + } + + export interface Transform { + /** + * If a string is returned and it is different from passed source, the transform is considered to be successful. + * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. + * If nothing is returned, the file is not supposed to be transformed (which is ok). + */ + (file: FileInfo, api: API, options: Options): string | null | undefined | void; + } + + export * from "ast-types/gen/nodes"; + export { Collection, Parser }; } -/*~ You can declare properties of the module using const, let, or var */ -export const myField: number; +declare module "jscodeshift/src/template" { + import { Parser } from "recast"; -/*~ If there are types, properties, or methods inside dotted names - *~ of the module, declare them inside a 'namespace'. - */ -export namespace subProp { - /*~ For example, given this definition, someone could write: - *~ import { subProp } from 'yourModule'; - *~ subProp.foo(); - *~ or - *~ import * as yourMod from 'yourModule'; - *~ yourMod.subProp.foo(); + export interface Template { + /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ + statements(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Statement AST node. */ + statement(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Expression AST node. */ + expression(...args: any[]): any; + } + + export default function withParser(parser: Parser): Template; + + export {}; // force module +} + +declare module "jscodeshift/src/Collection" { + import * as JSXElement from "jscodeshift/src/collections/JSXElement"; + import * as NodeCollection from "jscodeshift/src/collections/Node"; + import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; + import recast, { ASTNode, NodePath, Options } from "recast"; + + type Type = typeof recast.types.Type; + type ASTPath<N> = NodePath<N, N>; + + interface Collection<N> + extends NodeCollection.TraversalMethods, + NodeCollection.MutationMethods<N>, + VariableDeclarator.GlobalMethods, + VariableDeclarator.TransformMethods<N>, + JSXElement.GlobalMethods, + JSXElement.TraversalMethods { + /** + * @param paths An array of AST paths + * @param parent A parent collection + * @param types An array of types all the paths in the collection + * have in common. If not passed, it will be inferred from the paths. + */ + new (paths: ASTPath<N>[], parent: Collection<any>, types?: Type[]): this; + + /** + * Returns a new collection containing the nodes for which the callback returns true. + */ + filter<S extends N>( + callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => path is ASTPath<S> + ): Collection<S>; + filter( + callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean + ): Collection<N>; + + /** + * Executes callback for each node/path in the collection. + */ + forEach(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => void): this; + + /** + * Tests whether at-least one path passes the test implemented by the provided callback. + */ + some(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean): boolean; + + /** + * Tests whether all paths pass the test implemented by the provided callback. + */ + every(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean): boolean; + + /** + * Executes the callback for every path in the collection and returns a new + * collection from the return values (which must be paths). + * + * The callback can return null to indicate to exclude the element from the + * new collection. + * + * If an array is returned, the array will be flattened into the result + * collection. + * + * @param callback + * @param type Force the new collection to be of a specific type + */ + map<T = ASTNode>( + callback: ( + path: ASTPath<N>, + i: number, + paths: ASTPath<N>[] + ) => ASTPath<T> | ASTPath<T>[] | null | undefined, + type: Type + ): Collection<T>; + + /** Returns the number of elements in this collection. */ + size(): number; + + /** Returns the number of elements in this collection. */ + length: number; + + /** Returns an array of AST nodes in this collection. */ + nodes(): N[]; + + /** Returns an array of ASTPaths in this this collection. */ + paths(): ASTPath<N>[]; + + getAST(): ASTPath<any>[]; + + /** + * Converts the AST back to a string, using recast. + * @param options directly passed to recast's printer + */ + toSource(options?: Options): string; + + /** + * Returns a new collection containing only the element at position index. + * In case of a negative index, the element is taken from the end: + * .at(0) - first element + * .at(-1) - last element + */ + at(index: number): Collection<N>; + + /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ + get<T>(...fields: (string | number)[]): T; + + /** + * Returns the type(s) of the collection. This is only used for unit tests, + * don't think other consumers would need it. + */ + getTypes(): string[]; + + /** + * Returns true if this collection has the type 'type'. + */ + isOfType(type: Type): boolean; + } + + /** + * This function adds the provided methods to the prototype of the corresponding + * typed collection. If no type is passed, the methods are added to + * Collection.prototype and are available for all collections. + * + * @param methods Methods to add to the prototype + * @param type Optional type to add the methods to */ - export function foo(): void; -} \ No newline at end of file + export function registerMethods(methods: object, type?: Type): void; +} + +declare module "jscodeshift/src/collections/Node" { + import { Collection } from "jscodeshift/src/Collection"; + import { ASTNode, Type } from "recast"; + + export interface TraversalMethods { + /** + * Find nodes of a specific type within the nodes of this collection. + */ + find<T>(type: Type<T>): Collection<T>; + find<T>(type: Type<T>, filter: (value: any) => boolean): Collection<T>; + find<T>(type: Type<T>, filter: object): Collection<T>; + + /** + * Returns a collection containing the paths that create the scope of the + * currently selected paths. Dedupes the paths. + */ + closestScope<T>(): Collection<T>; + + /** + * Traverse the AST up and finds the closest node of the provided type. + */ + closest<T>(type: Type<T>, filter?: any): Collection<T>; + + /** + * Finds the declaration for each selected path. Useful for member expressions + * or JSXElements. Expects a callback function that maps each path to the name + * to look for. + * + * If the callback returns a falsey value, the element is skipped. + */ + getVariableDeclarators<T>(nameGetter: Function): Collection<T>; + } + + export interface MutationMethods<N> { + /** + * Simply replaces the selected nodes with the provided node. If a function + * is provided it is executed for every node and the node is replaced with the + * functions return value. + * + * @param {Node|Array<Node>|function} nodes + */ + replaceWith<T>(nodes: T | T[] | ((path: any, i: number) => T)): this; + + /** + * Inserts a new node before the current one. + * + * @param {Node|Array<Node>|function} insert + */ + insertBefore(insert: any): Collection<N>; + + /** + * Inserts a new node after the current one. + * + * @param {Node|Array<Node>|function} insert + */ + insertAfter(insert: any): Collection<N>; + + remove(): Collection<N>; + } + + export function register(): void; + + export {}; // force module +} + +declare module "jscodeshift/src/collections/VariableDeclarator" { + import { VariableDeclarator } from "ast-types/gen/nodes"; + import { Collection } from "jscodeshift/src/Collection"; + import recast, { NodePath } from "recast"; + + type Node = typeof recast.types.namedTypes.Node; + type ASTPath<N> = NodePath<N, N>; + + export interface GlobalMethods { + /** + * Finds all variable declarators, optionally filtered by name. + */ + findVariableDeclarators(name?: string): Collection<VariableDeclarator>; + } + + export interface TransformMethods<N> { + /** + * Renames a variable and all its occurrences. + * This method only applies to VariableDeclarator typed collections. + */ + renameTo(newName: string): Collection<N>; + } + + interface Filter { + (path: ASTPath<any>): boolean; + } + + export interface FilterMethods { + /** + * Returns a function that returns true if the provided path is a variable + * declarator and requires one of the specified module names. + * + * @param names A module name or an array of module names + */ + requiresModule(names: string | string[]): Filter; + } + + export function register(): void; + export const filters: FilterMethods; + + export {}; // force module +} + +declare module "jscodeshift/src/collections/JSXElement" { + import { JSXElement } from "ast-types/gen/nodes"; + import { Collection } from "jscodeshift/src/Collection"; + import { NodePath } from "recast"; + + type ASTPath<N> = NodePath<N, N>; + + export interface GlobalMethods { + /** + * Finds all JSXElements optionally filtered by name + */ + findJSXElements(name?: string): Collection<JSXElement>; + + /** + * Finds all JSXElements by module name. Given + * + * var Bar = require('Foo'); + * <Bar /> + * + * findJSXElementsByModuleName('Foo') will find <Bar />, without having to + * know the variable name. + */ + findJSXElementsByModuleName(moduleName: string): Collection<JSXElement>; + } + + type Defined<T> = T extends undefined ? never : T; + type JSXElementChild = Defined<JSXElement["children"]>[0]; + + export interface TraversalMethods { + /** + * Returns all child nodes, including literals and expressions. + * This method only applies to JSXElement typed collections. + */ + childNodes<T>(): Collection<JSXElementChild>; + + /** + * Returns all children that are JSXElements. + * This method only applies to JSXElement typed collections. + */ + childElements(): Collection<JSXElement>; + } + + interface Filter { + (path: ASTPath<any>): boolean; + } + + export interface FilterMethods { + /** + * Filter method for attributes. + */ + hasAttributes(attributeFilter: { [attributeName: string]: any }): Filter; + + /** + * Filter elements which contain a specific child type + */ + hasChildren(name: string): Filter; + } + + export interface MappingMethods { + /** + * Given a JSXElement, returns its "root" name. E.g. it would return "Foo" for + * both <Foo /> and <Foo.Bar />. + */ + getRootName(path: ASTPath<any>): string; + } + + export function register(): void; + export const filters: FilterMethods; + export const mappings: MappingMethods; + + export {}; // force module +} diff --git a/types/jscodeshift/jscodeshift-tests.ts b/types/jscodeshift/jscodeshift-tests.ts index e69de29bb2..8631e400c4 100644 --- a/types/jscodeshift/jscodeshift-tests.ts +++ b/types/jscodeshift/jscodeshift-tests.ts @@ -0,0 +1,50 @@ +import { ASTNode, FileInfo, API, Transform } from "jscodeshift"; + +// Can define transform with `function`. +function replaceWithFooTransform(fileInfo: FileInfo, api: API) { + return api + .jscodeshift(fileInfo.source) + .findVariableDeclarators("foo") + .renameTo("bar") + .toSource(); +} + +// Can define transform with arrow function, using `Transform` type. +const reverseIdentifiersTransform: Transform = (file, api) => { + const j = api.jscodeshift; + + return j(file.source) + .find(j.Identifier) + .forEach(path => { + j(path).replaceWith( + j.identifier( + path.node.name + .split("") + .reverse() + .join("") + ) + ); + }) + .toSource(); +}; + +// `ASTNode` supports type narrowing. +{ + const node = ({} as any) as ASTNode; + if (node.type === "CatchClause") { + // `node` is narrowed to `CatchClause` here + if (node.param && node.param.type === "Identifier") { + // `node.param` is narrowed to `Identifier` here + if ( + node.param.typeAnnotation && + node.param.typeAnnotation.type === "TSTypeAnnotation" + ) { + // `node.param.typeAnnotation` is narrowed to `TSTypeAnnotation` here + if (node.param.typeAnnotation.typeAnnotation.type === "TSArrayType") { + // `node.param.typeAnnotation.typeAnnotation` is narrowed to `TSArrayType` here + node.param.typeAnnotation.typeAnnotation.elementType; + } + } + } + } +} diff --git a/types/jscodeshift/package.json b/types/jscodeshift/package.json new file mode 100644 index 0000000000..65d03a5a7f --- /dev/null +++ b/types/jscodeshift/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "ast-types": "^0.12.0", + "recast": "^0.17.0" + } +} diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index 726b5b889f..f1ad7409d3 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 3e712a34cb4fca323d48ca5d627fa846947cacde Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 15:51:32 -0800 Subject: [PATCH 030/200] [jscodeshift] Fix lints --- types/jscodeshift/index.d.ts | 46 +++++++++++++++-------------------- types/jscodeshift/tslint.json | 9 ++++++- 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index 3e91d382ba..391b4a4f13 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -119,7 +119,7 @@ declare module "jscodeshift/src/template" { export default function withParser(parser: Parser): Template; - export {}; // force module + export {}; // to shut off automatic exporting } declare module "jscodeshift/src/Collection" { @@ -131,7 +131,7 @@ declare module "jscodeshift/src/Collection" { type Type = typeof recast.types.Type; type ASTPath<N> = NodePath<N, N>; - interface Collection<N> + export interface Collection<N> extends NodeCollection.TraversalMethods, NodeCollection.MutationMethods<N>, VariableDeclarator.GlobalMethods, @@ -144,32 +144,32 @@ declare module "jscodeshift/src/Collection" { * @param types An array of types all the paths in the collection * have in common. If not passed, it will be inferred from the paths. */ - new (paths: ASTPath<N>[], parent: Collection<any>, types?: Type[]): this; + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Type[]): this; /** * Returns a new collection containing the nodes for which the callback returns true. */ filter<S extends N>( - callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => path is ASTPath<S> + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => path is ASTPath<S> ): Collection<S>; filter( - callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean ): Collection<N>; /** * Executes callback for each node/path in the collection. */ - forEach(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => void): this; + forEach(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => void): this; /** * Tests whether at-least one path passes the test implemented by the provided callback. */ - some(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean): boolean; + some(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; /** * Tests whether all paths pass the test implemented by the provided callback. */ - every(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean): boolean; + every(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; /** * Executes the callback for every path in the collection and returns a new @@ -188,8 +188,8 @@ declare module "jscodeshift/src/Collection" { callback: ( path: ASTPath<N>, i: number, - paths: ASTPath<N>[] - ) => ASTPath<T> | ASTPath<T>[] | null | undefined, + paths: Array<ASTPath<N>> + ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, type: Type ): Collection<T>; @@ -203,9 +203,9 @@ declare module "jscodeshift/src/Collection" { nodes(): N[]; /** Returns an array of ASTPaths in this this collection. */ - paths(): ASTPath<N>[]; + paths(): Array<ASTPath<N>>; - getAST(): ASTPath<any>[]; + getAST(): Array<ASTPath<any>>; /** * Converts the AST back to a string, using recast. @@ -222,7 +222,7 @@ declare module "jscodeshift/src/Collection" { at(index: number): Collection<N>; /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ - get<T>(...fields: (string | number)[]): T; + get(...fields: Array<string | number>): any; /** * Returns the type(s) of the collection. This is only used for unit tests, @@ -245,6 +245,8 @@ declare module "jscodeshift/src/Collection" { * @param type Optional type to add the methods to */ export function registerMethods(methods: object, type?: Type): void; + + export {}; // to shut off automatic exporting } declare module "jscodeshift/src/collections/Node" { @@ -255,9 +257,7 @@ declare module "jscodeshift/src/collections/Node" { /** * Find nodes of a specific type within the nodes of this collection. */ - find<T>(type: Type<T>): Collection<T>; - find<T>(type: Type<T>, filter: (value: any) => boolean): Collection<T>; - find<T>(type: Type<T>, filter: object): Collection<T>; + find<T>(type: Type<T>, filter?: ((value: any) => boolean) | object): Collection<T>; /** * Returns a collection containing the paths that create the scope of the @@ -277,7 +277,7 @@ declare module "jscodeshift/src/collections/Node" { * * If the callback returns a falsey value, the element is skipped. */ - getVariableDeclarators<T>(nameGetter: Function): Collection<T>; + getVariableDeclarators<T>(nameGetter: (...args: any[]) => any): Collection<T>; } export interface MutationMethods<N> { @@ -285,22 +285,16 @@ declare module "jscodeshift/src/collections/Node" { * Simply replaces the selected nodes with the provided node. If a function * is provided it is executed for every node and the node is replaced with the * functions return value. - * - * @param {Node|Array<Node>|function} nodes */ replaceWith<T>(nodes: T | T[] | ((path: any, i: number) => T)): this; /** * Inserts a new node before the current one. - * - * @param {Node|Array<Node>|function} insert */ insertBefore(insert: any): Collection<N>; /** * Inserts a new node after the current one. - * - * @param {Node|Array<Node>|function} insert */ insertAfter(insert: any): Collection<N>; @@ -309,7 +303,7 @@ declare module "jscodeshift/src/collections/Node" { export function register(): void; - export {}; // force module + export {}; // to shut off automatic exporting } declare module "jscodeshift/src/collections/VariableDeclarator" { @@ -352,7 +346,7 @@ declare module "jscodeshift/src/collections/VariableDeclarator" { export function register(): void; export const filters: FilterMethods; - export {}; // force module + export {}; // to shut off automatic exporting } declare module "jscodeshift/src/collections/JSXElement" { @@ -425,5 +419,5 @@ declare module "jscodeshift/src/collections/JSXElement" { export const filters: FilterMethods; export const mappings: MappingMethods; - export {}; // force module + export {}; // to shut off automatic exporting } diff --git a/types/jscodeshift/tslint.json b/types/jscodeshift/tslint.json index 3db14f85ea..94991f356f 100644 --- a/types/jscodeshift/tslint.json +++ b/types/jscodeshift/tslint.json @@ -1 +1,8 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-declare-current-package": false, + "no-self-import": false, + "no-unnecessary-generics": false + } +} From 0cc491505e8284969ef2720aa10bf42c20b31ac6 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 16:16:12 -0800 Subject: [PATCH 031/200] [jscodeshift] Additional test cases --- types/jscodeshift/index.d.ts | 12 ++++----- types/jscodeshift/jscodeshift-tests.ts | 37 +++++++++++++++++++++----- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index 391b4a4f13..b9b15be825 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -126,9 +126,8 @@ declare module "jscodeshift/src/Collection" { import * as JSXElement from "jscodeshift/src/collections/JSXElement"; import * as NodeCollection from "jscodeshift/src/collections/Node"; import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; - import recast, { ASTNode, NodePath, Options } from "recast"; + import recast, { ASTNode, NodePath, Options, Type } from "recast"; - type Type = typeof recast.types.Type; type ASTPath<N> = NodePath<N, N>; export interface Collection<N> @@ -144,7 +143,7 @@ declare module "jscodeshift/src/Collection" { * @param types An array of types all the paths in the collection * have in common. If not passed, it will be inferred from the paths. */ - new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Type[]): this; + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<Type<any>>): this; /** * Returns a new collection containing the nodes for which the callback returns true. @@ -190,7 +189,7 @@ declare module "jscodeshift/src/Collection" { i: number, paths: Array<ASTPath<N>> ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, - type: Type + type: Type<any> ): Collection<T>; /** Returns the number of elements in this collection. */ @@ -233,7 +232,7 @@ declare module "jscodeshift/src/Collection" { /** * Returns true if this collection has the type 'type'. */ - isOfType(type: Type): boolean; + isOfType(type: Type<any>): boolean; } /** @@ -244,7 +243,7 @@ declare module "jscodeshift/src/Collection" { * @param methods Methods to add to the prototype * @param type Optional type to add the methods to */ - export function registerMethods(methods: object, type?: Type): void; + export function registerMethods(methods: object, type?: Type<any>): void; export {}; // to shut off automatic exporting } @@ -311,7 +310,6 @@ declare module "jscodeshift/src/collections/VariableDeclarator" { import { Collection } from "jscodeshift/src/Collection"; import recast, { NodePath } from "recast"; - type Node = typeof recast.types.namedTypes.Node; type ASTPath<N> = NodePath<N, N>; export interface GlobalMethods { diff --git a/types/jscodeshift/jscodeshift-tests.ts b/types/jscodeshift/jscodeshift-tests.ts index 8631e400c4..f426eb37b7 100644 --- a/types/jscodeshift/jscodeshift-tests.ts +++ b/types/jscodeshift/jscodeshift-tests.ts @@ -1,4 +1,4 @@ -import { ASTNode, FileInfo, API, Transform } from "jscodeshift"; +import { ASTNode, FileInfo, API, Transform, Parser } from "jscodeshift"; // Can define transform with `function`. function replaceWithFooTransform(fileInfo: FileInfo, api: API) { @@ -28,21 +28,46 @@ const reverseIdentifiersTransform: Transform = (file, api) => { .toSource(); }; +// Can define a custom parser. +const parser: Parser = { + parse(source, options) { + // return estree compatible AST + return { type: "root" }; + } +}; + +// Can pass options to recast +const transformWithRecastFormattingOptions: Transform = (file, { j }) => { + return j(file.source).toSource({ quote: "single" }); +}; + +const transformWithRecastParseOptions: Transform = (file, { j }) => { + return j(file.source, { + /* ...passes options to recast's parse method... */ + }).toSource(); +}; + // `ASTNode` supports type narrowing. { const node = ({} as any) as ASTNode; if (node.type === "CatchClause") { - // `node` is narrowed to `CatchClause` here + // $ExpectType CatchClause + node; + if (node.param && node.param.type === "Identifier") { - // `node.param` is narrowed to `Identifier` here + // $ExpectType Identifier + node.param; + if ( node.param.typeAnnotation && node.param.typeAnnotation.type === "TSTypeAnnotation" ) { - // `node.param.typeAnnotation` is narrowed to `TSTypeAnnotation` here + // $ExpectType TSTypeAnnotation + node.param.typeAnnotation; + if (node.param.typeAnnotation.typeAnnotation.type === "TSArrayType") { - // `node.param.typeAnnotation.typeAnnotation` is narrowed to `TSArrayType` here - node.param.typeAnnotation.typeAnnotation.elementType; + // $ExpectType TSArrayType + node.param.typeAnnotation.typeAnnotation; } } } From abfdaa340f1fb458f7b76c587a46c90c418ddaae Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 16:17:22 -0800 Subject: [PATCH 032/200] [jscodeshift] Move tests to /test subfolder --- types/jscodeshift/{ => test}/jscodeshift-tests.ts | 0 types/jscodeshift/tsconfig.json | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) rename types/jscodeshift/{ => test}/jscodeshift-tests.ts (100%) diff --git a/types/jscodeshift/jscodeshift-tests.ts b/types/jscodeshift/test/jscodeshift-tests.ts similarity index 100% rename from types/jscodeshift/jscodeshift-tests.ts rename to types/jscodeshift/test/jscodeshift-tests.ts diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index f1ad7409d3..c5f4e65e59 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -16,8 +16,8 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ + "include": [ "index.d.ts", - "jscodeshift-tests.ts" + "test" ] } From 277387c0b621e630dafb1a269009a7e9c253c037 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 16:50:27 -0800 Subject: [PATCH 033/200] [jscodeshift] Copy js-transforms for use as real-world test cases https://github.com/jhgg/js-transforms/tree/bfdc97240bfc07e30453a81407f98820d67439a8 --- .../bind-this-to-bind-expression.js | 22 +++ ...-bind-this-to-arrow-function-expression.js | 50 +++++++ ...expression-to-arrow-function-expression.js | 46 ++++++ .../js-transforms/props-to-destructuring.js | 137 ++++++++++++++++++ .../pure-to-composite-component.js | 61 ++++++++ 5 files changed, 316 insertions(+) create mode 100755 types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js create mode 100755 types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js create mode 100755 types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js create mode 100755 types/jscodeshift/test/js-transforms/props-to-destructuring.js create mode 100755 types/jscodeshift/test/js-transforms/pure-to-composite-component.js diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js new file mode 100755 index 0000000000..97248a7e35 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js @@ -0,0 +1,22 @@ +/** + * This transform converts stuff like: + * + * let x = this.foo.bind(this); + * + * to + * + * let x = ::this.foo; + * + */ + +module.exports = function (file, api) { + const j = api.jscodeshift; + return j(file.source) + // Find stuff that looks like this.xyz.bind(this) + .find(j.CallExpression, {callee: {object: {object: j.ThisExpression}, property: {name: 'bind'}}}) + // Ensure that .bind() is being called with only one argument, and that argument is "this". + .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") + // We can now replace it with ::this.xyz + .replaceWith(p => j.bindExpression(null, p.value.callee.object)) + .toSource(); +}; \ No newline at end of file diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js new file mode 100755 index 0000000000..727f2e950d --- /dev/null +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js @@ -0,0 +1,50 @@ +/** Converts + * onClick(function(a, b) { + * return a + b; + * }.bind(this), + * function(b, c) { + * return 1; + * }.bind(this)); + * + * onClick(function(a) { + * var a = 1; + * return a; + * }.bind(this)); + * + * var a = function(c) { return c; }.bind(this); + * + ** to + * onClick((a, b) => a + b, + * (b, c) => 1); + * + * onClick(a => { + * var a = 1; + * return a; + * }); + * + * var a = c => c; + * + */ + +module.exports = function(file, api) { + const j = api.jscodeshift; + + return j(file.source) + // We're looking for a CallExpression that's calling .bind() onto a FunctionExpression. + .find(j.CallExpression, {callee: {property: {name: 'bind'}, object: {type: 'FunctionExpression'}}}) + // Verify that .bind() is only being called with `this` as it's sole arguments. + .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") + .replaceWith(p => { + // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer + // to the FunctionExpression that's being called .bind(this) on. We need the body of that function + // to transform into an ArrowFunctionExpression. + var body = p.value.callee.object.body; + // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, + // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } + var useExpression = body.type == 'BlockStatement' && body.body.length == 1 && body.body[0].type == "ReturnStatement"; + body = useExpression ? body.body[0].argument : body; + + return j.arrowFunctionExpression(p.value.callee.object.params, body, useExpression); + }) + .toSource(); +}; \ No newline at end of file diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js new file mode 100755 index 0000000000..fdee1a994b --- /dev/null +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js @@ -0,0 +1,46 @@ +/** + * Converts a FunctionExpression to an ArrowFunctionExpression when safe to do so. + * + * var a = function(a, b) { + * return a + b; + * } + * + * var b = function(a, b) { + * var c = 0; + * return a + b + c; + * } + * + * var a = function(a, b) { + * return a + b + this.c; + * } + ** + * var a = (a, b) => a + b + * + * var b = (a, b) => { + * var c = 0; + * return a + b + c; + * } + * + * var a = function(a, b) { + * return a + b + this.c; + * } + */ + +module.exports = function (file, api) { + const j = api.jscodeshift; + + return j(file.source) + .find(j.FunctionExpression) + // We check for this expression, as if it's in a function expression, we don't want to re-bind "this" by + // using the arrowFunctionExpression. As that could potentially have some unintended consequences. + .filter(p => j(p).find(j.ThisExpression).size() == 0) + .replaceWith(p => { + var body = p.value.body; + // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, + // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } + var useExpression = body.type == 'BlockStatement' && body.body.length == 1 && body.body[0].type == "ReturnStatement"; + body = useExpression ? body.body[0].argument : body; + return j.arrowFunctionExpression(p.value.params, body, useExpression); + }) + .toSource(); +}; diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.js b/types/jscodeshift/test/js-transforms/props-to-destructuring.js new file mode 100755 index 0000000000..87def91d52 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.js @@ -0,0 +1,137 @@ +/** + * Transforms: + * class C extends React.Component() { + * render() { + * return <div foo={this.props.foo} bar={this.props.bar} /> + * } + * } + *** To: + * + * class C extends React.Component() { + * render() { + * const { + * foo, + * bar + * } = this.props; + * + * return <div foo={foo} bar={bar} /> + * } + * } + * + */ + +let keywords = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; +keywords = keywords.split(' ').reduce((f, k) => { + f[k] = true; + return f; +}, {}); +const isKeyword = k => keywords.hasOwnProperty(k); + +module.exports = function (file, api) { + const j = api.jscodeshift; + const {statement} = j.template; + + return j(file.source) + .find(j.FunctionExpression) + .replaceWith(p => { + console.log(p); + const root = j(p.value); + const variablesToReplace = {}; + + // Figure out if the variable was defined from props, so that we can re-use that definition. + const isFromProps = (name, resolvedScope) => { + return resolvedScope.getBindings()[name].every( + p => { + const decl = j(p).closest(j.VariableDeclarator); + // What happens when our VariableDeclarator is too high up the parent AST? + + if (!decl.size()) return false; + const node = decl.nodes()[0]; + + if (!(node.init.type == 'MemberExpression' && + node.init.object.type == 'ThisExpression' && + node.init.property.name == 'props')) + return false; + + // Check for the case where it could be aliased (i.e.) { baz: foo } = this.props; + // In this case, we won't do a substitution. + if (p.parentPath.value.type == 'Property' && p.parentPath.value.key.name !== name) + return false; + + return true; + } + ); + }; + + // Transform "this.props.xyz" to "xyz", and record what we've transformed. + // Transform as long as we don't have "xyz" already defined in the scope. + root + .find(j.MemberExpression, { + object: { + type: 'MemberExpression', + object: {type: 'ThisExpression'}, + property: {name: 'props'} + } + }) + .filter(e => { + const resolvedScope = e.scope.lookup(e.value.property.name); + // If the scope is null, that means that this property isn't defined in the scope yet, + // and we can use it. Otherwise, if it is defined, we should see if it was defined from `this.props` + // if none of these cases are true, we can't do substitution. + return resolvedScope == null || isFromProps(e.value.property.name, resolvedScope); + }) + // Ensure that our substitution won't cause us to define a keyword, i.e. `this.props.while` won't + // get converted into `while`. + .filter(p => !isKeyword(p.value.property.name)) + // Now, do the replacement, `this.props.xyz` => `xyz`. + .replaceWith(p => p.value.property) + // Finally, mark the variable as something we will need to define earlier in the function, + // if it's not already defined. + .forEach(p => { + // Is this prop already defined somewhere else. + if (!p.scope.lookup(p.value.name)) + variablesToReplace[p.value.name] = true; + }); + + + // Create property definitions for variables that we've replaced. + const properties = Object.keys(variablesToReplace) + .sort() + .map(k => { + const prop = j.property('init', j.identifier(k), j.identifier(k)); + prop.shorthand = true; + return prop; + }); + + // We have no properties to inject, so we can bail here. + if (!properties.length) + return p.value; + + // See if we already have a VariableDeclarator like { a, b, c } = this.props; + const propDefinitions = root + .find(j.VariableDeclarator, { + id: {type: 'ObjectPattern'}, + init: {type: 'MemberExpression', object: {type: 'ThisExpression'}, property: {name: 'props'}} + }); + + if (propDefinitions.size()) { + const nodePath = propDefinitions.paths()[0]; + const node = nodePath.value; + const newPattern = j.objectPattern(node.id.properties.concat(properties)); + nodePath.replace(j.variableDeclarator(newPattern, node.init)); + return p.value; + } + + // Otherwise, we'll have to create our own, as none were suitable for use. + // Create the variable definition `const { xyz } = this.props;` + const decl = statement`const { ${properties} } = this.props;`; + + // Add the variable definition to the top of the function expression body. + return j.functionExpression( + p.value.id, + p.value.params, + j.blockStatement([decl].concat(p.value.body.body)) + ); + } + ).toSource(); +}; diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.js b/types/jscodeshift/test/js-transforms/pure-to-composite-component.js new file mode 100755 index 0000000000..dd4b3bf5c2 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/pure-to-composite-component.js @@ -0,0 +1,61 @@ +/** For when you've gone too pure and want to go back. **/ +/** Converts + * let HistoryItem = (props) => { + * const { + * item + * } = props; + * return <li>{item}</li>; + * }; + * + * let X = (props) => <div>foo</div>; + * + * to + * + * class HistoryItem extends Component { + * render() { + * const { + * item + * } = this.props; + * return <li>{item}</li>; + * } + * } + * + * class X extends Component { + * render() { + * return <div>foo</div>; + * } + * } + */ + + +module.exports = function (file, api) { + const j = api.jscodeshift; + const {statement} = j.template; + + function hasJSXElement(ast) { + return j(ast).find(j.JSXElement).size() > 0; + } + + return j(file.source) + .find(j.VariableDeclaration) + .filter(p => p.value.declarations.length == 1) + .replaceWith(p => { + const decl = p.value.declarations[0]; + if (decl.init.type !== 'ArrowFunctionExpression' || + (!hasJSXElement(decl.init.body) && decl.init.body.type !== "JSXElement")) + return p.value; + + let body = decl.init.body; + body = body.type == "JSXElement" ? j.returnStatement(body) : body = body.body; + + j(body) + .find(j.Identifier, {name: 'props'}) + .replaceWith(p => j.memberExpression(j.thisExpression(), j.identifier('props'))); + + return statement`class ${decl.id} extends Component { + render() { ${body} } + }`; + + }) + .toSource(); +}; From 81cf624ae165314859216122efedd926d40e6fa5 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 16:52:05 -0800 Subject: [PATCH 034/200] [jscodeshift] Rename js-transforms from JS to TS --- ...this-to-bind-expression.js => bind-this-to-bind-expression.ts} | 0 ... => call-expression-bind-this-to-arrow-function-expression.ts} | 0 ...ion.js => function-expression-to-arrow-function-expression.ts} | 0 .../{props-to-destructuring.js => props-to-destructuring.ts} | 0 ...e-to-composite-component.js => pure-to-composite-component.ts} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename types/jscodeshift/test/js-transforms/{bind-this-to-bind-expression.js => bind-this-to-bind-expression.ts} (100%) rename types/jscodeshift/test/js-transforms/{call-expression-bind-this-to-arrow-function-expression.js => call-expression-bind-this-to-arrow-function-expression.ts} (100%) rename types/jscodeshift/test/js-transforms/{function-expression-to-arrow-function-expression.js => function-expression-to-arrow-function-expression.ts} (100%) rename types/jscodeshift/test/js-transforms/{props-to-destructuring.js => props-to-destructuring.ts} (100%) rename types/jscodeshift/test/js-transforms/{pure-to-composite-component.js => pure-to-composite-component.ts} (100%) diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js rename to types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js rename to types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js rename to types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.js b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/props-to-destructuring.js rename to types/jscodeshift/test/js-transforms/props-to-destructuring.ts diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.js b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/pure-to-composite-component.js rename to types/jscodeshift/test/js-transforms/pure-to-composite-component.ts From 17c8595115965054a9b57670f164d8a4bfe8a9e5 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 17:09:54 -0800 Subject: [PATCH 035/200] [jscodeshift] Fix compiler errors in test/js-transforms --- types/jscodeshift/index.d.ts | 6 ++-- .../jscodeshift/test/js-transforms/README.md | 2 ++ .../bind-this-to-bind-expression.ts | 5 +-- ...-bind-this-to-arrow-function-expression.ts | 19 +++++++--- ...expression-to-arrow-function-expression.ts | 13 +++++-- .../js-transforms/props-to-destructuring.ts | 36 ++++++++++--------- .../pure-to-composite-component.ts | 30 ++++++++-------- 7 files changed, 69 insertions(+), 42 deletions(-) create mode 100644 types/jscodeshift/test/js-transforms/README.md mode change 100755 => 100644 types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index b9b15be825..95a26cd0a4 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -250,7 +250,9 @@ declare module "jscodeshift/src/Collection" { declare module "jscodeshift/src/collections/Node" { import { Collection } from "jscodeshift/src/Collection"; - import { ASTNode, Type } from "recast"; + import { ASTNode, Type, NodePath } from "recast"; + + type ASTPath<N> = NodePath<N, N>; export interface TraversalMethods { /** @@ -285,7 +287,7 @@ declare module "jscodeshift/src/collections/Node" { * is provided it is executed for every node and the node is replaced with the * functions return value. */ - replaceWith<T>(nodes: T | T[] | ((path: any, i: number) => T)): this; + replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection<T>; /** * Inserts a new node before the current one. diff --git a/types/jscodeshift/test/js-transforms/README.md b/types/jscodeshift/test/js-transforms/README.md new file mode 100644 index 0000000000..f314daaa44 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/README.md @@ -0,0 +1,2 @@ +Sample jscodeshift transforms taken from https://github.com/jhgg/js-transforms +and converted to TypeScript, for use as real-world test cases. diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts old mode 100755 new mode 100644 index 97248a7e35..65161f8957 --- a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts @@ -8,8 +8,9 @@ * let x = ::this.foo; * */ +import { Transform, MemberExpression } from "jscodeshift"; -module.exports = function (file, api) { +const transform: Transform = function (file, api) { const j = api.jscodeshift; return j(file.source) // Find stuff that looks like this.xyz.bind(this) @@ -17,6 +18,6 @@ module.exports = function (file, api) { // Ensure that .bind() is being called with only one argument, and that argument is "this". .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") // We can now replace it with ::this.xyz - .replaceWith(p => j.bindExpression(null, p.value.callee.object)) + .replaceWith(p => j.bindExpression(null, (p.value.callee as MemberExpression).object)) .toSource(); }; \ No newline at end of file diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts index 727f2e950d..08bf424ae8 100755 --- a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts @@ -25,8 +25,9 @@ * var a = c => c; * */ +import { Transform, MemberExpression, FunctionExpression } from "jscodeshift"; -module.exports = function(file, api) { +const transform: Transform = function(file, api) { const j = api.jscodeshift; return j(file.source) @@ -35,16 +36,24 @@ module.exports = function(file, api) { // Verify that .bind() is only being called with `this` as it's sole arguments. .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") .replaceWith(p => { + var callee = p.value.callee as MemberExpression; + var object = callee.object as FunctionExpression; // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer // to the FunctionExpression that's being called .bind(this) on. We need the body of that function // to transform into an ArrowFunctionExpression. - var body = p.value.callee.object.body; + var body = object.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } - var useExpression = body.type == 'BlockStatement' && body.body.length == 1 && body.body[0].type == "ReturnStatement"; - body = useExpression ? body.body[0].argument : body; + var useExpression = false; + if (body.type == 'BlockStatement' && body.body.length == 1) { + const first = body.body[0]; + if (first.type == "ReturnStatement") { + useExpression = true; + body = first.argument!; + } + } - return j.arrowFunctionExpression(p.value.callee.object.params, body, useExpression); + return j.arrowFunctionExpression(object.params, body, useExpression); }) .toSource(); }; \ No newline at end of file diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts index fdee1a994b..ed633bc462 100755 --- a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts @@ -25,8 +25,9 @@ * return a + b + this.c; * } */ +import { Transform } from "jscodeshift"; -module.exports = function (file, api) { +const transform: Transform = function (file, api) { const j = api.jscodeshift; return j(file.source) @@ -38,8 +39,14 @@ module.exports = function (file, api) { var body = p.value.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } - var useExpression = body.type == 'BlockStatement' && body.body.length == 1 && body.body[0].type == "ReturnStatement"; - body = useExpression ? body.body[0].argument : body; + var useExpression = false; + if (body.type == 'BlockStatement' && body.body.length == 1) { + const first = body.body[0]; + if (first.type == "ReturnStatement") { + useExpression = true; + body = first.argument!; + } + } return j.arrowFunctionExpression(p.value.params, body, useExpression); }) .toSource(); diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts index 87def91d52..81f58c5bb7 100755 --- a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -19,37 +19,40 @@ * } * */ +import { Transform, VariableDeclarator, ObjectPattern, Identifier, BlockStatement } from "jscodeshift"; -let keywords = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; -keywords = keywords.split(' ').reduce((f, k) => { +const keywordsStr = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; +let keywords = keywordsStr.split(' ').reduce<{ [key: string]: boolean }>((f, k) => { f[k] = true; return f; }, {}); -const isKeyword = k => keywords.hasOwnProperty(k); +const isKeyword = (k: string) => keywords.hasOwnProperty(k); -module.exports = function (file, api) { +const transform: Transform = function (file, api) { const j = api.jscodeshift; const {statement} = j.template; return j(file.source) .find(j.FunctionExpression) .replaceWith(p => { - console.log(p); + // console.log(p); const root = j(p.value); - const variablesToReplace = {}; + const variablesToReplace: { [name: string]: boolean } = {}; // Figure out if the variable was defined from props, so that we can re-use that definition. - const isFromProps = (name, resolvedScope) => { + const isFromProps = (name: string, resolvedScope: any) => { return resolvedScope.getBindings()[name].every( - p => { + (p: any) => { const decl = j(p).closest(j.VariableDeclarator); // What happens when our VariableDeclarator is too high up the parent AST? if (!decl.size()) return false; - const node = decl.nodes()[0]; + const node: VariableDeclarator = decl.nodes()[0]; - if (!(node.init.type == 'MemberExpression' && + if (!(node.init != null && + node.init.type == 'MemberExpression' && node.init.object.type == 'ThisExpression' && + node.init.property.type == 'Identifier' && node.init.property.name == 'props')) return false; @@ -74,17 +77,17 @@ module.exports = function (file, api) { } }) .filter(e => { - const resolvedScope = e.scope.lookup(e.value.property.name); + const resolvedScope = e.scope.lookup((e.value.property as Identifier).name); // If the scope is null, that means that this property isn't defined in the scope yet, // and we can use it. Otherwise, if it is defined, we should see if it was defined from `this.props` // if none of these cases are true, we can't do substitution. - return resolvedScope == null || isFromProps(e.value.property.name, resolvedScope); + return resolvedScope == null || isFromProps((e.value.property as Identifier).name, resolvedScope); }) // Ensure that our substitution won't cause us to define a keyword, i.e. `this.props.while` won't // get converted into `while`. - .filter(p => !isKeyword(p.value.property.name)) + .filter(p => !isKeyword((p.value.property as Identifier).name)) // Now, do the replacement, `this.props.xyz` => `xyz`. - .replaceWith(p => p.value.property) + .replaceWith(p => p.value.property as Identifier) // Finally, mark the variable as something we will need to define earlier in the function, // if it's not already defined. .forEach(p => { @@ -117,7 +120,8 @@ module.exports = function (file, api) { if (propDefinitions.size()) { const nodePath = propDefinitions.paths()[0]; const node = nodePath.value; - const newPattern = j.objectPattern(node.id.properties.concat(properties)); + // TODO(brieb): support narrowing based on second argument to `find` + const newPattern = j.objectPattern((node.id as ObjectPattern).properties.concat(properties)); nodePath.replace(j.variableDeclarator(newPattern, node.init)); return p.value; } @@ -130,7 +134,7 @@ module.exports = function (file, api) { return j.functionExpression( p.value.id, p.value.params, - j.blockStatement([decl].concat(p.value.body.body)) + j.blockStatement([decl].concat((p.value.body as BlockStatement).body)) ); } ).toSource(); diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts index dd4b3bf5c2..a0ea249746 100755 --- a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts +++ b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts @@ -27,12 +27,13 @@ * } */ +import { Transform, ASTNode } from "jscodeshift"; -module.exports = function (file, api) { +const transform: Transform = function (file, api) { const j = api.jscodeshift; const {statement} = j.template; - function hasJSXElement(ast) { + function hasJSXElement(ast: ASTNode) { return j(ast).find(j.JSXElement).size() > 0; } @@ -41,21 +42,22 @@ module.exports = function (file, api) { .filter(p => p.value.declarations.length == 1) .replaceWith(p => { const decl = p.value.declarations[0]; - if (decl.init.type !== 'ArrowFunctionExpression' || - (!hasJSXElement(decl.init.body) && decl.init.body.type !== "JSXElement")) - return p.value; + if (decl.type === "VariableDeclarator" && decl.init != null) { + if (decl.init.type !== 'ArrowFunctionExpression' || + (!hasJSXElement(decl.init.body) && decl.init.body.type !== "JSXElement")) + return p.value; - let body = decl.init.body; - body = body.type == "JSXElement" ? j.returnStatement(body) : body = body.body; + let body: any = decl.init.body; + body = body.type == "JSXElement" ? j.returnStatement(body) : body = body.body; - j(body) - .find(j.Identifier, {name: 'props'}) - .replaceWith(p => j.memberExpression(j.thisExpression(), j.identifier('props'))); - - return statement`class ${decl.id} extends Component { - render() { ${body} } - }`; + j(body) + .find(j.Identifier, {name: 'props'}) + .replaceWith(p => j.memberExpression(j.thisExpression(), j.identifier('props'))); + return statement`class ${decl.id} extends Component { + render() { ${body} } + }`; + } }) .toSource(); }; From 60cec9121ecac6b8cc705f51056076c01980ae90 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 17:15:44 -0800 Subject: [PATCH 036/200] [jscodeshift] Fix lint violations in test/js-transforms --- .../bind-this-to-bind-expression.ts | 6 ++--- ...-bind-this-to-arrow-function-expression.ts | 23 ++++++++++--------- ...expression-to-arrow-function-expression.ts | 14 +++++------ .../js-transforms/props-to-destructuring.ts | 23 ++++++++++--------- .../pure-to-composite-component.ts | 11 +++++---- 5 files changed, 40 insertions(+), 37 deletions(-) diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts index 65161f8957..6bd9be1fc8 100644 --- a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts @@ -10,14 +10,14 @@ */ import { Transform, MemberExpression } from "jscodeshift"; -const transform: Transform = function (file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; return j(file.source) // Find stuff that looks like this.xyz.bind(this) .find(j.CallExpression, {callee: {object: {object: j.ThisExpression}, property: {name: 'bind'}}}) // Ensure that .bind() is being called with only one argument, and that argument is "this". - .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") + .filter(p => p.value.arguments.length === 1 && p.value.arguments[0].type === "ThisExpression") // We can now replace it with ::this.xyz .replaceWith(p => j.bindExpression(null, (p.value.callee as MemberExpression).object)) .toSource(); -}; \ No newline at end of file +}; diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts index 08bf424ae8..cfe672436e 100755 --- a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts @@ -1,4 +1,5 @@ -/** Converts +/** + * Converts * onClick(function(a, b) { * return a + b; * }.bind(this), @@ -13,7 +14,7 @@ * * var a = function(c) { return c; }.bind(this); * - ** to + * to * onClick((a, b) => a + b, * (b, c) => 1); * @@ -27,27 +28,27 @@ */ import { Transform, MemberExpression, FunctionExpression } from "jscodeshift"; -const transform: Transform = function(file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; return j(file.source) // We're looking for a CallExpression that's calling .bind() onto a FunctionExpression. .find(j.CallExpression, {callee: {property: {name: 'bind'}, object: {type: 'FunctionExpression'}}}) // Verify that .bind() is only being called with `this` as it's sole arguments. - .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") + .filter(p => p.value.arguments.length === 1 && p.value.arguments[0].type === "ThisExpression") .replaceWith(p => { - var callee = p.value.callee as MemberExpression; - var object = callee.object as FunctionExpression; + const callee = p.value.callee as MemberExpression; + const object = callee.object as FunctionExpression; // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer // to the FunctionExpression that's being called .bind(this) on. We need the body of that function // to transform into an ArrowFunctionExpression. - var body = object.body; + let body = object.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } - var useExpression = false; - if (body.type == 'BlockStatement' && body.body.length == 1) { + let useExpression = false; + if (body.type === 'BlockStatement' && body.body.length === 1) { const first = body.body[0]; - if (first.type == "ReturnStatement") { + if (first.type === "ReturnStatement") { useExpression = true; body = first.argument!; } @@ -56,4 +57,4 @@ const transform: Transform = function(file, api) { return j.arrowFunctionExpression(object.params, body, useExpression); }) .toSource(); -}; \ No newline at end of file +}; diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts index ed633bc462..5a1b50dc6b 100755 --- a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts @@ -13,7 +13,7 @@ * var a = function(a, b) { * return a + b + this.c; * } - ** + * * var a = (a, b) => a + b * * var b = (a, b) => { @@ -27,22 +27,22 @@ */ import { Transform } from "jscodeshift"; -const transform: Transform = function (file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; return j(file.source) .find(j.FunctionExpression) // We check for this expression, as if it's in a function expression, we don't want to re-bind "this" by // using the arrowFunctionExpression. As that could potentially have some unintended consequences. - .filter(p => j(p).find(j.ThisExpression).size() == 0) + .filter(p => j(p).find(j.ThisExpression).size() === 0) .replaceWith(p => { - var body = p.value.body; + let body = p.value.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } - var useExpression = false; - if (body.type == 'BlockStatement' && body.body.length == 1) { + let useExpression = false; + if (body.type === 'BlockStatement' && body.body.length === 1) { const first = body.body[0]; - if (first.type == "ReturnStatement") { + if (first.type === "ReturnStatement") { useExpression = true; body = first.argument!; } diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts index 81f58c5bb7..6db8fe49dd 100755 --- a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -5,7 +5,8 @@ * return <div foo={this.props.foo} bar={this.props.bar} /> * } * } - *** To: + * + * To: * * class C extends React.Component() { * render() { @@ -21,14 +22,15 @@ */ import { Transform, VariableDeclarator, ObjectPattern, Identifier, BlockStatement } from "jscodeshift"; +// tslint:disable-next-line max-line-length const keywordsStr = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; -let keywords = keywordsStr.split(' ').reduce<{ [key: string]: boolean }>((f, k) => { +const keywords = keywordsStr.split(' ').reduce<{ [key: string]: boolean }>((f, k) => { f[k] = true; return f; }, {}); const isKeyword = (k: string) => keywords.hasOwnProperty(k); -const transform: Transform = function (file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; const {statement} = j.template; @@ -50,15 +52,15 @@ const transform: Transform = function (file, api) { const node: VariableDeclarator = decl.nodes()[0]; if (!(node.init != null && - node.init.type == 'MemberExpression' && - node.init.object.type == 'ThisExpression' && - node.init.property.type == 'Identifier' && - node.init.property.name == 'props')) + node.init.type === 'MemberExpression' && + node.init.object.type === 'ThisExpression' && + node.init.property.type === 'Identifier' && + node.init.property.name === 'props')) return false; // Check for the case where it could be aliased (i.e.) { baz: foo } = this.props; // In this case, we won't do a substitution. - if (p.parentPath.value.type == 'Property' && p.parentPath.value.key.name !== name) + if (p.parentPath.value.type === 'Property' && p.parentPath.value.key.name !== name) return false; return true; @@ -81,10 +83,10 @@ const transform: Transform = function (file, api) { // If the scope is null, that means that this property isn't defined in the scope yet, // and we can use it. Otherwise, if it is defined, we should see if it was defined from `this.props` // if none of these cases are true, we can't do substitution. - return resolvedScope == null || isFromProps((e.value.property as Identifier).name, resolvedScope); + return resolvedScope === null || isFromProps((e.value.property as Identifier).name, resolvedScope); }) // Ensure that our substitution won't cause us to define a keyword, i.e. `this.props.while` won't - // get converted into `while`. + // get converted into `while`. .filter(p => !isKeyword((p.value.property as Identifier).name)) // Now, do the replacement, `this.props.xyz` => `xyz`. .replaceWith(p => p.value.property as Identifier) @@ -96,7 +98,6 @@ const transform: Transform = function (file, api) { variablesToReplace[p.value.name] = true; }); - // Create property definitions for variables that we've replaced. const properties = Object.keys(variablesToReplace) .sort() diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts index a0ea249746..6d1a30c378 100755 --- a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts +++ b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts @@ -1,5 +1,6 @@ -/** For when you've gone too pure and want to go back. **/ -/** Converts +/** For when you've gone too pure and want to go back. */ +/** + * Converts * let HistoryItem = (props) => { * const { * item @@ -29,7 +30,7 @@ import { Transform, ASTNode } from "jscodeshift"; -const transform: Transform = function (file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; const {statement} = j.template; @@ -39,7 +40,7 @@ const transform: Transform = function (file, api) { return j(file.source) .find(j.VariableDeclaration) - .filter(p => p.value.declarations.length == 1) + .filter(p => p.value.declarations.length === 1) .replaceWith(p => { const decl = p.value.declarations[0]; if (decl.type === "VariableDeclarator" && decl.init != null) { @@ -48,7 +49,7 @@ const transform: Transform = function (file, api) { return p.value; let body: any = decl.init.body; - body = body.type == "JSXElement" ? j.returnStatement(body) : body = body.body; + body = body.type === "JSXElement" ? j.returnStatement(body) : body = body.body; j(body) .find(j.Identifier, {name: 'props'}) From 4162211dcc844212a7b7a4282a602b1f6fab0f32 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 17:47:26 -0800 Subject: [PATCH 037/200] [jscodeshift] In tsconfig, don't use "include", must use "files" --- ...-expression-bind-this-to-arrow-function-expression.ts | 0 .../function-expression-to-arrow-function-expression.ts | 0 .../test/js-transforms/props-to-destructuring.ts | 0 .../test/js-transforms/pure-to-composite-component.ts | 0 types/jscodeshift/tsconfig.json | 9 +++++++-- 5 files changed, 7 insertions(+), 2 deletions(-) mode change 100755 => 100644 types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts mode change 100755 => 100644 types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts mode change 100755 => 100644 types/jscodeshift/test/js-transforms/props-to-destructuring.ts mode change 100755 => 100644 types/jscodeshift/test/js-transforms/pure-to-composite-component.ts diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts old mode 100755 new mode 100644 diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts old mode 100755 new mode 100644 diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts old mode 100755 new mode 100644 diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts old mode 100755 new mode 100644 diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index c5f4e65e59..8ad162be32 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -16,8 +16,13 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "include": [ + "files": [ "index.d.ts", - "test" + "test/jscodeshift-tests.ts", + "test/js-transforms/bind-this-to-bind-expression.ts", + "test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts", + "test/js-transforms/function-expression-to-arrow-function-expression.ts", + "test/js-transforms/props-to-destructuring.ts", + "test/js-transforms/pure-to-composite-component.ts" ] } From 5a750fd73fbc5f673054c25a2615fdbbf072db45 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Mon, 28 Jan 2019 21:44:19 -0800 Subject: [PATCH 038/200] [jscodeshift] Update ast-types to 0.12.1 and recast to 0.17.2 --- types/jscodeshift/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jscodeshift/package.json b/types/jscodeshift/package.json index 65d03a5a7f..6fd3d8b70f 100644 --- a/types/jscodeshift/package.json +++ b/types/jscodeshift/package.json @@ -1,7 +1,7 @@ { "private": true, "dependencies": { - "ast-types": "^0.12.0", - "recast": "^0.17.0" + "ast-types": "^0.12.1", + "recast": "^0.17.2" } } From 5fd8f52edf25db7a902cd13658b8b47472fa0df1 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.fr> Date: Tue, 29 Jan 2019 07:05:37 +0100 Subject: [PATCH 039/200] added tests for default import --- types/debug/debug-tests.ts | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index 22ac083a14..b1356f08f9 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -1,24 +1,31 @@ -import debug = require("debug"); +import * as debug1 from "debug"; -debug.disable(); -debug.enable("DefinitelyTyped:*"); +import debug2 from 'debug'; -const log: debug.Debugger = debug("DefinitelyTyped:log"); +const log2:debug1.Debugger = debug2("DefinitelyTyped:log"); +log2("Just text"); +log2("Formatted test (%d arg)", 1); +log2("Formatted %s (%d args)", "test", 2); + +debug1.disable(); +debug1.enable("DefinitelyTyped:*"); + +const log: debug1.Debugger = debug1("DefinitelyTyped:log"); log("Just text"); log("Formatted test (%d arg)", 1); log("Formatted %s (%d args)", "test", 2); -log("Enabled?: %s", debug.enabled("DefinitelyTyped:log")); -log("Name Enabled: %s", debug.names.some(name => name.test("DefinitelyTyped:log"))); +log("Enabled?: %s", debug1.enabled("DefinitelyTyped:log")); +log("Name Enabled: %s", debug1.names.some(name => name.test("DefinitelyTyped:log"))); log("Namespace: %s", log.namespace); -const error: debug.Debugger = debug("DefinitelyTyped:error"); +const error: debug1.Debugger = debug1("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); -const extendedLog: debug.Debugger = log.extend('extended'); +const extendedLog: debug1.Debugger = log.extend('extended'); extendedLog("Testing this is also an IDebugger."); -const extendedWithCustomDelimiter: debug.Debugger = log.extend('with-delim', '.'); +const extendedWithCustomDelimiter: debug1.Debugger = log.extend('with-delim', '.'); extendedWithCustomDelimiter("Testing this is an IDebugger, too."); From f3e79d7ac831cf8826a541b12f72025dd097ac77 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Mon, 28 Jan 2019 21:46:09 -0800 Subject: [PATCH 040/200] [jscodeshift] Fix TSC errors and DTS lints --- .../call-expression-bind-this-to-arrow-function-expression.ts | 4 ++-- .../function-expression-to-arrow-function-expression.ts | 4 ++-- .../jscodeshift/test/js-transforms/props-to-destructuring.ts | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts index cfe672436e..09cdf3f29e 100644 --- a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts @@ -26,7 +26,7 @@ * var a = c => c; * */ -import { Transform, MemberExpression, FunctionExpression } from "jscodeshift"; +import { Transform, MemberExpression, FunctionExpression, ArrowFunctionExpression } from "jscodeshift"; const transform: Transform = (file, api) => { const j = api.jscodeshift; @@ -42,7 +42,7 @@ const transform: Transform = (file, api) => { // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer // to the FunctionExpression that's being called .bind(this) on. We need the body of that function // to transform into an ArrowFunctionExpression. - let body = object.body; + let body: ArrowFunctionExpression['body'] = object.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } let useExpression = false; diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts index 5a1b50dc6b..b960c920cd 100644 --- a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts @@ -25,7 +25,7 @@ * return a + b + this.c; * } */ -import { Transform } from "jscodeshift"; +import { Transform, ArrowFunctionExpression } from "jscodeshift"; const transform: Transform = (file, api) => { const j = api.jscodeshift; @@ -36,7 +36,7 @@ const transform: Transform = (file, api) => { // using the arrowFunctionExpression. As that could potentially have some unintended consequences. .filter(p => j(p).find(j.ThisExpression).size() === 0) .replaceWith(p => { - let body = p.value.body; + let body: ArrowFunctionExpression['body'] = p.value.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } let useExpression = false; diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts index 6db8fe49dd..138d61a620 100644 --- a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -135,7 +135,7 @@ const transform: Transform = (file, api) => { return j.functionExpression( p.value.id, p.value.params, - j.blockStatement([decl].concat((p.value.body as BlockStatement).body)) + j.blockStatement([decl].concat(p.value.body.body)) ); } ).toSource(); From 86ed80563e7a0256cabe7162f78624013443820e Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.fr> Date: Tue, 29 Jan 2019 11:10:47 +0100 Subject: [PATCH 041/200] fixed tslint issues --- types/debug/debug-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index b1356f08f9..92d6f5eb8e 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -1,8 +1,8 @@ import * as debug1 from "debug"; - +/*tslint:disable-next-line:no-duplicate-imports*/ import debug2 from 'debug'; -const log2:debug1.Debugger = debug2("DefinitelyTyped:log"); +const log2: debug1.Debugger = debug2("DefinitelyTyped:log"); log2("Just text"); log2("Formatted test (%d arg)", 1); log2("Formatted %s (%d args)", "test", 2); From 556fe818a8bd84bc0ac5bcedc52f06268dc83ac2 Mon Sep 17 00:00:00 2001 From: Dave Cardwell <hello@davecardwell.com> Date: Tue, 29 Jan 2019 11:59:28 -0500 Subject: [PATCH 042/200] [webpack-dev-server] Add writeToDisk configuration https://github.com/webpack/webpack-dev-server/releases/tag/v3.1.10 https://webpack.js.org/configuration/dev-server/#devserver-writetodisk- --- types/webpack-dev-server/index.d.ts | 3 +++ types/webpack-dev-server/webpack-dev-server-tests.ts | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/types/webpack-dev-server/index.d.ts b/types/webpack-dev-server/index.d.ts index 48abc9a44c..30fd2482e7 100644 --- a/types/webpack-dev-server/index.d.ts +++ b/types/webpack-dev-server/index.d.ts @@ -5,6 +5,7 @@ // Zheyang Song <https://github.com/ZheyangSong> // Alan Agius <https://github.com/alan-agius4> // Artur Androsovych <https://github.com/arturovt> +// Dave Cardwell <https://github.com/davecardwell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -165,6 +166,8 @@ declare namespace WebpackDevServer { watchContentBase?: boolean; /** Control options related to watching the files. */ watchOptions?: webpack.WatchOptions; + /** Tells devServer to write generated assets to the disk. */ + writeToDisk?: boolean | ((filePath: string) => boolean); } } diff --git a/types/webpack-dev-server/webpack-dev-server-tests.ts b/types/webpack-dev-server/webpack-dev-server-tests.ts index f570dd134e..755245b035 100644 --- a/types/webpack-dev-server/webpack-dev-server-tests.ts +++ b/types/webpack-dev-server/webpack-dev-server-tests.ts @@ -72,6 +72,7 @@ const config: WebpackDevServer.Configuration = { aggregateTimeout: 300, poll: 1000 }, + writeToDisk: true, // It's a required option. publicPath: "/assets/", headers: { "X-Custom-Header": "yes" } @@ -83,6 +84,9 @@ const c2: WebpackDevServer.Configuration = { const c3: WebpackDevServer.Configuration = { stats: "verbose", }; +const c4: WebpackDevServer.Configuration = { + writeToDisk: (filePath: string) => true, +}; // API example server = new WebpackDevServer(compiler, config); From e5ae20b1b6533ee751adbfc13d5dbd7aa075bbce Mon Sep 17 00:00:00 2001 From: Anthony Dionise <dionisea@frib.msu.edu> Date: Tue, 29 Jan 2019 16:53:12 -0500 Subject: [PATCH 043/200] include esclusions typings --- .../connect-history-api-fallback-tests.ts | 63 +++++++++++++++++++ .../index.d.ts | 36 +++++++++++ .../tsconfig.json | 23 +++++++ .../tslint.json | 1 + 4 files changed, 123 insertions(+) create mode 100644 types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts create mode 100644 types/connect-history-api-fallback-exclusions/index.d.ts create mode 100644 types/connect-history-api-fallback-exclusions/tsconfig.json create mode 100644 types/connect-history-api-fallback-exclusions/tslint.json diff --git a/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts new file mode 100644 index 0000000000..33fae5bde4 --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts @@ -0,0 +1,63 @@ +import historyApiFallback = require('connect-history-api-fallback-exclusions'); +import express = require('express'); + +const app = express(); +app.use(historyApiFallback()); + +historyApiFallback({ + verbose: true +}); + +historyApiFallback({ + logger: console.log.bind(console) +}); + +historyApiFallback({ + rewrites: [ + { from: /\/soccer/, to: '/soccer.html' } + ] +}); + +historyApiFallback({ + index: 'default.html' +}); + +historyApiFallback({ + htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] +}); + +historyApiFallback({ + rewrites: [ + { + from: /^\/libs\/(.*)$/, + to(context) { + return './bower_components' + context.parsedUrl.pathname; + } + } + ] +}); + +historyApiFallback({ + rewrites: [ + { + from: /\/app\/login/, + to: function onMatch(ctx) { + if (ctx.parsedUrl.path && ctx.parsedUrl.path.indexOf('.js')) { + return ctx.parsedUrl.href || ''; + } + return '/app/login/index.html'; + } + } + ] +}); + +historyApiFallback({ + rewrites: [ + { + from: /^\/libs\/(.*)$/, + to(context) { + return `/${context.match[2]}/${context.match[3]}`; + } + } + ] +}); diff --git a/types/connect-history-api-fallback-exclusions/index.d.ts b/types/connect-history-api-fallback-exclusions/index.d.ts new file mode 100644 index 0000000000..19a48e0bab --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for connect-history-api-fallback-exclusions 1.5.1 +// Project: https://github.com/Wirewheel/connect-history-api-fallback#readme +// Definitions by: Tony Stone <https://github.com/tonystonee> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// <reference types="node" /> + +import { Url } from 'url'; + +import * as core from "express-serve-static-core"; + +declare function historyApiFallback(options?: Options): core.RequestHandler; +declare namespace historyApiFallback {} +export = historyApiFallback; + +interface Options { + exclusions?: string[]; + disableDotRule?: true; + htmlAcceptHeaders?: string[]; + index?: string; + logger?: typeof console.log; + rewrites?: Rewrite[]; + verbose?: boolean; +} + +interface Context { + match: RegExpMatchArray; + parsedUrl: Url; +} +type RewriteTo = (context: Context) => string; + +interface Rewrite { + from: RegExp; + to: string | RegExp | RewriteTo; +} diff --git a/types/connect-history-api-fallback-exclusions/tsconfig.json b/types/connect-history-api-fallback-exclusions/tsconfig.json new file mode 100644 index 0000000000..ad8919e94e --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "connect-history-api-fallback-tests.ts" + ] +} \ No newline at end of file diff --git a/types/connect-history-api-fallback-exclusions/tslint.json b/types/connect-history-api-fallback-exclusions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/connect-history-api-fallback-exclusions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 0683afa221a63ff779155c458fd184a9287fe75c Mon Sep 17 00:00:00 2001 From: Anthony Dionise <dionisea@frib.msu.edu> Date: Tue, 29 Jan 2019 17:19:30 -0500 Subject: [PATCH 044/200] testing --- .../connect-history-api-fallback-tests.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts index 33fae5bde4..291622b349 100644 --- a/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts +++ b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts @@ -12,6 +12,13 @@ historyApiFallback({ logger: console.log.bind(console) }); +historyApiFallback({ + exclusions: [ + '/api/*', + '/health', + ], +}); + historyApiFallback({ rewrites: [ { from: /\/soccer/, to: '/soccer.html' } From 67814548e7fa99f9f5554412cc9b5e4fee5b6ef3 Mon Sep 17 00:00:00 2001 From: Unknown <rkarilka@campus.haifa.ac.il> Date: Wed, 30 Jan 2019 21:44:41 +0200 Subject: [PATCH 045/200] @type/leaflet: Add comment --- types/leaflet/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index c88a505b8b..22f71a9187 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -585,7 +585,7 @@ export interface VideoOverlayOptions extends ImageOverlayOptions { loop?: boolean; } -export class VideoOverlay extends Layer { +export class VideoOverlay extends Layer { /** VideoOverlay doesn't extend ImageOverlay because ImageOverlay.getElement returns HTMLImageElement */ constructor(video: string | string[] | HTMLVideoElement, bounds: LatLngBoundsExpression, options?: VideoOverlayOptions); setOpacity(opacity: number): this; bringToFront(): this; From ec53d243ab29017137f070c9f70104fc6d001768 Mon Sep 17 00:00:00 2001 From: JPMaheux <jpmaheux@arcbees.com> Date: Wed, 30 Jan 2019 15:28:53 -0500 Subject: [PATCH 046/200] fix: added scrollEnabled property --- types/react-native-modal-dropdown/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-native-modal-dropdown/index.d.ts b/types/react-native-modal-dropdown/index.d.ts index 01470ec1cf..01e5dcf30b 100644 --- a/types/react-native-modal-dropdown/index.d.ts +++ b/types/react-native-modal-dropdown/index.d.ts @@ -21,6 +21,7 @@ declare namespace RNModalDropdown { defaultValue?: string; options?: any[]; animated?: boolean; + scrollEnabled?: boolean; showsVerticalScrollIndicator?: boolean; style?: any; textStyle?: any; From 828f081238d78f06c9aa38030b064407c7bee072 Mon Sep 17 00:00:00 2001 From: denis <denisname@users.noreply.github.com> Date: Thu, 31 Jan 2019 15:07:01 +0100 Subject: [PATCH 047/200] Update to 1.2 Add iterations argument to `simulation.tick`. --- types/d3-force/d3-force-tests.ts | 1 + types/d3-force/index.d.ts | 14 ++++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/types/d3-force/d3-force-tests.ts b/types/d3-force/d3-force-tests.ts index 6b73a1dbf4..9bf424c1b6 100644 --- a/types/d3-force/d3-force-tests.ts +++ b/types/d3-force/d3-force-tests.ts @@ -685,6 +685,7 @@ nodeLinkSimulation = nodeLinkSimulation.stop(); // tick() ----------------------------------------------------------------------------- nodeLinkSimulation.tick(); +nodeLinkSimulation.tick(10); // find() ----------------------------------------------------------------------------- diff --git a/types/d3-force/index.d.ts b/types/d3-force/index.d.ts index 35f4d06657..98f372e2cc 100644 --- a/types/d3-force/index.d.ts +++ b/types/d3-force/index.d.ts @@ -1,9 +1,12 @@ // Type definitions for D3JS d3-force module 1.1 // Project: https://github.com/d3/d3-force/ -// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov> +// Definitions by: Tom Wanzek <https://github.com/tomwanzek> +// Alex Ford <https://github.com/gustavderdrache> +// Boris Yankov <https://github.com/borisyankov> +// denisname <https://github.com/denisname> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1.0 +// Last module patch version validated against: 1.2.0 // ----------------------------------------------------------------------- // Force Simulation @@ -108,13 +111,16 @@ export interface Simulation<NodeDatum extends SimulationNodeDatum, LinkDatum ext stop(): this; /** - * Increments the current alpha by (alphaTarget - alpha) × alphaDecay; then invokes each registered force, passing the new alpha; + * Manually steps the simulation by the specified number of *iterations*, and returns the simulation. If *iterations* is not specified, it defaults to 1 (single step). + * + * For each iteration, it increments the current alpha by (alphaTarget - alpha) × alphaDecay; then invokes each registered force, passing the new alpha; * then decrements each node’s velocity by velocity × velocityDecay; lastly increments each node’s position by velocity. + * * This method does not dispatch events; events are only dispatched by the internal timer when the simulation is started automatically upon * creation or by calling simulation.restart. The natural number of ticks when the simulation is started is * ⌈log(alphaMin) / log(1 - alphaDecay)⌉; by default, this is 300. */ - tick(): void; + tick(iterations?: number): void; /** * Returns the simulation’s array of nodes as specified to the constructor. From 66001ee7644cbbc4101265cbb4be96a730114fb0 Mon Sep 17 00:00:00 2001 From: Anton Astashov <aastashov@indeed.com> Date: Thu, 31 Jan 2019 09:03:56 -0600 Subject: [PATCH 048/200] [@types/koa-compose]: Provide way for typesafe compose Right now it's impossible to compose a bunch of middlewares, and preserve their state/context type. It will be either erased and converted to `any`, or will show an error. For example, we have 3 middlewares: ```ts type FooCtx = { foo: string }; type BarCtx = { bar: string }; type WooCtx = { woo: string }; const fooMiddleware: Koa.Middleware<FooCtx, {}> = async (ctx, next) => { ctx.state.foo = 'foo'; await next(); }; const barMiddleware: Koa.Middleware<BarCtx, {}> = async (ctx, next) => { ctx.state.bar = 'bar'; await next(); }; const wooMiddleware: Koa.Middleware<WooCtx, {}> = async (ctx, next) => { ctx.state.woo = 'woo'; await next(); }; ``` If we try to compose them together, we'll get an error: ```ts const composed = compose([fooMiddleware, barMiddleware, wooMiddleware]); // types of params context and context are incompatible // Type ParameterizedContext<FooCtx, {}> is not assignable to // ParameterizedContext<BarCtx, {}> ``` We can shut it up by providing `<any>` type parameter, but that will erase their types: ```ts const composed = compose<any>([fooMiddleware, barMiddleware, wooMiddleware]); // `composed` type is `compose.ComposedMiddleware<any>`. ``` As a solution, I don't think there's a way to do typesafe `compose` for variable number of middlewares, but we can overload `compose` and make a typesafe one for 2 middlewares. You can then compose `compose`s to compose more than 2 middleares :) Like, instead of: ```ts compose([fooMiddleware, barMiddleware, wooMiddleware]) ``` It will be: ```ts compose([fooMiddleware, compose([barMiddleware, wooMiddleware])) // `composed` type is `Middleware<ParameterizedContext<FooCtx & BarCtx & WooCtx, {}>` ``` What do you think? --- types/koa-compose/index.d.ts | 7 +++++ types/koa-compose/koa-compose-tests.ts | 38 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/types/koa-compose/index.d.ts b/types/koa-compose/index.d.ts index 88047abcc9..f35b9ca208 100644 --- a/types/koa-compose/index.d.ts +++ b/types/koa-compose/index.d.ts @@ -2,6 +2,13 @@ // Project: https://github.com/koajs/compose // Definitions by: jKey Lu <https://github.com/jkeylu> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as Koa from "koa"; + +declare function compose<T, U, V, W>( + middleware: [Koa.Middleware<T, U>, Koa.Middleware<V, W>] +): Koa.Middleware<T & V, U & W>; declare function compose<T>(middleware: Array<compose.Middleware<T>>): compose.ComposedMiddleware<T>; diff --git a/types/koa-compose/koa-compose-tests.ts b/types/koa-compose/koa-compose-tests.ts index ed1c705e5d..56b105e900 100644 --- a/types/koa-compose/koa-compose-tests.ts +++ b/types/koa-compose/koa-compose-tests.ts @@ -1,4 +1,5 @@ import compose = require('koa-compose'); +import * as Koa from "koa"; const fn1: compose.Middleware<any> = (context: any, next: () => Promise<void>): Promise<any> => Promise @@ -11,3 +12,40 @@ const fn2: compose.Middleware<any> = (context: any, next: () => Promise<void>): .then(next); const fn = compose([fn1, fn2]); + +interface FooCtx { + foo: string; +} + +const fooMiddleware: Koa.Middleware<FooCtx> = async (ctx, next) => { + ctx.state.foo = "foo"; + await next(); +}; + +interface BarCtx { + bar: string; +} + +const barMiddleware: Koa.Middleware<BarCtx> = async (ctx, next) => { + ctx.state.bar = "bar"; + await next(); +}; + +interface WooCtx { + woo: string; +} + +const wooMiddleware: Koa.Middleware<WooCtx> = async (ctx, next) => { + ctx.state.woo = "woo"; + await next(); +}; + +new Koa<{}, {}>() + .use(compose([compose([fooMiddleware, barMiddleware]), wooMiddleware])) + .use(async (ctx, next) => { + ctx.state.foo; + ctx.state.bar; + ctx.state.woo; + ctx.body = "Something"; + await next(); + }); From 9da338ad53056646df90a7380ecb0efb53c9d080 Mon Sep 17 00:00:00 2001 From: Tom Spencer <tom.spencer@studiozeffa.com> Date: Thu, 31 Jan 2019 17:08:27 +0000 Subject: [PATCH 049/200] add useNativeValidation to MDC textfield --- types/material__textfield/foundation.d.ts | 2 ++ types/material__textfield/index.d.ts | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/types/material__textfield/foundation.d.ts b/types/material__textfield/foundation.d.ts index ffc0436f45..255495f003 100644 --- a/types/material__textfield/foundation.d.ts +++ b/types/material__textfield/foundation.d.ts @@ -71,6 +71,8 @@ export default class MDCTextFieldFoundation extends MDCFoundation<MDCTextFieldAd setValid(isValid: boolean): void; + setUseNativeValidation(useNativeValidation: boolean): void; + isDisabled(): boolean; setDisabled(disabled: boolean): void; diff --git a/types/material__textfield/index.d.ts b/types/material__textfield/index.d.ts index b3e61550c9..883be449a1 100644 --- a/types/material__textfield/index.d.ts +++ b/types/material__textfield/index.d.ts @@ -78,4 +78,12 @@ export class MDCTextField extends MDCComponent<MDCTextFieldAdapter, MDCTextField * Recomputes the outline SVG path for the outline element. */ layout(): void; + + /** + * Ideally we would use a 'writeonly' modifier here since this is a setter, + * but such a thing does not exist. + * https://github.com/Microsoft/TypeScript/issues/4839 + * https://github.com/Microsoft/TypeScript/issues/21759 + */ + useNativeValidation: boolean; } From c467d277abeb1464e696fb2257fc2d456e64e293 Mon Sep 17 00:00:00 2001 From: Spencer Elliott <me@elliottsj.com> Date: Thu, 31 Jan 2019 10:47:37 -0500 Subject: [PATCH 050/200] [next] Add `enhanceApp` / `enhanceComponent` https://github.com/zeit/next.js/tree/cf31021e25f8d90f91ef3f7cb4f36a46d52fc56d#customizing-renderpage https://github.com/zeit/next.js/blob/7e7be0e2e8419b28d9c562e04cba1fc52a39f086/packages/next-server/server/render.tsx#L13-L32 --- types/next/document.d.ts | 11 +++++++++-- types/next/test/next-document-tests.tsx | 16 ++++++++++++---- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/types/next/document.d.ts b/types/next/document.d.ts index e0879e1c68..d0e6d2c91b 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -27,8 +27,15 @@ export type Enhancer<E extends PageProps = AnyPageProps, P extends any = E> = ( */ export interface NextDocumentContext<Q extends DefaultQuery = DefaultQuery> extends NextContext<Q> { /** A callback that executes the actual React rendering logic (synchronously) */ - renderPage<E extends PageProps = AnyPageProps, P extends any = E>( - enhancer?: Enhancer<E, P> // tslint:disable-line no-unnecessary-generics + renderPage< + E extends PageProps = AnyPageProps, + P = E, + EA extends PageProps = AnyPageProps, + PA = EA, + >( + enhancer?: + | Enhancer<E, P> // tslint:disable-line no-unnecessary-generics + | { enhanceApp?: Enhancer<EA, PA>; enhanceComponent?: Enhancer<E, P> } // tslint:disable-line no-unnecessary-generics ): RenderPageResponse; } diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 83d0a0e8a3..1cd217a749 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -38,12 +38,20 @@ class MyDoc extends Document<WithUrlProps> { static async getInitialProps(ctx: NextDocumentContext) { const { req, renderPage } = ctx; - // without callback + // without enhancer const _page = renderPage(); - // with callback - const enhancer: Enhancer<PageProps, {}> = App => props => <App />; - const { html, head, buildManifest } = renderPage(enhancer); + // with component enhancer + const enhancer: Enhancer<PageProps, {}> = Component => props => <Component />; + const _enhancedPage = renderPage(enhancer); + + // with app and component enhancers + const enhanceApp: Enhancer<PageProps, {}> = App => props => <App />; + const enhanceComponent: Enhancer<PageProps, {}> = Component => props => <Component />; + const { html, head, buildManifest } = renderPage({ + enhanceApp, + enhanceComponent + }); const initialProps = await Document.getInitialProps(ctx); From d83588bc8f4382187208b7f42f3edf501acec8f9 Mon Sep 17 00:00:00 2001 From: denis <denisname@users.noreply.github.com> Date: Thu, 31 Jan 2019 21:52:59 +0100 Subject: [PATCH 051/200] Update version in definition header --- types/d3-force/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-force/index.d.ts b/types/d3-force/index.d.ts index 98f372e2cc..563ca925c3 100644 --- a/types/d3-force/index.d.ts +++ b/types/d3-force/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-force module 1.1 +// Type definitions for D3JS d3-force module 1.2 // Project: https://github.com/d3/d3-force/ // Definitions by: Tom Wanzek <https://github.com/tomwanzek> // Alex Ford <https://github.com/gustavderdrache> From 2eb3ca741dbb6ec79af53d0def5c409da43a2dd2 Mon Sep 17 00:00:00 2001 From: Krantisinh Deshmukh <krantisinh@monjin.com> Date: Fri, 1 Feb 2019 10:32:21 +0530 Subject: [PATCH 052/200] [Ramda] - Added type definition for R.move --- types/ramda/es/move.d.ts | 2 ++ types/ramda/index.d.ts | 8 ++++++++ types/ramda/ramda-tests.ts | 17 +++++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 types/ramda/es/move.d.ts diff --git a/types/ramda/es/move.d.ts b/types/ramda/es/move.d.ts new file mode 100644 index 0000000000..3df4ee626e --- /dev/null +++ b/types/ramda/es/move.d.ts @@ -0,0 +1,2 @@ +import { move } from '../index'; +export default move; diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index d84c148d96..a35b2612ee 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -26,6 +26,7 @@ // Drew Wyatt <https://github.com/drewwyatt> // John Ottenlips <https://github.com/jottenlips> // Nitesh Phadatare <https://github.com/minitesh> +// Krantisinh Deshmukh <https://github.com/krantisinh> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -163,6 +164,7 @@ /// <reference path="./es/minBy.d.ts" /> /// <reference path="./es/min.d.ts" /> /// <reference path="./es/modulo.d.ts" /> +/// <reference path="./es/move.d.ts" /> /// <reference path="./es/multiply.d.ts" /> /// <reference path="./es/nAry.d.ts" /> /// <reference path="./es/negate.d.ts" /> @@ -1575,6 +1577,12 @@ declare namespace R { multiply(a: number, b: number): number; multiply(a: number): (b: number) => number; + /** + * Moves an item, at index `from`, to index `to`, in a list of elements. + * A new list will be created containing the new elements order. + */ + move: CurriedFunction3<number, number, any[], any[]>; + /** * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. * Any extraneous parameters will not be passed to the supplied function. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index c67ef3944d..abc7b60775 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -2762,3 +2762,20 @@ class Why { () => { R.bind(console.log, console); }; + +() => { + const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; + + R.move(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + R.move(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation + + const moveCurried1 = R.move(0, 2); + moveCurried1(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried2 = R.move(0); + moveCurried2(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried3 = R.move(0); + const moveCurried4 = moveCurried3(2); + moveCurried4(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] +}; From fe88e628b899dec72ef84ff5255aa4a607b65953 Mon Sep 17 00:00:00 2001 From: Krantisinh Deshmukh <krantisinh@monjin.com> Date: Fri, 1 Feb 2019 12:36:10 +0530 Subject: [PATCH 053/200] [RAMDA] - Moved tests to list category. --- types/ramda/ramda-tests.ts | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index abc7b60775..87c4c7a099 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1115,6 +1115,23 @@ interface Obj { R.addIndex(R.map)(squareEnds)([8, 5, 3, 0, 9]); // => [64, 5, 3, 0, 81] }; +() => { + const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; + + R.move(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + R.move(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation + + const moveCurried1 = R.move(0, 2); + moveCurried1(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried2 = R.move(0); + moveCurried2(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried3 = R.move(0); + const moveCurried4 = moveCurried3(2); + moveCurried4(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] +}; + () => { R.none(R.isNaN, [1, 2, 3]); // => true R.none(R.isNaN, [1, 2, 3, NaN]); // => false @@ -2762,20 +2779,3 @@ class Why { () => { R.bind(console.log, console); }; - -() => { - const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; - - R.move(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - R.move(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation - - const moveCurried1 = R.move(0, 2); - moveCurried1(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - - const moveCurried2 = R.move(0); - moveCurried2(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - - const moveCurried3 = R.move(0); - const moveCurried4 = moveCurried3(2); - moveCurried4(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] -}; From 50e5bfc5a78579214d452d71f741bf57a36ee5c7 Mon Sep 17 00:00:00 2001 From: Tobias Gimpel <gimpel@pisa.hom> Date: Fri, 1 Feb 2019 11:56:50 +0100 Subject: [PATCH 054/200] Added types for cordova-plugin-background-download --- ...ordova-plugin-background-download-tests.ts | 25 +++++ .../index.d.ts | 92 +++++++++++++++++++ .../tsconfig.json | 24 +++++ .../tslint.json | 3 + 4 files changed, 144 insertions(+) create mode 100644 types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts create mode 100644 types/cordova-plugin-background-download/index.d.ts create mode 100644 types/cordova-plugin-background-download/tsconfig.json create mode 100644 types/cordova-plugin-background-download/tslint.json diff --git a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts new file mode 100644 index 0000000000..3db8c9a4b4 --- /dev/null +++ b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts @@ -0,0 +1,25 @@ + var fileName = "PointerEventsCordovaPlugin.wmv", + uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv"; + + // open target file for download + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) { + fileSystem.root.getFile(fileName, { create: true }, function (targetFile) { + + // plugin callbacks to track operation execution status and progress + var onSuccess = function() { + console.log('Done'); + }; + var onError = function (err) { + console.log(err); + }; + var onProgress = function(progress) { + console.log((100 * progress.bytesReceived / progress.totalBytesToReceive) + '%'); + }; + + var downloader = new BackgroundTransfer.BackgroundDownloader(); + // Create a new download operation. + var download = downloader.createDownload(uriString, targetFile); + // Start the download and persist the promise to be able to cancel the download. + app.downloadPromise = download.startAsync().then(onSuccess, onError, onProgress); + }); + }); \ No newline at end of file diff --git a/types/cordova-plugin-background-download/index.d.ts b/types/cordova-plugin-background-download/index.d.ts new file mode 100644 index 0000000000..5a3319ce8e --- /dev/null +++ b/types/cordova-plugin-background-download/index.d.ts @@ -0,0 +1,92 @@ +// Type definitions for cordova-plugin-background-download 0.5.0 +// Project: https://github.com/sgrebnov/cordova-plugin-background-download +// Definitions by: Tobias Gimpel <https://github.com/mrbullfinsh> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.2.2 + +/** + * Provides an advanced file transfer functionality that persists beyond app termination and + * runs in the background. Background transfer doesn't support concurrent downloads of the same uri. + */ +declare var BackgroundTransfer: IBackgroundTransfer; +declare interface IBackgroundTransfer { + BackgroundDownloader: typeof BackgroundDownloader; +} + +declare class BackgroundDownloader { + /** + * Initializes a new instance of BackgroundDownloader object. + * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. + * + * @param {string} uriMatcher The regexp to compare location of the resources with already downloading ones. + */ + constructor(uriMatcher?: RegExp); + /** + * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. + * + * @param {string} uri The location of the resource. + * @param {File} resultFile The file that the response will be written to. + * @param {string} notificationTitle The title for downloading in notification. + */ + createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; +} + +declare class DownloadOperation { + /** + * Performs an asynchronous download operation in the background. + * + * @param {string} uri The location of the resource. + * @param {File} resultFile The file that the response will be written to. + * @param {string} uriMatcher The regexp to compare location of the resources with already downloading ones. + * @param {string} notificationTitle The title for downloading in notification. + */ + constructor(uri: string, resultFile: File, uriMatcher?: RegExp, notificationTitle?: string); + /** + * Starts an asynchronous download operation. + */ + startAsync(): BackgroundDownloadPromise; + /** + * Stops a download operation. + */ + stop(): void; +} + +interface BackgroundDownloadProgress { + bytesReceived: number, + totalBytesToReceive: number +} + +declare class BackgroundDownloadPromise { + /** + * Provides a mechanism for managing interactions with asynchronous APIs based on Promises. + * See 'Asynchronous programming in JavaScript' for more details + * http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx + * http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx + * Note. Functionality is limited, support of .then and .cancel methods only, other methods are in progress. + */ + constructor(); + static Deferral: typeof Deferral; + _completeCallbacks: Array<Function>; + _errorCallbacks: Array<Function>; + _progressCallbacks: Array<Function>; + _chainedDefer: Deferral; + _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; + result: any; + then(onComplete?: () => void, onError?: (error: any) => void, onProgress?: (progress: BackgroundDownloadProgress) => void): BackgroundDownloadPromise; + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and + * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx + * @param {boolean} flag + */ + cancel(flag?: boolean): void; + executeCallback(callback: Function, args: any): void; +} + +declare class Deferral { + constructor(); + resolve(data: any); + reject(error: any); + notify(value: any); + bind(promise: BackgroundDownloadPromise); +} \ No newline at end of file diff --git a/types/cordova-plugin-background-download/tsconfig.json b/types/cordova-plugin-background-download/tsconfig.json new file mode 100644 index 0000000000..830f1483ca --- /dev/null +++ b/types/cordova-plugin-background-download/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-background-download-tests.ts" + ] +} \ No newline at end of file diff --git a/types/cordova-plugin-background-download/tslint.json b/types/cordova-plugin-background-download/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/cordova-plugin-background-download/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file From 6054156ce1e6b50d2bb9d460338dfe02a707a761 Mon Sep 17 00:00:00 2001 From: Tobias Gimpel <gimpel@pisa.hom> Date: Fri, 1 Feb 2019 15:25:36 +0100 Subject: [PATCH 055/200] [index.d.ts] Applied linting --- ...ordova-plugin-background-download-tests.ts | 27 +++++----- .../index.d.ts | 52 +++++++++---------- 2 files changed, 39 insertions(+), 40 deletions(-) diff --git a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts index 3db8c9a4b4..b531c96570 100644 --- a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts +++ b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts @@ -1,25 +1,24 @@ - var fileName = "PointerEventsCordovaPlugin.wmv", - uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv"; - + let fileName = "PointerEventsCordovaPlugin.wmv"; + let uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv"; + // open target file for download - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) { - fileSystem.root.getFile(fileName, { create: true }, function (targetFile) { - + (window as any).requestFileSystem(1, 0, (fileSystem: any) => { + fileSystem.root.getFile(fileName, { create: true }, (targetFile: File) => { // plugin callbacks to track operation execution status and progress - var onSuccess = function() { + const onSuccess = () => { console.log('Done'); }; - var onError = function (err) { + const onError = (err: any) => { console.log(err); }; - var onProgress = function(progress) { + const onProgress = (progress: BackgroundDownloadProgress) => { console.log((100 * progress.bytesReceived / progress.totalBytesToReceive) + '%'); }; - - var downloader = new BackgroundTransfer.BackgroundDownloader(); + + const downloader = new BackgroundTransfer.BackgroundDownloader(); // Create a new download operation. - var download = downloader.createDownload(uriString, targetFile); + const download = downloader.createDownload(uriString, targetFile); // Start the download and persist the promise to be able to cancel the download. - app.downloadPromise = download.startAsync().then(onSuccess, onError, onProgress); + const downloadPromise = download.startAsync().then(onSuccess, onError, onProgress); }); - }); \ No newline at end of file + }); diff --git a/types/cordova-plugin-background-download/index.d.ts b/types/cordova-plugin-background-download/index.d.ts index 5a3319ce8e..f99b655c47 100644 --- a/types/cordova-plugin-background-download/index.d.ts +++ b/types/cordova-plugin-background-download/index.d.ts @@ -1,15 +1,15 @@ -// Type definitions for cordova-plugin-background-download 0.5.0 +// Type definitions for cordova-plugin-background-download 0.5 // Project: https://github.com/sgrebnov/cordova-plugin-background-download // Definitions by: Tobias Gimpel <https://github.com/mrbullfinsh> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.2.2 +// TypeScript Version: 3.2 /** - * Provides an advanced file transfer functionality that persists beyond app termination and + * Provides an advanced file transfer functionality that persists beyond app termination and * runs in the background. Background transfer doesn't support concurrent downloads of the same uri. */ -declare var BackgroundTransfer: IBackgroundTransfer; -declare interface IBackgroundTransfer { +declare var BackgroundTransfer: BackgroundTransferInterface; +interface BackgroundTransferInterface { BackgroundDownloader: typeof BackgroundDownloader; } @@ -17,16 +17,16 @@ declare class BackgroundDownloader { /** * Initializes a new instance of BackgroundDownloader object. * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. - * - * @param {string} uriMatcher The regexp to compare location of the resources with already downloading ones. + * + * @param uriMatcher The regexp to compare location of the resources with already downloading ones. */ constructor(uriMatcher?: RegExp); /** * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. * - * @param {string} uri The location of the resource. - * @param {File} resultFile The file that the response will be written to. - * @param {string} notificationTitle The title for downloading in notification. + * @param uri The location of the resource. + * @param resultFile The file that the response will be written to. + * @param notificationTitle The title for downloading in notification. */ createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; } @@ -35,10 +35,10 @@ declare class DownloadOperation { /** * Performs an asynchronous download operation in the background. * - * @param {string} uri The location of the resource. - * @param {File} resultFile The file that the response will be written to. - * @param {string} uriMatcher The regexp to compare location of the resources with already downloading ones. - * @param {string} notificationTitle The title for downloading in notification. + * @param uri The location of the resource. + * @param resultFile The file that the response will be written to. + * @param uriMatcher The regexp to compare location of the resources with already downloading ones. + * @param notificationTitle The title for downloading in notification. */ constructor(uri: string, resultFile: File, uriMatcher?: RegExp, notificationTitle?: string); /** @@ -52,8 +52,8 @@ declare class DownloadOperation { } interface BackgroundDownloadProgress { - bytesReceived: number, - totalBytesToReceive: number + bytesReceived: number; + totalBytesToReceive: number; } declare class BackgroundDownloadPromise { @@ -66,9 +66,9 @@ declare class BackgroundDownloadPromise { */ constructor(); static Deferral: typeof Deferral; - _completeCallbacks: Array<Function>; - _errorCallbacks: Array<Function>; - _progressCallbacks: Array<Function>; + _completeCallbacks: Array<() => void>; + _errorCallbacks: Array<(error: any) => void>; + _progressCallbacks: Array<(progress: BackgroundDownloadProgress) => void>; _chainedDefer: Deferral; _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; result: any; @@ -77,16 +77,16 @@ declare class BackgroundDownloadPromise { * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx - * @param {boolean} flag + * @param flag */ cancel(flag?: boolean): void; - executeCallback(callback: Function, args: any): void; + executeCallback(callback: (() => void) | ((error: any) => void) | ((progress: BackgroundDownloadProgress) => void), args: any): void; } declare class Deferral { constructor(); - resolve(data: any); - reject(error: any); - notify(value: any); - bind(promise: BackgroundDownloadPromise); -} \ No newline at end of file + resolve(data: any): void; + reject(error: any): void; + notify(value: any): void; + bind(promise: BackgroundDownloadPromise): void; +} From c52b655134afcd571f2642da9fee94ce259191fe Mon Sep 17 00:00:00 2001 From: Dale Fenton <fentondale@gmail.com> Date: Fri, 1 Feb 2019 10:27:31 -0500 Subject: [PATCH 056/200] add types for spellchecker package --- types/spellchecker/index.d.ts | 63 ++++++++++++++++++++++++ types/spellchecker/spellchecker-tests.ts | 41 +++++++++++++++ types/spellchecker/tsconfig.json | 23 +++++++++ types/spellchecker/tslint.json | 1 + 4 files changed, 128 insertions(+) create mode 100644 types/spellchecker/index.d.ts create mode 100644 types/spellchecker/spellchecker-tests.ts create mode 100644 types/spellchecker/tsconfig.json create mode 100644 types/spellchecker/tslint.json diff --git a/types/spellchecker/index.d.ts b/types/spellchecker/index.d.ts new file mode 100644 index 0000000000..0863e19646 --- /dev/null +++ b/types/spellchecker/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for spellchecker 3.5 +// Project: http://atom.github.io/node-spellchecker +// Definitions by: Dale Fenton <https://github.com/dalevfenton> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace Spellchecker; + +/* --------------------------------------------------------------------------- + Custom Types / Interfaces +--------------------------------------------------------------------------- */ +/** + * MisspelledLocation - shape of an object returned by checkSpelling to + * identify locations of misspelled words in a corpus. + * @description a misspelled word can be found by corpus.slice(start, end) + * start - start index of a misspelled word in a corpus + * end - end index of a misspelled word in a corpus + */ +export interface MisspelledLocation { + start: number; + end: number; +} + +/* --------------------------------------------------------------------------- + Methods +--------------------------------------------------------------------------- */ +/** + * Spellchecker.isMisspelled - Check if a word is misspelled. + * @param word - String word to check. + * @returns boolean - true if the word is misspelled, false otherwise. + */ +export function isMisspelled(word: string): boolean; + +/** + * Spellchecker.getCorrectionsForMisspelling - Get the corrections for a misspelled word. + * @param word - String word to get corrections for. + * @returns array - Returns a non-null but possibly empty array of string corrections. + */ +export function getCorrectionsForMisspelling(word: string): string[]; + +/** + * Spellchecker.checkSpelling - Identify misspelled words in a corpus of text. + * @param corpus - String corpus of text to spellcheck. + * @returns array - Returns an Array containing {start, end} objects that describe an + * index range within the original String that contains a misspelled word. + */ +export function checkSpelling(corpus: string): MisspelledLocation[]; + +/** + * Spellchecker.checkSpellingAsync - Asynchronously identify misspelled words. + * @param corpus - String corpus of text to spellcheck. + * @returns array - Returns a Promise that resolves with the Array described by checkSpelling(). + */ +export function checkSpellingAsync(corpus: string): Promise<MisspelledLocation[]>; + +/** + * Spellchecker.add - Adds a word to the dictionary. + * When using Hunspell, this will not modify the .dic file; + * new words must be added each time the spellchecker is created. Use a custom dictionary file. + * @param word - String word to add. + * @returns void + */ +export function add(word: string): void; diff --git a/types/spellchecker/spellchecker-tests.ts b/types/spellchecker/spellchecker-tests.ts new file mode 100644 index 0000000000..7f53b26ab0 --- /dev/null +++ b/types/spellchecker/spellchecker-tests.ts @@ -0,0 +1,41 @@ +import * as Spellchecker from 'spellchecker'; + +const additionalDictionary = ['Xynoronmalade']; + +// add words to the dictionary +additionalDictionary.forEach(word => Spellchecker.add(word)); + +let testWord = 'kat'; +let testCorpus = 'The queeck brown fox jumped over the lazy dog, from Xynoronmalade'; +let testCorpusAsync = 'The queeck brown fox jumped over the lazy dog, from Xynoronmalade'; + +// check and correct a single word +if (Spellchecker.isMisspelled(testWord)) { + const corrections = Spellchecker.getCorrectionsForMisspelling(testWord); + if (corrections.length > 0) { + testWord = corrections[0]; + } +} + +// check and correct words in a body of text +const misspellings = Spellchecker.checkSpelling(testCorpus); +misspellings.forEach(location => { + const misspelled = testCorpus.slice(location.start, location.end); + const corrections = Spellchecker.getCorrectionsForMisspelling(misspelled); + if (corrections.length > 0) { + testCorpus = testCorpus.replace(misspelled, corrections[0]); + } +}); + +// check for corrections asynchronously +const asyncSpellCheck = async () => { + // check and correct words in a body of text + const misspellings = await Spellchecker.checkSpellingAsync(testCorpusAsync); + misspellings.forEach(location => { + const misspelled = testCorpusAsync.slice(location.start, location.end); + const corrections = Spellchecker.getCorrectionsForMisspelling(misspelled); + if (corrections.length > 0) { + testCorpusAsync = testCorpusAsync.replace(misspelled, corrections[0]); + } + }); +}; diff --git a/types/spellchecker/tsconfig.json b/types/spellchecker/tsconfig.json new file mode 100644 index 0000000000..6817057d8c --- /dev/null +++ b/types/spellchecker/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "spellchecker-tests.ts" + ] +} diff --git a/types/spellchecker/tslint.json b/types/spellchecker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/spellchecker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From dbf5f097ccd90edb24dd01c9605ffd19ed0a1bca Mon Sep 17 00:00:00 2001 From: Sara Federico <gretzky@users.noreply.github.com> Date: Fri, 1 Feb 2019 14:11:23 -0500 Subject: [PATCH 057/200] [rebass] fix `as` prop per styled-components docs --- types/rebass/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/rebass/index.d.ts b/types/rebass/index.d.ts index 0536a600ee..20c73079ad 100644 --- a/types/rebass/index.d.ts +++ b/types/rebass/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: rhysd <https://github.com/rhysd> // ryee-dev <https://github.com/ryee-dev> // jamesmckenzie <https://github.com/jamesmckenzie> +// sara f-p <https://github.com/gretzky> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -10,7 +11,7 @@ import * as React from "react"; export interface BaseProps<C> extends React.ClassAttributes<C> { className?: string; - as?: string; + as?: any; } export interface SpaceProps<C> extends BaseProps<C> { From d0b43ffafd0e195c1e00a02d26768f8dd73f7180 Mon Sep 17 00:00:00 2001 From: Kevin Rambaud <kevin.rambaud@gmail.com> Date: Tue, 22 Jan 2019 16:14:57 -0500 Subject: [PATCH 058/200] Export ReactPaginateProps interface in v5 and v6 --- types/react-paginate/index.d.ts | 3 ++- types/react-paginate/v5/index.d.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/types/react-paginate/index.d.ts b/types/react-paginate/index.d.ts index d66309d489..626f459fc5 100644 --- a/types/react-paginate/index.d.ts +++ b/types/react-paginate/index.d.ts @@ -7,12 +7,13 @@ // Yasunori Ohoka <https://github.com/yasupeke> // Shingo Sato <https://github.com/sugarshin> // SPWizard01 <https://github.com/SPWizard01> +// Kevin Rambaud <https://github.com/kevinrambaud> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -interface ReactPaginateProps { +export interface ReactPaginateProps { /** * The total number of pages. */ diff --git a/types/react-paginate/v5/index.d.ts b/types/react-paginate/v5/index.d.ts index 83a03ac838..7529a6b12f 100644 --- a/types/react-paginate/v5/index.d.ts +++ b/types/react-paginate/v5/index.d.ts @@ -5,12 +5,13 @@ // pegel03 <https://github.com/pegel03> // Simon Archer <https://github.com/archy-bold> // Yasunori Ohoka <https://github.com/yasupeke> +// Kevin Rambaud <https://github.com/kevinrambaud> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -interface ReactPaginateProps { +export interface ReactPaginateProps { /** * The total number of pages. */ From fbca2f74db132b331c4152cb951ffc965e93deb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= <takeda@youmind.jp> Date: Sat, 2 Feb 2019 09:26:56 +0900 Subject: [PATCH 059/200] fix `Optional Parameters in Callbacks` http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#optional-parameters-in-callbacks --- types/hexo/index.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/types/hexo/index.d.ts b/types/hexo/index.d.ts index 0688b1631a..0f3a9dcc78 100644 --- a/types/hexo/index.d.ts +++ b/types/hexo/index.d.ts @@ -603,7 +603,7 @@ declare namespace Hexo { /** * Executed when creating a post to determine the path of new posts. */ - register(type: 'new_post_path', fn: (data: Post.Data, replace?: boolean) => void, priority?: number): void; + register(type: 'new_post_path', fn: (data: Post.Data, replace: boolean|undefined) => void, priority?: number): void; /** * Used to determine the permalink of posts. @@ -675,13 +675,13 @@ declare namespace Hexo { } interface Renderer { - register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => string, sync: true): void; - register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => Promise<string>, sync: false): void; - register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => Promise<string>): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => string, sync: true): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => Promise<string>, sync: false): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => Promise<string>): void; } interface Tag { - register(name: string, fn: (args: string[], content?: string) => string, options?: Tag.Options): void; + register(name: string, fn: (args: string[], content: string|undefined) => string, options?: Tag.Options): void; } namespace Tag { interface Options { From b9b4bd8adedee32a8a5182dd743cca7d7a45f937 Mon Sep 17 00:00:00 2001 From: Jeffrey Meng <jeffkmeng@gmail.com> Date: Fri, 1 Feb 2019 18:52:57 -0800 Subject: [PATCH 060/200] Use typescript exports and also export interfaces --- types/list.js/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 0c31e24e20..0c2e4fb905 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -60,4 +60,5 @@ declare class ListItem { visible(): boolean; } -export = List; +export default List; +export {ListOptions, SortOptions, ListItem, List}; From 31a2c8c5e5a706f2c1a1855adde19499c80b3225 Mon Sep 17 00:00:00 2001 From: nossbigg <chenggibson@gmail.com> Date: Sat, 2 Feb 2019 12:39:59 +0800 Subject: [PATCH 061/200] Add typings for react-native-modal-filter-picker --- .../index.d.ts | 61 ++++++++++++++++++ ...react-native-modal-filter-picker-tests.tsx | 64 +++++++++++++++++++ .../tsconfig.json | 17 +++++ .../tslint.json | 1 + 4 files changed, 143 insertions(+) create mode 100644 types/react-native-modal-filter-picker/index.d.ts create mode 100644 types/react-native-modal-filter-picker/react-native-modal-filter-picker-tests.tsx create mode 100644 types/react-native-modal-filter-picker/tsconfig.json create mode 100644 types/react-native-modal-filter-picker/tslint.json diff --git a/types/react-native-modal-filter-picker/index.d.ts b/types/react-native-modal-filter-picker/index.d.ts new file mode 100644 index 0000000000..8188a32319 --- /dev/null +++ b/types/react-native-modal-filter-picker/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for react-native-modal-filter-picker 1.3 +// Project: https://github.com/hiddentao/react-native-modal-filter-picker#readme +// Definitions by: Chang Yanwei <https://github.com/ywchang> +// Cheng Gibson <https://github.com/nossbigg> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; +import { + StyleProp, + ViewStyle, + TextStyle, + ListView, + KeyboardAvoidingView, + ModalProps, + ListViewProps +} from "react-native"; + +export interface ModalFilterPickerOption { + label: string; + key: string; +} + +export interface ModalFilterPickerProps<T extends ModalFilterPickerOption> { + options: T[]; + onSelect: (key: string) => void; + onCancel: () => void; + placeholderText?: string; + placeholderTextColor?: string; + androidUnderlineColor?: string; + cancelButtonText?: string; + title?: string; + noResultsText?: string; + visible?: boolean; + showFilter?: boolean; + modal?: ModalProps; + selectedOption?: string; + listViewProps?: Partial<ListViewProps>; + renderOption?: (option: T, isSelected: boolean) => JSX.Element; + renderList?: () => JSX.Element; + renderCancelButton?: () => JSX.Element; + keyboardShouldPersistTaps?: "never" | "always" | "handle"; + autoFocus?: boolean; + + // styling props + overlayStyle?: StyleProp<KeyboardAvoidingView>; + listContainerStyle?: StyleProp<ViewStyle>; + filterTextInputContainerStyle?: StyleProp<ViewStyle>; + filterTextInputStyle?: StyleProp<TextStyle>; + cancelContainerStyle?: StyleProp<ViewStyle>; + cancelButtonStyle?: StyleProp<ViewStyle>; + cancelButtonTextStyle?: StyleProp<TextStyle>; + titleTextStyle?: StyleProp<TextStyle>; + optionTextStyle?: StyleProp<TextStyle>; +} + +declare class ModalFilterPicker< + T extends ModalFilterPickerOption +> extends React.Component<ModalFilterPickerProps<T>> {} + +export default ModalFilterPicker; diff --git a/types/react-native-modal-filter-picker/react-native-modal-filter-picker-tests.tsx b/types/react-native-modal-filter-picker/react-native-modal-filter-picker-tests.tsx new file mode 100644 index 0000000000..05fc770e5a --- /dev/null +++ b/types/react-native-modal-filter-picker/react-native-modal-filter-picker-tests.tsx @@ -0,0 +1,64 @@ +import * as React from "react"; +import ModalFilterPicker, { + ModalFilterPickerOption +} from "react-native-modal-filter-picker"; +import { View, Button, Text } from "react-native"; + +interface MyModalFilterPickerOption extends ModalFilterPickerOption { + customField: string; +} + +const modalFilterPickerOptions: MyModalFilterPickerOption[] = [ + { + label: "some-label-1", + key: "some-key-1", + customField: "some-customfield-1" + }, + { + label: "some-label-2", + key: "some-key-2", + customField: "some-customfield-2" + } +]; + +const renderPicker = () => ( + <ModalFilterPicker + options={modalFilterPickerOptions} + onSelect={key => { + console.log(key); + }} + onCancel={() => {}} + placeholderText="Filter..." + placeholderTextColor="#ccc" + androidUnderlineColor="rgba(0,0,0,0)" + cancelButtonText="Cancel" + title="some-title" + noResultsText="No matches" + visible + showFilter + modal={{ animated: true }} + selectedOption="some-option-key" + listViewProps={{ accessible: true }} + renderOption={(option, isSelected) => ( + <View key={option.key}> + <Text> + `${option.label} ${option.customField} ${isSelected}` + </Text> + </View> + )} + renderList={() => <View />} + renderCancelButton={() => <Button title="Cancel" onPress={() => {}} />} + keyboardShouldPersistTaps={"never"} + autoFocus={false} + /> +); + +const renderPickerWithRequiredPropsOnly = () => ( + <ModalFilterPicker + options={modalFilterPickerOptions} + onSelect={key => { + console.log(key); + }} + onCancel={() => {}} + /> +); diff --git a/types/react-native-modal-filter-picker/tsconfig.json b/types/react-native-modal-filter-picker/tsconfig.json new file mode 100644 index 0000000000..66da37bb6b --- /dev/null +++ b/types/react-native-modal-filter-picker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": ["index.d.ts", "react-native-modal-filter-picker-tests.tsx"] +} diff --git a/types/react-native-modal-filter-picker/tslint.json b/types/react-native-modal-filter-picker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-modal-filter-picker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 1d1af425ff2e542460c927cd90f34eabf577f661 Mon Sep 17 00:00:00 2001 From: Ryo Ota <nwtgck@gmail.com> Date: Sat, 2 Feb 2019 15:35:07 +0900 Subject: [PATCH 062/200] Sort fields in IncomingHttpHeaders --- types/node/http.d.ts | 14 +++++++------- types/node/v4/index.d.ts | 14 +++++++------- types/node/v6/index.d.ts | 14 +++++++------- types/node/v7/index.d.ts | 14 +++++++------- types/node/v8/index.d.ts | 16 ++++++++-------- types/node/v9/index.d.ts | 16 ++++++++-------- 6 files changed, 44 insertions(+), 44 deletions(-) diff --git a/types/node/http.d.ts b/types/node/http.d.ts index e5f3741003..98b730c0c6 100644 --- a/types/node/http.d.ts +++ b/types/node/http.d.ts @@ -7,14 +7,14 @@ declare module "http" { // incoming headers will never contain number interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -50,9 +50,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 26210a1857..f52a8d01f8 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -672,14 +672,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -703,9 +703,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 5ed74da702..6dd1ad1dc0 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -741,14 +741,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -772,9 +772,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 932d988912..a4fde30a97 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -738,14 +738,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -769,9 +769,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index e0e901fea6..1fac090367 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -967,18 +967,18 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -999,9 +999,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 5bafe1ec47..220afd9e60 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -1052,18 +1052,18 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -1084,9 +1084,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; From 2f31fadccb4ccd59ac50f7a7796c9115e897a056 Mon Sep 17 00:00:00 2001 From: Dale Fenton <fentondale@gmail.com> Date: Sat, 2 Feb 2019 09:56:06 -0500 Subject: [PATCH 063/200] remove Spellchecker from global namespace --- types/spellchecker/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/spellchecker/index.d.ts b/types/spellchecker/index.d.ts index 0863e19646..01064d0688 100644 --- a/types/spellchecker/index.d.ts +++ b/types/spellchecker/index.d.ts @@ -4,8 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -export as namespace Spellchecker; - /* --------------------------------------------------------------------------- Custom Types / Interfaces --------------------------------------------------------------------------- */ From 778a6b93b5cc9d43ba2c5b86838f77a3076947bc Mon Sep 17 00:00:00 2001 From: Dimitri Benin <dimitri.benin@gmail.com> Date: Sat, 2 Feb 2019 19:41:50 +0100 Subject: [PATCH 064/200] [acl] Export all module interfaces, fix lint exceptions --- types/acl/index.d.ts | 289 +++++++++++++++++-------------- types/acl/test/index.ts | 71 ++++---- types/acl/test/mongodbBackend.ts | 4 +- types/acl/test/redisBackend.ts | 4 +- types/acl/tslint.json | 78 +-------- 5 files changed, 199 insertions(+), 247 deletions(-) diff --git a/types/acl/index.d.ts b/types/acl/index.d.ts index 3f4df31aa2..931452dc52 100644 --- a/types/acl/index.d.ts +++ b/types/acl/index.d.ts @@ -1,150 +1,179 @@ -// Type definitions for node_acl 0.4.8 +// Type definitions for acl 0.4 // Project: https://github.com/optimalbits/node_acl // Definitions by: Qubo <https://github.com/tkQubo> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <reference types="node"/> -/// <reference types="express"/> import http = require('http'); -import Promise = require("bluebird"); -import express = require("express"); +import Promise = require('bluebird'); +import express = require('express'); +import redis = require('redis'); +import mongo = require('mongodb'); -type strings = string|string[]; -type Value = string|number; -type Values = Value|Value[]; +export = AclStatic; + +declare const AclStatic: AclStatic; + +type strings = string | string[]; +type Value = string | number; +type Values = Value | Value[]; type Action = () => any; -type Callback = (err: Error) => any; +type Callback = (err?: Error) => any; type AnyCallback = (err: Error, obj: any) => any; type AllowedCallback = (err: Error, allowed: boolean) => any; type GetUserId = (req: http.IncomingMessage, res: http.ServerResponse) => Value; interface AclStatic { - new (backend: Backend<any>, logger: Logger, options: Option): Acl; - new (backend: Backend<any>, logger: Logger): Acl; - new (backend: Backend<any>): Acl; - memoryBackend: MemoryBackendStatic; + new ( + backend: AclStatic.Backend<any>, + logger?: AclStatic.Logger, + options?: AclStatic.Option + ): AclStatic.Acl; + readonly memoryBackend: AclStatic.MemoryBackendStatic; + readonly mongodbBackend: AclStatic.MongodbBackendStatic; + readonly redisBackend: AclStatic.RedisBackendStatic; } -interface Logger { - debug: (msg: string) => any; -} - -interface Acl { - addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>; - removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>; - userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise<string[]>; - roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise<any>; - hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean) => any) => Promise<boolean>; - addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>; - removeRole: (role: string, cb?: Callback) => Promise<void>; - removeResource: (resource: string, cb?: Callback) => Promise<void>; - allow: { - (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>; - (aclSets: AclSet | AclSet[]): Promise<void>; +declare namespace AclStatic { + interface Logger { + debug: (msg: string) => any; } - removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise<void>; - removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise<void>; - allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>; - isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise<boolean>; - areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise<any>; - whatResources: { - (roles: strings, cb?: AnyCallback): Promise<any>; - (roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>; + + interface Acl { + addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>; + removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>; + userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise<string[]>; + roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise<any>; + hasRole: ( + userId: Value, + role: string, + cb?: (err: Error, isInRole: boolean) => any + ) => Promise<boolean>; + addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>; + removeRole: (role: string, cb?: Callback) => Promise<void>; + removeResource: (resource: string, cb?: Callback) => Promise<void>; + allow: { + (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>; + (aclSets: AclSet | AclSet[]): Promise<void>; + }; + removeAllow: ( + role: string, + resources: strings, + permissions: strings, + cb?: Callback + ) => Promise<void>; + removePermissions: ( + role: string, + resources: strings, + permissions: strings, + cb?: Callback + ) => Promise<void>; + allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>; + isAllowed: ( + userId: Value, + resources: strings, + permissions: strings, + cb?: AllowedCallback + ) => Promise<boolean>; + areAnyRolesAllowed: ( + roles: strings, + resource: strings, + permissions: strings, + cb?: AllowedCallback + ) => Promise<any>; + whatResources: { + (roles: strings, cb?: AnyCallback): Promise<any>; + (roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>; + }; + permittedResources: (roles: strings, permissions: strings, cb?: Callback) => Promise<void>; + middleware: ( + numPathComponents?: number, + userId?: Value | GetUserId, + actions?: strings + ) => express.RequestHandler; + } + + interface Option { + buckets?: BucketsOption; + } + + interface BucketsOption { + meta?: string; + parents?: string; + permissions?: string; + resources?: string; + roles?: string; + users?: string; + } + + interface AclSet { + roles: strings; + allows: AclAllow[]; + } + + interface AclAllow { + resources: strings; + permissions: strings; + } + + interface MemoryBackend extends Backend<Action[]> {} + interface MemoryBackendStatic { + new (): MemoryBackend; + } + + // + // For internal use + // + interface Backend<T> { + begin: () => T; + end: (transaction: T, cb?: Action) => void; + clean: (cb?: Action) => void; + get: (bucket: string, key: Value, cb?: Action) => void; + union: (bucket: string, keys: Value[], cb?: Action) => void; + add: (transaction: T, bucket: string, key: Value, values: Values) => void; + del: (transaction: T, bucket: string, keys: Value[]) => void; + remove: (transaction: T, bucket: string, key: Value, values: Values) => void; + + endAsync: (transaction: T, cb?: (err: Error | null) => void) => Promise<void>; + getAsync: ( + bucket: string, + key: Value, + cb?: (err: Error | null, value: any) => void + ) => Promise<any>; + cleanAsync: (cb?: (error?: Error) => void) => Promise<void>; + unionAsync: ( + bucket: string, + keys: Value[], + cb?: (error: Error | undefined, results: any[]) => void + ) => Promise<any[]>; + } + + interface Contract { + (args: IArguments): Contract | NoOp; + debug: boolean; + fulfilled: boolean; + args: any[]; + checkedParams: string[]; + params: (...types: string[]) => Contract | NoOp; + end: () => void; + } + + interface NoOp { + params: (...types: string[]) => NoOp; + end: () => void; + } + + // for redis backend + interface RedisBackend extends Backend<redis.RedisClient> {} + interface RedisBackendStatic { + new (redis: redis.RedisClient, prefix?: string): RedisBackend; + } + + // for mongodb backend + interface MongodbBackend extends Backend<Callback> {} + interface MongodbBackendStatic { + new (db: mongo.Db, prefix?: string, useSingle?: boolean): MongodbBackend; } - permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>; - middleware: (numPathComponents?: number, userId?: Value | GetUserId, actions?: strings) => express.RequestHandler; } - -interface Option { - buckets?: BucketsOption; -} - -interface BucketsOption { - meta?: string; - parents?: string; - permissions?: string; - resources?: string; - roles?: string; - users?: string; -} - -interface AclSet { - roles: strings; - allows: AclAllow[]; -} - -interface AclAllow { - resources: strings; - permissions: strings; -} - -interface MemoryBackend extends Backend<Action[]> { } -interface MemoryBackendStatic { - new (): MemoryBackend; -} - -// -// For internal use -// -interface Backend<T> { - begin: () => T; - end: (transaction: T, cb?: Action) => void; - clean: (cb?: Action) => void; - get: (bucket: string, key: Value, cb?: Action) => void; - union: (bucket: string, keys: Value[], cb?: Action) => void; - add: (transaction: T, bucket: string, key: Value, values: Values) => void; - del: (transaction: T, bucket: string, keys: Value[]) => void; - remove: (transaction: T, bucket: string, key: Value, values: Values) => void; - - endAsync: Function; //TODO: Give more specific function signature - getAsync: Function; - cleanAsync: Function; - unionAsync: Function; -} - -interface Contract { - (args: IArguments): Contract | NoOp; - debug: boolean; - fulfilled: boolean; - args: any[]; - checkedParams: string[]; - params: (...types: string[]) => Contract | NoOp; - end: () => void; -} - -interface NoOp { - params: (...types: string[]) => NoOp; - end: () => void; -} - -// for redis backend -import redis = require('redis'); - -interface AclStatic { - redisBackend: RedisBackendStatic; -} - -interface RedisBackend extends Backend<redis.RedisClient> { } -interface RedisBackendStatic { - new (redis: redis.RedisClient, prefix: string): RedisBackend; - new (redis: redis.RedisClient): RedisBackend; -} - -// for mongodb backend -import mongo = require('mongodb'); - -interface AclStatic { - mongodbBackend: MongodbBackendStatic; -} - -interface MongodbBackend extends Backend<Callback> { } -interface MongodbBackendStatic { - new (db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; - new (db: mongo.Db, prefix: string): MongodbBackend; - new (db: mongo.Db): MongodbBackend; -} - -declare var _: AclStatic; -export = _; diff --git a/types/acl/test/index.ts b/types/acl/test/index.ts index bb3e6fa54e..3485ab3662 100644 --- a/types/acl/test/index.ts +++ b/types/acl/test/index.ts @@ -2,15 +2,15 @@ // https://github.com/OptimalBits/node_acl/blob/master/Readme.md import Acl = require('acl'); -var report = <T>(err: Error, value: T) => { - if (err) { - console.error(err); - } - console.info(value); +const report = (err: Error, value: any) => { + if (err) { + console.error(err); + } + console.info(value); }; // Using the memory backend -var acl = new Acl(new Acl.memoryBackend()); +const acl: Acl.Acl = new Acl(new Acl.memoryBackend()); // middleware with no optional parameters acl.middleware(); @@ -18,11 +18,11 @@ acl.middleware(); acl.middleware(1); acl.middleware(1, () => { - return "joed"; + return 'joed'; }); acl.middleware(1, () => { - return 2; + return 2; }); acl.middleware(1, 'joed'); @@ -33,36 +33,36 @@ acl.middleware(3, 'joed', 'post'); acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); acl.addUserRoles('joed', 'guest'); -acl.addRoleParents('baz', ['foo','bar']); +acl.addRoleParents('baz', ['foo', 'bar']); -acl.allow('foo', ['blogs','forums','news'], ['view', 'delete']); +acl.allow('foo', ['blogs', 'forums', 'news'], ['view', 'delete']); -acl.allow('admin', ['blogs','forums'], '*'); +acl.allow('admin', ['blogs', 'forums'], '*'); acl.allow([ { - roles:['guest','special-member'], - allows:[ - {resources:'blogs', permissions:'get'}, - {resources:['forums','news'], permissions:['get','put','delete']} - ] + roles: ['guest', 'special-member'], + allows: [ + { resources: 'blogs', permissions: 'get' }, + { resources: ['forums', 'news'], permissions: ['get', 'put', 'delete'] }, + ], }, { - roles:['gold','silver'], - allows:[ - {resources:'cash', permissions:['sell','exchange']}, - {resources:['account','deposit'], permissions:['put','delete']} - ] - } + roles: ['gold', 'silver'], + allows: [ + { resources: 'cash', permissions: ['sell', 'exchange'] }, + { resources: ['account', 'deposit'], permissions: ['put', 'delete'] }, + ], + }, ]); acl.isAllowed('joed', 'blogs', 'view', (err, res) => { if (res) { - console.log("User joed is allowed to view blogs"); + console.log('User joed is allowed to view blogs'); } }); @@ -78,15 +78,14 @@ acl.whatResources('foo', 'view', (err, res) => { } }); -acl.isAllowed('jsmith', 'blogs', ['edit','view','delete']) -.then((result) => { - console.dir('jsmith is allowed blogs ' + result); - acl.addUserRoles('jsmith', 'member'); -}).then(() => - acl.isAllowed('jsmith', 'blogs', ['edit','view','delete']) -).then((result) => - console.dir('jsmith is allowed blogs ' + result) -).then(() => { - acl.allowedPermissions('james', ['blogs','forums'], report); - acl.allowedPermissions('jsmith', ['blogs','forums'], report); -}); +acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete']) + .then(result => { + console.dir('jsmith is allowed blogs ' + result); + acl.addUserRoles('jsmith', 'member'); + }) + .then(() => acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete'])) + .then(result => console.dir('jsmith is allowed blogs ' + result)) + .then(() => { + acl.allowedPermissions('james', ['blogs', 'forums'], report); + acl.allowedPermissions('jsmith', ['blogs', 'forums'], report); + }); diff --git a/types/acl/test/mongodbBackend.ts b/types/acl/test/mongodbBackend.ts index ae3b1d03c9..449cefa030 100644 --- a/types/acl/test/mongodbBackend.ts +++ b/types/acl/test/mongodbBackend.ts @@ -5,10 +5,10 @@ import mongodb = require('mongodb'); declare var db: mongodb.Db; // Using the mongo db backend -var acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true)); +const acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true)); // guest is allowed to view blogs acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); diff --git a/types/acl/test/redisBackend.ts b/types/acl/test/redisBackend.ts index ec1924cce6..669d28ed6d 100644 --- a/types/acl/test/redisBackend.ts +++ b/types/acl/test/redisBackend.ts @@ -5,10 +5,10 @@ import redis = require('redis'); declare var client: redis.RedisClient; // Using the redis backend -var acl = new Acl(new Acl.redisBackend(client, 'acl_')); +const acl = new Acl(new Acl.redisBackend(client, 'acl_')); // guest is allowed to view blogs acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); diff --git a/types/acl/tslint.json b/types/acl/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/acl/tslint.json +++ b/types/acl/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From fed19a461850f2e3881b5efd1d1a62eb26879d06 Mon Sep 17 00:00:00 2001 From: Jeffrey Meng <jeffreymeng@users.noreply.github.com> Date: Sat, 2 Feb 2019 11:37:25 -0800 Subject: [PATCH 065/200] Keep old exports --- types/list.js/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 0c2e4fb905..8dd43dd1df 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -60,5 +60,6 @@ declare class ListItem { visible(): boolean; } +export = List; export default List; export {ListOptions, SortOptions, ListItem, List}; From 49d2ea60d65c14ac298123bb19b7fe8a9f168388 Mon Sep 17 00:00:00 2001 From: Jeffrey Meng <jeffkmeng@gmail.com> Date: Sat, 2 Feb 2019 11:46:28 -0800 Subject: [PATCH 066/200] Revert "Keep old exports" This reverts commit fed19a461850f2e3881b5efd1d1a62eb26879d06. --- types/list.js/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 8dd43dd1df..0c2e4fb905 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -60,6 +60,5 @@ declare class ListItem { visible(): boolean; } -export = List; export default List; export {ListOptions, SortOptions, ListItem, List}; From b20f6fa61f901ad3c78af6b44e33b7b776c0fa88 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Sat, 2 Feb 2019 18:56:12 -0800 Subject: [PATCH 067/200] [jscodeshift] Split into multiple files --- types/jscodeshift/index.d.ts | 457 +++--------------- types/jscodeshift/src/Collection.d.ts | 123 +++++ .../src/collections/JSXElement.d.ts | 70 +++ types/jscodeshift/src/collections/Node.d.ts | 57 +++ .../src/collections/VariableDeclarator.d.ts | 39 ++ types/jscodeshift/src/template.d.ts | 14 + types/jscodeshift/tsconfig.json | 5 + types/jscodeshift/tslint.json | 7 +- 8 files changed, 378 insertions(+), 394 deletions(-) create mode 100644 types/jscodeshift/src/Collection.d.ts create mode 100644 types/jscodeshift/src/collections/JSXElement.d.ts create mode 100644 types/jscodeshift/src/collections/Node.d.ts create mode 100644 types/jscodeshift/src/collections/VariableDeclarator.d.ts create mode 100644 types/jscodeshift/src/template.d.ts diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index 95a26cd0a4..f4cee2db55 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -4,420 +4,101 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 -declare module "jscodeshift" { - import { Collection, registerMethods } from "jscodeshift/src/Collection"; - import * as JSXElement from "jscodeshift/src/collections/JSXElement"; - import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; - import { Template } from "jscodeshift/src/template"; - import recast, { Builders, NamedTypes, NodePath, Options, Parser } from "recast"; - import { ASTNode } from "ast-types/gen/nodes"; +import { ASTNode } from "ast-types/gen/nodes"; +import recast, { Builders, NamedTypes, NodePath, Options, Parser } from "recast"; +import { Collection, registerMethods } from "./src/Collection"; +import * as JSXElement from "./src/collections/JSXElement"; +import * as VariableDeclarator from "./src/collections/VariableDeclarator"; +import { Template } from "./src/template"; - export type ASTPath<N = ASTNode> = NodePath<N, N>; +export type ASTPath<N = ASTNode> = NodePath<N, N>; - export interface Filters { - JSXElement: JSXElement.FilterMethods; - VariableDeclarator: VariableDeclarator.FilterMethods; - } - - export interface Mappings { - JSXElement: JSXElement.MappingMethods; - } - - export interface Plugin { - (core: Core): void; - } - - export interface FileInfo { - /** The absolute path to the current file. */ - path: string; - /** The source code of the current file. */ - source: string; - } - - export interface Stats { - /** - * Helper function to collect data during --dry runs. - * This function keeps a counter for how often it was called with a specific argument. - * The result is shown in the console. Useful for finding out how many files match a criterion. - */ - (name: string, quantity?: number): void; - } - - interface Core { - (source: string, options?: Options): Collection<any>; - (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection<any>; - - registerMethods: typeof registerMethods; - - types: typeof recast.types; - - match(path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode): boolean; - - /** template, bound to default parser */ - template: Template; - - filters: Filters; - - mappings: Mappings; - - /** - * Utility function for registering plugins. - * - * Plugins are simple functions that are passed the core jscodeshift instance. - * They should extend jscodeshift by calling `registerMethods`, etc. - * This method guards against repeated registrations (the plugin callback will only be called once). - */ - use(plugin: Plugin): void; - - /** - * Returns a version of the core jscodeshift function "bound" to a specific - * parser. - */ - withParser(parser: string | Parser): JSCodeshift; - } - - type JSCodeshift = Core & NamedTypes & Builders; - - const core: JSCodeshift; - export default core; - - export interface API { - j: JSCodeshift; - jscodeshift: JSCodeshift; - stats: Stats; - report: (msg: string) => void; - } - - export interface Options { - [option: string]: any; - } - - export interface Transform { - /** - * If a string is returned and it is different from passed source, the transform is considered to be successful. - * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. - * If nothing is returned, the file is not supposed to be transformed (which is ok). - */ - (file: FileInfo, api: API, options: Options): string | null | undefined | void; - } - - export * from "ast-types/gen/nodes"; - export { Collection, Parser }; +export interface Filters { + JSXElement: JSXElement.FilterMethods; + VariableDeclarator: VariableDeclarator.FilterMethods; } -declare module "jscodeshift/src/template" { - import { Parser } from "recast"; - - export interface Template { - /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ - statements(...args: any[]): any; - /** Tagged template function. Parses the string as source and returns an Statement AST node. */ - statement(...args: any[]): any; - /** Tagged template function. Parses the string as source and returns an Expression AST node. */ - expression(...args: any[]): any; - } - - export default function withParser(parser: Parser): Template; - - export {}; // to shut off automatic exporting +export interface Mappings { + JSXElement: JSXElement.MappingMethods; } -declare module "jscodeshift/src/Collection" { - import * as JSXElement from "jscodeshift/src/collections/JSXElement"; - import * as NodeCollection from "jscodeshift/src/collections/Node"; - import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; - import recast, { ASTNode, NodePath, Options, Type } from "recast"; +export interface Plugin { + (core: Core): void; +} - type ASTPath<N> = NodePath<N, N>; +export interface FileInfo { + /** The absolute path to the current file. */ + path: string; + /** The source code of the current file. */ + source: string; +} - export interface Collection<N> - extends NodeCollection.TraversalMethods, - NodeCollection.MutationMethods<N>, - VariableDeclarator.GlobalMethods, - VariableDeclarator.TransformMethods<N>, - JSXElement.GlobalMethods, - JSXElement.TraversalMethods { - /** - * @param paths An array of AST paths - * @param parent A parent collection - * @param types An array of types all the paths in the collection - * have in common. If not passed, it will be inferred from the paths. - */ - new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<Type<any>>): this; +export interface Stats { + /** + * Helper function to collect data during --dry runs. + * This function keeps a counter for how often it was called with a specific argument. + * The result is shown in the console. Useful for finding out how many files match a criterion. + */ + (name: string, quantity?: number): void; +} - /** - * Returns a new collection containing the nodes for which the callback returns true. - */ - filter<S extends N>( - callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => path is ASTPath<S> - ): Collection<S>; - filter( - callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean - ): Collection<N>; +interface Core { + (source: string, options?: Options): Collection<any>; + (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection<any>; - /** - * Executes callback for each node/path in the collection. - */ - forEach(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => void): this; + registerMethods: typeof registerMethods; - /** - * Tests whether at-least one path passes the test implemented by the provided callback. - */ - some(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + types: typeof recast.types; - /** - * Tests whether all paths pass the test implemented by the provided callback. - */ - every(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + match(path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode): boolean; - /** - * Executes the callback for every path in the collection and returns a new - * collection from the return values (which must be paths). - * - * The callback can return null to indicate to exclude the element from the - * new collection. - * - * If an array is returned, the array will be flattened into the result - * collection. - * - * @param callback - * @param type Force the new collection to be of a specific type - */ - map<T = ASTNode>( - callback: ( - path: ASTPath<N>, - i: number, - paths: Array<ASTPath<N>> - ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, - type: Type<any> - ): Collection<T>; + /** template, bound to default parser */ + template: Template; - /** Returns the number of elements in this collection. */ - size(): number; + filters: Filters; - /** Returns the number of elements in this collection. */ - length: number; - - /** Returns an array of AST nodes in this collection. */ - nodes(): N[]; - - /** Returns an array of ASTPaths in this this collection. */ - paths(): Array<ASTPath<N>>; - - getAST(): Array<ASTPath<any>>; - - /** - * Converts the AST back to a string, using recast. - * @param options directly passed to recast's printer - */ - toSource(options?: Options): string; - - /** - * Returns a new collection containing only the element at position index. - * In case of a negative index, the element is taken from the end: - * .at(0) - first element - * .at(-1) - last element - */ - at(index: number): Collection<N>; - - /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ - get(...fields: Array<string | number>): any; - - /** - * Returns the type(s) of the collection. This is only used for unit tests, - * don't think other consumers would need it. - */ - getTypes(): string[]; - - /** - * Returns true if this collection has the type 'type'. - */ - isOfType(type: Type<any>): boolean; - } + mappings: Mappings; /** - * This function adds the provided methods to the prototype of the corresponding - * typed collection. If no type is passed, the methods are added to - * Collection.prototype and are available for all collections. + * Utility function for registering plugins. * - * @param methods Methods to add to the prototype - * @param type Optional type to add the methods to + * Plugins are simple functions that are passed the core jscodeshift instance. + * They should extend jscodeshift by calling `registerMethods`, etc. + * This method guards against repeated registrations (the plugin callback will only be called once). */ - export function registerMethods(methods: object, type?: Type<any>): void; + use(plugin: Plugin): void; - export {}; // to shut off automatic exporting + /** + * Returns a version of the core jscodeshift function "bound" to a specific + * parser. + */ + withParser(parser: string | Parser): JSCodeshift; } -declare module "jscodeshift/src/collections/Node" { - import { Collection } from "jscodeshift/src/Collection"; - import { ASTNode, Type, NodePath } from "recast"; +type JSCodeshift = Core & NamedTypes & Builders; - type ASTPath<N> = NodePath<N, N>; +declare const core: JSCodeshift; +export default core; - export interface TraversalMethods { - /** - * Find nodes of a specific type within the nodes of this collection. - */ - find<T>(type: Type<T>, filter?: ((value: any) => boolean) | object): Collection<T>; - - /** - * Returns a collection containing the paths that create the scope of the - * currently selected paths. Dedupes the paths. - */ - closestScope<T>(): Collection<T>; - - /** - * Traverse the AST up and finds the closest node of the provided type. - */ - closest<T>(type: Type<T>, filter?: any): Collection<T>; - - /** - * Finds the declaration for each selected path. Useful for member expressions - * or JSXElements. Expects a callback function that maps each path to the name - * to look for. - * - * If the callback returns a falsey value, the element is skipped. - */ - getVariableDeclarators<T>(nameGetter: (...args: any[]) => any): Collection<T>; - } - - export interface MutationMethods<N> { - /** - * Simply replaces the selected nodes with the provided node. If a function - * is provided it is executed for every node and the node is replaced with the - * functions return value. - */ - replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection<T>; - - /** - * Inserts a new node before the current one. - */ - insertBefore(insert: any): Collection<N>; - - /** - * Inserts a new node after the current one. - */ - insertAfter(insert: any): Collection<N>; - - remove(): Collection<N>; - } - - export function register(): void; - - export {}; // to shut off automatic exporting +export interface API { + j: JSCodeshift; + jscodeshift: JSCodeshift; + stats: Stats; + report: (msg: string) => void; } -declare module "jscodeshift/src/collections/VariableDeclarator" { - import { VariableDeclarator } from "ast-types/gen/nodes"; - import { Collection } from "jscodeshift/src/Collection"; - import recast, { NodePath } from "recast"; - - type ASTPath<N> = NodePath<N, N>; - - export interface GlobalMethods { - /** - * Finds all variable declarators, optionally filtered by name. - */ - findVariableDeclarators(name?: string): Collection<VariableDeclarator>; - } - - export interface TransformMethods<N> { - /** - * Renames a variable and all its occurrences. - * This method only applies to VariableDeclarator typed collections. - */ - renameTo(newName: string): Collection<N>; - } - - interface Filter { - (path: ASTPath<any>): boolean; - } - - export interface FilterMethods { - /** - * Returns a function that returns true if the provided path is a variable - * declarator and requires one of the specified module names. - * - * @param names A module name or an array of module names - */ - requiresModule(names: string | string[]): Filter; - } - - export function register(): void; - export const filters: FilterMethods; - - export {}; // to shut off automatic exporting +export interface Options { + [option: string]: any; } -declare module "jscodeshift/src/collections/JSXElement" { - import { JSXElement } from "ast-types/gen/nodes"; - import { Collection } from "jscodeshift/src/Collection"; - import { NodePath } from "recast"; - - type ASTPath<N> = NodePath<N, N>; - - export interface GlobalMethods { - /** - * Finds all JSXElements optionally filtered by name - */ - findJSXElements(name?: string): Collection<JSXElement>; - - /** - * Finds all JSXElements by module name. Given - * - * var Bar = require('Foo'); - * <Bar /> - * - * findJSXElementsByModuleName('Foo') will find <Bar />, without having to - * know the variable name. - */ - findJSXElementsByModuleName(moduleName: string): Collection<JSXElement>; - } - - type Defined<T> = T extends undefined ? never : T; - type JSXElementChild = Defined<JSXElement["children"]>[0]; - - export interface TraversalMethods { - /** - * Returns all child nodes, including literals and expressions. - * This method only applies to JSXElement typed collections. - */ - childNodes<T>(): Collection<JSXElementChild>; - - /** - * Returns all children that are JSXElements. - * This method only applies to JSXElement typed collections. - */ - childElements(): Collection<JSXElement>; - } - - interface Filter { - (path: ASTPath<any>): boolean; - } - - export interface FilterMethods { - /** - * Filter method for attributes. - */ - hasAttributes(attributeFilter: { [attributeName: string]: any }): Filter; - - /** - * Filter elements which contain a specific child type - */ - hasChildren(name: string): Filter; - } - - export interface MappingMethods { - /** - * Given a JSXElement, returns its "root" name. E.g. it would return "Foo" for - * both <Foo /> and <Foo.Bar />. - */ - getRootName(path: ASTPath<any>): string; - } - - export function register(): void; - export const filters: FilterMethods; - export const mappings: MappingMethods; - - export {}; // to shut off automatic exporting +export interface Transform { + /** + * If a string is returned and it is different from passed source, the transform is considered to be successful. + * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. + * If nothing is returned, the file is not supposed to be transformed (which is ok). + */ + (file: FileInfo, api: API, options: Options): string | null | undefined | void; } + +export * from "ast-types/gen/nodes"; +export { Collection, Parser }; diff --git a/types/jscodeshift/src/Collection.d.ts b/types/jscodeshift/src/Collection.d.ts new file mode 100644 index 0000000000..5ddf7b2bdc --- /dev/null +++ b/types/jscodeshift/src/Collection.d.ts @@ -0,0 +1,123 @@ +import { ASTNode, NodePath, Options, Type } from "recast"; +import * as JSXElement from "./collections/JSXElement"; +import * as NodeCollection from "./collections/Node"; +import * as VariableDeclarator from "./collections/VariableDeclarator"; + +type ASTPath<N> = NodePath<N, N>; + +export interface Collection<N> + extends NodeCollection.TraversalMethods, + NodeCollection.MutationMethods<N>, + VariableDeclarator.GlobalMethods, + VariableDeclarator.TransformMethods<N>, + JSXElement.GlobalMethods, + JSXElement.TraversalMethods { + /** + * @param paths An array of AST paths + * @param parent A parent collection + * @param types An array of types all the paths in the collection + * have in common. If not passed, it will be inferred from the paths. + */ + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<Type<any>>): this; + + /** + * Returns a new collection containing the nodes for which the callback returns true. + */ + filter<S extends N>( + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => path is ASTPath<S> + ): Collection<S>; + filter( + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean + ): Collection<N>; + + /** + * Executes callback for each node/path in the collection. + */ + forEach(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => void): this; + + /** + * Tests whether at-least one path passes the test implemented by the provided callback. + */ + some(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + + /** + * Tests whether all paths pass the test implemented by the provided callback. + */ + every(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + + /** + * Executes the callback for every path in the collection and returns a new + * collection from the return values (which must be paths). + * + * The callback can return null to indicate to exclude the element from the + * new collection. + * + * If an array is returned, the array will be flattened into the result + * collection. + * + * @param callback + * @param type Force the new collection to be of a specific type + */ + map<T = ASTNode>( + callback: ( + path: ASTPath<N>, + i: number, + paths: Array<ASTPath<N>> + ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, + type: Type<any> + ): Collection<T>; + + /** Returns the number of elements in this collection. */ + size(): number; + + /** Returns the number of elements in this collection. */ + length: number; + + /** Returns an array of AST nodes in this collection. */ + nodes(): N[]; + + /** Returns an array of ASTPaths in this this collection. */ + paths(): Array<ASTPath<N>>; + + getAST(): Array<ASTPath<any>>; + + /** + * Converts the AST back to a string, using recast. + * @param options directly passed to recast's printer + */ + toSource(options?: Options): string; + + /** + * Returns a new collection containing only the element at position index. + * In case of a negative index, the element is taken from the end: + * .at(0) - first element + * .at(-1) - last element + */ + at(index: number): Collection<N>; + + /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ + get(...fields: Array<string | number>): any; + + /** + * Returns the type(s) of the collection. This is only used for unit tests, + * don't think other consumers would need it. + */ + getTypes(): string[]; + + /** + * Returns true if this collection has the type 'type'. + */ + isOfType(type: Type<any>): boolean; +} + +/** + * This function adds the provided methods to the prototype of the corresponding + * typed collection. If no type is passed, the methods are added to + * Collection.prototype and are available for all collections. + * + * @param methods Methods to add to the prototype + * @param type Optional type to add the methods to + */ +export function registerMethods(methods: object, type?: Type<any>): void; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/src/collections/JSXElement.d.ts b/types/jscodeshift/src/collections/JSXElement.d.ts new file mode 100644 index 0000000000..730c33ad90 --- /dev/null +++ b/types/jscodeshift/src/collections/JSXElement.d.ts @@ -0,0 +1,70 @@ +import { JSXElement } from "ast-types/gen/nodes"; +import { NodePath } from "recast"; +import { Collection } from "../Collection"; + +type ASTPath<N> = NodePath<N, N>; + +export interface GlobalMethods { + /** + * Finds all JSXElements optionally filtered by name + */ + findJSXElements(name?: string): Collection<JSXElement>; + + /** + * Finds all JSXElements by module name. Given + * + * var Bar = require('Foo'); + * <Bar /> + * + * findJSXElementsByModuleName('Foo') will find <Bar />, without having to + * know the variable name. + */ + findJSXElementsByModuleName(moduleName: string): Collection<JSXElement>; +} + +type Defined<T> = T extends undefined ? never : T; +type JSXElementChild = Defined<JSXElement["children"]>[0]; + +export interface TraversalMethods { + /** + * Returns all child nodes, including literals and expressions. + * This method only applies to JSXElement typed collections. + */ + childNodes(): Collection<JSXElementChild>; + + /** + * Returns all children that are JSXElements. + * This method only applies to JSXElement typed collections. + */ + childElements(): Collection<JSXElement>; +} + +interface Filter { + (path: ASTPath<any>): boolean; +} + +export interface FilterMethods { + /** + * Filter method for attributes. + */ + hasAttributes(attributeFilter: { [attributeName: string]: any }): Filter; + + /** + * Filter elements which contain a specific child type + */ + hasChildren(name: string): Filter; +} + +export interface MappingMethods { + /** + * Given a JSXElement, returns its "root" name. E.g. it would return "Foo" for + * both <Foo /> and <Foo.Bar />. + */ + getRootName(path: ASTPath<any>): string; +} + +export function register(): void; +export const filters: FilterMethods; +export const mappings: MappingMethods; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/src/collections/Node.d.ts b/types/jscodeshift/src/collections/Node.d.ts new file mode 100644 index 0000000000..e596c8a8ab --- /dev/null +++ b/types/jscodeshift/src/collections/Node.d.ts @@ -0,0 +1,57 @@ +import { VariableDeclarator } from "ast-types/gen/nodes"; +import { ASTNode, NodePath, Type } from "recast"; +import { Collection } from "../Collection"; + +type ASTPath<N> = NodePath<N, N>; + +export interface TraversalMethods { + /** + * Find nodes of a specific type within the nodes of this collection. + */ + find<T>(type: Type<T>, filter?: ((value: any) => boolean) | object): Collection<T>; + + /** + * Returns a collection containing the paths that create the scope of the + * currently selected paths. Dedupes the paths. + */ + closestScope(): Collection<ASTNode>; + + /** + * Traverse the AST up and finds the closest node of the provided type. + */ + closest<T>(type: Type<T>, filter?: any): Collection<T>; + + /** + * Finds the declaration for each selected path. Useful for member expressions + * or JSXElements. Expects a callback function that maps each path to the name + * to look for. + * + * If the callback returns a falsey value, the element is skipped. + */ + getVariableDeclarators(nameGetter: (...args: any[]) => any): Collection<VariableDeclarator>; +} + +export interface MutationMethods<N> { + /** + * Simply replaces the selected nodes with the provided node. If a function + * is provided it is executed for every node and the node is replaced with the + * functions return value. + */ + replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection<T>; + + /** + * Inserts a new node before the current one. + */ + insertBefore(insert: any): Collection<N>; + + /** + * Inserts a new node after the current one. + */ + insertAfter(insert: any): Collection<N>; + + remove(): Collection<N>; +} + +export function register(): void; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/src/collections/VariableDeclarator.d.ts b/types/jscodeshift/src/collections/VariableDeclarator.d.ts new file mode 100644 index 0000000000..8627b316db --- /dev/null +++ b/types/jscodeshift/src/collections/VariableDeclarator.d.ts @@ -0,0 +1,39 @@ +import { VariableDeclarator } from "ast-types/gen/nodes"; +import { NodePath } from "recast"; +import { Collection } from "../Collection"; + +type ASTPath<N> = NodePath<N, N>; + +export interface GlobalMethods { + /** + * Finds all variable declarators, optionally filtered by name. + */ + findVariableDeclarators(name?: string): Collection<VariableDeclarator>; +} + +export interface TransformMethods<N> { + /** + * Renames a variable and all its occurrences. + * This method only applies to VariableDeclarator typed collections. + */ + renameTo(newName: string): Collection<N>; +} + +interface Filter { + (path: ASTPath<any>): boolean; +} + +export interface FilterMethods { + /** + * Returns a function that returns true if the provided path is a variable + * declarator and requires one of the specified module names. + * + * @param names A module name or an array of module names + */ + requiresModule(names: string | string[]): Filter; +} + +export function register(): void; +export const filters: FilterMethods; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/src/template.d.ts b/types/jscodeshift/src/template.d.ts new file mode 100644 index 0000000000..44bfab9be3 --- /dev/null +++ b/types/jscodeshift/src/template.d.ts @@ -0,0 +1,14 @@ +import { Parser } from "recast"; + +export interface Template { + /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ + statements(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Statement AST node. */ + statement(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Expression AST node. */ + expression(...args: any[]): any; +} + +export default function withParser(parser: Parser): Template; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index 8ad162be32..a2c90ce266 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -18,6 +18,11 @@ }, "files": [ "index.d.ts", + "src/Collection.d.ts", + "src/collections/JSXElement.d.ts", + "src/collections/Node.d.ts", + "src/collections/VariableDeclarator.d.ts", + "src/template.d.ts", "test/jscodeshift-tests.ts", "test/js-transforms/bind-this-to-bind-expression.ts", "test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts", diff --git a/types/jscodeshift/tslint.json b/types/jscodeshift/tslint.json index 94991f356f..f93cf8562a 100644 --- a/types/jscodeshift/tslint.json +++ b/types/jscodeshift/tslint.json @@ -1,8 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-declare-current-package": false, - "no-self-import": false, - "no-unnecessary-generics": false - } + "extends": "dtslint/dt.json" } From 716a420713c9b0f3cc604f7278ae5c559de90f76 Mon Sep 17 00:00:00 2001 From: Jeffrey Meng <jeffkmeng@gmail.com> Date: Sat, 2 Feb 2019 19:12:38 -0800 Subject: [PATCH 068/200] Move interfaces into namespace --- types/list.js/index.d.ts | 69 ++++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 34 deletions(-) diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 0c2e4fb905..8209d87e67 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -4,25 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 -interface ListOptions { - valueNames?: string[]; - item?: string; - listClass?: string; - searchClass?: string; - sortClass?: string; - indexAsync?: boolean; - page?: number; - i?: number; - pagination?: boolean; -} - -interface SortOptions { - order?: string; - alphabet?: string; - insensitive?: boolean; - sortFunction?: ((a: object, b: object) => number|undefined); -} - declare class List { listContainer: HTMLElement; list: HTMLElement; @@ -32,15 +13,15 @@ declare class List { searched: boolean; filtered: boolean; - constructor(element: string|HTMLElement, options?: ListOptions, values?: object[]); + constructor(element: string|HTMLElement, options?: List.ListOptions, values?: object[]); - add(values: object[], callback?: (item: ListItem) => void): void; + add(values: object[], callback?: (item: List.ListItem) => void): void; remove(valueName: string, value: any): number; - get(valueName: string, value: any): ListItem[]; - sort(valueName: string, options: SortOptions): void; + get(valueName: string, value: any): List.ListItem[]; + sort(valueName: string, options: List.SortOptions): void; search(searchString: string, columns?: string[]): void; clear(): void; - filter(filterFunction: (item: ListItem) => boolean): void; + filter(filterFunction: (item: List.ListItem) => boolean): void; size(): number; show(i: number, page: number): void; update(): void; @@ -49,16 +30,36 @@ declare class List { on(event: string, callback: () => void): void; } -declare class ListItem { - elm: HTMLElement; +declare namespace List { + interface ListItem { + elm: HTMLElement; - values(newValues: object): void; - values(): object; - show(): void; - hide(): void; - matching(): boolean; - visible(): boolean; + values(newValues: object): void; + values(): object; + show(): void; + hide(): void; + matching(): boolean; + visible(): boolean; + } + + interface ListOptions { + valueNames?: string[]; + item?: string; + listClass?: string; + searchClass?: string; + sortClass?: string; + indexAsync?: boolean; + page?: number; + i?: number; + pagination?: boolean; + } + + interface SortOptions { + order?: string; + alphabet?: string; + insensitive?: boolean; + sortFunction?: ((a: object, b: object) => number|undefined); + } } -export default List; -export {ListOptions, SortOptions, ListItem, List}; +export = List; From d60993c576df1a0f451fe21da5032cd3b3b75429 Mon Sep 17 00:00:00 2001 From: Ifiok Jr <ifiokotung@gmail.com> Date: Sun, 3 Feb 2019 05:30:25 +0000 Subject: [PATCH 069/200] feat(prosemirror-test-builder): add type definition --- types/prosemirror-test-builder/index.d.ts | 126 ++++++++++++++++++ .../prosemirror-test-builder-tests.ts | 123 +++++++++++++++++ types/prosemirror-test-builder/tsconfig.json | 18 +++ types/prosemirror-test-builder/tslint.json | 1 + 4 files changed, 268 insertions(+) create mode 100644 types/prosemirror-test-builder/index.d.ts create mode 100644 types/prosemirror-test-builder/prosemirror-test-builder-tests.ts create mode 100644 types/prosemirror-test-builder/tsconfig.json create mode 100644 types/prosemirror-test-builder/tslint.json diff --git a/types/prosemirror-test-builder/index.d.ts b/types/prosemirror-test-builder/index.d.ts new file mode 100644 index 0000000000..f6c01420c4 --- /dev/null +++ b/types/prosemirror-test-builder/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for prosemirror-test-builder 1.0 +// Project: https://github.com/prosemirror/prosemirror-test-builder#readme +// Definitions by: Ifiok Jr. <https://github.com/ifiokjr> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Node as ProsemirrorNode, Schema } from 'prosemirror-model'; + +export interface NodeTypeAttributes extends Record<string, any> { + nodeType: string; +} + +export interface MarkTypeAttributes extends Record<string, any> { + markType: string; +} + +export interface TaggedFlatObject<S extends Schema = any> { + tag: Record<string, number>; + flat: Array<TaggedProsemirrorNode<S> | TaggedFlatObject<S>>; +} + +export interface TaggedProsemirrorNode<S extends Schema = any> + extends TaggedFlatObject<S>, + ProsemirrorNode {} + +type TestNodesUnion = + | 'p' + | 'pre' + | 'h1' + | 'h2' + | 'h3' + | 'li' + | 'ul' + | 'ol' + | 'br' + | 'img' + | 'hr' + | 'ordered_list' + | 'bullet_list' + | 'list_item' + | 'doc' + | 'paragraph' + | 'blockquote' + | 'horizontal_rule' + | 'heading' + | 'code_block' + | 'text' + | 'image' + | 'hard_break'; +type TestMarksUnion = 'a' | 'link' | 'em' | 'strong' | 'code'; + +export type TestSchema = Schema<TestNodesUnion, TestMarksUnion>; + +type Args = Array<string | TaggedProsemirrorNode | TaggedFlatObject>; + +type NodeBuilderMethod<S extends Schema = any> = ( + ...args: Args +) => TaggedProsemirrorNode<S>; + +type MarkBuilderMethod<S extends Schema = any> = ( + ...args: Args +) => TaggedFlatObject<S>; + +export interface EqMethod { + eq(param: EqMethod): boolean; +} + +export type Builder = < + Obj extends Record< + string, + NodeTypeAttributes | MarkTypeAttributes + > = Record<string, NodeTypeAttributes | MarkTypeAttributes>, + N extends string = string, + M extends string = string +>( + testSchema: Schema<N, M>, + names: Obj, +) => Record<N, NodeBuilderMethod<Schema<N, M>>> & + Record<M, MarkBuilderMethod<Schema<N, M>>> & + { + [P in keyof Obj]: Obj[P] extends NodeTypeAttributes + ? NodeBuilderMethod<Schema<N, M>> + : MarkBuilderMethod<Schema<N, M>> + }; + +export interface ProsemirrorTestBuilder { + schema: TestSchema; + builders: Builder; + eq(a: EqMethod, b: EqMethod): boolean; + p: NodeBuilderMethod<TestSchema>; + pre: NodeBuilderMethod<TestSchema>; + h1: NodeBuilderMethod<TestSchema>; + h2: NodeBuilderMethod<TestSchema>; + h3: NodeBuilderMethod<TestSchema>; + li: NodeBuilderMethod<TestSchema>; + ul: NodeBuilderMethod<TestSchema>; + ol: NodeBuilderMethod<TestSchema>; + br: NodeBuilderMethod<TestSchema>; + img: NodeBuilderMethod<TestSchema>; + hr: NodeBuilderMethod<TestSchema>; + a: MarkBuilderMethod<TestSchema>; + + // From schema list + ordered_list: NodeBuilderMethod<TestSchema>; + bullet_list: NodeBuilderMethod<TestSchema>; + list_item: NodeBuilderMethod<TestSchema>; + doc: NodeBuilderMethod<TestSchema>; + + // From schema basic + paragraph: NodeBuilderMethod<TestSchema>; + blockquote: NodeBuilderMethod<TestSchema>; + horizontal_rule: NodeBuilderMethod<TestSchema>; + heading: NodeBuilderMethod<TestSchema>; + code_block: NodeBuilderMethod<TestSchema>; + text: NodeBuilderMethod<TestSchema>; + image: NodeBuilderMethod<TestSchema>; + hard_break: NodeBuilderMethod<TestSchema>; + link: MarkBuilderMethod<TestSchema>; + em: MarkBuilderMethod<TestSchema>; + strong: MarkBuilderMethod<TestSchema>; + code: MarkBuilderMethod<TestSchema>; +} + +declare const prosemirrorTestBuilder: ProsemirrorTestBuilder; + +export default prosemirrorTestBuilder; diff --git a/types/prosemirror-test-builder/prosemirror-test-builder-tests.ts b/types/prosemirror-test-builder/prosemirror-test-builder-tests.ts new file mode 100644 index 0000000000..dd5aa0c345 --- /dev/null +++ b/types/prosemirror-test-builder/prosemirror-test-builder-tests.ts @@ -0,0 +1,123 @@ +import { Schema } from 'prosemirror-model'; +import { + EditorState, + NodeSelection, + Selection, + TextSelection, + Transaction, +} from 'prosemirror-state'; +import pm, { TaggedProsemirrorNode } from 'prosemirror-test-builder'; + +export type DispatchFunction = (tr: Transaction) => void; +export type CommandFunction = ( + state: EditorState, + dispatch?: DispatchFunction, +) => boolean; + +function selectionFor(docNode: TaggedProsemirrorNode) { + const aTag = docNode.tag.a; + if (aTag != null) { + const $aTag = docNode.resolve(aTag); + if ($aTag.parent.inlineContent) { + return new TextSelection( + $aTag, + docNode.tag.b != null + ? docNode.resolve(docNode.tag.b) + : undefined, + ); + } else { + return new NodeSelection($aTag); + } + } + return Selection.atStart(docNode); +} + +function createState(d: TaggedProsemirrorNode) { + return EditorState.create({ doc: d, selection: selectionFor(d) }); +} + +export function apply( + docNode: TaggedProsemirrorNode, + command: CommandFunction, + result?: TaggedProsemirrorNode, +): [boolean, TaggedProsemirrorNode] { + let state = createState(docNode); + command(state, tr => (state = state.apply(tr))); + + if (!pm.eq(state.doc, result || docNode)) { + return [false, state.doc as TaggedProsemirrorNode]; + } + + if (result && result.tag.a != null) { + return [ + pm.eq(state.selection, selectionFor(result)), + result || docNode, + ]; + } + return [true, state.doc as TaggedProsemirrorNode]; +} + +const { p, doc, builders } = pm; + +apply(doc(p('hi'), p('<a>there')), () => true, doc(p('hi there'))); + +export const schema = new Schema<'doc' | 'paragraph' | 'blockquote', 'em'>({ + nodes: { + doc: { + content: 'block+', + }, + + paragraph: { + group: 'block', + parseDOM: [{ tag: 'p' }], + toDOM() { + return ['p', 0]; + }, + }, + + blockquote: { + content: 'block+', + group: 'block', + parseDOM: [{ tag: 'blockquote' }], + toDOM() { + return ['blockquote', 0]; + }, + }, + }, + + marks: { + em: { + parseDOM: [ + { tag: 'i' }, + { tag: 'em' }, + { + style: 'font-style', + getAttrs: value => value === 'italic' && null, + }, + ], + toDOM() { + return ['em']; + }, + }, + }, +}); + +const { h1, a } = builders(schema, { + p: { nodeType: 'paragraph' }, + h1: { nodeType: 'heading', level: 1 }, + h2: { nodeType: 'heading', level: 2 }, + hr: { nodeType: 'horizontal_rule' }, + li: { nodeType: 'list_item' }, + ol: { nodeType: 'ordered_list' }, + ul: { nodeType: 'bullet_list' }, + pre: { nodeType: 'code_block' }, + a: { markType: 'link', href: 'foo' }, + br: { nodeType: 'hard_break' }, + img: { nodeType: 'image', src: 'img.png', alt: 'x' }, +}); + +const TEST1 = h1; // $ExpectType NodeBuilderMethod<Schema<"doc" | "paragraph" | "blockquote", "em">> +const TEST2 = a; // $ExpectType MarkBuilderMethod<Schema<"doc" | "paragraph" | "blockquote", "em">> + +h1(''); // $ExpectType TaggedProsemirrorNode<Schema<"doc" | "paragraph" | "blockquote", "em">> +a(''); // $ExpectType TaggedFlatObject<Schema<"doc" | "paragraph" | "blockquote", "em">> diff --git a/types/prosemirror-test-builder/tsconfig.json b/types/prosemirror-test-builder/tsconfig.json new file mode 100644 index 0000000000..3869b95fde --- /dev/null +++ b/types/prosemirror-test-builder/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noEmit": true, + "lib": ["es6", "dom"], + "noUnusedLocals": false, + "noUnusedParameters": false, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "prosemirror-test-builder-tests.ts"] +} diff --git a/types/prosemirror-test-builder/tslint.json b/types/prosemirror-test-builder/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/prosemirror-test-builder/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From fff62884caad593567558d422cf0f15728fa488b Mon Sep 17 00:00:00 2001 From: Krantisinh Deshmukh <krantisinh@monjin.com> Date: Mon, 4 Feb 2019 12:57:43 +0530 Subject: [PATCH 070/200] [Ramda] - Improved type signatures of R.move. --- types/ramda/index.d.ts | 6 ++++-- types/ramda/ramda-tests.ts | 12 ++++-------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index a35b2612ee..05b629137d 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1578,10 +1578,12 @@ declare namespace R { multiply(a: number): (b: number) => number; /** - * Moves an item, at index `from`, to index `to`, in a list of elements. + * Moves an item, at index `from`, to index `to`, in a `list` of elements. * A new list will be created containing the new elements order. */ - move: CurriedFunction3<number, number, any[], any[]>; + move<T>(from: number, to: number, list: ReadonlyArray<T>): T[]; + move(from: number, to: number): <T>(list: ReadonlyArray<T>) => T[]; + move(from: number): (<T>(to: number, list: ReadonlyArray<T>) => T[]); /** * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 87c4c7a099..6c568d4a56 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1118,18 +1118,14 @@ interface Obj { () => { const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; - R.move(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - R.move(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation + R.move<string>(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + R.move<string>(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation const moveCurried1 = R.move(0, 2); - moveCurried1(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + moveCurried1<string>(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] const moveCurried2 = R.move(0); - moveCurried2(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - - const moveCurried3 = R.move(0); - const moveCurried4 = moveCurried3(2); - moveCurried4(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + moveCurried2<string>(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] }; () => { From b1d57876b3e38aef24d91c0a0c579a8805a83ff2 Mon Sep 17 00:00:00 2001 From: Tobias Gimpel <gimpel@pisa.hom> Date: Mon, 4 Feb 2019 13:02:42 +0100 Subject: [PATCH 071/200] [index.d.ts] Made BackgroundTransfer a namespace, changed inaccessible classes to interfaces --- ...ordova-plugin-background-download-tests.ts | 2 +- .../index.d.ts | 112 +++++++++--------- 2 files changed, 54 insertions(+), 60 deletions(-) diff --git a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts index b531c96570..e56d14ce04 100644 --- a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts +++ b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts @@ -11,7 +11,7 @@ const onError = (err: any) => { console.log(err); }; - const onProgress = (progress: BackgroundDownloadProgress) => { + const onProgress = (progress: BackgroundTransfer.Progress) => { console.log((100 * progress.bytesReceived / progress.totalBytesToReceive) + '%'); }; diff --git a/types/cordova-plugin-background-download/index.d.ts b/types/cordova-plugin-background-download/index.d.ts index f99b655c47..815d20bf66 100644 --- a/types/cordova-plugin-background-download/index.d.ts +++ b/types/cordova-plugin-background-download/index.d.ts @@ -8,27 +8,61 @@ * Provides an advanced file transfer functionality that persists beyond app termination and * runs in the background. Background transfer doesn't support concurrent downloads of the same uri. */ -declare var BackgroundTransfer: BackgroundTransferInterface; -interface BackgroundTransferInterface { - BackgroundDownloader: typeof BackgroundDownloader; -} +declare namespace BackgroundTransfer { + class BackgroundDownloader { + /** + * Initializes a new instance of BackgroundDownloader object. + * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. + * + * @param uriMatcher The regexp to compare location of the resources with already downloading ones. + */ + constructor(uriMatcher?: RegExp); + /** + * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. + * + * @param uri The location of the resource. + * @param resultFile The file that the response will be written to. + * @param notificationTitle The title for downloading in notification. + */ + createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; + } + + interface Progress { + bytesReceived: number; + totalBytesToReceive: number; + } -declare class BackgroundDownloader { /** - * Initializes a new instance of BackgroundDownloader object. - * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. - * - * @param uriMatcher The regexp to compare location of the resources with already downloading ones. + * Provides a mechanism for managing interactions with asynchronous APIs based on Promises. + * See 'Asynchronous programming in JavaScript' for more details + * http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx + * http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx + * Note. Functionality is limited, support of .then and .cancel methods only, other methods are in progress. */ - constructor(uriMatcher?: RegExp); - /** - * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. - * - * @param uri The location of the resource. - * @param resultFile The file that the response will be written to. - * @param notificationTitle The title for downloading in notification. - */ - createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; + interface Promise { + _completeCallbacks: Array<() => void>; + _errorCallbacks: Array<(error: any) => void>; + _progressCallbacks: Array<(progress: Progress) => void>; + _chainedDefer: Deferral; + _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; + result: any; + then(onComplete?: () => void, onError?: (error: any) => void, onProgress?: (progress: Progress) => void): Promise; + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and + * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx + * @param flag + */ + cancel(flag?: boolean): void; + executeCallback(callback: (() => void) | ((error: any) => void) | ((progress: Progress) => void), args: any): void; + } + + interface Deferral { + resolve(data: any): void; + reject(error: any): void; + notify(value: any): void; + bind(promise: Promise): void; + } } declare class DownloadOperation { @@ -44,49 +78,9 @@ declare class DownloadOperation { /** * Starts an asynchronous download operation. */ - startAsync(): BackgroundDownloadPromise; + startAsync(): BackgroundTransfer.Promise; /** * Stops a download operation. */ stop(): void; } - -interface BackgroundDownloadProgress { - bytesReceived: number; - totalBytesToReceive: number; -} - -declare class BackgroundDownloadPromise { - /** - * Provides a mechanism for managing interactions with asynchronous APIs based on Promises. - * See 'Asynchronous programming in JavaScript' for more details - * http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx - * http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx - * Note. Functionality is limited, support of .then and .cancel methods only, other methods are in progress. - */ - constructor(); - static Deferral: typeof Deferral; - _completeCallbacks: Array<() => void>; - _errorCallbacks: Array<(error: any) => void>; - _progressCallbacks: Array<(progress: BackgroundDownloadProgress) => void>; - _chainedDefer: Deferral; - _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; - result: any; - then(onComplete?: () => void, onError?: (error: any) => void, onProgress?: (progress: BackgroundDownloadProgress) => void): BackgroundDownloadPromise; - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and - * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx - * @param flag - */ - cancel(flag?: boolean): void; - executeCallback(callback: (() => void) | ((error: any) => void) | ((progress: BackgroundDownloadProgress) => void), args: any): void; -} - -declare class Deferral { - constructor(); - resolve(data: any): void; - reject(error: any): void; - notify(value: any): void; - bind(promise: BackgroundDownloadPromise): void; -} From 8fcf35037f5ed17cf50c4ca6d09eb313e788e13a Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Thu, 31 Jan 2019 13:46:46 +0100 Subject: [PATCH 072/200] [node] correct SlowBuffer --- types/node/buffer.d.ts | 10 ++++++++-- types/node/globals.d.ts | 10 ---------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/types/node/buffer.d.ts b/types/node/buffer.d.ts index 86fdfdb36c..1d618f2c4b 100644 --- a/types/node/buffer.d.ts +++ b/types/node/buffer.d.ts @@ -1,6 +1,12 @@ declare module "buffer" { export const INSPECT_MAX_BYTES: number; const BuffType: typeof Buffer; - const SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; + + export const SlowBuffer: { + /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ + new(size: number): Buffer; + prototype: Buffer; + }; + + export { BuffType as Buffer }; } diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index e4f6f40fd1..f95386c9cd 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -249,16 +249,6 @@ declare var module: NodeModule; // Same as module.exports declare var exports: any; -declare const SlowBuffer: { - new(str: string, encoding?: string): Buffer; - new(size: number): Buffer; - new(size: Uint8Array): Buffer; - new(array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; -}; // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; From f97a9bdf813ada53361142f59240c1a3da42f5b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B8=D1=85=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2=20=D0=90?= =?UTF-8?q?=D0=BD=D1=82=D0=BE=D0=BD?= <anion155@gmail.com> Date: Tue, 5 Feb 2019 01:04:55 +0500 Subject: [PATCH 073/200] [react-intl] Fix: defineMessage autocomplete --- types/react-intl/index.d.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 33effbff95..9a0156b861 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -10,8 +10,9 @@ // Martin Raedlinger <https://github.com/formatlos> // Kanitkorn Sujautra <https://github.com/lukyth> // obedm503 <https://github.com/obedm503> +// anion155 <https://github.com/anion155> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.3 declare namespace ReactIntl { type DateSource = Date | string | number; @@ -35,11 +36,11 @@ declare namespace ReactIntl { function addLocaleData(data: Locale[] | Locale): void; - interface Messages { - [key: string]: FormattedMessage.MessageDescriptor; - } + type Messages<Names extends keyof any = string> = { + [key in Names]: FormattedMessage.MessageDescriptor; + }; - function defineMessages<T extends Messages>(messages: T): T; + function defineMessages<Names extends keyof any>(messages: Messages<Names>): Messages<Names>; interface IntlConfig { locale: React.Requireable<any>; From 23e4b5090b9b810b838be525456e226b9837a0c2 Mon Sep 17 00:00:00 2001 From: Bradley Hill <brad.hill@jostens.com> Date: Mon, 4 Feb 2019 14:35:18 -0600 Subject: [PATCH 074/200] Fabricjs missing pattern transform definitions --- types/fabric/fabric-impl.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 6a90a19481..1508148001 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -614,6 +614,10 @@ interface IPatternOptions { * The source for the pattern */ source: string | HTMLImageElement; + /** + * Transform matrix to change the pattern, imported from svgs + */ + patternTransform?: Array<number>; } export interface Pattern extends IPatternOptions { } export class Pattern { @@ -4638,6 +4642,11 @@ interface IUtilMisc { */ qrDecompose(a: number[]): { angle: number, scaleX: number, scaleY: number, skewX: number, skewY: number, translateX: number, translateY: number }; + /** + * Creates a transform matrix with the specified scale and skew + */ + customTransformMatrix(scaleX: number, scaleY: number, skewX: number): Array<number>; + /** * Returns string representation of function body * @param fn Function to get body of From 775f5f54c2a669314e7b75b1c0f1eec91988e44b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B8=D1=85=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2=20=D0=90?= =?UTF-8?q?=D0=BD=D1=82=D0=BE=D0=BD?= <anion155@gmail.com> Date: Tue, 5 Feb 2019 02:16:15 +0500 Subject: [PATCH 075/200] [react-intl] Revert ts version react-intl-redux is not happy with 3.3 --- types/react-intl/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 9a0156b861..60a647e744 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -12,7 +12,7 @@ // obedm503 <https://github.com/obedm503> // anion155 <https://github.com/anion155> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.3 +// TypeScript Version: 2.8 declare namespace ReactIntl { type DateSource = Date | string | number; From c8b7da0e192b340c4a72a88359d196a8c2079819 Mon Sep 17 00:00:00 2001 From: Anthony Dionise <dionisea@frib.msu.edu> Date: Mon, 4 Feb 2019 18:22:43 -0500 Subject: [PATCH 076/200] rename tests --- ...-tests.ts => connect-history-api-fallback-exclusions-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename types/connect-history-api-fallback-exclusions/{connect-history-api-fallback-tests.ts => connect-history-api-fallback-exclusions-tests.ts} (100%) diff --git a/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts b/types/connect-history-api-fallback-exclusions/connect-history-api-fallback-exclusions-tests.ts similarity index 100% rename from types/connect-history-api-fallback-exclusions/connect-history-api-fallback-tests.ts rename to types/connect-history-api-fallback-exclusions/connect-history-api-fallback-exclusions-tests.ts From 59984df37d57a7ca5cbd9aec26bce50f344840c3 Mon Sep 17 00:00:00 2001 From: Anthony Dionise <dionisea@frib.msu.edu> Date: Mon, 4 Feb 2019 18:29:10 -0500 Subject: [PATCH 077/200] tsconfig --- types/connect-history-api-fallback-exclusions/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/connect-history-api-fallback-exclusions/tsconfig.json b/types/connect-history-api-fallback-exclusions/tsconfig.json index ad8919e94e..1fc7fec2ca 100644 --- a/types/connect-history-api-fallback-exclusions/tsconfig.json +++ b/types/connect-history-api-fallback-exclusions/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "connect-history-api-fallback-tests.ts" + "connect-history-api-fallback-exclusions-tests.ts" ] } \ No newline at end of file From dacd441485616ed5c513252998def8d92b4245fc Mon Sep 17 00:00:00 2001 From: Anthony Dionise <dionisea@frib.msu.edu> Date: Mon, 4 Feb 2019 18:37:00 -0500 Subject: [PATCH 078/200] remove patch version --- types/connect-history-api-fallback-exclusions/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/connect-history-api-fallback-exclusions/index.d.ts b/types/connect-history-api-fallback-exclusions/index.d.ts index 19a48e0bab..fa69b20e17 100644 --- a/types/connect-history-api-fallback-exclusions/index.d.ts +++ b/types/connect-history-api-fallback-exclusions/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for connect-history-api-fallback-exclusions 1.5.1 +// Type definitions for connect-history-api-fallback-exclusions 1.5 // Project: https://github.com/Wirewheel/connect-history-api-fallback#readme // Definitions by: Tony Stone <https://github.com/tonystonee> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From ce19f8a19b9572016cc7e19757e2da9f8be8c5ed Mon Sep 17 00:00:00 2001 From: nossbigg <chenggibson@gmail.com> Date: Sat, 2 Feb 2019 23:48:00 +0800 Subject: [PATCH 079/200] [react-native] Enhance Keyboard API Event typings --- types/react-native/index.d.ts | 37 +++++++++++++++++++++++++++++++ types/react-native/test/index.tsx | 6 +++++ 2 files changed, 43 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 4b06119df2..2be1a48992 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -16,6 +16,7 @@ // Kacper Wiszczuk <https://github.com/esemesek> // Ryan Nickel <https://github.com/mrnickel> // Souvik Ghosh <https://github.com/souvik-ghosh> +// Cheng Gibson <https://github.com/nossbigg> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -8995,8 +8996,44 @@ export interface ARTStatic { Text: typeof ARTText; } +export type KeyboardEventName = + | "keyboardWillShow" + | "keyboardDidShow" + | "keyboardWillHide" + | "keyboardDidHide" + | "keyboardWillChangeFrame" + | "keyboardDidChangeFrame"; + +export type KeyboardEventEasing = + | "easeIn" + | "easeInEaseOut" + | "easeOut" + | "linear" + | "keyboard"; + +type ScreenRect = { + screenX: number; + screenY: number; + width: number; + height: number; +}; + +export interface KeyboardEvent { + duration: number; + easing: KeyboardEventEasing; + endCoordinates: ScreenRect; + startCoordinates: ScreenRect; + isEventFromThisApp: boolean; +} + +type KeyboardEventListener = (event: KeyboardEvent) => void; + export interface KeyboardStatic extends NativeEventEmitter { dismiss: () => void; + addListener( + eventType: KeyboardEventName, + listener: KeyboardEventListener + ): EmitterSubscription; } ////////////////////////////////////////////////////////////////////////// diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 801565dc8d..dfa327ce7b 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -85,6 +85,7 @@ import { DatePickerAndroid, ViewPropTypes, requireNativeComponent, + Keyboard, } from "react-native"; declare module "react-native" { @@ -843,3 +844,8 @@ const ShareTest = () => { } }); }; + +const KeyboardTest = () => { + const subscriber = Keyboard.addListener("keyboardDidHide", (event) => {event}); + subscriber.remove(); +} From 94ca48114444439f8e4bea0cfb451126c62c52a7 Mon Sep 17 00:00:00 2001 From: Kristoffer <hello@kristoffer.is> Date: Tue, 5 Feb 2019 10:44:22 +0100 Subject: [PATCH 080/200] libxmljs: Allow boolean options --- types/libxmljs/index.d.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index a29a6adeda..db37035f06 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -14,12 +14,15 @@ export const libxml_parser_version: string; // tslint:disable-next-line:strict-export-declare-modifiers interface StringMap { [key: string]: string; } -export function parseXml(source: string, options?: StringMap): Document; -export function parseXmlString(source: string, options?: StringMap): Document; +// tslint:disable-next-line:strict-export-declare-modifiers +interface ParserOptions { [key: string]: boolean | string; } -export function parseHtml(source: string, options?: StringMap): Document; -export function parseHtmlString(source: string, options?: StringMap): Document; -export function parseHtmlFragment(source: string, options?: StringMap): Document; +export function parseXml(source: string, options?: ParserOptions): Document; +export function parseXmlString(source: string, options?: ParserOptions): Document; + +export function parseHtml(source: string, options?: ParserOptions): Document; +export function parseHtmlString(source: string, options?: ParserOptions): Document; +export function parseHtmlFragment(source: string, options?: ParserOptions): Document; export function memoryUsage(): number; export function nodeCount(): number; From fa571007ef0139333283209c3e740351562cbb22 Mon Sep 17 00:00:00 2001 From: Satyajit Sahoo <satyajit.happy@gmail.com> Date: Wed, 9 Jan 2019 15:25:11 +0100 Subject: [PATCH 081/200] Update Expo APIs for SDK 32 --- types/expo/expo-tests.tsx | 16 +- types/expo/index.d.ts | 130 +- types/expo/v31/expo-tests.tsx | 1263 ++++++++++++ types/expo/v31/index.d.ts | 3606 +++++++++++++++++++++++++++++++++ types/expo/v31/tsconfig.json | 30 + types/expo/v31/tslint.json | 7 + 6 files changed, 5003 insertions(+), 49 deletions(-) create mode 100644 types/expo/v31/expo-tests.tsx create mode 100644 types/expo/v31/index.d.ts create mode 100644 types/expo/v31/tsconfig.json create mode 100644 types/expo/v31/tslint.json diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 12a88703c5..10045e57e6 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -21,6 +21,9 @@ import { Constants, Contacts, DocumentPicker, + EdgeInsets, + EdgePadding, + EventUserLocation, Facebook, FacebookAds, FaceDetector, @@ -30,29 +33,24 @@ import { ImagePicker, IntentLauncherAndroid, KeepAwake, + KmlMapEvent, LinearGradient, Linking, Location, MailComposer, + MapEvent, + MapStyleElement, MapView, MediaLibrary, Permissions, PublisherBanner, + Region, registerRootComponent, ScreenOrientation, SecureStore, Svg, Updates } from 'expo'; -import { - EdgeInsets, - EdgePadding, - EventUserLocation, - KmlMapEvent, - MapEvent, - MapStyleElement, - Region -} from 'react-native-maps'; const reverseGeocode: Promise<Location.GeocodeData[]> = Location.reverseGeocodeAsync({ latitude: 0, diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 591174c6e8..e0bb71f195 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for expo 31.0 +// Type definitions for expo 32.0 // Project: https://github.com/expo/expo-sdk // Definitions by: Konstantin Kai <https://github.com/KonstantinKai> // Martynas Kadiša <https://github.com/martynaskadisa> @@ -19,6 +19,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +export * from 'react-native-maps'; +export { default as MapView } from 'react-native-maps'; + import { EventSubscription } from 'fbemitter'; import { Component, ComponentClass, Ref, ComponentType } from 'react'; import { @@ -33,8 +36,6 @@ import { StyleProp } from 'react-native'; -export { default as MapView } from 'react-native-maps'; - export type Axis = number; export type BarCodeScannedCallback = (result: { type: string; data: string; }) => void; export type Md5 = string; @@ -2161,7 +2162,7 @@ export const Linking: LinkingStatic; */ export namespace Location { interface LocationOptions { - enableHighAccuracy?: boolean; + accuracy: number; timeInterval?: number; distanceInterval?: number; timeout?: number; @@ -2207,6 +2208,20 @@ export namespace Location { name: string; } + interface LocationTaskOptions { + accuracy?: number; + showsBackgroundLocationIndicator?: boolean; + } + + interface Region { + identifier?: string; + latitude: number; + longitude: number; + radius: number; + notifyOnEnter?: boolean; + notifyOnExit?: boolean; + } + type LocationCallback = (data: LocationData) => void; function getCurrentPositionAsync(options: LocationOptions): Promise<LocationData>; @@ -2216,6 +2231,14 @@ export namespace Location { function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; function geocodeAsync(address: string): Promise<Coords>; function reverseGeocodeAsync(location: LocationProps): Promise<GeocodeData[]>; + function requestPermissionsAsync(): Promise<void>; + function hasServicesEnabledAsync(): Promise<boolean>; + function startgeocodUpdatesAsync(taskName: string, options: LocationTaskOptions): Promise<void>; + function stopLocationUpdatesAsync(taskName: string): Promise<void>; + function hasStartedLocationUpdatesAsync(taskName: string): Promise<boolean>; + function startGeofencingAsync(taskName: string, regions: Region[]): Promise<void>; + function stopGeofencingAsync(taskName: string): Promise<void>; + function hasStartedGeofencingAsync(taskName: string): Promise<boolean>; function setApiKey(key: string): void; } @@ -2253,46 +2276,72 @@ export namespace Notifications { sound?: boolean }; android?: { - sound?: boolean; + channelId?: string; icon?: string; color?: string; - priority?: 'min' | 'low' | 'high' | 'max'; sticky?: boolean; - vibrate?: boolean | number[]; - link?: string; }; } - interface SchedulingOptions { - time: Date | number; - repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; - intervalMs?: number; - } - - interface ChannelAndroid { - name: string; - description?: string; - sound?: boolean; - priority?: 'min' | 'low' | 'default' | 'high' | 'max'; - vibrate?: boolean | number[]; - badge?: boolean; - } - type LocalNotificationId = string | number; - function addListener(listener: (notification: Notification) => any): EventSubscription; + interface Channel { + name: string; + description?: string; + priority?: string; + sound?: boolean; + vibrate?: boolean | number[]; + badge?: boolean; + } + + interface ActionType { + actionId: string; + buttonTitle: string; + isDestructive?: boolean; + isAuthenticationRequired?: boolean; + textInput?: { + submitButtonTitle: string; + placeholder: string; + }; + } + + function createCategoryAsync(categoryId: string, actions: ActionType[]): Promise<void>; + function deleteCategoryAsync(categoryId: string): Promise<void>; function getExpoPushTokenAsync(): Promise<string>; - function presentLocalNotificationAsync(localNotification: LocalNotification): Promise<LocalNotificationId>; - function scheduleLocalNotificationAsync( - localNotification: LocalNotification, - schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } - ): Promise<LocalNotificationId>; - function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise<void>; - function dismissAllNotificationsAsync(): Promise<void>; - function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise<void>; - function cancelAllScheduledNotificationsAsync(): Promise<void>; - function createChannelAndroidAsync(id: string, channel: ChannelAndroid): Promise<void>; + function getDevicePushTokenAsync(config: { + gcmSenderId?: string; + }): Promise<{ type: string; data: string }>; + function createChannelAndroidAsync(id: string, channel: Channel): Promise<void>; function deleteChannelAndroidAsync(id: string): Promise<void>; + + /* Shows a notification instantly */ + function presentLocalNotificationAsync( + notification: LocalNotification + ): Promise<LocalNotificationId>; + + /** Schedule a notification at a later date */ + function scheduleLocalNotificationAsync( + notification: LocalNotification, + options?: { + time?: Date | number; + repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + intervalMs?: number; + } + ): Promise<LocalNotificationId>; + + /** Dismiss currently shown notification with ID (Android only) */ + function dismissNotificationAsync(notificationId: LocalNotificationId): Promise<void>; + + /** Dismiss all currently shown notifications (Android only) */ + function dismissAllNotificationsAsync(): Promise<void>; + + /** Cancel scheduled notification notification with ID */ + function cancelScheduledNotificationAsync(notificationId: LocalNotificationId): Promise<void>; + + /** Cancel all scheduled notifications */ + function cancelAllScheduledNotificationsAsync(): Promise<void>; + + function addListener(listener: (notification: Notification) => any): EventSubscription; function getBadgeNumberAsync(): Promise<number>; function setBadgeNumberAsync(number: number): Promise<void>; } @@ -2651,13 +2700,14 @@ export class Svg extends Component<{ width: number, height: number, viewBox?: st * Take Snapshot */ export function takeSnapshotAsync( - view?: (number | React.ReactElement<any>), + node: number | React.ReactElement<any> | React.RefObject<any>, options?: { - width?: number, - height?: number, - format?: 'png' | 'jpg' | 'jpeg' | 'webm', - quality?: number, - result?: 'file' | 'base64' | 'data-uri', + width?: number; + height?: number; + format: 'png' | 'jpg' | 'raw' | 'webm'; + quality: number; + snapshotContentContainer: boolean; + result: "tmpfile" | "base64" | "data-uri" | "zip-base64"; } ): Promise<string>; diff --git a/types/expo/v31/expo-tests.tsx b/types/expo/v31/expo-tests.tsx new file mode 100644 index 0000000000..10045e57e6 --- /dev/null +++ b/types/expo/v31/expo-tests.tsx @@ -0,0 +1,1263 @@ +import * as React from 'react'; +import { Text } from 'react-native'; + +import { + Accelerometer, + AdMobAppEvent, + AdMobBanner, + AdMobInterstitial, + AdMobRewarded, + Amplitude, + AppLoading, + Asset, + Audio, + AuthSession, + BarCodeScanner, + BlurView, + Brightness, + Calendar, + Camera, + CameraObject, + Constants, + Contacts, + DocumentPicker, + EdgeInsets, + EdgePadding, + EventUserLocation, + Facebook, + FacebookAds, + FaceDetector, + FileSystem, + Haptic, + ImageManipulator, + ImagePicker, + IntentLauncherAndroid, + KeepAwake, + KmlMapEvent, + LinearGradient, + Linking, + Location, + MailComposer, + MapEvent, + MapStyleElement, + MapView, + MediaLibrary, + Permissions, + PublisherBanner, + Region, + registerRootComponent, + ScreenOrientation, + SecureStore, + Svg, + Updates +} from 'expo'; + +const reverseGeocode: Promise<Location.GeocodeData[]> = Location.reverseGeocodeAsync({ + latitude: 0, + longitude: 0 +}); + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +() => ( + <AdMobBanner + bannerSize="leaderboard" + adUnitID="ca-app-pub-3940256099942544/6300978111" + testDeviceID="EMULATOR" + didFailToReceiveAdWithError={(error: string) => console.log(error)} + style={{ flex: 1 }} + /> +); + +() => ( + <PublisherBanner + bannerSize="leaderboard" + adUnitID="ca-app-pub-3940256099942544/6300978111" + testDeviceID="EMULATOR" + didFailToReceiveAdWithError={(error: string) => console.log(error)} + onAdMobDispatchAppEvent={(event: AdMobAppEvent) => console.log(event)} + style={{ flex: 1 }} + /> +); + +AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/1033173712'); // Test ID, Replace with your-admob-unit-id +AdMobInterstitial.setTestDeviceID('EMULATOR'); +async () => { + await AdMobInterstitial.requestAdAsync(); + await AdMobInterstitial.showAdAsync(); +}; + +AdMobRewarded.setAdUnitID('ca-app-pub-3940256099942544/1033173712'); // Test ID, Replace with your-admob-unit-id +AdMobRewarded.setTestDeviceID('EMULATOR'); +async () => { + await AdMobRewarded.requestAdAsync(); + await AdMobRewarded.showAdAsync(); +}; + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', ['value']); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: undefined +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true, +}); +Audio.setIsEnabledAsync(true); + +Audio.INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS === 0; +Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS === 2; + +Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS === 2; + +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP === 1; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4 === 2; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB === 3; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB === 4; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF === 5; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS === 6; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP === 7; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS === 8; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM === 9; + +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB === 1; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB === 2; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC === 3; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC === 4; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD === 5; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS === 6; + +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM === 'lpcm'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3 === 'ac-3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3 === 'cac3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4 === 'ima4'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC === 'aac '; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP === 'celp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC === 'hvxc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ === 'twvq'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3 === 'MAC3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6 === 'MAC6'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW === 'ulaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW === 'alaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN === 'QDMC'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2 === 'QDM2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM === 'Qclp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1 === '.mp1'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2 === '.mp2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3 === '.mp3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS === 'alac'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE === 'aach'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD === 'aacl'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD === 'aace'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR === 'aacf'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2 === 'aacg'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2 === 'aacp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL === 'aacs'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR === 'samr'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB === 'sawb'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE === 'AUDB'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC === 'ilbc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA === 0x6d730011; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM === 0x6d730031; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3 === 'aes3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3 === 'ec-3'; + +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN === 0; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW === 0x20; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM === 0x40; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH === 0x60; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX === 0x7f; + +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT === 0; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE === 1; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED === 2; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3; + +Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY; +Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY; +async () => { + const result = await Audio.Sound.createAsync({uri: 'uri'}, { + volume: 0.55, + rate: 16.5 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync({uri: 'uri'}); +}; + +() => ( + <AppLoading + startAsync={() => Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + <AppLoading /> +); + +const barcodeReadCallback = () => {}; +() => ( + <BarCodeScanner + type="front" + torchMode="off" + barCodeTypes={[BarCodeScanner.Constants.BarCodeType.aztec]} + onBarCodeScanned={barcodeReadCallback} /> +); + +() => ( + <BlurView + tint="dark" + intensity={2} /> +); + +async () => { + await Brightness.setBrightnessAsync(0.65); + await Brightness.setSystemBrightnessAsync(0.75); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return(<Camera ref={(component: any) => { + if (component) { + component.recordAsync(); + } + }} />); +}; +async (camera: CameraObject) => { + const picture = await camera.takePictureAsync({ + quality: 0.5, + base64: true, + exif: true + }); + + picture.uri; + picture.width; + picture.height; + picture.exif; + picture.base64; + + camera.takePictureAsync({ + quality: 1, + onPictureSaved: pic => { + pic.uri; + pic.width; + pic.height; + pic.exif; + pic.base64; + } + }); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const { type, expires, token } = await Facebook.logInWithReadPermissionsAsync("appId"); +}; + +() => ( + <FacebookAds.BannerView + type="large" + placementId="str" + onPress={() => {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string: string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; +}; + +async () => { + // Video test + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Videos, + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + result.duration; + result.type; + } +}; + +async () => { + // Image test + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Images, + base64: true, + aspect: [4, 3], + quality: 1, + exif: true, + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + result.exif; + result.base64; + result.type; + } +}; + +async () => { + const result = await ImageManipulator.manipulateAsync('url', [ + { rotate: 90 }, + { resize: { width: 300 } }, + { resize: { height: 300 } }, + { resize: { height: 300, width: 300 } }, + ], { + compress: 0.75 + }); + + result.height; + result.uri; + result.width; +}; + +async () => { + const result = await ImageManipulator.manipulateAsync('url', [ + { rotate: 360 }, + { resize: { width: 300 } }, + { resize: { height: 300 } }, + { resize: { height: 300, width: 300 } }, + ], { + compress: 0.75 + }); + + result.height; + result.uri; + result.width; +}; + +FaceDetector.Constants.Mode.fast; +FaceDetector.Constants.Mode.accurate; +FaceDetector.Constants.Landmarks.all; +FaceDetector.Constants.Landmarks.none; +FaceDetector.Constants.Classifications.all; +FaceDetector.Constants.Classifications.none; +async () => { + const result = await FaceDetector.detectFaces('url', { + mode: FaceDetector.Constants.Mode.fast, + detectLandmarks: FaceDetector.Constants.Landmarks.all, + runClassifications: FaceDetector.Constants.Classifications.none + }); + + result.faces[0]; +}; + +async () => { + function isBoolean(x: boolean) { + } + function isString(x: string) { + } + // Two examples of members inherited from react-native Linking + // to prove that inheritence is working. + Linking.addEventListener('url', (e) => { + e.url === ''; + }); + isBoolean(await Linking.canOpenURL('expo://')); + + // Extensions added by expo. + + isString(Linking.makeUrl('path')); + isString(Linking.makeUrl('path', { q: 2, u: 'ery', })); + + const { + path, + queryParams, + } = Linking.parse(''); + isString(path); + isString(queryParams['x'] || ''); + + const { + path: path2, + queryParams: queryParams2, + } = await Linking.parseInitialURLAsync(); + isString(path2); + isString(queryParams2['y'] || ''); +}; + +// #region securestore +async () => { + await SecureStore.setItemAsync('some-key', 'some-val', { + keychainService: "some-service", + keychainAccessible: SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY, + }); + const result = await SecureStore.getItemAsync('some-key', { keychainService: "some-service" }); + if (result != null) { + result.slice() === 'some-val'; + } + await SecureStore.deleteItemAsync('some-key', { keychainService: "some-service" }); +}; + +const allSecureStoreKeychainAccessibleValues: number[] = [ + SecureStore.WHEN_UNLOCKED, + SecureStore.AFTER_FIRST_UNLOCK, + SecureStore.ALWAYS, + SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY, + SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY, + SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY, + SecureStore.ALWAYS_THIS_DEVICE_ONLY, +]; +// #endregion + +() => ( + <Svg width={100} height={50}> + <Svg.Rect + x={25} + y={5} + width={150} + height={50} + fill='rgb(0,0,255)' + strokeWidth={3} + stroke='rgb(0,0,0)' + transform="translate(0, 0)" + /> + <Svg.Circle + cx={50} + cy={50} + r={50} + fill="pink" + transform="translate(0, 0)" + /> + <Svg.Ellipse + cx={55} + cy={55} + rx={50} + ry={30} + stroke="purple" + strokeWidth={2} + fill="yellow" + transform="translate(0, 0)" + /> + <Svg.Line + x1={0} + y1={0} + x2={100} + y2={100} + stroke="red" + strokeWidth={2} + transform="translate(0, 0)" + /> + <Svg.Polygon + points="40,5 70,80 25,95" + fill="lime" + stroke="purple" + strokeWidth={1} + transform="translate(0, 0)" + /> + <Svg.Polyline + points="10,10 20,12 30,20 40,60 60,70 95,90" + fill="none" + stroke="black" + strokeWidth={3} + transform="translate(0, 0)" + /> + <Svg.Text + fill="none" + stroke="purple" + fontSize={20} + fontWeight="bold" + x={100} + y={20} + textAnchor="middle" + transform="translate(0, 0)" + > + STROKED TEXT + </Svg.Text> + <Svg.Defs> + <Svg.Path + id="path" + d="" + /> + </Svg.Defs> + <Svg.G transform="translate(0, 0)" y={20}> + <Svg.Text fill="blue" transform={{ translateX: 0, translateY: 0 }}> + <Svg.TextPath href="#path" startOffset="-10%"> + We go up and down, + <Svg.TSpan fill="red" dy="5,5,5">then up again</Svg.TSpan> + </Svg.TextPath> + </Svg.Text> + <Svg.Path + d="" + fill="none" + stroke="red" + strokeWidth={1} + /> + </Svg.G> + <Svg.Use href="#shape" transform="translate(0, 0)" x="20" y="0" /> + <Svg.Use href="#shape" transform={{ translateX: 0, translateY: 0 }} x="20" y="0" width="20" height="20"/> + <Svg.Symbol id="symbol" viewBox="0 0 150 110" width="100" height="50"> + <Svg.Circle cx="50" cy="50" r="40" strokeWidth="8" stroke="red" fill="red"/> + <Svg.Circle cx="90" cy="60" r="40" strokeWidth="8" stroke="green" fill="white"/> + </Svg.Symbol> + <Svg.Defs> + <Svg.ClipPath id="clip"> + <Svg.Circle cx="50%" cy="50%" r="40%"/> + </Svg.ClipPath> + <Svg.RadialGradient id="grad" cx="50%" cy="50%" rx="50%" ry="50%" fx="50%" fy="50%" gradientUnits="userSpaceOnUse"> + <Svg.Stop + offset="0%" + stopColor="#ff0" + stopOpacity="1" + /> + </Svg.RadialGradient> + <Svg.LinearGradient id="grad" x1="0" y1="0" x2="170" y2="0"> + <Svg.Stop offset="1" stopColor="red" stopOpacity="1" /> + </Svg.LinearGradient> + </Svg.Defs> + </Svg> +); + +() => ( + <Svg width={100} height={50} preserveAspectRatio="none" /> +); + +IntentLauncherAndroid.ACTION_ACCESSIBILITY_SETTINGS === 'android.settings.ACCESSIBILITY_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_REDACTION === 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; +IntentLauncherAndroid.ACTION_CONDITION_PROVIDER_SETTINGS === 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_LISTENER_SETTINGS === 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_PRINT_SETTINGS === 'android.settings.ACTION_PRINT_SETTINGS'; +IntentLauncherAndroid.ACTION_ADD_ACCOUNT_SETTINGS === 'android.settings.ADD_ACCOUNT_SETTINGS'; +IntentLauncherAndroid.ACTION_AIRPLANE_MODE_SETTINGS === 'android.settings.AIRPLANE_MODE_SETTINGS'; +IntentLauncherAndroid.ACTION_APN_SETTINGS === 'android.settings.APN_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DETAILS_SETTINGS === 'android.settings.APPLICATION_DETAILS_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DEVELOPMENT_SETTINGS === 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_SETTINGS === 'android.settings.APPLICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_SETTINGS === 'android.settings.APP_NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_OPS_SETTINGS === 'android.settings.APP_OPS_SETTINGS'; +IntentLauncherAndroid.ACTION_BATTERY_SAVER_SETTINGS === 'android.settings.BATTERY_SAVER_SETTINGS'; +IntentLauncherAndroid.ACTION_BLUETOOTH_SETTINGS === 'android.settings.BLUETOOTH_SETTINGS'; +IntentLauncherAndroid.ACTION_CAPTIONING_SETTINGS === 'android.settings.CAPTIONING_SETTINGS'; +IntentLauncherAndroid.ACTION_CAST_SETTINGS === 'android.settings.CAST_SETTINGS'; +IntentLauncherAndroid.ACTION_DATA_ROAMING_SETTINGS === 'android.settings.DATA_ROAMING_SETTINGS'; +IntentLauncherAndroid.ACTION_DATE_SETTINGS === 'android.settings.DATE_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_INFO_SETTINGS === 'android.settings.DEVICE_INFO_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_NAME === 'android.settings.DEVICE_NAME'; +IntentLauncherAndroid.ACTION_DISPLAY_SETTINGS === 'android.settings.DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_DREAM_SETTINGS === 'android.settings.DREAM_SETTINGS'; +IntentLauncherAndroid.ACTION_HARD_KEYBOARD_SETTINGS === 'android.settings.HARD_KEYBOARD_SETTINGS'; +IntentLauncherAndroid.ACTION_HOME_SETTINGS === 'android.settings.HOME_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS === 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS === 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SETTINGS === 'android.settings.INPUT_METHOD_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS === 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; +IntentLauncherAndroid.ACTION_INTERNAL_STORAGE_SETTINGS === 'android.settings.INTERNAL_STORAGE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCALE_SETTINGS === 'android.settings.LOCALE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCATION_SOURCE_SETTINGS === 'android.settings.LOCATION_SOURCE_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_DEFAULT_APPS_SETTINGS === 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; +IntentLauncherAndroid.ACTION_MEMORY_CARD_SETTINGS === 'android.settings.MEMORY_CARD_SETTINGS'; +IntentLauncherAndroid.ACTION_MONITORING_CERT_INFO === 'android.settings.MONITORING_CERT_INFO'; +IntentLauncherAndroid.ACTION_NETWORK_OPERATOR_SETTINGS === 'android.settings.NETWORK_OPERATOR_SETTINGS'; +IntentLauncherAndroid.ACTION_NFCSHARING_SETTINGS === 'android.settings.NFCSHARING_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_PAYMENT_SETTINGS === 'android.settings.NFC_PAYMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_SETTINGS === 'android.settings.NFC_SETTINGS'; +IntentLauncherAndroid.ACTION_NIGHT_DISPLAY_SETTINGS === 'android.settings.NIGHT_DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS === 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_SETTINGS === 'android.settings.NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_PAIRING_SETTINGS === 'android.settings.PAIRING_SETTINGS'; +IntentLauncherAndroid.ACTION_PRIVACY_SETTINGS === 'android.settings.PRIVACY_SETTINGS'; +IntentLauncherAndroid.ACTION_QUICK_LAUNCH_SETTINGS === 'android.settings.QUICK_LAUNCH_SETTINGS'; +IntentLauncherAndroid.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS === 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; +IntentLauncherAndroid.ACTION_SECURITY_SETTINGS === 'android.settings.SECURITY_SETTINGS'; +IntentLauncherAndroid.ACTION_SETTINGS === 'android.settings.SETTINGS'; +IntentLauncherAndroid.ACTION_SHOW_ADMIN_SUPPORT_DETAILS === 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; +IntentLauncherAndroid.ACTION_SHOW_INPUT_METHOD_PICKER === 'android.settings.SHOW_INPUT_METHOD_PICKER'; +IntentLauncherAndroid.ACTION_SHOW_REGULATORY_INFO === 'android.settings.SHOW_REGULATORY_INFO'; +IntentLauncherAndroid.ACTION_SHOW_REMOTE_BUGREPORT_DIALOG === 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; +IntentLauncherAndroid.ACTION_SOUND_SETTINGS === 'android.settings.SOUND_SETTINGS'; +IntentLauncherAndroid.ACTION_STORAGE_MANAGER_SETTINGS === 'android.settings.STORAGE_MANAGER_SETTINGS'; +IntentLauncherAndroid.ACTION_SYNC_SETTINGS === 'android.settings.SYNC_SETTINGS'; +IntentLauncherAndroid.ACTION_SYSTEM_UPDATE_SETTINGS === 'android.settings.SYSTEM_UPDATE_SETTINGS'; +IntentLauncherAndroid.ACTION_TETHER_PROVISIONING_UI === 'android.settings.TETHER_PROVISIONING_UI'; +IntentLauncherAndroid.ACTION_TRUSTED_CREDENTIALS_USER === 'android.settings.TRUSTED_CREDENTIALS_USER'; +IntentLauncherAndroid.ACTION_USAGE_ACCESS_SETTINGS === 'android.settings.USAGE_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_INSERT === 'android.settings.USER_DICTIONARY_INSERT'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_SETTINGS === 'android.settings.USER_DICTIONARY_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_SETTINGS === 'android.settings.USER_SETTINGS'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_AIRPLANE_MODE === 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE === 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE === 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; +IntentLauncherAndroid.ACTION_VOICE_INPUT_SETTINGS === 'android.settings.VOICE_INPUT_SETTINGS'; +IntentLauncherAndroid.ACTION_VPN_SETTINGS === 'android.settings.VPN_SETTINGS'; +IntentLauncherAndroid.ACTION_VR_LISTENER_SETTINGS === 'android.settings.VR_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_WEBVIEW_SETTINGS === 'android.settings.WEBVIEW_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_IP_SETTINGS === 'android.settings.WIFI_IP_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_SETTINGS === 'android.settings.WIFI_SETTINGS'; +IntentLauncherAndroid.ACTION_WIRELESS_SETTINGS === 'android.settings.WIRELESS_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_AUTOMATION_SETTINGS === 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EVENT_RULE_SETTINGS === 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS === 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_PRIORITY_SETTINGS === 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS === 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SETTINGS === 'android.settings.ZEN_MODE_SETTINGS'; + +KeepAwake.activate(); +KeepAwake.deactivate(); + +() => ( + <LinearGradient + colors={['#fff']} + start={[1, 1]} /> +); + +() => ( + <LinearGradient + colors={['#fff']} + style={{ flex: 1 }} /> +); + +Permissions.CAMERA === 'camera'; +Permissions.CAMERA_ROLL === 'cameraRoll'; +Permissions.AUDIO_RECORDING === 'audioRecording'; +Permissions.CONTACTS === 'contacts'; +Permissions.NOTIFICATIONS === 'notifications'; +Permissions.SYSTEM_BRIGHTNESS === 'systemBrightness'; +Permissions.USER_FACING_NOTIFICATIONS === 'userFacingNotifications'; +Permissions.REMINDERS === 'reminders'; +async () => { + const result = await Permissions.askAsync(Permissions.CAMERA, Permissions.CONTACTS); + + result.status === 'granted'; + result.status === 'denied'; + result.status === 'undetermined'; + + result.expires === 'never'; +}; + +ScreenOrientation.Orientation.ALL; +ScreenOrientation.allow(ScreenOrientation.Orientation.ALL); + +class __TestEntry__ extends React.Component { + render() { + return( + <Text>test</Text> + ); + } +} +registerRootComponent(__TestEntry__); + +Calendar.EntityTypes.EVENT === 'event'; +Calendar.EntityTypes.REMINDER === 'reminder'; + +Calendar.CalendarType.LOCAL === 'local'; +Calendar.CalendarType.CALDAV === 'caldav'; +Calendar.CalendarType.EXCHANGE === 'exchange'; +Calendar.CalendarType.SUBSCRIBED === 'subscribed'; +Calendar.CalendarType.BIRTHDAYS === 'birthdays'; + +async () => { + const result = await Calendar.getCalendarsAsync(Calendar.EntityTypes.EVENT); + result.length; + + const calendar = result[0]; + calendar.id === ''; + calendar.title === ''; + calendar.sourceId === ''; + calendar.type === Calendar.CalendarType.BIRTHDAYS; + calendar.color === ''; + calendar.entityType === Calendar.EntityTypes.EVENT; + calendar.allowsModifications === true; + calendar.allowedAvailabilities === ['']; + calendar.isPrimary === true; + calendar.name === ''; + calendar.ownerAccount === ''; + calendar.timeZone === ''; + calendar.allowedReminders === ['']; + calendar.allowedAttendeeTypes === ['']; + calendar.isVisible === false; + calendar.isSynced === false; + calendar.accessLevel === Calendar.CalendarAccessLevel.CONTRIBUTOR; + + if (calendar.source) { + calendar.source.id === ''; + calendar.source.type === ''; + calendar.source.name === ''; + calendar.source.isLocalAccount === false; + } + + const id1 = await Calendar.createCalendarAsync({ + accessLevel: Calendar.CalendarAccessLevel.EDITOR + }); + + id1 === ''; + + const id2 = await Calendar.updateCalendarAsync('1234', { + isVisible: false + }); + + id2 === ''; + + const id3 = await Calendar.updateCalendarAsync('1234', null); + + await Calendar.deleteCalendarAsync('1234'); + + const events = await Calendar.getEventsAsync( + ['123', '124'], + new Date(), + new Date() + ); + + const event1 = events[0]; + + event1.accessLevel === Calendar.EventAccessLevel.CONFIDENTIAL; + event1.alarms === []; + event1.allDay === true; + event1.availability === Calendar.Availability.FREE; + event1.calendarId === ''; + event1.creationDate === ''; + event1.endDate === ''; + event1.endTimeZone === ''; + event1.guestsCanInviteOthers === true; + event1.guestsCanModify === true; + event1.guestsCanSeeGuests === false; + event1.id === ''; + event1.instanceId === ''; + event1.isDetached === false; + + const event2 = await Calendar.getEventAsync('123', { + futureEvents: true + }); + + const eventId1 = await Calendar.createEventAsync('123'); + + const eventId2 = await Calendar.updateEventAsync('1234'); + + await Calendar.deleteEventAsync('1234'); + + const attendees = await Calendar.getAttendeesForEventAsync('123'); + + const aId1 = await Calendar.createAttendeeAsync('123'); + + const aId2 = await Calendar.updateAttendeeAsync('123'); + + await Calendar.deleteAttendeeAsync('123'); + + const reminders = await Calendar.getRemindersAsync(['123']); + + const reminder = await Calendar.getReminderAsync('123'); + + const remId1 = await Calendar.createReminderAsync('123'); + + const remId2 = await Calendar.updateReminderAsync('123'); + + await Calendar.deleteReminderAsync('123'); + + const sources = await Calendar.getSourcesAsync(); + + const source = await Calendar.getSourceAsync('123'); + + Calendar.openEventInCalendar('123'); +}; + +async () => { + const result = await MailComposer.composeAsync({ + subject: 'sss' + }); + + result.status === 'saved'; +}; + +// #region MapView +const initialRegion: Region = { + latitude: 0, + longitude: 0, + latitudeDelta: 0, + longitudeDelta: 0, +}; + +const edgePadding: EdgePadding = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const edgeInsets: EdgeInsets = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const mapStyleElements: MapStyleElement[] = [{ + featureType: 'featureType', + elementType: 'elementType', + stylers: [{}, {}], +}]; + +const mapEventCallback = (event: MapEvent) => console.log(event); +const regionCallback = (region: Region) => console.log(region); +const kmlCallback = (kml: KmlMapEvent) => console.log(kml); +const userLocationCallback = (event: EventUserLocation) => console.log(event); + +() => ( + <MapView + provider="google" + customMapStyle={mapStyleElements} + customMapStyleString="some-string" + showsUserLocation={true} + userLocationAnnotationTitle="title" + showsMyLocationButton={true} + followsUserLocation={true} + showsPointsOfInterest={true} + showsCompass={true} + zoomEnabled={true} + zoomControlEnabled={true} + rotateEnabled={true} + cacheEnabled={true} + loadingEnabled={true} + loadingBackgroundColor="#000" + loadingIndicatorColor="#000" + scrollEnabled={true} + pitchEnabled={true} + toolbarEnabled={true} + moveOnMarkerPress={true} + showsScale={true} + showsBuildings={true} + showsTraffic={true} + showsIndoors={true} + showsIndoorLevelPicker={true} + mapType="standard" + region={initialRegion} + initialRegion={initialRegion} + liteMode={true} + mapPadding={edgePadding} + maxDelta={0} + minDelta={0} + legalLabelInsets={edgeInsets} + + onMapReady={() => ({})} + onKmlReady={kmlCallback} + onRegionChange={regionCallback} + onRegionChangeComplete={regionCallback} + onPress={mapEventCallback} + onLongPress={mapEventCallback} + onUserLocationChange={userLocationCallback} + onPanDrag={mapEventCallback} + onPoiClick={(event: MapEvent<{ placeId: string, name: string }>) => console.log(event)} + onMarkerPress={(event: MapEvent<{ action: 'marker-press', id: string }>) => console.log(event)} + onMarkerSelect={(event: MapEvent<{ action: 'marker-select', id: string }>) => console.log(event)} + onMarkerDeselect={(event: MapEvent<{ action: 'marker-deselect', id: string }>) => console.log(event)} + onCalloutPress={(event: MapEvent<{ action: 'callout-press' }>) => console.log(event)} + onMarkerDragStart={mapEventCallback} + onMarkerDrag={mapEventCallback} + onMarkerDragEnd={mapEventCallback} + + minZoomLevel={0} + maxZoomLevel={0} + kmlSrc="src" + style={{ flex: 1 }} + /> +); +// #endregion + +async () => { + const updateEventListener: Updates.UpdateEventListener = ({ type }) => { + switch (type) { + case Updates.EventType.DOWNLOAD_STARTED: + case Updates.EventType.DOWNLOAD_PROGRESS: + case Updates.EventType.DOWNLOAD_FINISHED: + case Updates.EventType.NO_UPDATE_AVAILABLE: + case Updates.EventType.ERROR: + return true; + } + }; + + Updates.reload(); + + Updates.reloadFromCache(); + + Updates.addListener(updateEventListener); + + const updateCheckResult = await Updates.checkForUpdateAsync(); + + if (updateCheckResult.isAvailable) { + console.log(updateCheckResult.manifest); + } + + Updates.fetchUpdateAsync({ eventListener: updateEventListener }); + + const bundleFetchResult = await Updates.fetchUpdateAsync(); + + if (bundleFetchResult.isNew) { + console.log(bundleFetchResult.manifest); + } +}; + +async () => { + const asset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('some-url'); + const getAssetsOptions: MediaLibrary.GetAssetsOptions = { + first: 0, + after: 'lastAssetId', + album: 'albumId', + sortBy: MediaLibrary.SortBy.creationTime, + mediaType: MediaLibrary.MediaType.photo + }; + const assetsList: MediaLibrary.GetAssetsResult = await MediaLibrary.getAssetsAsync(getAssetsOptions); + const endCursor: string = assetsList.endCursor; + const hasNextPage: boolean = assetsList.hasNextPage; + const totalCount: number = assetsList.totalCount; + const asset1: MediaLibrary.Asset = await MediaLibrary.getAssetInfoAsync(asset); + if (await MediaLibrary.deleteAssetsAsync(assetsList.assets)) { + console.log('assets deleted'); + } + const albums: MediaLibrary.Album[] = await MediaLibrary.getAlbumsAsync(); + const album: MediaLibrary.Album | null = await MediaLibrary.getAlbumAsync('albumName'); + const album1: MediaLibrary.Album = await MediaLibrary.createAlbumAsync('albumName', asset1); + if (await MediaLibrary.addAssetsToAlbumAsync([asset, asset1], album1, true)) { + console.log('assets added'); + } + + const moments: MediaLibrary.Album[] = await MediaLibrary.getMomentsAsync(); + + switch (getAssetsOptions.mediaType) { + case MediaLibrary.MediaType.audio: + case MediaLibrary.MediaType.photo: + case MediaLibrary.MediaType.video: + case MediaLibrary.MediaType.unknow: + return true; + } + + switch (getAssetsOptions.sortBy) { + case MediaLibrary.SortBy.default: + case MediaLibrary.SortBy.id: + case MediaLibrary.SortBy.creationTime: + case MediaLibrary.SortBy.modificationTime: + case MediaLibrary.SortBy.mediaType: + case MediaLibrary.SortBy.width: + case MediaLibrary.SortBy.height: + case MediaLibrary.SortBy.duration: + return true; + } +}; + +// #region MediaLibrary +async () => { + const mlAsset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('localUri'); + const mlAssetResult: MediaLibrary.GetAssetsResult = await MediaLibrary.getAssetsAsync({ + first: 0, + after: '', + album: 'Album', + sortBy: MediaLibrary.SortBy.creationTime, + mediaType: MediaLibrary.MediaType.photo + }); + const mlAsset1: MediaLibrary.Asset = await MediaLibrary.getAssetInfoAsync(mlAsset); + const areDeleted: boolean = await MediaLibrary.deleteAssetsAsync([mlAsset]); + const albums: MediaLibrary.Album[] = await MediaLibrary.getAlbumsAsync(); + const album: MediaLibrary.Album = await MediaLibrary.getAlbumAsync('album'); + const album1: MediaLibrary.Album = await MediaLibrary.createAlbumAsync('album', mlAsset); + const areAddedToAlbum: boolean = await MediaLibrary.addAssetsToAlbumAsync([mlAsset, mlAsset1], 'album'); + const areDeletedFromAlbum: boolean = await MediaLibrary.removeAssetsFromAlbumAsync([mlAsset, mlAsset1], 'album'); + const momuents: MediaLibrary.Album[] = await MediaLibrary.getMomentsAsync(); +}; +//#endregion + +// #region Haptic +Haptic.impact(Haptic.ImpactStyles.Heavy); +Haptic.impact(Haptic.ImpactStyles.Light); +Haptic.impact(Haptic.ImpactStyles.Medium); + +Haptic.notification(Haptic.NotificationType.Error); +Haptic.notification(Haptic.NotificationType.Success); +Haptic.notification(Haptic.NotificationType.Error); + +Haptic.selection(); +// #endregion + +// #region Constants +async () => { + const appOwnerShip = Constants.appOwnership; + const expoVersion = Constants.expoVersion; + const installationId = Constants.installationId; + const deviceId = Constants.deviceId; + const deviceName = Constants.deviceName; + const deviceYearClass = Constants.deviceYearClass; + const isDevice = Constants.isDevice; + const platform = Constants.platform; + const sessionId = Constants.sessionId; + const statusBarHeight = Constants.statusBarHeight; + const systemFonts = Constants.systemFonts; + const manifest = Constants.manifest; + const linkingUri = Constants.linkingUri; + const userAgent: string = await Constants.getWebViewUserAgentAsync(); +}; +// #endregion + +// #region Contacts +Contacts.Fields.ID === 'id'; +Contacts.Fields.Name === 'name'; +Contacts.Fields.FirstName === 'firstName'; +Contacts.Fields.MiddleName === 'middleName'; +Contacts.Fields.LastName === 'lastName'; +Contacts.Fields.NamePrefix === 'namePrefix'; +Contacts.Fields.NameSuffix === 'nameSuffix'; +Contacts.Fields.PhoneticFirstName === 'phoneticFirstName'; +Contacts.Fields.PhoneticMiddleName === 'phoneticMiddleName'; +Contacts.Fields.PhoneticLastName === 'phoneticLastName'; +Contacts.Fields.Birthday === 'birthday'; +Contacts.Fields.Emails === 'emails'; +Contacts.Fields.PhoneNumbers === 'phoneNumbers'; +Contacts.Fields.Addresses === 'addresses'; +Contacts.Fields.InstantMessageAddresses === 'instantMessageAddresses'; +Contacts.Fields.UrlAddresses === 'urlAddresses'; +Contacts.Fields.Company === 'company'; +Contacts.Fields.JobTitle === 'jobTitle'; +Contacts.Fields.Department === 'department'; +Contacts.Fields.ImageAvailable === 'imageAvailable'; +Contacts.Fields.Image === 'image'; +Contacts.Fields.Note === 'note'; +Contacts.Fields.Dates === 'dates'; +Contacts.Fields.Relationships === 'relationships'; +Contacts.Fields.Nickname === 'nickname'; +Contacts.Fields.RawImage === 'rawImage'; +Contacts.Fields.MaidenName === 'maidenName'; +Contacts.Fields.ContactType === 'contactType'; +Contacts.Fields.SocialProfiles === 'socialProfiles'; +Contacts.Fields.NonGregorianBirthday === 'nonGregorianBirthday'; + +const contact: Contacts.Contact = { + [Contacts.Fields.ID]: 'id', + [Contacts.Fields.Name]: 'name', + [Contacts.Fields.FirstName]: 'firstName', + [Contacts.Fields.MiddleName]: 'middleName', + [Contacts.Fields.LastName]: 'lastName', + [Contacts.Fields.NamePrefix]: 'namePrefix', + [Contacts.Fields.NameSuffix]: 'nameSuffix', + [Contacts.Fields.PhoneticFirstName]: 'phoneticFirstName', + [Contacts.Fields.PhoneticMiddleName]: 'phoneticMiddleName', + [Contacts.Fields.PhoneticLastName]: 'phoneticLastName', + [Contacts.Fields.Birthday]: { + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Gregorian, + id: 'id', + label: 'label' + }, + [Contacts.Fields.Emails]: [{ + email: 'email', + isPrimary: true, + id: 'id', + label: 'label' + }], + [Contacts.Fields.PhoneNumbers]: [{ + number: 'number', + isPrimary: true, + digits: 'digits', + countryCode: 'countryCode', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Addresses]: [{ + street: 'street', + city: 'city', + country: 'country', + region: 'region', + neighborhood: 'neighborhood', + postalCode: 'postalCode', + poBox: 'poBox', + isoCountryCode: 'isoCountryCode', + id: 'id', + label: 'label' + }], + [Contacts.Fields.InstantMessageAddresses]: [{ + service: 'service', + username: 'username', + localizedProfile: 'localizedProfile', + id: 'id', + label: 'label' + }], + [Contacts.Fields.UrlAddresses]: [{ + url: 'url', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Company]: 'company', + [Contacts.Fields.JobTitle]: 'jobTitle', + [Contacts.Fields.Department]: 'department', + [Contacts.Fields.ImageAvailable]: true, + [Contacts.Fields.Image]: { + uri: 'uri' + }, + [Contacts.Fields.Note]: 'note', + [Contacts.Fields.Dates]: [{ + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Gregorian, + id: 'id', + label: 'label' + }], + [Contacts.Fields.Relationships]: [{ + name: 'name', + id: 'id', + label: 'label' + }], + [Contacts.Fields.Nickname]: 'nickname', + [Contacts.Fields.RawImage]: { + uri: 'uri' + }, + [Contacts.Fields.MaidenName]: 'maidenName', + [Contacts.Fields.ContactType]: Contacts.ContactTypes.Person, + [Contacts.Fields.SocialProfiles]: [{ + service: 'service', + username: 'username', + localizedProfile: 'localizedProfile', + url: 'url', + userId: 'userId', + id: 'id', + label: 'label' + }], + [Contacts.Fields.NonGregorianBirthday]: { + day: 1, + month: 1, + year: 2010, + format: Contacts.CalendarFormats.Hebrew, + id: 'id', + label: 'label' + } +}; + +async () => { + const response1: Contacts.ContactResponse = await Contacts.getContactsAsync(); + const response2: Contacts.ContactResponse = await Contacts.getContactsAsync({ id: 'contactId' }); + + const response3: Contacts.Contact = await Contacts.getContactByIdAsync('contactId'); + const response4: Contacts.Contact = await Contacts.getContactByIdAsync('contactId', [Contacts.Fields.Name]); + + const response5: string = await Contacts.addContactAsync(contact); + const response6: string = await Contacts.addContactAsync(contact, 'containerId'); + + const response7: string = await Contacts.updateContactAsync(contact); + await Contacts.removeContactAsync('contactId'); + const response8: string = await Contacts.writeContactToFileAsync({ id: 'contactId' }); + await Contacts.presentFormAsync('contactId'); + await Contacts.addExistingGroupToContainerAsync('groupId', 'containerId'); + + const response9: string = await Contacts.createGroupAsync('groupId'); + const response10: string = await Contacts.createGroupAsync('groupId', 'containerId'); + + await Contacts.updateGroupNameAsync('groupName', 'groupId'); + await Contacts.removeGroupAsync('groupId'); + await Contacts.addExistingContactToGroupAsync('contactId', 'groupId'); + await Contacts.removeContactFromGroupAsync('contactId', 'groupId'); + + const response11 = await Contacts.getGroupsAsync({ groupName: 'groupName' }); + response11.forEach((_: Contacts.Group) => _); + + const response12: string = await Contacts.getDefaultContainerIdAsync(); + + const response13 = await Contacts.getContainersAsync({ containerId: 'containerId' }); + response13.forEach((_: Contacts.Container) => _); +}; +// #endregion diff --git a/types/expo/v31/index.d.ts b/types/expo/v31/index.d.ts new file mode 100644 index 0000000000..5f560a8546 --- /dev/null +++ b/types/expo/v31/index.d.ts @@ -0,0 +1,3606 @@ +// Type definitions for expo 31.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai <https://github.com/KonstantinKai> +// Martynas Kadiša <https://github.com/martynaskadisa> +// Jan Aagaard <https://github.com/janaagaard75> +// Sergio Sánchez <https://github.com/ssanchezmarc> +// Fernando Helwanger <https://github.com/fhelwanger> +// Umidbek Karimov <https://github.com/umidbekkarimov> +// Moshe Feuchtwanger <https://github.com/moshfeu> +// Michael Prokopchuk <https://github.com/prokopcm> +// Tina Roh <https://github.com/tinaroh> +// Nathan Phillip Brink <https://github.com/binki> +// Martin Olsson <https://github.com/mo> +// Levan Basharuli <https://github.com/levansuper> +// Pavel Ihm <https://github.com/ihmpavel> +// Bartosz Dotryw <https://github.com/burtek> +// Jason Killian <https://github.com/jkillian> +// Satyajit Sahoo <https://github.com/satya164> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export * from 'react-native-maps'; +export { default as MapView } from 'react-native-maps'; + +import { EventSubscription } from 'fbemitter'; +import { Component, ComponentClass, Ref, ComponentType } from 'react'; +import { + ColorPropType, + ImageRequireSource, + ImageURISource, + LinkingStatic as ReactNativeLinkingStatic, + NativeEventEmitter, + ViewProps, + ViewStyle, + Permission, + StyleProp +} from 'react-native'; + +export type Axis = number; +export type BarCodeScannedCallback = (result: { type: string; data: string; }) => void; +export type Md5 = string; +export type Orientation = 'portrait' | 'landscape'; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type URISource = ImageURISource; + +export interface HashMap { [key: string]: any; } +export interface StringHashMap { [key: string]: string; } + +/** Access the device accelerometer sensor(s) to respond to changes in acceleration in 3d space. */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** + * Subscribe for updates to the accelerometer. + * @param listener A callback that is invoked when an accelerometer update is available. When invoked, the listener is provided a single argumument that is an object containing keys x, y, z. + * @returns An EventSubscription object that you can call remove() on when you would like to unsubscribe the listener. + */ + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** + * Subscribe for updates to the accelerometer. + * @param intervalMs Desired interval in milliseconds between accelerometer updates. + */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Admob + */ +export type AdMobBannerSize = + | 'banner' + | 'largeBanner' + | 'mediumRectangle' + | 'fullBanner' + | 'leaderboard' + | 'smartBannerPortrait' + | 'smartBannerLandscape'; +export interface AdMobBannerProperties extends ViewProps { + bannerSize?: AdMobBannerSize; + adUnitID?: string; + testDeviceID?: string; + didFailToReceiveAdWithError?(errorDescription: string): void; + adViewDidReceiveAd?(): void; + adViewWillPresentScreen?(): void; + adViewWillDismissScreen?(): void; + adViewDidDismissScreen?(): void; + adViewWillLeaveApplication?(): void; +} + +export class AdMobBanner extends Component<AdMobBannerProperties> { } +export interface AdMobAppEvent { + name: string; + info: string; +} +export interface PublisherBannerProperties extends AdMobBannerProperties { + onAdMobDispatchAppEvent?(event: AdMobAppEvent): void; +} +export class PublisherBanner extends Component<PublisherBannerProperties> { } + +export type AdMobInterstitialEmptyEvent = + | 'interstitialDidLoad' + | 'interstitialDidOpen' + | 'interstitialDidClose' + | 'interstitialWillLeaveApplication'; +export type AdMobInterstitialEvent = AdMobInterstitialEmptyEvent | 'interstitialDidFailToLoad'; +export namespace AdMobInterstitial { + function setAdUnitID(id: string): void; + function setTestDeviceID(id: string): void; + function requestAdAsync(): Promise<void>; + function showAdAsync(): Promise<void>; + function dismissAdAsync(): Promise<void>; + function getIsReadyAsync(): Promise<boolean>; + function addEventListener(event: 'interstitialDidFailToLoad', handler: (error: string) => void): void; + function addEventListener(event: AdMobInterstitialEmptyEvent, handler: () => void): void; + function removeEventListener(event: 'interstitialDidFailToLoad', handler: (error: string) => void): void; + function removeEventListener(event: AdMobInterstitialEmptyEvent, handler: () => void): void; + function removeAllListeners(): void; +} + +export type AdMobRewardedEmptyEvent = + | 'rewardedVideoDidLoad' + | 'rewardedVideoDidOpen' + | 'rewardedVideoDidStart' + | 'rewardedVideoDidClose' + | 'rewardedVideoWillLeaveApplication'; +export type AdMobRewardedEvent = AdMobRewardedEmptyEvent | 'rewardedVideoDidRewardUser' | 'rewardedVideoDidFailToLoad'; +export namespace AdMobRewarded { + function setAdUnitID(id: string): void; + function setTestDeviceID(id: string): void; + function requestAdAsync(): Promise<void>; + function showAdAsync(): Promise<void>; + function dismissAdAsync(): Promise<void>; + function getIsReadyAsync(): Promise<boolean>; + function addEventListener(event: 'rewardedVideoDidRewardUser', handler: (type: string, amount: number) => void): void; + function addEventListener(event: 'rewardedVideoDidFailToLoad', handler: (error: string) => void): void; + function addEventListener(event: AdMobRewardedEmptyEvent, handler: () => void): void; + function removeEventListener(event: 'rewardedVideoDidRewardUser', handler: (type: string, amount: number) => void): void; + function removeEventListener(event: 'rewardedVideoDidFailToLoad', handler: (error: string) => void): void; + function removeEventListener(event: AdMobRewardedEmptyEvent, handler: () => void): void; + function removeAllListeners(): void; +} + +/** + * Provides access to Amplitude mobile analytics which basically lets you log various events to the Cloud. This module wraps Amplitude’s iOS and Android SDKs. + * + * Note: Session tracking may not work correctly when running Experiences in the main Expo app. It will work correctly if you create a standalone app. + */ +export namespace Amplitude { + /** Initializes Amplitude with your Amplitude API key. */ + function initialize(apiKey: string): void; + + /** Assign a user ID to the current user. If you don’t have a system for user IDs you don’t need to call this. */ + function setUserId(userId: string): void; + + /** Set properties for the current user. */ + function setUserProperties(userProperties: HashMap): void; + + /** Clear properties set by `setUserProperties()`. */ + function clearUserProperties(): void; + + /** Log an event to Amplitude. */ + function logEvent(eventName: string): void; + + /** Log an event to Amplitude with custom properties. */ + function logEventWithProperties( + eventName: string, + + /** A map of custom properties. */ + properties: HashMap + ): void; + + /** Add the current user to a group. */ + function setGroup( + /** The group name, e.g. `'sports'`. */ + groupType: string, + + /** An array of group names, e.g. `['tennis', 'soccer']`. */ + groupNames: string[] + ): void; +} + +// #region AppLoading +/** The following props are recommended, but optional for the sake of backwards compatibility (they were introduced in SDK21). If you do not provide any props, you are responsible for coordinating loading assets, handling errors, and updating state to unmount the `AppLoading` component. */ +export interface AppLoadingProps { + /** A `function` that returns a `Promise`. The `Promise` should resolve when the app is done loading data and assets. */ + startAsync?: () => Promise<void>; + + /** Required if you provide `startAsync`. Called when `startAsync` resolves or rejects. This should be used to set state and unmount the `AppLoading` component. */ + onFinish?: () => void; + + /** If `startAsync` throws an error, it is caught and passed into the function provided to `onError`. */ + onError?: (error: Error) => void; +} + +/** + * A React component that tells Expo to keep the app loading screen open if it is the first and only component rendered in your app. When it is removed, the loading screen will disappear and your app will be visible. + * + * This is incredibly useful to let you download and cache fonts, logo and icon images and other assets that you want to be sure the user has on their device for an optimal experience before rendering they start using the app. + */ +export class AppLoading extends Component<AppLoadingProps> { } +// #endregion AppLoading + +/** This module provides an interface to Expo’s asset system. An asset is any file that lives alongside the source code of your app that the app needs at runtime. Examples include images, fonts and sounds. Expo’s asset system integrates with React Native’s, so that you can refer to files with require('path/to/file'). This is how you refer to static image files in React Native for use in an Image component, for example. */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + + /** The MD5 hash of the asset’s data. */ + hash: Md5; + + /** The name of the asset file without the extension. Also without the part from @ onward in the filename (used to specify scale factor for images). */ + name: string; + + /** The extension of the asset filename. */ + type: string; + + /** A URI that points to the asset’s data on the remote server. When running the published version of your app, this refers to the the location on Expo’s asset server where Expo has stored your asset. When running the app from XDE during development, this URI points to XDE’s server running on your computer and the asset is served directly from your computer. */ + uri: string; + + /** If the asset has been downloaded (by calling `downloadAsync()`), the `file://` URI pointing to the local file on the device that contains the asset data. */ + localUri: string; + + /** If the asset is an image, the width of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + width?: number; + + /** If the asset is an image, the height of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + /** Downloads the asset data to a local file in the device’s cache directory. Once the returned promise is fulfilled without error, the localUri field of this asset points to a local file containing the asset data. The asset is only downloaded if an up-to-date local file for the asset isn’t already present due to an earlier download. */ + downloadAsync(): Promise<void>; + + /** Returns the `Expo.Asset` instance representing an asset given its module. */ + static fromModule(module: RequireSource): Asset; + + /** + * A helper that wraps `Expo.Asset.fromModule(module).downloadAsync` for convenience. + * @param moduleIds An array of `require('path/to/file')`. Can also be just one module without an Array. + */ + static loadAsync(module: RequireSource[] | RequireSource): Promise<void>; +} + +/** + * Provides basic sample playback and recording. + * + * Note that Expo does not yet support backgrounding, so audio is not available to play in the background of your experience. Audio also automatically stops if headphones / bluetooth audio devices are disconnected. + */ +export namespace Audio { + enum InterruptionModeIos { + /** This is the default option. If this option is set, your experience’s audio is mixed with audio playing in background apps. */ + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + + /** If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS: 0; + const INTERRUPTION_MODE_IOS_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_IOS_DUCK_OTHERS: 2; + + enum InterruptionModeAndroid { + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + + /** This is the default option. If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_ANDROID_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_ANDROID_DUCK_OTHERS: 2; + + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP: 1; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4: 2; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB: 3; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB: 4; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF: 5; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS: 6; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP: 7; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS: 8; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM: 9; + + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB: 1; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB: 2; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC: 3; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC: 4; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD: 5; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS: 6; + + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM: 'lpcm'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3: 'ac-3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3: 'cac3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4: 'ima4'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC: 'aac '; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP: 'celp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC: 'hvxc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ: 'twvq'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3: 'MAC3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6: 'MAC6'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW: 'ulaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW: 'alaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN: 'QDMC'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2: 'QDM2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM: 'Qclp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1: '.mp1'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2: '.mp2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3: '.mp3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS: 'alac'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE: 'aach'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD: 'aacl'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD: 'aace'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR: 'aacf'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2: 'aacg'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2: 'aacp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL: 'aacs'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR: 'samr'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB: 'sawb'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE: 'AUDB'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC: 'ilbc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA: 0x6d730011; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM: 0x6d730031; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3: 'aes3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3: 'ec-3'; + + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN: 0; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW: 0x20; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM: 0x40; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH: 0x60; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX: 0x7f; + + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT: 0; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE: 1; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED: 2; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE: 3; + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + const RECORDING_OPTIONS_PRESET_HIGH_QUALITY: RecordingOptions; + const RECORDING_OPTIONS_PRESET_LOW_QUALITY: RecordingOptions; + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + interface AudioMode { + /** Boolean selecting if your experience’s audio should play in silent mode on iOS. This value defaults to `false`. */ + playsInSilentModeIOS: boolean; + + /** Boolean selecting if recording is enabled on iOS. This value defaults to `false`. NOTE: when this flag is set to true, playback may be routed to the phone receiver instead of to the speaker. */ + allowsRecordingIOS: boolean; + + /** Enum selecting how your experience’s audio should interact with the audio from other apps on iOS. */ + interruptionModeIOS: InterruptionModeIos; + + /** Boolean selecting if your experience’s audio should automatically be lowered in volume ("duck") if audio from another app interrupts your experience. This value defaults to true. If false, audio from other apps will pause your audio. */ + shouldDuckAndroid: boolean; + + /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise<void>; + function setAudioModeAsync(mode: AudioMode): Promise<void>; + + /** This class represents a sound corresponding to an Asset or URL. */ + class Sound extends PlaybackObject { + constructor(); + + /** + * Creates and loads a sound from source, with optional `initialStatus`, `onPlaybackStatusUpdate`, and `downloadFirst`. + * + * @returns A `Promise` that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: The newly created and loaded Sound object. + * - `status`: The PlaybackStatus of the Sound object. See the AV documentation for further information. + */ + static createAsync( + /** + * The source of the sound. The following forms are supported: + * + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to an audio file on the web. + * - `require('path/to/file')` for an audio file asset in the source code directory. + * - An `Expo.Asset` object for an audio file asset. + */ + source: PlaybackSource, + + /** The initial intended PlaybackStatusToSet of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter PlaybackStatus. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + + /** If set to true, the system will attempt to download the resource to the device before loading. This value defaults to `true`. Note that at the moment, this will only work for `source`s of the form `require('path/to/file')` or `Asset` objects. */ + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + class Recording { + constructor(); + + /** Gets the `status` of the `Recording`. */ + getStatusAsync(): Promise<RecordingStatus>; + + /** Sets a function to be called regularly with the `status` of the `Recording`. */ + setOnRecordingStatusUpdate(onRecordingStatusUpdate?: (status: RecordingStatus) => void): void; + + /** Sets the interval with which onRecordingStatusUpdate is called while the recording can record. This value defaults to 500 milliseconds. */ + setProgressUpdateInterval(progressUpdateIntervalMillis: number): void; + + /** Loads the recorder into memory and prepares it for recording. This must be called before calling `startAsync()`. This method can only be called if the `Recording` instance has never yet been prepared. */ + prepareToRecordAsync( + /** Options for the recording, including sample rate, bitrate, channels, format, encoder, and extension. If no options are passed to `prepareToRecordAsync()`, the recorder will be created with options `Expo.Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY`. */ + options?: RecordingOptions + ): Promise<RecordingStatus>; + + /** Begins recording. This method can only be called if the `Recording` has been prepared. */ + startAsync(): Promise<RecordingStatus>; + + /** + * Pauses recording. This method can only be called if the Recording has been prepared. + * + * NOTE: This is only available on Android API version 24 and later. + */ + pauseAsync(): Promise<RecordingStatus>; + + /** Stops the recording and deallocates the recorder from memory. This reverts the Recording instance to an unprepared state, and another Recording instance must be created in order to record again. This method can only be called if the `Recording` has been prepared. */ + stopAndUnloadAsync(): Promise<RecordingStatus>; + + /** + * Gets the local URI of the Recording. Note that this will only succeed once the Recording is prepared to record. + * + * @returns A string with the local URI of the `Recording`, or `null` if the `Recording` is not prepared to record. + */ + getURI(): string | null | undefined; + + /** + * Creates and loads a new `Sound` object to play back the `Recording`. Note that this will only succeed once the `Recording` is done recording (once `stopAndUnloadAsync()` has been called). + * + * @returns A Promise that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: the newly created and loaded Sound object. + * - `status`: the PlaybackStatus of the Sound object. + */ + createNewLoadedSound( + /** The initial intended `PlaybackStatusToSet` of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter `PlaybackStatus`. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * AuthSession + */ +export namespace AuthSession { + type StartAsyncResponse = { + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }; + + function startAsync(options: { authUrl: string; returnUrl?: string; }): Promise<StartAsyncResponse>; + function dismiss(): void; + function getRedirectUrl(): string; +} + +// #region AV +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + + /** Populated exactly once when an error forces the object to unload. */ + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + + /** True exactly once when the track plays to finish. */ + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + isLooping?: boolean; + isMuted?: boolean; + positionMillis?: number; + progressUpdateIntervalMillis?: number; + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate?: number; + shouldCorrectPitch?: boolean; + shouldPlay?: boolean; + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume?: number; +} + +export type PlaybackSource = RequireSource | { uri: string } | Asset; + +export class PlaybackObject { + /** + * Gets the `PlaybackStatus` of the `playbackObject`. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject`. + */ + getStatusAsync(): Promise<PlaybackStatus>; + + /** + * Loads the media from source into memory and prepares it for playing. This must be called before calling setStatusAsync() or any of the convenience set status methods. This method can only be called if the playbackObject is in an unloaded state. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is loaded, or rejects if loading failed. The `Promise` will also reject if the `playbackObject` was already loaded. See below for details on `PlaybackStatus`. + */ + loadAsync( + /** + * The source of the media. The following forms are supported: + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to a media file on the web. + * - `require('path/to/file')` for a media file asset in the source code directory. + * - An `Expo.Asset object` for a media file asset. + */ + source: PlaybackSource, + + /** The initial intended `PlaybackStatusToSet` of the `playbackObject`, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. See below for details on `PlaybackStatusToSet` and the default initial playback status. */ + initialStatus?: PlaybackStatusToSet, + + /** If set to `true`, the system will attempt to download the resource to the device before loading. This value defaults to true. Note that at the moment, this will only work for sources of the form `require('path/to/file')` or `Expo.Asset` objects. */ + downloadFirst?: boolean + ): Promise<PlaybackStatus>; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false })`. */ + pauseAsync(): Promise<PlaybackStatus>; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the `isPlaying` and `isBuffering` properties of the `PlaybackStatus`. + */ + playAsync(): Promise<PlaybackStatus>; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true, positionMillis: millis })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the isPlaying and `isBuffering` properties of the `PlaybackStatus`. + */ + playFromPositionAsync( + /** The desired position of playback in milliseconds. */ + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise<PlaybackStatus>; + + /** + * Replays the item. When using `playFromPositionAsync(0)` the item is seeked to the position at `0` ms. On iOS this method uses internal implementation of the player and is able to play the item from the beginning immediately. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. + */ + replayAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise<PlaybackStatus>; + + /** This is equivalent to `playbackObject.setStatusAsync({ isLooping: value })`. */ + setIsLoopingAsync( + /** A boolean describing if the media should play once (`false`) or loop indefinitely (`true`). */ + isLooping: boolean + ): Promise<PlaybackStatus>; + + /** This is equivalent to `playbackObject.setStatusAsync({ isMuted: value })`. */ + setIsMutedAsync( + /** A boolean describing if the audio of this media should be muted. */ + isMuted: boolean + ): Promise<PlaybackStatus>; + + /** + * Sets a function to be called regularly with the `PlaybackStatus` of the `playbackObject`. See below for details on `PlaybackStatus` and an example use case of this function. + * + * `onPlaybackStatusUpdate` will be called whenever a call to the API for this `playbackObject` completes (such as `setStatusAsync()`, `getStatusAsync()`, or `unloadAsync()`), and will also be called at regular intervals while the media is in the loaded state. Set `progressUpdateIntervalMillis` via `setStatusAsync()` or `setProgressUpdateIntervalAsync()` to modify the interval with which `onPlaybackStatusUpdate` is called while loaded. + */ + setOnPlaybackStatusUpdate( + /** A function taking a single parameter `PlaybackStatus`. */ + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void + ): void; + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis })`. */ + setPositionAsync( + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise<PlaybackStatus>; + + /** This is equivalent to `playbackObject.setStatusAsync({ progressUpdateIntervalMillis: millis })`. */ + setProgressUpdateIntervalAsync( + /** The new minimum interval in milliseconds between calls of `onPlaybackStatusUpdate`. */ + progressUpdateIntervalMillis: number + ): Promise<PlaybackStatus>; + + /** This is equivalent to `playbackObject.setStatusAsync({ rate: value, shouldCorrectPitch: shouldCorrectPitch })`. */ + setRateAsync( + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate: number, + /** A boolean describing if we should correct the pitch for a changed rate. If set to `true`, the pitch of the audio will be corrected (so a rate different than `1.0` will timestretch the audio). */ + shouldCorrectPitch: boolean + ): Promise<PlaybackStatus>; + + /** Sets a new `PlaybackStatusToSet` on the `playbackObject`. This method can only be called if the media has been loaded. Return a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. */ + setStatusAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise<PlaybackStatus>; + + /** This is equivalent to `playbackObject.setStatusAsync({ volume: value })`. */ + setVolumeAsync( + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume: number + ): Promise<PlaybackStatus>; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false, positionMillis: 0 })`. */ + stopAsync(): Promise<PlaybackStatus>; + + /** + * Unloads the media from memory. `loadAsync()` must be called again in order to be able to play the media. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is unloaded, or rejects if unloading failed. See below for details on `PlaybackStatus`. + */ + unloadAsync(): Promise<PlaybackStatus>; +} +// #endregion + +// #region BarCodeScanner +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProps { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeScanned?: BarCodeScannedCallback; +} + +export class BarCodeScanner extends Component<BarCodeScannerProps> { + static Constants: { + TorchMode: { + on: string; + off: string + } + } & CameraConstants; +} +// #endregion + +// #region BlurView +/** + * BlurView + */ +export interface BlurViewProps extends ViewProps { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component<BlurViewProps> { } +// #endregion + +/** + * An API to get and set screen brightness. + */ +export namespace Brightness { + /** Sets screen brightness. */ + function setBrightnessAsync( + /** A number between `0` and `1`, representing the desired screen brightness. */ + brightnessValue: number + ): Promise<void>; + + /** + * Gets screen brightness. + * @returns A Promise that is resolved with a number between `0` and `1`, representing the current screen brightness. + */ + function getBrightnessAsync(): Promise<number>; + + /** + * Gets global system screen brightness. + * @returns A Promise that is resolved with a number between `0` and `1`, representing the current system screen brightness. + */ + function getSystemBrightnessAsync(): Promise<number>; + + /** Sets global system screen brightness, requires `WRITE_SETTINGS` permissions on Android. */ + function setSystemBrightnessAsync( + /** A number between `0` and `1`, representing the desired screen brightness. */ + brightnessValue: number + ): Promise<void>; +} + +// #region Camera +/** + * Camera + */ +export interface PictureOptions { + quality?: number; + base64?: boolean; + exif?: boolean; + onPictureSaved?: (data: PictureResponse) => void; +} + +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} + +export interface RecordingOptions { + quality?: string | number; + maxDuration?: number; + maxFileSize?: number; +} + +export class CameraObject { + takePictureAsync(options?: PictureOptions): Promise<PictureResponse>; + recordAsync(options: RecordingOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise<string[]>; // Android only +} + +export interface CameraProps extends ViewProps { + zoom?: number; + ratio?: string; + /** Distance to plane of sharpest focus. A value between `0` and `1`. `0`: infinity focus, `1`: focus as close as possible. Default: `0`. For Android this is available only for some devices and when `useCamera2Api` is set to `true`. */ + focusDepth?: number; + type?: number | string; + onCameraReady?: () => void; + useCamera2Api?: boolean; + flashMode?: number | string; + whiteBalance?: number | string; + autoFocus?: string | boolean | number; + pictureSize?: string; + videoStabilizationMode?: number; + onMountError?: (error: { message: string }) => void; + barCodeScannerSettings?: { barCodeTypes?: Array<string | number>; }; + onBarCodeScanned?: BarCodeScannedCallback; + faceDetectorSettings?: { + mode?: number; + runClassifications?: number; + detectLandmarks?: number; + }; + onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; + ref?: Ref<CameraObject>; +} + +export interface CameraConstants { + readonly Type: { + back: string; + front: string; + }; + readonly FlashMode: { + on: string; + off: string; + auto: string; + torch: string; + }; + readonly AutoFocus: { + on: string; + off: string; + }; + readonly WhiteBalance: { + auto: string; + sunny: string; + cloudy: string; + shadow: string; + fluorescent: string; + incandescent: string; + }; + readonly VideoQuality: { + [videoQuality: string]: number; + }; + readonly BarCodeType: { + aztec: string; + codabar: string; + code39: string; + code93: string; + code128: string; + code138: string; + code39mod43: string; + datamatrix: string; + ean13: string; + ean8: string; + interleaved2of5: string; + itf14: string; + maxicode: string; + pdf417: string; + rss14: string; + rssexpanded: string; + upc_a: string; + upc_e: string; + upc_ean: string; + qr: string; + }; +} + +export class Camera extends Component<CameraProps> { + static readonly Constants: CameraConstants; +} +// #endregion + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const installationId: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios?: { + platform: string; + model: string; + userInterfaceIdiom: string; + buildNumber: string; + }; + android?: { + versionCode: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + privacy?: 'public' | 'unlisted'; + scheme?: string; + icon?: string; + platforms?: string[]; + githubUrl?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBar?: { + barStyle?: 'light-content' | 'dark-content', + backgroundColor?: string + }; + androidShowExponentNotificationInShellApp?: boolean; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme?: any; + facebookAppId?: string; + facebookDisplayName?: string; + splash?: { + backgroundColor?: string; + resizeMode?: ResizeModeContain | ResizeModeCover; + image?: string; + }; + assetBundlePatterns?: string[]; + releaseChannel: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; + + function getWebViewUserAgentAsync(): Promise<string>; +} + +/** + * Contacts + */ +export namespace Contacts { + // Constants + + namespace Fields { + type ID = 'id'; + type Name = 'name'; + type FirstName = 'firstName'; + type MiddleName = 'middleName'; + type LastName = 'lastName'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type Birthday = 'birthday'; + type Emails = 'emails'; + type PhoneNumbers = 'phoneNumbers'; + type Addresses = 'addresses'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Company = 'company'; + type JobTitle = 'jobTitle'; + type Department = 'department'; + type ImageAvailable = 'imageAvailable'; + type Image = 'image'; + type Note = 'note'; + type Dates = 'dates'; + type Relationships = 'relationships'; + type Nickname = 'nickname'; + type RawImage = 'rawImage'; + type MaidenName = 'maidenName'; + type ContactType = 'contactType'; + type SocialProfiles = 'socialProfiles'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + + const ID: ID; + const Name: Name; + const FirstName: FirstName; + const MiddleName: MiddleName; + const LastName: LastName; + const NamePrefix: NamePrefix; + const NameSuffix: NameSuffix; + const PhoneticFirstName: PhoneticFirstName; + const PhoneticMiddleName: PhoneticMiddleName; + const PhoneticLastName: PhoneticLastName; + const Birthday: Birthday; + const Emails: Emails; + const PhoneNumbers: PhoneNumbers; + const Addresses: Addresses; + const InstantMessageAddresses: InstantMessageAddresses; + const UrlAddresses: UrlAddresses; + const Company: Company; + const JobTitle: JobTitle; + const Department: Department; + const ImageAvailable: ImageAvailable; + const Image: Image; + const Note: Note; + const Dates: Dates; + const Relationships: Relationships; + const Nickname: Nickname; + const RawImage: RawImage; + const MaidenName: MaidenName; + const ContactType: ContactType; + const SocialProfiles: SocialProfiles; + const NonGregorianBirthday: NonGregorianBirthday; + } + + type Field = + | Fields.ID + | Fields.Name + | Fields.FirstName + | Fields.MiddleName + | Fields.LastName + | Fields.NamePrefix + | Fields.NameSuffix + | Fields.PhoneticFirstName + | Fields.PhoneticMiddleName + | Fields.PhoneticLastName + | Fields.Birthday + | Fields.Emails + | Fields.PhoneNumbers + | Fields.Addresses + | Fields.InstantMessageAddresses + | Fields.UrlAddresses + | Fields.Company + | Fields.JobTitle + | Fields.Department + | Fields.ImageAvailable + | Fields.Image + | Fields.Note + | Fields.Dates + | Fields.Relationships + | Fields.Nickname + | Fields.RawImage + | Fields.MaidenName + | Fields.ContactType + | Fields.SocialProfiles + | Fields.NonGregorianBirthday; + + namespace FormTypes { + type New = 'new'; + type Unknown = 'unknown'; + type Default = 'default'; + + const New: New; + const Unknown: Unknown; + const Default: Default; + } + + type FormType = FormTypes.New | FormTypes.Unknown | FormTypes.Default; + + /** + * iOS Only + */ + namespace ContactTypes { + type Person = 'person'; + type Company = 'company'; + + const Person: Person; + const Company: Company; + } + + type ContactType = ContactTypes.Person | ContactTypes.Company; + + namespace SortTypes { + type FirstName = 'firstName'; + type LastName = 'lastName'; + type UserDefault = 'userDefault'; + + const FirstName: FirstName; + const LastName: LastName; + const UserDefault: UserDefault; + } + + type SortType = SortTypes.FirstName | SortTypes.LastName | SortTypes.UserDefault; + + /** + * iOS Only + */ + namespace ContainerTypes { + type Local = 'local'; + type Exchange = 'exchange'; + type CardDAV = 'cardDAV'; + type Unassigned = 'unassigned'; + + const Local: Local; + const Exchange: Exchange; + const CardDAV: CardDAV; + const Unassigned: Unassigned; + } + + type ContainerType = ContainerTypes.Local | ContainerTypes.Exchange | ContainerTypes.CardDAV | ContainerTypes.Unassigned; + + namespace CalendarFormats { + type Gregorian = 'gregorian'; + type Chinese = 'chinese'; + type Hebrew = 'hebrew'; + type Islamic = 'islamic'; + + const Gregorian: Gregorian; + const Chinese: Chinese; + const Hebrew: Hebrew; + const Islamic: Islamic; + } + + type CalendarFormat = CalendarFormats.Gregorian | CalendarFormats.Chinese | CalendarFormats.Hebrew | CalendarFormats.Islamic; + + // Types + + /** + * A set of fields that define information about a single entity. + */ + interface Contact { + id: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + maidenName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + company?: string; + jobTitle?: string; + department?: string; + note?: string; + imageAvailable?: boolean; + image?: Image; + rawImage?: Image; + contactType: ContactType; + birthday?: ContactDate; + dates?: ContactDate[]; + relationships?: Relationship[]; + emails?: Email[]; + phoneNumbers?: PhoneNumber[]; + addresses?: Address[]; + instantMessageAddresses?: InstantMessageAddress[]; + urlAddresses?: UrlAddress[]; + /** + * iOS only + */ + nonGregorianBirthday?: ContactDate; + /** + * iOS only + */ + socialProfiles?: SocialProfile[]; + } + + interface ContactDate { + day: number; + month: number; + year: number; + format: CalendarFormat; + id: string; + label: string; + } + + interface Relationship { + name: string; + id: string; + label: string; + } + + interface Email { + email: string; + isPrimary: boolean; + id: string; + label: string; + } + + interface PhoneNumber { + number: string; + isPrimary: boolean; + digits: string; + countryCode: string; + id: string; + label: string; + } + + interface Address { + street: string; + city: string; + country: string; + region: string; + neighborhood: string; + postalCode: string; + poBox: string; + isoCountryCode: string; + id: string; + label: string; + } + + /** + * iOS only + */ + interface SocialProfile { + service: string; + username: string; + localizedProfile: string; + url: string; + userId: string; + id: string; + label: string; + } + + interface InstantMessageAddress { + service: string; + username: string; + localizedProfile: string; + id: string; + label: string; + } + + interface UrlAddress { + url: string; + id: string; + label: string; + } + + /** + * Information regarding thumbnail images + */ + interface Image { + uri: string; + /** + * iOS only + * In Android you can get dimensions using `ReactNative.Image.getSize` + */ + width?: number; + /** + * iOS only + * In Android you can get dimensions using `ReactNative.Image.getSize` + */ + height?: number; + /** + * Avoid using Base 64 in React Native + * iOS only + */ + base64?: string; + } + + /** + * A parent to contacts. A contact can belong to multiple groups. + * iOS Only + */ + interface Group { + id: string; + name: string; + } + + /** + * A parent to contacts and groups. + * iOS Only + */ + interface Container { + id: string; + name: string; + } + + /** + * Denotes the functionality of a native contact form + */ + interface FormOptions { + displayedPropertyKeys?: Field[]; + message?: string; + alternateName?: string; + cancelButtonTitle?: string; + groupId?: string; + allowsEditing?: boolean; + allowsActions?: boolean; + shouldShowLinkedContacts?: boolean; + isNew?: boolean; + preventAnimation?: boolean; + } + + /** + * Used to query contacts from the user's device + */ + interface ContactQuery { + fields?: Field[]; + pageSize?: number; + pageOffset?: number; + id?: string; + /** Android Only */ + sort?: SortType; + /** iOS Only */ + name?: string; + /** iOS Only */ + groupId?: string; + /** iOS Only */ + containerID?: string; + /** iOS Only */ + rawContacts?: boolean; + } + + interface ContactResponse { + data: Contact[]; + /** + * This will be true if there are more contacts to retrieve beyond what is returned + */ + hasNextPage: boolean; + /** + * `true` if there are previous contacts that weren't retrieved due to `pageOffset` + */ + hasPreviousPage: boolean; + } + + /** + * Used to query native contact groups. + * iOS Only + */ + interface GroupQuery { + groupName?: string; + groupId?: string; + containerId?: string; + } + + /** + * Used to query native contact containers. + * iOS Only + */ + interface ContainerQuery { + contactId?: string; + groupId?: string; + containerId?: string; + } + + // Methods + + /** + * Return a list of contacts that fit a given criteria. You can get all of the contacts by passing no criteria. + */ + function getContactsAsync(contactQuery?: ContactQuery): Promise<ContactResponse>; + /** + * Returns a contact matching the input id. Used for gathering precise data about a contact. + */ + function getContactByIdAsync(contactId: string, fields?: Field[]): Promise<Contact>; + + // iOS Only - temporary + /** + * Creates a new contact and adds it to the system. + * iOS Only - temporary + */ + function addContactAsync(contact: Contact, containerId?: string): Promise<string>; + /** + * Mutate the information of an existing contact. + * iOS Only - temporary + */ + function updateContactAsync(contact: Contact): Promise<string>; + /** + * Delete a contact from the system. + * iOS Only - temporary + */ + function removeContactAsync(contactId: string): Promise<void>; + /** + * Query a set of contacts and write them to a local uri that can be used for sharing with `ReactNative.Share`. + * iOS Only - temporary + */ + function writeContactToFileAsync(contactQuery: ContactQuery): Promise<string>; + + // iOS Only + /** + * Present a native form for manipulating contacts. + * iOS Only + */ + function presentFormAsync(contactId: string, contact?: Contact, formOptions?: FormOptions): Promise<void>; + /** + * Add a group to a container. + * iOS Only + */ + function addExistingGroupToContainerAsync(groupId: string, containerId: string): Promise<void>; + /** + * Create a group with a name, and add it to a container. If the container is undefined, the default container will be targeted. + * iOS Only + */ + function createGroupAsync(groupName: string, containerId?: string): Promise<string>; + /** + * Change the name of an existing group. + * iOS Only + */ + function updateGroupNameAsync(groupName: string, groupId: string): Promise<void>; + /** + * Delete a group from the device. + * iOS Only + */ + function removeGroupAsync(groupId: string): Promise<void>; + /** + * Add a contact as a member to a group. A contact can be a member of multiple groups. + * iOS Only + */ + function addExistingContactToGroupAsync(contactId: string, groupId: string): Promise<void>; + /** + * Remove a contact's membership from a given group. This will not delete the contact. + * iOS Only + */ + function removeContactFromGroupAsync(contactId: string, groupId: string): Promise<void>; + /** + * Query and return a list of system groups. + * iOS Only + */ + function getGroupsAsync(query: GroupQuery): Promise<Group[]>; + /** + * Get the default container's ID. + * iOS Only + */ + function getDefaultContainerIdAsync(): Promise<string>; + /** + * Query a list of system containers. + * iOS Only + */ + function getContainersAsync(containerQuery: ContainerQuery): Promise<Container[]>; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type?: string; + } + + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options?: Options): Promise<Response>; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + interface Response { + type: 'cancel' | 'success'; + token?: string; + expires?: number; + } + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise<Response>; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise<boolean>; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + interface NativeAd { + /** + * The headline the advertiser entered when they created their ad. This is usually the ad's main + * title. + */ + headline?: string; + + /** + * The link description which is additional information that the advertiser may have entered + */ + linkDescription?: string; + + /** + * The name of the Facebook Page or mobile app that represents the business running the ad + */ + advertiserName?: string; + + /** + * The ad's social context, such as, "Over half a million users" + */ + socialContext?: string; + + /** + * The call-to-action phrase of the ad, such as, "Install Now" + */ + callToActionText?: string; + + /** + * The body text, truncated to 90 characters, that contains the text the advertiser entered when + * they created their ad to tell people what the ad promotes + */ + bodyText?: string; + + /** + * The word "ad", translated into the viewer's language + */ + adTranslation?: string; + + /** + * The word "promoted", translated into the viewer's language + */ + promotedTranslation?: string; + + /** + * The word "sponsored", translated into the viewer's language + */ + sponsoredTranslation?: string; + } + + function withNativeAd<P>(component: Component<P & { nativeAd: NativeAd }>): Component< + { + adsManager: NativeAdsManager, + onAdLoaded?: ((ad: NativeAd) => void) | null; + } & P, + { ad: NativeAd | null, canRequestAds: boolean } + >; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component<BannerViewProps> { } + + type AdTriggerViewProps<P> = { + renderInteractiveComponent?: (props: P) => React.ReactElement<P>; + } & P; + + class AdTriggerView<P> extends Component<AdTriggerViewProps<P>> { } + + class AdIconView extends Component { } + + class AdMediaView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FaceDetector + */ +export interface Point { + x: Axis; + y: Axis; +} + +export interface FaceFeature { + bounds: { + size: { + width: number; + height: number; + }, + origin: Point; + }; + smilingProbability?: number; + leftEarPosition?: Point; + rightEarPosition?: Point; + leftEyePosition?: Point; + leftEyeOpenProbability?: number; + rightEyePosition?: Point; + rightEyeOpenProbability?: number; + leftCheekPosition?: Point; + rightCheekPosition?: Point; + leftMouthPosition?: Point; + mouthPosition?: Point; + rightMouthPosition?: Point; + bottomMouthPosition?: Point; + noseBasePosition?: Point; + yawAngle?: number; + rollAngle?: number; +} + +export interface TrackedFaceFeature extends FaceFeature { + faceID?: number; +} + +export namespace FaceDetector { + interface DetectFaceResult { + faces: FaceFeature[]; + image: { + uri: string; + width: number; + height: number; + orientation: number; + }; + } + interface Mode { + fast: 'fast'; + accurate: 'accurate'; + } + interface _Shared { + all: 'all'; + none: 'none'; + } + type Landmarks = _Shared; + type Classifications = _Shared; + interface _Constants { + Mode: Mode; + Landmarks: Landmarks; + Classifications: Classifications; + } + + const Constants: _Constants; + + interface DetectionOptions { + mode?: keyof Mode; + detectLandmarks?: keyof Landmarks; + runClassifications?: keyof Classifications; + } + + function detectFaces(uri: string, options?: DetectionOptions): Promise<DetectFaceResult>; +} +/** + * FileSystem + */ +export namespace FileSystem { + type EncodingType = "utf8" | "base64"; + + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: Md5; + } | { + exists: false; + isDirectory: false; + }; + + interface ReadingOptions { + encoding?: EncodingType; + position?: number; + length?: number; + } + + interface WritingOptions { + encoding?: EncodingType; + } + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: Md5; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise<FileInfo>; + function readAsStringAsync(fileUri: string, options?: ReadingOptions): Promise<string>; + function writeAsStringAsync(fileUri: string, contents: string, options?: WritingOptions): Promise<void>; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise<void>; + function moveAsync(options: { from: string, to: string; }): Promise<void>; + function copyAsync(options: { from: string, to: string; }): Promise<void>; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise<void>; + function readDirectoryAsync(dirUri: string): Promise<string[]>; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise<DownloadResult>; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + + downloadAsync(): Promise<DownloadResult>; + pauseAsync(): Promise<PauseResult>; + resumeAsync(): Promise<DownloadResult>; + savable(): PauseResult; + } +} + +/** Use TouchID/FaceID (iOS) or the Fingerprint API (Android) to authenticate the user with a fingerprint scan. */ +export namespace LocalAuthentication { + type LocalAuthenticationResult = { + success: true + } | { + success: false, + + /** Error code in the case where authentication fails. */ + error: string + }; + + interface AuthenticationTypeType { + FINGERPRINT: number; + FACIAL_RECOGNITION: number; + } + + /** Determine the auhentication types supported on the device. */ + function supportedAuthenticationTypesAsync(): Promise<AuthenticationTypeType[]>; + + /** Determine whether a face or fingerprint scanner is available on the device. */ + function hasHardwareAsync(): Promise<boolean>; + + /** Determine whether the device has saved fingerprints or facial data to use for authentication. */ + function isEnrolledAsync(): Promise<boolean>; + + /** + * Attempts to authenticate via Fingerprint. Android: When using the fingerprint module on Android, you need to provide a UI component to prompt the user to scan their fingerprint, as the OS has no default alert for it. + * + * @param promptMessage A message that is shown alongside the TouchID/FaceID prompt. (iOS only) + */ + function authenticateAsync(promptMessageIOS?: string): Promise<LocalAuthenticationResult>; + + /** Cancels the fingerprint authentication flow. (Android only) */ + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise<void>; + function loadAsync(map: FontMap): Promise<void>; +} + +// #region GLView +export interface ExpoWebGLRenderingContext extends WebGLRenderingContext { + endFrameEXP(): void; +} + +/** + * A View that acts as an OpenGL ES render target. On mounting, an OpenGL ES + * context is created. Its drawing buffer is presented as the contents of + * the View every frame. + */ +export interface GLViewProps extends ViewProps { + /** + * A function that will be called when the OpenGL ES context is created. + * Passes an object with a WebGLRenderingContext interface as an argument. + */ + onContextCreate(gl: ExpoWebGLRenderingContext): void; + + /** Number of MSAA samples to use on iOS. Defaults to 4. Ignored on Android. */ + msaaSamples?: number; +} + +export class GLView extends Component<GLViewProps, { msaaSamples: number }> { } +// #endregion + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise<LogInResult>; +} + +/** Access the device gyroscope sensor to respond to changes in rotation in 3d space. */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** A callback that is invoked when an gyroscope update is available. */ + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** Subscribe for updates to the gyroscope. */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * ImageManipulator + */ +export namespace ImageManipulator { + type Action = Resize | Rotate | Flip | Crop; + + interface Resize { + resize: { width?: number, height?: number }; + } + + interface Rotate { + rotate: number; + } + + interface Flip { + flip?: { vertical?: boolean; horizontal?: boolean }; + } + + interface Crop { + originX: number; + originY: number; + width: number; + height: number; + } + + interface ImageResult { + uri: string; + width: number; + height: number; + base64?: string; + } + + interface SaveOptions { + base64?: boolean; + /** A value in range `0` - `1` specifying compression level of the result image. `1` means no compression and `0` the highest compression. */ + compress?: number; + format?: 'jpeg' | 'png'; + } + + function manipulateAsync(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise<ImageResult>; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + type: 'video' | 'image'; + base64?: string; + exif?: object; + duration?: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface _MediaTypeOptions { + All: 'All'; + Videos: 'Videos'; + Images: 'Images'; + } + + const MediaTypeOptions: _MediaTypeOptions; + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + base64?: boolean; + exif?: boolean; + mediaTypes?: keyof _MediaTypeOptions; + } + + /** + * require Permissions.CAMERA_ROLL + */ + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise<ImageResult>; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + base64?: boolean; + exif?: boolean; + } + + /** + * require Permissions.CAMERA_ROLL + */ + function launchCameraAsync(options?: CameraOptions): Promise<ImageResult>; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: 'android.settings.ACCESSIBILITY_SETTINGS'; + const ACTION_APP_NOTIFICATION_REDACTION: 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; + const ACTION_CONDITION_PROVIDER_SETTINGS: 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; + const ACTION_PRINT_SETTINGS: 'android.settings.ACTION_PRINT_SETTINGS'; + const ACTION_ADD_ACCOUNT_SETTINGS: 'android.settings.ADD_ACCOUNT_SETTINGS'; + const ACTION_AIRPLANE_MODE_SETTINGS: 'android.settings.AIRPLANE_MODE_SETTINGS'; + const ACTION_APN_SETTINGS: 'android.settings.APN_SETTINGS'; + const ACTION_APPLICATION_DETAILS_SETTINGS: 'android.settings.APPLICATION_DETAILS_SETTINGS'; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; + const ACTION_APPLICATION_SETTINGS: 'android.settings.APPLICATION_SETTINGS'; + const ACTION_APP_NOTIFICATION_SETTINGS: 'android.settings.APP_NOTIFICATION_SETTINGS'; + const ACTION_APP_OPS_SETTINGS: 'android.settings.APP_OPS_SETTINGS'; + const ACTION_BATTERY_SAVER_SETTINGS: 'android.settings.BATTERY_SAVER_SETTINGS'; + const ACTION_BLUETOOTH_SETTINGS: 'android.settings.BLUETOOTH_SETTINGS'; + const ACTION_CAPTIONING_SETTINGS: 'android.settings.CAPTIONING_SETTINGS'; + const ACTION_CAST_SETTINGS: 'android.settings.CAST_SETTINGS'; + const ACTION_DATA_ROAMING_SETTINGS: 'android.settings.DATA_ROAMING_SETTINGS'; + const ACTION_DATE_SETTINGS: 'android.settings.DATE_SETTINGS'; + const ACTION_DEVICE_INFO_SETTINGS: 'android.settings.DEVICE_INFO_SETTINGS'; + const ACTION_DEVICE_NAME: 'android.settings.DEVICE_NAME'; + const ACTION_DISPLAY_SETTINGS: 'android.settings.DISPLAY_SETTINGS'; + const ACTION_DREAM_SETTINGS: 'android.settings.DREAM_SETTINGS'; + const ACTION_HARD_KEYBOARD_SETTINGS: 'android.settings.HARD_KEYBOARD_SETTINGS'; + const ACTION_HOME_SETTINGS: 'android.settings.HOME_SETTINGS'; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; + const ACTION_INPUT_METHOD_SETTINGS: 'android.settings.INPUT_METHOD_SETTINGS'; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; + const ACTION_INTERNAL_STORAGE_SETTINGS: 'android.settings.INTERNAL_STORAGE_SETTINGS'; + const ACTION_LOCALE_SETTINGS: 'android.settings.LOCALE_SETTINGS'; + const ACTION_LOCATION_SOURCE_SETTINGS: 'android.settings.LOCATION_SOURCE_SETTINGS'; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; + const ACTION_MEMORY_CARD_SETTINGS: 'android.settings.MEMORY_CARD_SETTINGS'; + const ACTION_MONITORING_CERT_INFO: 'android.settings.MONITORING_CERT_INFO'; + const ACTION_NETWORK_OPERATOR_SETTINGS: 'android.settings.NETWORK_OPERATOR_SETTINGS'; + const ACTION_NFCSHARING_SETTINGS: 'android.settings.NFCSHARING_SETTINGS'; + const ACTION_NFC_PAYMENT_SETTINGS: 'android.settings.NFC_PAYMENT_SETTINGS'; + const ACTION_NFC_SETTINGS: 'android.settings.NFC_SETTINGS'; + const ACTION_NIGHT_DISPLAY_SETTINGS: 'android.settings.NIGHT_DISPLAY_SETTINGS'; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; + const ACTION_NOTIFICATION_SETTINGS: 'android.settings.NOTIFICATION_SETTINGS'; + const ACTION_PAIRING_SETTINGS: 'android.settings.PAIRING_SETTINGS'; + const ACTION_PRIVACY_SETTINGS: 'android.settings.PRIVACY_SETTINGS'; + const ACTION_QUICK_LAUNCH_SETTINGS: 'android.settings.QUICK_LAUNCH_SETTINGS'; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; + const ACTION_SECURITY_SETTINGS: 'android.settings.SECURITY_SETTINGS'; + const ACTION_SETTINGS: 'android.settings.SETTINGS'; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; + const ACTION_SHOW_INPUT_METHOD_PICKER: 'android.settings.SHOW_INPUT_METHOD_PICKER'; + const ACTION_SHOW_REGULATORY_INFO: 'android.settings.SHOW_REGULATORY_INFO'; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; + const ACTION_SOUND_SETTINGS: 'android.settings.SOUND_SETTINGS'; + const ACTION_STORAGE_MANAGER_SETTINGS: 'android.settings.STORAGE_MANAGER_SETTINGS'; + const ACTION_SYNC_SETTINGS: 'android.settings.SYNC_SETTINGS'; + const ACTION_SYSTEM_UPDATE_SETTINGS: 'android.settings.SYSTEM_UPDATE_SETTINGS'; + const ACTION_TETHER_PROVISIONING_UI: 'android.settings.TETHER_PROVISIONING_UI'; + const ACTION_TRUSTED_CREDENTIALS_USER: 'android.settings.TRUSTED_CREDENTIALS_USER'; + const ACTION_USAGE_ACCESS_SETTINGS: 'android.settings.USAGE_ACCESS_SETTINGS'; + const ACTION_USER_DICTIONARY_INSERT: 'android.settings.USER_DICTIONARY_INSERT'; + const ACTION_USER_DICTIONARY_SETTINGS: 'android.settings.USER_DICTIONARY_SETTINGS'; + const ACTION_USER_SETTINGS: 'android.settings.USER_SETTINGS'; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; + const ACTION_VOICE_INPUT_SETTINGS: 'android.settings.VOICE_INPUT_SETTINGS'; + const ACTION_VPN_SETTINGS: 'android.settings.VPN_SETTINGS'; + const ACTION_VR_LISTENER_SETTINGS: 'android.settings.VR_LISTENER_SETTINGS'; + const ACTION_WEBVIEW_SETTINGS: 'android.settings.WEBVIEW_SETTINGS'; + const ACTION_WIFI_IP_SETTINGS: 'android.settings.WIFI_IP_SETTINGS'; + const ACTION_WIFI_SETTINGS: 'android.settings.WIFI_SETTINGS'; + const ACTION_WIRELESS_SETTINGS: 'android.settings.WIRELESS_SETTINGS'; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; + const ACTION_ZEN_MODE_SETTINGS: 'android.settings.ZEN_MODE_SETTINGS'; + + function startActivityAsync(activity: string, data?: HashMap): Promise<boolean>; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +// #region LinearGradient +/** + * LinearGradient + */ +export interface LinearGradientProps { + colors: string[]; + start?: [number, number]; + end?: [number, number]; + locations?: number[]; + style?: StyleProp<ViewStyle>; +} + +export class LinearGradient extends Component<LinearGradientProps> { } +// #endregion + +/** + * Linking + */ +export interface LinkInfo { + path: string; + queryParams: Partial<StringHashMap>; +} + +export interface LinkingStatic extends ReactNativeLinkingStatic { + makeUrl(path: string, queryParams?: HashMap): string; + parse(url: string): LinkInfo; + parseInitialURLAsync(): Promise<LinkInfo>; +} +export const Linking: LinkingStatic; + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + timeout?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise<LocationData>; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise<ProviderStatus>; + function getHeadingAsync(): Promise<HeadingStatus>; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise<Coords>; + function reverseGeocodeAsync(location: LocationProps): Promise<GeocodeData[]>; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + interface SchedulingOptions { + time: Date | number; + repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + intervalMs?: number; + } + + interface ChannelAndroid { + name: string; + description?: string; + sound?: boolean; + priority?: 'min' | 'low' | 'default' | 'high' | 'max'; + vibrate?: boolean | number[]; + badge?: boolean; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExpoPushTokenAsync(): Promise<string>; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise<LocalNotificationId>; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise<LocalNotificationId>; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise<void>; + function dismissAllNotificationsAsync(): Promise<void>; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise<void>; + function cancelAllScheduledNotificationsAsync(): Promise<void>; + function createChannelAndroidAsync(id: string, channel: ChannelAndroid): Promise<void>; + function deleteChannelAndroidAsync(id: string): Promise<void>; + function getBadgeNumberAsync(): Promise<number>; + function setBadgeNumberAsync(number: number): Promise<void>; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise<boolean>; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'audioRecording' | 'calendar' | + 'cameraRoll' | 'camera' | 'contacts' | 'location' | 'reminders' | + 'notifications' | 'systemBrightness' | 'userFacingNotifications' | 'SMS'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + + interface SinglePermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + permissions: { + [key in PermissionType]: SinglePermissionResponse + }; + } + + function getAsync(...permissionTypes: PermissionType[]): Promise<PermissionResponse>; + function askAsync(...permissionTypes: PermissionType[]): Promise<PermissionResponse>; + + const AUDIO_RECORDING: 'audioRecording'; + const CALENDAR: 'calendar'; + const CAMERA_ROLL: 'cameraRoll'; + const CAMERA: 'camera'; + const CONTACTS: 'contacts'; + const LOCATION: 'location'; + const NOTIFICATIONS: 'notifications'; + const REMINDERS: 'reminders'; + const SYSTEM_BRIGHTNESS: 'systemBrightness'; + const USER_FACING_NOTIFICATIONS: 'userFacingNotifications'; + /** + * Will be removed in SDK 32 + */ + const SMS: 'SMS'; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: ComponentType): void; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientations { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + + const Orientation: Orientations; + + function allow(orientation: keyof Orientations): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + } + + interface SecureStoreSetOptions extends SecureStoreOptions { + keychainAccessible?: number; + } + + function setItemAsync(key: string, value: string, options?: SecureStoreSetOptions): Promise<void>; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise<string | null>; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise<void>; + + const WHEN_UNLOCKED: number; + const AFTER_FIRST_UNLOCK: number; + const ALWAYS: number; + const WHEN_UNLOCKED_THIS_DEVICE_ONLY: number; + const WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: number; + const AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: number; + const ALWAYS_THIS_DEVICE_ONLY: number; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function alias(newId: string, options?: { [key: string]: any }): Promise<boolean>; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; + function getEnabledAsync(): void; + function setEnabledAsync(enabled: boolean): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: Error) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise<boolean>; + + /** Available on iOS only */ + function pause(): void; + + /** Available on iOS only */ + function resume(): void; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +// #region Svg +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number | string; + fillRule?: 'nonzero' | 'evenodd'; + opacity?: number | string; + stroke?: string; + strokeWidth?: number | string; + strokeOpacity?: number | string; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + transform?: string | object; + x?: number | string; + y?: number | string; + rotate?: number | string; + rotation?: number | string; + scale?: number | string; + origin?: number | string; + originX?: number | string; + originY?: number | string; + id?: string; + disabled?: boolean; + onPress?: () => any; + onPressIn?: () => any; + onPressOut?: () => any; + onLongPress?: () => any; + delayPressIn?: number; + delayPressOut?: number; + delayLongPress?: number; +} + +export interface SvgRectProps extends SvgCommonProps { + width: number | string; + height: number | string; +} + +export interface SvgCircleProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + r: number | string; +} + +export interface SvgEllipseProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; +} + +export interface SvgLineProps extends SvgCommonProps { + x1: number | string; + y1: number | string; + x2: number | string; + y2: number | string; +} + +export interface SvgPolyProps extends SvgCommonProps { + points: string; +} + +export interface SvgPathProps extends SvgCommonProps { + d: string; +} + +export interface SvgTextProps extends SvgCommonProps { + textAnchor?: string; + fontSize?: number | string; + fontWeight?: string; +} + +export interface SvgTSpanProps extends SvgTextProps { + dx?: string; + dy?: string; +} + +export interface SvgTextPathProps extends SvgCommonProps { + href?: string; + startOffset?: string; +} + +export interface SvgUseProps extends SvgCommonProps { + href: string; + x: number | string; + y: number | string; + width?: number | string; + height?: number | string; +} + +export interface SvgSymbolProps extends SvgCommonProps { + viewBox: string; + preserveAspectRatio?: string; + width: number | string; + height: number | string; +} + +export interface SvgLinearGradientProps extends SvgCommonProps { + x1: number | string; + x2: number | string; + y1: number | string; + y2: number | string; +} + +export interface SvgRadialGradientProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; + fx: number | string; + fy: number | string; + gradientUnits?: string; +} + +export interface SvgStopProps extends SvgCommonProps { + offset?: string; + stopColor?: string; + stopOpacity?: string; +} + +export class Svg extends Component<{ width: number, height: number, viewBox?: string, preserveAspectRatio?: string }> { + static Circle: ComponentClass<SvgCircleProps>; + static ClipPath: ComponentClass<SvgCommonProps>; + static Defs: ComponentClass; + static Ellipse: ComponentClass<SvgEllipseProps>; + static G: ComponentClass<SvgCommonProps>; + static Line: ComponentClass<SvgLineProps>; + static LinearGradient: ComponentClass<SvgLinearGradientProps>; + static Path: ComponentClass<SvgPathProps>; + static Polygon: ComponentClass<SvgPolyProps>; + static Polyline: ComponentClass<SvgPolyProps>; + static RadialGradient: ComponentClass<SvgRadialGradientProps>; + static Rect: ComponentClass<SvgRectProps>; + static Stop: ComponentClass<SvgStopProps>; + static Symbol: ComponentClass<SvgSymbolProps>; + static Text: ComponentClass<SvgTextProps>; + static TextPath: ComponentClass<SvgTextPathProps>; + static TSpan: ComponentClass<SvgTSpanProps>; + static Use: ComponentClass<SvgUseProps>; +} +// #endregion + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement<any>), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise<string>; + +/** Helpful utility functions that don’t fit anywhere else, including some localization and internationalization methods. */ +export namespace Util { + /** Returns the current device country code. */ + function getCurrentDeviceCountryAsync(): Promise<string>; + + /** Returns the current device locale as a string. */ + function getCurrentLocaleAsync(): Promise<string>; + + /** Returns the current device time zone name. */ + function getCurrentTimeZoneAsync(): Promise<string>; + + /** Reloads the current experience. This will fetch and load the newest available JavaScript supported by the device’s Expo environment. This is useful for triggering an update of your experience if you have published a new version. */ + function reload(): void; + + /** _Android only_. Invokes a callback when a new version of your app is successfully downloaded in the background. */ + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; +} + +// #region Video +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: PlaybackSource | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref<PlaybackObject>; + style?: StyleProp<ViewStyle>; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component<VideoProps, VideoState> { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} +// #endregion + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} + +// #region Calendar +/** + * Calendar + * + * Provides an API for interacting with the device’s system calendars, events, reminders, and associated records. + */ +export namespace Calendar { + interface Calendar { + /** Internal ID that represents this calendar on the device */ + id?: string; + + /** Visible name of the calendar */ + title?: string; + + sourceId?: string; // iOS + + /** Object representing the source to be used for the calendar */ + source?: Source; + + /** Type of calendar this object represents */ + type?: CalendarType; // iOS + + /** Color used to display this calendar’s events */ + color?: string; + + /** Whether the calendar is used in the Calendar or Reminders OS app */ + entityType?: EntityTypes; // iOS + + /** Boolean value that determines whether this calendar can be modified */ + allowsModifications?: boolean; + + /** Availability types that this calendar supports */ + allowedAvailabilities?: Availability[]; + + /** Boolean value indicating whether this is the device’s primary calendar */ + isPrimary?: boolean; // Android + + /** Internal system name of the calendar */ + name?: string; // Android + + /** Name for the account that owns this calendar */ + ownerAccount?: string; // Android + + /** Time zone for the calendar */ + timeZone?: string; // Android + + /** Alarm methods that this calendar supports */ + allowedReminders?: AlarmMethod[]; // Android + + /** Attendee types that this calendar supports */ + allowedAttendeeTypes?: AttendeeType[]; // Android + + /** Indicates whether the OS displays events on this calendar */ + isVisible?: boolean; // Android + + /** Indicates whether this calendar is synced and its events stored on the device */ + isSynced?: boolean; // Android + + /** Level of access that the user has for the calendar */ + accessLevel?: CalendarAccessLevel; // Android + } + + interface Source { + /** Internal ID that represents this source on the device */ + id?: string; // iOS only ?? + + /** Type of account that owns this calendar */ + type?: string; + + /** Name for the account that owns this calendar */ + name?: string; + + /** Whether this source is the local phone account */ + isLocalAccount?: boolean; // Android + } + + interface Event { + /** Internal ID that represents this event on the device */ + id?: string; + + /** ID of the calendar that contains this event */ + calendarId?: string; + + /** Visible name of the event */ + title?: string; + + /** Location field of the event */ + location?: string; + + /** Date when the event record was created */ + creationDate?: string; // iOS + + /** Date when the event record was last modified */ + lastModifiedDate?: string; // iOS + + /** Time zone the event is scheduled in */ + timeZone?: string; + + /** Time zone for the event end time */ + endTimeZone?: string; // Android + + /** URL for the event */ + url?: string; // iOS + + /** Description or notes saved with the event */ + notes?: string; + + /** Array of Alarm objects which control automated reminders to the user */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeating events. Null for one-time events. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the time when the event starts */ + startDate?: string | Date; + + /** Date object or string representing the time when the event ends */ + endDate?: string | Date; + + /** For recurring events, the start date for the first (original) instance of the event */ + originalStartDate?: string; // iOS + + /** Boolean value indicating whether or not the event is a detached (modified) instance of a recurring event */ + isDetached?: boolean; // iOS + + /** Whether the event is displayed as an all-day event on the calendar */ + allDay?: boolean; + + /** The availability setting for the event */ + availability?: Availability; // Availability + + /** Status of the event */ + status?: EventStatus; // Status + + /** Organizer of the event, as an Attendee object */ + organizer?: string; // Organizer - iOS + + /** Email address of the organizer of the event */ + organizerEmail?: string; // Android + + /** User’s access level for the event */ + accessLevel?: EventAccessLevel; // Android, + + /** Whether invited guests can modify the details of the event */ + guestsCanModify?: boolean; // Android, + + /** Whether invited guests can invite other guests */ + guestsCanInviteOthers?: boolean; // Android + + /** Whether invited guests can see other guests */ + guestsCanSeeGuests?: boolean; // Android + + /** For detached (modified) instances of recurring events, the ID of the original recurring event */ + originalId?: string; // Android + + /** For instances of recurring events, volatile ID representing this instance; not guaranteed to always refer to the same instance */ + instanceId?: string; // Android + } + + interface Attendee { + /** Internal ID that represents this attendee on the device */ + id?: string; // Android + + /** Indicates whether or not this attendee is the current OS user */ + isCurrentUser?: boolean; // iOS + + /** Displayed name of the attendee */ + name?: string; + + /** Role of the attendee at the event */ + role?: AttendeeRole; + + /** Status of the attendee in relation to the event */ + status?: AttendeeStatus; + + /** Type of the attendee */ + type?: AttendeeType; + + /** URL for the attendee */ + url?: string; // iOS + + /** Email address of the attendee */ + email?: string; // Android + } + + interface Reminder { + /** Internal ID that represents this reminder on the device */ + id?: string; + + /** ID of the calendar that contains this reminder */ + calendarId?: string; + + /** Visible name of the reminder */ + title?: string; + + /** Location field of the reminder */ + location?: string; + + /** Date when the reminder record was created */ + creationDate?: string; + + /** Date when the reminder record was last modified */ + lastModifiedDate?: string; + + /** Time zone the reminder is scheduled in */ + timeZone?: string; + + /** URL for the reminder */ + url?: string; + + /** Description or notes saved with the reminder */ + notes?: string; + + /** Array of Alarm objects which control automated alarms to the user about the task */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeated reminders. Null for one-time tasks. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the start date of the reminder task */ + startDate?: string; + + /** Date object or string representing the time when the reminder task is due */ + dueDate?: string; + + /** Indicates whether or not the task has been completed */ + completed?: boolean; + + /** Date object or string representing the date of completion, if completed is true */ + completionDate?: string; + } + + interface Alarm { + /** Date object or string representing an absolute time the alarm should occur; overrides relativeOffset and structuredLocation if specified alongside either */ + absoluteDate?: string; // iOS + + /** Number of minutes from the startDate of the calendar item that the alarm should occur; use negative values to have the alarm occur before the startDate */ + relativeOffset?: string; + structuredLocation?: { + // iOS + title?: string; + proximity?: string; // Proximity + radius?: number; + coords?: { + latitude?: number; + longitude?: number; + }; + }; + + /** Method of alerting the user that this alarm should use; on iOS this is always a notification */ + method?: AlarmMethod; // Method, Android + } + + interface RecurrenceRule { + /** How often the calendar item should recur */ + frequency: Frequency; // Frequency + + /** Interval at which the calendar item should recur. For example, an interval: 2 with frequency: DAILY would yield an event that recurs every other day. Defaults to 1 . */ + interval?: number; + + /** Date on which the calendar item should stop recurring; overrides occurrence if both are specified */ + endDate?: string; + + /** Number of times the calendar item should recur before stopping */ + occurrence?: number; + } + + enum EntityTypes { + EVENT = 'event', + REMINDER = 'reminder', + } + + enum CalendarType { + LOCAL = 'local', + CALDAV = 'caldav', + EXCHANGE = 'exchange', + SUBSCRIBED = 'subscribed', + BIRTHDAYS = 'birthdays' + } + + enum Availability { + NOT_SUPPORTED = 'notSupported', // iOS + BUSY = 'busy', + FREE = 'free', + TENTATIVE = 'tentative', + UNAVAILABLE = 'unavailable' // iOS + } + + enum AlarmMethod { + ALARM = 'alarm', + ALERT = 'alert', + EMAIL = 'email', + SMS = 'sms', + DEFAULT = 'default', + } + + enum AttendeeType { + UNKNOWN = 'unknown', // iOS + PERSON = 'person', // iOS + ROOM = 'room', // iOS + GROUP = 'group', // iOS + RESOURCE = 'resource', + OPTIONAL = 'optional', // Android + REQUIRED = 'required', // Android + NONE = 'none' // Android + } + + enum CalendarAccessLevel { + CONTRIBUTOR = 'contributor', + EDITOR = 'editor', + FREEBUSY = 'freebusy', + OVERRIDE = 'override', + OWNER = 'owner', + READ = 'read', + RESPOND = 'respond', + ROOT = 'root', + NONE = 'none' + } + + enum EventAccessLevel { + CONFIDENTIAL = 'confidential', + PRIVATE = 'private', + PUBLIC = 'public', + DEFAULT = 'default' + } + + enum EventStatus { + NONE = 'none', + CONFIRMED = 'confirmed', + TENTATIVE = 'tentative', + CANCELED = 'canceled' + } + + enum AttendeeRole { + UNKNOWN = 'unknown', // iOS + REQUIRED = 'required', // iOS + OPTIONAL = 'optional', // iOS + CHAIR = 'chair', // iOS + NON_PARTICIPANT = 'nonParticipant', // iOS + ATTENDEE = 'attendee', // Android + ORGANIZER = 'organizer', // Android + PERFORMER = 'performer', // Android + SPEAKER = 'speaker', // Android + NONE = 'none' // Android + } + + enum AttendeeStatus { + UNKNOWN = 'unknown', // iOS + PENDING = 'pending', // iOS + ACCEPTED = 'accepted', + DECLINED = 'declined', + TENTATIVE = 'tentative', + DELEGATED = 'delegated', // iOS + COMPLETED = 'completed', // iOS + IN_PROCESS = 'inProcess', // iOS + INVITED = 'invited', // Android + NONE = 'none' // Android + } + + enum Frequency { + DAILY = 'daily', + WEEKLY = 'weekly', + MONTHLY = 'monthly', + YEARLY = 'yearly' + } + + enum ReminderStatus { + COMPLETED = 'completed', + INCOMPLETE = 'incomplete' + } + + interface RecurringEventOptions { + futureEvents?: boolean; + instanceStartDate?: string; + } + + /** Gets an array of calendar objects with details about the different calendars stored on the device. */ + function getCalendarsAsync( + /** (iOS only) Not required, but if defined, filters the returned calendars to a specific entity type. */ + entityType?: EntityTypes + ): Promise<Calendar[]>; + + /** Creates a new calendar on the device, allowing events to be added later and displayed. */ + function createCalendarAsync(details: Calendar): Promise<string>; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateCalendarAsync(id: string, details?: Calendar | null): Promise<string>; + + /** Deletes an existing calendar and all associated events/reminders/attendees from the device. Use with caution. */ + function deleteCalendarAsync(id: string): Promise<void>; + + /** Returns all events in a given set of calendars over a specified time period. */ + function getEventsAsync( + /** Array of IDs of calendars to search for events in. Required. */ + calendarIds: string[], + + /** Beginning of time period to search for events in. Required. */ + startDate: Date, + + /** End of time period to search for events in. Required. */ + endDate: Date + ): Promise<Event[]>; + + /** Returns a specific event selected by ID. If a specific instance of a recurring event is desired, the start date of this instance must also be provided, as instances of recurring events do not have their own unique and stable IDs on either iOS or Android. */ + function getEventAsync( + /** ID of the event to return. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise<Event>; + + /** Creates a new event on the specified calendar. */ + function createEventAsync( + /** ID of the calendar to create this event in. Required. */ + calendarId: string, + details?: Event + ): Promise<string>; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateEventAsync( + /** ID of the event to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Event | null, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise<string>; + + /** Deletes an existing event from the device. Use with caution. */ + function deleteEventAsync( + /** ID of the event to be deleted. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise<void>; + + /** Gets all attendees for a given event (or instance of a recurring event). */ + function getAttendeesForEventAsync( + /** ID of the event to return attendees for. Required. */ + eventId: string, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise<Attendee[]>; + + /** Available on Android only. Creates a new attendee record and adds it to the specified event. Note that if eventId specifies a recurring event, this will add the attendee to every instance of the event. */ + function createAttendeeAsync( + /** ID of the event to add this attendee to. Required. */ + eventId: string, + + /** A map of details for the attendee to be created */ + details?: Attendee + ): Promise<string>; + + /** Available on Android only. Updates an existing attendee record. To remove a property, explicitly set it to null in details. */ + function updateAttendeeAsync( + /** ID of the attendee record to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Attendee | null + ): Promise<string>; + + /** Available on Android only. Deletes an existing attendee record from the device. Use with caution. */ + function deleteAttendeeAsync(id: string): Promise<void>; + + /** Available on iOS only. Returns a list of reminders matching the provided criteria. */ + function getRemindersAsync( + /** Array of IDs of calendars to search for reminders in. Required. */ + calendarIds: string[], + + status?: ReminderStatus, + + /** Beginning of time period to search for reminders in. Required if status is defined. */ + startDate?: Date, + + /** End of time period to search for reminders in. Required if status is defined. */ + endDate?: Date + ): Promise<Reminder[]>; + + /** Available on iOS only. Returns a specific reminder selected by ID. */ + function getReminderAsync(id: string): Promise<Reminder>; + + /** Available on iOS only. Creates a new reminder on the specified calendar. */ + function createReminderAsync( + /** ID of the calendar to create this reminder in. Required. */ + calendarId: string, + + /** A map of details for the reminder to be created */ + details?: Reminder + ): Promise<string>; + + /** Available on iOS only. Updates the provided details of an existing reminder stored on the device. To remove a property, explicitly set it to null in details. */ + function updateReminderAsync( + /** ID of the reminder to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Reminder | null + ): Promise<string>; + + /** Available on iOS only. Deletes an existing reminder from the device. Use with caution. */ + function deleteReminderAsync(id: string): Promise<void>; + + /** Available on iOS only. */ + function getSourcesAsync(): Promise<Source[]>; + + /** Available on iOS only. Returns a specific source selected by ID. */ + function getSourceAsync(id: string): Promise<Source>; + + /** Available on Android only. Sends an intent to open the specified event in the OS Calendar app. */ + function openEventInCalendar( + /** ID of the event to open. Required. */ + id: string + ): void; +} +// #endregion + +// #region MailComposer +/** + * An API to compose mails using OS specific UI. + */ +export namespace MailComposer { + interface ComposeOptions { + /** An array of e-mail addressess of the recipients. */ + recipients?: string[]; + + /** An array of e-mail addressess of the CC recipients. */ + ccRecipients?: string[]; + + /** An array of e-mail addressess of the BCC recipients. */ + bccRecipients?: string[]; + + /** Subject of the mail. */ + subject?: string; + + /** Body of the mail. */ + body?: string; + + /** Whether the body contains HTML tags so it could be formatted properly. Not working perfectly on Android. */ + isHtml?: boolean; + + /** An array of app’s internal file uris to attach. */ + attachments?: string[]; + } + + /** Resolves to a promise with object containing status field that could be either sent, saved or cancelled. Android does not provide such info so it always resolves to sent. */ + function composeAsync( + /** A map defining the data to fill the mail */ + options: ComposeOptions + ): Promise<{ status: 'sent' | 'saved' | 'cancelled' }>; +} +// #endregion + +export namespace Updates { + namespace EventType { + /** A new update is available and has started downloading. */ + type DownloadStart = 'downloadStart'; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + type DownloadProgress = 'downloadProgress'; + /** A new update has finished downloading and is now stored in the device's cache. */ + type DownloadFinished = 'downloadFinished'; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + type NoUpdateAvailable = 'noUpdateAvailable'; + /** An error occurred trying to fetch the latest update. */ + type Error = 'error'; + + /** A new update is available and has started downloading. */ + const DOWNLOAD_STARTED: DownloadStart; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + const DOWNLOAD_PROGRESS: DownloadProgress; + /** A new update has finished downloading and is now stored in the device's cache. */ + const DOWNLOAD_FINISHED: DownloadFinished; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + const NO_UPDATE_AVAILABLE: NoUpdateAvailable; + /** An error occurred trying to fetch the latest update. */ + const ERROR: Error; + } + + interface UpdateCheck { + /** True if an update is available, false if you're already running the most up-to-date JS bundle. */ + isAvailable: boolean; + /** If `isAvailable` is true, the manifest of the available update. Undefined otherwise. */ + manifest?: Constants.Manifest; + } + + interface UpdateBundle { + /** True if the fetched bundle is new (i.e. a different version that the what's currently running). */ + isNew: boolean; + /** Manifest of the fetched update. */ + manifest: Constants.Manifest; + } + + /** An object that is passed into each event listener when a new version is available. */ + interface UpdateEvent { + /** Type of the event */ + type: EventType.DownloadStart + | EventType.DownloadProgress + | EventType.DownloadFinished + | EventType.NoUpdateAvailable + | EventType.Error; + /** If `type === Expo.Updates.EventType.DOWNLOAD_FINISHED`, the manifest of the newly downloaded update. Undefined otherwise. */ + manifest?: Constants.Manifest; + /** If `type === Expo.Updates.EventType.ERROR`, the error message. Undefined otherwise. */ + message?: string; + } + + /** An optional params object passed to fetchUpdateAsync. */ + interface FetchUpdateAsyncParams { + eventListener: UpdateEventListener; + } + + type UpdateEventListener = (event: UpdateEvent) => any; + + /** + * Invokes a callback when updates-related events occur, + * either on the initial app load or as a result of a call to `Expo.Updates.fetchUpdateAsync`. + */ + function addListener(listener: UpdateEventListener): EventSubscription; + + /** + * Check if a new published version of your project is available. + * Does not actually download the update. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function checkForUpdateAsync(): Promise<UpdateCheck>; + + /** + * Downloads the most recent published version of your experience to the device's local cache. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function fetchUpdateAsync(params?: FetchUpdateAsyncParams): Promise<UpdateBundle>; + + /** + * Immediately reloads the current experience. + * This will use your app.json updates configuration to fetch and load the newest available JS supported by the device's Expo environment. + * This is useful for triggering an update of your experience if you have published a new version. + */ + function reload(): void; + + /** + * Immediately reloads the current experience using the most recent cached version. + * This is useful for triggering an update of your experience if you have published and already downloaded a new version. + */ + function reloadFromCache(): void; +} + +// #region MediaLibrary +/** + * https://docs.expo.io/versions/latest/sdk/media-library + * Provides access to user's media library + * Requires Permissions.CAMERA_ROLL permissions. + */ + +export namespace MediaLibrary { + /** + * Creates an asset from existing file. The most common use case is to save a picture taken by Camera. + */ + function createAssetAsync(localUri: string): Promise<Asset>; + + /** + * Fetches a page of assets matching the provided criteria. + */ + function getAssetsAsync(options: GetAssetsOptions): Promise<GetAssetsResult>; + + /** + * Provides more informations about an asset, including GPS location, local URI and EXIF metadata. + */ + function getAssetInfoAsync(asset: string | Asset): Promise<Asset>; + + /** + * Deletes assets from the library. On iOS it deletes assets from all albums they belong to, while on Android it keeps all copies of them + * (album is strictly connected to the asset). Also, there is additional dialog on iOS that requires user to confirm this action. + */ + function deleteAssetsAsync(asset: string[] | Asset[]): Promise<boolean>; + + /** + * Queries for user-created albums in media gallery. + */ + function getAlbumsAsync(): Promise<Album[]>; + + /** + * Queries for an album with a specific name. + */ + function getAlbumAsync(albumName: string): Promise<Album>; + + /** + * Creates an album with given name and initial asset. + * The asset parameter is required on Android, since it's not possible to create empty album on this platform. + */ + function createAlbumAsync(albumName: string, asset: string | Asset): Promise<Album>; + + /** + * Adds array of assets to the album. + * On Android, by default it copies assets from the current album to provided one, however it's also possible to move them by passing false as copyAssets argument. + * In case they're copied you should keep in mind that getAssetsAsync will return duplicated assets. + */ + function addAssetsToAlbumAsync(assets: Asset[], album: string | Album, copyAssets?: boolean /* default true */): Promise<boolean>; + + /** + * Removes given assets from album. + * On Android, album will be automatically deleted if there are no more assets inside. + */ + function removeAssetsFromAlbumAsync(assets: Asset[], album: string | Album): Promise<boolean>; + + /** + * Available on iOS only. Fetches a list of moments, which is a group of assets taken around the same place and time. + */ + function getMomentsAsync(): Promise<Album[]>; + + enum MediaType { + audio = 'audio', + photo = 'photo', + video = 'video', + unknow = 'unknow' + } + + enum SortBy { + default = 'default', + id = 'id', + creationTime = 'creationTime', + modificationTime = 'modificationTime', + mediaType = 'mediaType', + width = 'width', + height = 'height', + duration = 'duration' + } + + // region Asset + interface AssetAndroid { + albumId?: string; + } + + interface AssetIos { + mediaSubtypes?: MediaType[]; + // * + orientation: number; + // * + isFavorite: boolean; + } + + interface Asset extends AssetAndroid, AssetIos { + id: string; + filename: string; + uri: string; + mediaType: string; + width: number; + height: number; + creationTime: number; + modificationTime: number; + duration: number; + // * + localUri?: string; + // * + location?: Location.LocationProps; + // * + exif?: object; + } + + /** + * These fields can be obtained only by calling getAssetInfoAsync method + */ + //#endregion + + // #region Album + interface AlbumIos { + type?: string; + // * + startTime: number; + // * + endTime: number; + // * + approximateLocation?: Location.LocationProps; + // * + locationNames?: string[]; + } + + /** + * These fields apply only to albums whose type is moment + */ + + interface Album extends AlbumIos { + id: string; + title: string; + assetCount: number; + } + // #endregion + + interface GetAssetsOptions { + first?: number; + after?: string; + album?: string | Album; + sortBy?: SortBy; + mediaType?: MediaType; + } + + interface GetAssetsResult { + assets: Asset[]; + endCursor: string; + hasNextPage: boolean; + totalCount: number; + } +} +// #endregion + +// #region Haptic +/** + * https://docs.expo.io/versions/latest/sdk/haptic + * Provides haptic feedback for iOS 10+ devices using the Taptic Engine. + * If this is used in Android the device will use ReactNative.Vibrate instead, it's best to just avoid this. + */ +export namespace Haptic { + /** + * Used to let a user know when a selection change has been registered + */ + function selection(): void; + function notification(notificationType?: NotificationType): void; + function impact(impactStyles?: ImpactStyles): void; + + enum ImpactStyles { + Light = 'light', + Medium = 'medium', + Heavy = 'heavy' + } + + enum NotificationType { + Success = 'success', + Warning = 'warning', + Error = 'error' + } +} +// #endregion diff --git a/types/expo/v31/tsconfig.json b/types/expo/v31/tsconfig.json new file mode 100644 index 0000000000..ae698d5f5e --- /dev/null +++ b/types/expo/v31/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "expo": [ + "expo/v31" + ], + "expo/*": [ + "expo/v31/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.tsx" + ] +} diff --git a/types/expo/v31/tslint.json b/types/expo/v31/tslint.json new file mode 100644 index 0000000000..8270136207 --- /dev/null +++ b/types/expo/v31/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "void-return": false, + "max-line-length": false + } +} From b469f0266920b5538ade64c7d9b6731519568085 Mon Sep 17 00:00:00 2001 From: Ifiok Jr <ifiokotung@gmail.com> Date: Tue, 5 Feb 2019 11:15:36 +0000 Subject: [PATCH 082/200] feat: add wait-on types --- types/wait-on/index.d.ts | 94 ++++++++++++++++++++++++++++++++++ types/wait-on/tsconfig.json | 16 ++++++ types/wait-on/tslint.json | 1 + types/wait-on/wait-on-tests.ts | 75 +++++++++++++++++++++++++++ 4 files changed, 186 insertions(+) create mode 100644 types/wait-on/index.d.ts create mode 100644 types/wait-on/tsconfig.json create mode 100644 types/wait-on/tslint.json create mode 100644 types/wait-on/wait-on-tests.ts diff --git a/types/wait-on/index.d.ts b/types/wait-on/index.d.ts new file mode 100644 index 0000000000..55275a24e0 --- /dev/null +++ b/types/wait-on/index.d.ts @@ -0,0 +1,94 @@ +// Type definitions for wait-on 3.2 +// Project: https://github.com/jeffbski/wait-on#readme +// Definitions by: Ifiok Jr. <https://github.com/ifiokjr> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = waitOn; + +declare function waitOn(options: waitOn.WaitOnOptions): Promise<void>; +declare function waitOn( + options: waitOn.WaitOnOptions, + cb: (err: any) => void, +): void; + +declare namespace waitOn { + interface WaitOnOptions { + /** + * Array of string resources to wait for. prefix determines the type of resource with the default type of file: + */ + resources: string[]; + /** + * Initial delay in ms. + * @default 0 + */ + delay?: number; + /** + * Poll resource interval in ms, + * @default 250ms + */ + interval?: number; + /** + * Flag which outputs to stdout, remaining resources waited on and when complete or any error occurs. + */ + log?: boolean; + /** + * Flag to reverse operation so checks are for resources being NOT available. + * @default false + */ + reverse?: boolean; + /** + * Timeout in ms until it aborts with error. + * @default Infinity + */ + timeout?: number; + /** + * Tcp timeout in ms. + * @default 300 + */ + tcpTimeout?: number; + /** + * Flag which outputs debug output. + * @default false + */ + verbose?: boolean; + /** + * Stabilization time in ms + * Waits this amount of time for file sizes to stabilize or other resource availability to remain unchanged. + * @default 750ms. + */ + window?: number; + + /** + * Https specific option. + * see https:// github.com/request/request#readme for specific details + */ + auth?: WaitOnAuth; + httpSignature?: HttpSignature; + strictSSL?: boolean; + followAllRedirects?: boolean; + followRedirect?: boolean; + headers?: Record<string, any>; + } + + interface HttpSignature { + keyId: string; + key: string; + } + + type WaitOnAuth = + | { + username: string; + password: string; + } + | { + /** + * Alias of username + */ + user: string; + /** + * Alias of password + */ + pass: string; + }; +} diff --git a/types/wait-on/tsconfig.json b/types/wait-on/tsconfig.json new file mode 100644 index 0000000000..c400fad2fe --- /dev/null +++ b/types/wait-on/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "wait-on-tests.ts"] +} diff --git a/types/wait-on/tslint.json b/types/wait-on/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/wait-on/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/wait-on/wait-on-tests.ts b/types/wait-on/wait-on-tests.ts new file mode 100644 index 0000000000..dea9a9c262 --- /dev/null +++ b/types/wait-on/wait-on-tests.ts @@ -0,0 +1,75 @@ +import waitOn = require('wait-on'); + +const opts = { + resources: [ + 'file1', + 'http://foo.com:8000/bar', + 'https://my.com/cat', + 'http-get://foo.com:8000/bar', + 'https-get://my.com/cat', + 'tcp:foo.com:8000', + 'socket:/my/sock', + 'http://unix:/my/sock:/my/url', + 'http-get://unix:/my/sock:/my/url', + ], + delay: 1000, // initial delay in ms, default 0 + interval: 100, // poll interval in ms, default 250ms + timeout: 30000, // timeout in ms, default Infinity + tcpTimeout: 1000, // tcp timeout in ms, default 300ms + window: 1000, // stabilization time in ms, default 750ms + + // http options + ca: [ + /* strings or binaries */ + ], + cert: [ + /* strings or binaries */ + ], + key: [ + /* strings or binaries */ + ], + passphrase: 'yourpassphrase', + auth: { + user: 'theuser', // or username + pass: 'thepassword', // or password + }, + httpSignature: { + keyId: 'yourKeyId', + key: 'yourKey', + }, + strictSSL: false, + followAllRedirects: true, + followRedirect: true, + headers: { + 'x-custom': 'headers', + }, +}; + +const handleError = (err: any) => undefined; + +// Usage with callback function +waitOn(opts, err => { + if (err) { + return handleError(err); + } + // once here, all resources are available +}); + +// Usage with promises +waitOn(opts) + .then(() => { + // once here, all resources are available + }) + .catch(err => { + handleError(err); + }); + +// Usage with async await +(async () => { + try { + await waitOn(opts); + // once here, all resources are available + } catch (err) { + handleError(err); + } +})(); From 4a377ec1644108760f7317f780b7c938096bcf5b Mon Sep 17 00:00:00 2001 From: Alex Kvak <a.kvak@adara.io> Date: Tue, 5 Feb 2019 14:35:57 +0300 Subject: [PATCH 083/200] [stellar-base]: add TransactionBuilder.setTimeout and TimeoutInfinite according to v0.10.0 changes --- types/stellar-base/index.d.ts | 3 +++ types/stellar-base/stellar-base-tests.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/types/stellar-base/index.d.ts b/types/stellar-base/index.d.ts index a230c36942..7af7c38770 100644 --- a/types/stellar-base/index.d.ts +++ b/types/stellar-base/index.d.ts @@ -439,10 +439,13 @@ export class Transaction<TMemo extends Memo = Memo, TOps extends Operation[] = O signatures: xdr.DecoratedSignature[]; } +export const TimeoutInfinite = 0; + export class TransactionBuilder { constructor(sourceAccount: Account, options?: TransactionBuilder.TransactionBuilderOptions) addOperation(operation: xdr.Operation): this; addMemo(memo: Memo): this; + setTimeout(timeoutInSeconds: number): this; build(): Transaction; } diff --git a/types/stellar-base/stellar-base-tests.ts b/types/stellar-base/stellar-base-tests.ts index 83a52cbe7b..4884a5a6a5 100644 --- a/types/stellar-base/stellar-base-tests.ts +++ b/types/stellar-base/stellar-base-tests.ts @@ -6,6 +6,7 @@ const account = new StellarSdk.Account(sourceKey.publicKey(), '1'); const transaction = new StellarSdk.TransactionBuilder(account) .addOperation(StellarSdk.Operation.accountMerge({destination: destKey.publicKey()})) .addMemo(new StellarSdk.Memo(StellarSdk.MemoText, "memo")) + .setTimeout(5) .build(); // $ExpectType () => Transaction<Memo<MemoType>, Operation[]> const sig = StellarSdk.xdr.DecoratedSignature.fromXDR(Buffer.of(1, 2)); // $ExpectType DecoratedSignature @@ -38,3 +39,5 @@ StellarSdk.Operation.fromXDRObject(newSignerXDR2).signer; // $ExpectType Sha256H const newSignerXDR3 = StellarSdk.Operation.setOptions({signer: {preAuthTx: '', weight: 1}}); StellarSdk.Operation.fromXDRObject(newSignerXDR3).signer; // $ExpectType PreAuthTx + +StellarSdk.TimeoutInfinite; // $ExpectType 0 From 971d40fedcd64d7f04209e778c70855ae9f06db9 Mon Sep 17 00:00:00 2001 From: Christian Boehlke <christian@boehlkes.de> Date: Tue, 5 Feb 2019 12:54:56 +0100 Subject: [PATCH 084/200] [pubnub] Add grant method --- types/pubnub/index.d.ts | 29 ++++++++++++++++++++++++++++- types/pubnub/pubnub-tests.ts | 11 +++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index c10cd506b9..4a8b497506 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -4,7 +4,8 @@ // rollymaduk <https://github.com/rollymaduk>, // vitosamson <https://github.com/vitosamson>, // FlorianDr <https://github.com/FlorianDr>, -// danduh <https://github.com/danduh> +// danduh <https://github.com/danduh>, +// ChristianBoehlke <https://github.com/ChristianBoehlke> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration // TypeScript Version: 2.2 @@ -99,6 +100,15 @@ declare class Pubnub { params: Pubnub.SetStateParameters ): Promise<Pubnub.SetStateResponse>; + grant( + params: Pubnub.GrantParameters, + callback: (status: Pubnub.GrantStatus, response: {}) => void + ): void; + + grant( + params: Pubnub.GrantParameters + ): Promise<{}>; + encrypt( data: string, customCipherKey?: string, @@ -348,6 +358,23 @@ declare namespace Pubnub { }; } + // grant + interface GrantParameters { + channels?: string[]; + channelGroups?: string[]; + authKeys?: string[]; + ttl?: number; + read?: boolean; + write?: boolean; + manage?: boolean; + } + + interface GrantStatus { + error: boolean; + operation: string; + statusCode: number; + } + // encrypt & decrypt interface CryptoParameters { encryptKey?: boolean; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 96dd4202ba..8750919e59 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -87,6 +87,17 @@ pubnub.setState({ channels: [] }).then(res => { console.log(res.state); }); +const grantOptions = { + channels: ['channel-1'], + authKeys: ['auth-key'], + read: true, + write: false, + manage: false +}; +pubnub.grant(grantOptions).then(status => { + console.log(status); +}); + pubnub.history({channel: 'channel-1', count: 2}, (status, res) => { console.log(status); console.log(res); From e9dcde5f70ddb7bf72c047c23402c7cdfdb693ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kalvis=20Kalni=C5=86=C5=A1?= <kalvis@factury.co> Date: Tue, 5 Feb 2019 14:39:38 +0200 Subject: [PATCH 085/200] fix(keypair): Keypair.type and sign/verify --- types/stellar-base/index.d.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/types/stellar-base/index.d.ts b/types/stellar-base/index.d.ts index a230c36942..6e9acfaa94 100644 --- a/types/stellar-base/index.d.ts +++ b/types/stellar-base/index.d.ts @@ -49,6 +49,8 @@ export class Asset { export const FastSigning: boolean; +export type KeypairType = 'ed25519'; + export class Keypair { static fromRawEd25519Seed(secretSeed: Buffer): Keypair; static fromBase58Seed(secretSeed: string): Keypair; @@ -57,17 +59,18 @@ export class Keypair { static fromPublicKey(publicKey: string): Keypair; static random(): Keypair; - constructor(keys: { type: 'ed25519', secretKey: string } | { type: 'ed25519', Key: string }) + constructor(keys: { type: KeypairType, secretKey: string, publicKey?: string } | { type: KeypairType, publicKey: string }) + readonly type: KeypairType; publicKey(): string; secret(): string; rawPublicKey(): Buffer; rawSecretKey(): Buffer; canSign(): boolean; - sign(data: Buffer): Buffer; + sign(data: Buffer): xdr.Signature; signDecorated(data: Buffer): xdr.DecoratedSignature; signatureHint(): xdr.SignatureHint; - verify(data: Buffer, signature: Buffer): boolean; + verify(data: Buffer, signature: xdr.Signature): boolean; } export const MemoNone = 'none'; @@ -498,5 +501,5 @@ export namespace xdr { } export function hash(data: Buffer): Buffer; -export function sign(data: Buffer, rawSecret: Buffer): Buffer; -export function verify(data: Buffer, signature: Buffer, rawPublicKey: Buffer): boolean; +export function sign(data: Buffer, rawSecret: Buffer): xdr.Signature; +export function verify(data: Buffer, signature: xdr.Signature, rawPublicKey: Buffer): boolean; From b4683d718608a517a0a925d0537ca0783a088fe2 Mon Sep 17 00:00:00 2001 From: Erik Krogh Kristensen <erik@webbies.dk> Date: Tue, 5 Feb 2019 14:20:00 +0100 Subject: [PATCH 086/200] loglevel: Move noConflict and getLogger to a DefaultLogger interface --- types/loglevel/index.d.ts | 48 ++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/types/loglevel/index.d.ts b/types/loglevel/index.d.ts index 3ad9faf707..64eee88aa6 100644 --- a/types/loglevel/index.d.ts +++ b/types/loglevel/index.d.ts @@ -6,7 +6,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -declare var log: log.Logger; +declare var log: log.DefaultLogger; export as namespace log; export = log; @@ -44,6 +44,30 @@ declare namespace log { type MethodFactory = (methodName: string, level: LogLevelNumbers, loggerName: string) => LoggingMethod; + interface DefaultLogger extends Logger { + /** + * If you're using another JavaScript library that exposes a 'log' global, you can run into conflicts with loglevel. + * Similarly to jQuery, you can solve this by putting loglevel into no-conflict mode immediately after it is loaded + * onto the page. This resets to 'log' global to its value before loglevel was loaded (typically undefined), and + * returns the loglevel object, which you can then bind to another name yourself. + */ + noConflict(): any; + + /** + * This gets you a new logger object that works exactly like the root log object, but can have its level and + * logging methods set independently. All loggers must have a name (which is a non-empty string). Calling + * getLogger() multiple times with the same name will return an identical logger object. + * In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are + * working with them. Using the getLogger() method lets you create a separate logger for each part of your + * application with its own logging level. Likewise, for small, independent modules, using a named logger instead + * of the default root logger allows developers using your module to selectively turn on deep, trace-level logging + * when trying to debug problems, while logging only errors or silencing logging altogether under normal + * circumstances. + * @param name The name of the produced logger + */ + getLogger(name: string): Logger; + } + interface Logger { /** * Available log levels. @@ -105,14 +129,6 @@ declare namespace log { */ setLevel(level: LogLevelDesc, persist?: boolean): void; - /** - * If you're using another JavaScript library that exposes a 'log' global, you can run into conflicts with loglevel. - * Similarly to jQuery, you can solve this by putting loglevel into no-conflict mode immediately after it is loaded - * onto the page. This resets to 'log' global to its value before loglevel was loaded (typically undefined), and - * returns the loglevel object, which you can then bind to another name yourself. - */ - noConflict(): any; - /** * Returns the current logging level, as a value from LogLevel. * It's very unlikely you'll need to use this for normal application logging; it's provided partly to help plugin @@ -137,20 +153,6 @@ declare namespace log { */ setDefaultLevel(level: LogLevelDesc): void; - /** - * This gets you a new logger object that works exactly like the root log object, but can have its level and - * logging methods set independently. All loggers must have a name (which is a non-empty string). Calling - * getLogger() multiple times with the same name will return an identical logger object. - * In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are - * working with them. Using the getLogger() method lets you create a separate logger for each part of your - * application with its own logging level. Likewise, for small, independent modules, using a named logger instead - * of the default root logger allows developers using your module to selectively turn on deep, trace-level logging - * when trying to debug problems, while logging only errors or silencing logging altogether under normal - * circumstances. - * @param name The name of the produced logger - */ - getLogger(name: string): Logger; - /** * This enables all log messages, and is equivalent to log.setLevel("trace"). * From b238ecd1fa8f768e56ee71787f229692b55db0a6 Mon Sep 17 00:00:00 2001 From: chang liu <3dslayer@gmail.com> Date: Wed, 6 Feb 2019 00:22:32 +1100 Subject: [PATCH 087/200] [reactstrap] Update type of CustomInput label prop --- types/reactstrap/lib/CustomInput.d.ts | 2 +- types/reactstrap/reactstrap-tests.tsx | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/types/reactstrap/lib/CustomInput.d.ts b/types/reactstrap/lib/CustomInput.d.ts index 8527c29455..5d0af9f5c8 100644 --- a/types/reactstrap/lib/CustomInput.d.ts +++ b/types/reactstrap/lib/CustomInput.d.ts @@ -10,7 +10,7 @@ export type CustomInputType = export type CustomInputProps<T = {}> = React.InputHTMLAttributes<HTMLInputElement> & { type: CustomInputType; - label?: string; + label?: React.ReactNode; inline?: boolean; bsSize?: 'lg' | 'sm'; valid?: boolean; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index f3678813de..67c24bce28 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -4112,7 +4112,8 @@ class Example119 extends React.Component<any, any> { <div> <CustomInput type="checkbox" id="exampleCustomCheckbox" label="Check this custom checkbox" /> <CustomInput type="checkbox" id="exampleCustomCheckbox2" label="Or this one" /> - <CustomInput type="checkbox" id="exampleCustomCheckbox3" label="But not this disabled one" disabled /> + <CustomInput type="checkbox" id="exampleCustomCheckbox3" label={<span>Or this one</span>} /> + <CustomInput type="checkbox" id="exampleCustomCheckbox4" label="But not this disabled one" disabled /> </div> </FormGroup> <FormGroup> @@ -4120,7 +4121,8 @@ class Example119 extends React.Component<any, any> { <div> <CustomInput type="radio" id="exampleCustomRadio" name="customRadio" label="Select this custom radio" /> <CustomInput type="radio" id="exampleCustomRadio2" name="customRadio" label="Or this one" /> - <CustomInput type="radio" id="exampleCustomRadio3" label="But not this disabled one" disabled /> + <CustomInput type="radio" id="exampleCustomRadio3" name="customRadio" label={<span>Or this one</span>} /> + <CustomInput type="radio" id="exampleCustomRadio4" label="But not this disabled one" disabled /> </div> </FormGroup> <FormGroup> @@ -4128,6 +4130,7 @@ class Example119 extends React.Component<any, any> { <div> <CustomInput type="checkbox" id="exampleCustomInline" label="An inline custom input" inline /> <CustomInput type="checkbox" id="exampleCustomInline2" label="and another one" inline /> + <CustomInput type="checkbox" id="exampleCustomInline3" label={<span>and this one</span>} inline /> </div> </FormGroup> <FormGroup> @@ -4181,6 +4184,7 @@ class Example119 extends React.Component<any, any> { <FormGroup> <Label for="exampleCustomFileBrowser">File Browser with Custom Label</Label> <CustomInput type="file" id="exampleCustomFileBrowser" name="customFile" label="Yo, pick a file!" /> + <CustomInput type="file" id="exampleCustomFileBrowser1" name="customFile" label={<span>Yo, pick a file!</span>} /> </FormGroup> <FormGroup> <Label for="exampleCustomFileBrowser">File Browser Disabled</Label> From dfbfa7edd93ec60f12d1dd441a88907ee9c0cfd4 Mon Sep 17 00:00:00 2001 From: Erik Krogh Kristensen <erik@webbies.dk> Date: Tue, 5 Feb 2019 14:59:30 +0100 Subject: [PATCH 088/200] default_type went away in mime v2 --- types/mime/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/mime/index.d.ts b/types/mime/index.d.ts index 2ff497ac12..771898cf91 100644 --- a/types/mime/index.d.ts +++ b/types/mime/index.d.ts @@ -13,5 +13,3 @@ export interface TypeMap { [key: string]: string[]; } export function getType(path: string): string | null; export function getExtension(mime: string): string | null; export function define(mimes: TypeMap, force?: boolean): void; - -export const default_type: string; From a407d194a1fadf0da0af61144cea1decf43947dd Mon Sep 17 00:00:00 2001 From: Erik Krogh Kristensen <erik@webbies.dk> Date: Tue, 5 Feb 2019 15:14:45 +0100 Subject: [PATCH 089/200] pathjs: various small fixes --- types/pathjs/index.d.ts | 16 ++++++++++------ types/pathjs/pathjs-tests.ts | 4 ++-- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/types/pathjs/index.d.ts b/types/pathjs/index.d.ts index fa652d0245..2ab8198c59 100644 --- a/types/pathjs/index.d.ts +++ b/types/pathjs/index.d.ts @@ -3,6 +3,10 @@ // Definitions by: Lokesh Peta <https://github.com/lokeshpeta> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export interface IDictionary<T> { + [id: string]: T; +} + interface IPathHistory{ initial: any; pushState(state: any, title: string, path: string):void; @@ -19,11 +23,11 @@ interface IPathRoute{ } interface IPathRoutes{ - current: IPathRoute, - root: IPathRoute, - rescue: Function, - previous: IPathRoute, - defined: {} + current?: string, + root?: string, + rescue?: Function, + previous?: string, + defined: IDictionary<IPathRoute> } interface IPathCore{ @@ -43,7 +47,7 @@ interface IPath { history: IPathHistory; - match(path: string, parameterize: boolean): IPathRoute; + match(path: string, parameterize: boolean): IPathRoute | null; dispatch(passed_route: string): void; diff --git a/types/pathjs/pathjs-tests.ts b/types/pathjs/pathjs-tests.ts index f64fa2a15b..e71dcc7dbb 100644 --- a/types/pathjs/pathjs-tests.ts +++ b/types/pathjs/pathjs-tests.ts @@ -1,4 +1,4 @@ - +import {Path} from "./index"; Path.map("/test/:id") .to(()=>{ }); @@ -30,4 +30,4 @@ var funs = new Array<Function>(); funs.push(test1); funs.push(test2); -route.enter(funs); \ No newline at end of file +route.enter(funs); From d22f3983568ccd58293c5db758165cd7b2a52fd8 Mon Sep 17 00:00:00 2001 From: Hanna Greaves <hgreav@microsoft.com> Date: Tue, 5 Feb 2019 14:47:51 +0000 Subject: [PATCH 090/200] Correct method return type --- types/slate/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 22cf22f8ef..567b7ee52e 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -299,7 +299,7 @@ export class Text extends Immutable.Record({}) { ): Immutable.Set<Mark>; getMarks(): Immutable.OrderedSet<Mark>; getMarksAsArray(): Mark[]; - getMarksAtIndex(index: number): Mark; + getMarksAtIndex(index: number): Immutable.OrderedSet<Mark>; getNode(key: string): Node | null; getPath(key: string | Path): Path; hasNode(key: string): boolean; From 98d33a0834730342fb0b2bbbf0dac59949a4a590 Mon Sep 17 00:00:00 2001 From: Bradley Hill <brad.hill@jostens.com> Date: Tue, 5 Feb 2019 09:15:18 -0600 Subject: [PATCH 091/200] Fabricjs missing pattern transform definitions (looks like DT prefers [] to Array, that's OK, i'll still play) --- types/fabric/fabric-impl.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 1508148001..68c0a73efe 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -617,7 +617,7 @@ interface IPatternOptions { /** * Transform matrix to change the pattern, imported from svgs */ - patternTransform?: Array<number>; + patternTransform?: number[]; } export interface Pattern extends IPatternOptions { } export class Pattern { @@ -4645,7 +4645,7 @@ interface IUtilMisc { /** * Creates a transform matrix with the specified scale and skew */ - customTransformMatrix(scaleX: number, scaleY: number, skewX: number): Array<number>; + customTransformMatrix(scaleX: number, scaleY: number, skewX: number): number[]; /** * Returns string representation of function body From c21a992f56d3d25c2c1d9edf564f4f8eff9d2ed6 Mon Sep 17 00:00:00 2001 From: Stefan Wullems <stefanwullems1998@gmail.com> Date: Tue, 5 Feb 2019 16:44:40 +0100 Subject: [PATCH 092/200] Fixed wrong typing for onLayoutChange --- types/react-grid-layout/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-grid-layout/index.d.ts b/types/react-grid-layout/index.d.ts index 91c8ad1f9c..abf384dac0 100644 --- a/types/react-grid-layout/index.d.ts +++ b/types/react-grid-layout/index.d.ts @@ -285,7 +285,7 @@ declare namespace ReactGridLayout { /** * Callback so you can save the layout. */ - onLayoutChange?(currentLayout: Layout, allLayouts: Layouts): void; + onLayoutChange?(currentLayout: Layout[], allLayouts: Layouts): void; /** * Callback when the width changes, so you can modify the layout as needed. From 6e6f3036c95940af9ce0c1873f2dddd876ee2798 Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Tue, 5 Feb 2019 11:27:19 -0500 Subject: [PATCH 093/200] Stricter tslint rules Fix bugs found --- types/react-tabs/index.d.ts | 14 +++--- types/react-tabs/react-tabs-tests.ts | 24 ++++++---- types/react-tabs/tslint.json | 69 +--------------------------- 3 files changed, 23 insertions(+), 84 deletions(-) diff --git a/types/react-tabs/index.d.ts b/types/react-tabs/index.d.ts index e6793ebb4e..0eabf0c613 100644 --- a/types/react-tabs/index.d.ts +++ b/types/react-tabs/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for react-tabs 2.3.0 +// Type definitions for react-tabs 2.3 // Project: https://github.com/reactjs/react-tabs/ -// Definitions by: Yuu Igarashi <https://github.com/yu-i9/>, Daniel Tschinder <https://github.com/danez>, Ummon Karpe <https://github.com/Equationist> +// Definitions by: Yuu Igarashi <https://github.com/yu-i9> +// Daniel Tschinder <https://github.com/danez> +// Ummon Karpe <https://github.com/Equationist> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -10,7 +12,7 @@ type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; export interface TabsProps extends Omit<React.HTMLProps<HTMLDivElement>, "className" | "onSelect"> { - className?: string | Array<string> | { [name: string]: boolean }; + className?: string | string[] | { [name: string]: boolean }; defaultFocus?: boolean; defaultIndex?: number; disabledTabClassName?: string; @@ -24,12 +26,12 @@ export interface TabsProps export interface TabListProps extends Omit<React.HTMLProps<HTMLUListElement>, "className"> { - className?: string | Array<string> | { [name: string]: boolean }; + className?: string | string[] | { [name: string]: boolean }; } export interface TabProps extends Omit<React.HTMLProps<HTMLLIElement>, "className" | "tabIndex"> { - className?: string | Array<string> | { [name: string]: boolean }; + className?: string | string[] | { [name: string]: boolean }; disabled?: boolean; disabledClassName?: string; selectedClassName?: string; @@ -38,7 +40,7 @@ export interface TabProps export interface TabPanelProps extends Omit<React.HTMLProps<HTMLDivElement>, "className"> { - className?: string | Array<string> | { [name: string]: boolean }; + className?: string | string[] | { [name: string]: boolean }; forceRender?: boolean; selectedClassName?: string; } diff --git a/types/react-tabs/react-tabs-tests.ts b/types/react-tabs/react-tabs-tests.ts index ec9a88c11e..7488a8a55a 100644 --- a/types/react-tabs/react-tabs-tests.ts +++ b/types/react-tabs/react-tabs-tests.ts @@ -9,7 +9,8 @@ import { TabProps, TabPanel, TabPanelProps, - resetIdCounter } from "react-tabs"; + resetIdCounter +} from "react-tabs"; resetIdCounter(); @@ -26,15 +27,18 @@ class TestApp extends React.Component { } render() { - return React.createElement(Tabs, {onSelect: this.onSelect, selectedIndex: 1, defaultFocus:true, name:'Tabs', autoFocus:true}, - React.createElement(TabList, {className: "test-class"}, - React.createElement(Tab, {disabled: true}, "Tab1"), - React.createElement(Tab, {selectedClassName: "active"}, "Tab2"), - React.createElement(Tab, {}, "Tab3")), - React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content1")), - React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content2")), - React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content3"))); + return React.createElement(Tabs, { onSelect: this.onSelect, selectedIndex: 1, defaultFocus: true, name: 'Tabs', autoFocus: true }, + React.createElement(TabList, { className: "test-class" }, + React.createElement(Tab, { disabled: true }, "Tab1"), + React.createElement(Tab, { selectedClassName: "active" }, "Tab2"), + React.createElement(Tab, {}, "Tab3")), + React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content1")), + React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content2")), + React.createElement(TabPanel, {}, React.createElement("h2", {}, "Content3"))); } } -ReactDOM.render(React.createElement(TestApp, {}), document.getElementById("test-app")); +ReactDOM.render( + React.createElement(TestApp, {}), + document.getElementById("test-app") +); diff --git a/types/react-tabs/tslint.json b/types/react-tabs/tslint.json index a41bf5d19a..3d429fc065 100644 --- a/types/react-tabs/tslint.json +++ b/types/react-tabs/tslint.json @@ -1,79 +1,12 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "void-return": false } } From 5216292904f3b3863bccdf5b74510e2a58fe1c55 Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Tue, 5 Feb 2019 12:17:50 -0500 Subject: [PATCH 094/200] Add missing prop types for VictoryBar Stricter tslint and related cleanup --- types/victory/index.d.ts | 132 ++++++++++++++++++-------------- types/victory/tslint.json | 61 +-------------- types/victory/victory-tests.tsx | 17 ++-- 3 files changed, 85 insertions(+), 125 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 49cfcf7a83..c6909a4886 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -34,7 +34,7 @@ declare module "victory" { // Many victory components accept string or number or callback which returns string or number type StringOrNumberOrCallback = string | number | { (): string | number }; - type NumberOrCallback = { (): number } | number; + type NumberOrCallback = ((datum: any, active: boolean) => number) | number; /** * Style interface used in components/themeing @@ -188,7 +188,7 @@ declare module "victory" { * with a viewBox attribute, or a static container with absolute width and height. * @default true */ - responsive?: boolean + responsive?: boolean; /** * The style prop specifies styles for your VictoryContainer. Any valid inline style properties * will be applied. Height and width should be specified via the height @@ -244,7 +244,7 @@ declare module "victory" { type CursorData = { x: number; y: number; - } + }; export interface VictoryCursorContainerProps extends VictoryContainerProps { /** @@ -294,7 +294,7 @@ declare module "victory" { /** * When the disable prop is set to true, VictoryCursorContainer events will not fire. */ - disable?: boolean + disable?: boolean; /** * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). * When this prop is not specified, the cursor will be a 2-dimensional crosshair. @@ -302,7 +302,7 @@ declare module "victory" { * the cursor will then be a vertical line that will inspect the time value of the current mouse position. * @example onChange={(value, props) => this.setState({cursorValue: value})} */ - onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void + onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; } export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} @@ -571,7 +571,8 @@ declare module "victory" { flyoutStyle?: React.CSSProperties; /** * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. - * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. + * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, + * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. * If flyoutComponent is omitted, a default Flyout component will be created with props described above. * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} @@ -590,7 +591,8 @@ declare module "victory" { height?: NumberOrCallback; /** * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. - * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. negative values result in a left orientation and positive values will result in a right orientation by default. + * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. + * negative values result in a left orientation and positive values will result in a right orientation by default. */ horizontal?: boolean; /** @@ -617,11 +619,13 @@ declare module "victory" { */ pointerLength?: NumberOrCallback; /** - * The pointerWidth prop determines the width of the base of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. + * The pointerWidth prop determines the width of the base of the triangular pointer extending from + * the flyout. This prop may be given as a positive number or a function of datum. */ pointerWidth?: NumberOrCallback; /** - * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element within VictoryContainer. Note: This prop should not be set to true when using a custom container element. + * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element + * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. */ renderInPortal?: boolean; /** @@ -636,10 +640,11 @@ declare module "victory" { /** * VictoryAxis uses the standard theme prop. Read about it here * @default VictoryTheme.grayscale - */ + */ theme?: VictoryThemeDefinition; /** - * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. */ width?: NumberOrCallback; /** @@ -652,9 +657,9 @@ declare module "victory" { y?: number; } - /** - * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. + * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label + * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. * VictoryTooltip renders text as well as a configurable Flyout container. */ export class VictoryTooltip extends React.Component< @@ -735,9 +740,7 @@ declare module "victory" { * Targets may be any valid style namespace for a given component */ target: TTarget; - /** - * - */ + eventKey?: TEventKey; /** * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks @@ -1037,7 +1040,7 @@ declare module "victory" { * } * ]} *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; /** * The interpolation prop determines how data points should be connected when plotting a line @@ -1251,7 +1254,7 @@ declare module "victory" { * The tickValues prop explicitly specifies which tick values to draw on the axis. * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] */ - tickValues?: any[] + tickValues?: any[]; } /** @@ -1262,12 +1265,41 @@ declare module "victory" { export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The alignment prop specifies how bars should be aligned relative to their data points. + * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, + * bars will have “middle” alignment relative to their data points. + */ + alignment?: "start" | "middle" | "end"; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; /** * The cornerRadius prop specifies a radius to apply to each bar. * If this prop is given as a single number, the radius will only be applied to the top of each bar. * When this prop is given as a function, it will be evaluated with the arguments datum, and active. */ - cornerRadius?: NumberOrCallback; + cornerRadius?: NumberOrCallback + | { + top?: number | (NumberOrCallback), + topLeft?: number | (NumberOrCallback), + topRight?: number | (NumberOrCallback), + bottom?: number | (NumberOrCallback), + bottomLeft?: number | (NumberOrCallback), + bottomRight?: number | (NumberOrCallback) + }; /** * The event prop take an array of event objects. Event objects are composed of * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace @@ -1308,7 +1340,7 @@ declare module "victory" { * } * ]} *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -1331,21 +1363,6 @@ declare module "victory" { * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} */ style?: VictoryStyleInterface; - /** - * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. - * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will - * be used to calculate a default width for each bar given the total number of bars in the data series - * and the overall width of the chart. - */ - barRatio?: number; - /** - * The barWidth prop is used to specify the width of each bar. This prop may be given as - * a number of pixels or as a function that returns a number. When this prop is given as - * a function, it will be evaluated with the arguments datum, and active. When this value - * is not given, a default value will be calculated based on the overall dimensions of - * the chart, and the number of bars. - */ - barWidth?: NumberOrCallback; } /** @@ -1669,7 +1686,7 @@ declare module "victory" { * } * ]} *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -1688,16 +1705,16 @@ declare module "victory" { * case of groups of bars, this number should be equal to the width of the bar * plus the desired spacing between bars. */ - offset?:number + offset?: number; /** * The style prop specifies styles for your grouped chart. These styles will be * applied to all grouped children */ style?: VictoryStyleInterface; } - + export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} - + export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The event prop take an array of event objects. Event objects are composed of @@ -1736,7 +1753,7 @@ declare module "victory" { * } * ]} *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** * The interpolation prop determines how data points should be connected @@ -1770,13 +1787,13 @@ declare module "victory" { */ style?: VictoryStyleInterface; } - + /** * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. * Check out VictoryChart for easy to use line charts and more. */ export class VictoryLine extends React.Component<VictoryLineProps, any> {} - + export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The colorScale prop defines a color scale to be applied to each data @@ -1925,14 +1942,14 @@ declare module "victory" { x?: number; y?: number; } - + /** * VictoryLegend renders a chart legend component. */ export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} - + type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; - + export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { /** * The bubbleProperty prop indicates which property of the data object should be used @@ -1979,7 +1996,7 @@ declare module "victory" { * } * ]} *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -2014,13 +2031,13 @@ declare module "victory" { */ symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; } - + /** * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. * Check out VictoryChart for easy to use scatter plots and more. */ export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} - + export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The categories prop specifies how categorical data for a chart should be ordered. @@ -2097,7 +2114,7 @@ declare module "victory" { * } * ]} *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -2121,9 +2138,9 @@ declare module "victory" { */ xOffset?: number; } - + export class VictoryStack extends React.Component<VictoryStackProps, any> {} - + export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The colorScale prop is an optional prop that defines the color scale the pie @@ -2204,7 +2221,7 @@ declare module "victory" { * } * ]} *}} - */ + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally @@ -2212,10 +2229,10 @@ declare module "victory" { */ eventKey?: StringOrNumberOrCallback; /** - * Specifies the radius of the chart. If this property is not provided it is computed - * from width, height, and padding props - * - */ + * Specifies the radius of the chart. If this property is not provided it is computed + * from width, height, and padding props + * + */ radius?: number; /** * When creating a donut chart, this prop determines the number of pixels between @@ -2267,7 +2284,7 @@ declare module "victory" { */ y?: DataGetterPropType; } - + /** * victory-pie draws an SVG pie or donut chart with React. * Styles and data can be customized by passing in your own values as properties to the component. @@ -2275,4 +2292,3 @@ declare module "victory" { */ export class VictoryPie extends React.Component<VictoryPieProps, any> {} } - \ No newline at end of file diff --git a/types/victory/tslint.json b/types/victory/tslint.json index a0357daa61..d100149dde 100644 --- a/types/victory/tslint.json +++ b/types/victory/tslint.json @@ -1,78 +1,19 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, "array-type": false, - "arrow-return-shorthand": false, "ban-types": false, "callable-types": false, - "comment-format": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, "interface-over-type-literal": false, "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + "void-return": false } } diff --git a/types/victory/victory-tests.tsx b/types/victory/victory-tests.tsx index 0c9992494e..fc6ec678d4 100644 --- a/types/victory/victory-tests.tsx +++ b/types/victory/victory-tests.tsx @@ -34,7 +34,7 @@ let test = <VictoryAnimation {(style: AnimationStyle) => <span style={{color: style["color"] as string}}>Hello!</span> } -</VictoryAnimation> +</VictoryAnimation>; // VictoryLabel test test = <VictoryLabel x={50} y={10} @@ -51,7 +51,7 @@ test = <VictoryLabel x={50} y={10} dy={10} lineHeight={1.5}> {"data viz \n is \n fun!"} -</VictoryLabel> +</VictoryLabel>; // VictoryArea test test = ( @@ -91,19 +91,19 @@ test = ( onClick: () => { return { mutation: (props) => { - return { style: { fill: "orange" } } + return { style: { fill: "orange" } }; } - } + }; }, onMouseEnter: () => { return [ { target: "labels", mutation: (props) => { - return { text: "hey" } + return { text: "hey" }; } } - ] + ]; } } } @@ -189,7 +189,7 @@ test = ( dependentAxis padding={{left: 50, top: 20, bottom: 20}} scale="log" - domain={{ x: [new Date(Date.UTC(2016, 0, 1)), new Date()], y: [1,5] }} + domain={{ x: [new Date(Date.UTC(2016, 0, 1)), new Date()], y: [1, 5] }} /> ); @@ -278,6 +278,9 @@ test = ( {x: 4, y: 2}, {x: 5, y: 1} ]} + alignment="start" + barWidth={(datum, active) => active ? datum.x : datum.y} + cornerRadius={{top: 2, bottom: 4}} events={[ { target: "data", From 7cfcc63349263b36d1dba5a64a7039b5e646145b Mon Sep 17 00:00:00 2001 From: Offir Golan <offirgolan@gmail.com> Date: Tue, 5 Feb 2019 09:38:15 -0800 Subject: [PATCH 095/200] fix(url-parse): Add optional stringify fn to `toString` --- types/url-parse/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/url-parse/index.d.ts b/types/url-parse/index.d.ts index 8fc22dbfc0..e9dbd83208 100644 --- a/types/url-parse/index.d.ts +++ b/types/url-parse/index.d.ts @@ -23,6 +23,8 @@ declare namespace URLParse { | 'username'; type QueryParser = (query: string) => object; + + type StringifyQuery = (query: object) => string; } interface URLParse { @@ -40,7 +42,7 @@ interface URLParse { readonly slashes: boolean; readonly username: string; set(part: URLParse.URLPart, value: string | object | number | undefined, fn?: boolean | URLParse.QueryParser): URLParse; - toString(): string; + toString(stringify?: URLParse.StringifyQuery): string; } declare const URLParse: { @@ -57,7 +59,7 @@ declare const URLParse: { location(url: string): object; qs: { parse: URLParse.QueryParser; - stringify(query: object): string; + stringify: URLParse.StringifyQuery; }; }; From f68b114c80675cbec1c6de875c77e6dd0681ccdf Mon Sep 17 00:00:00 2001 From: Offir Golan <offirgolan@gmail.com> Date: Tue, 5 Feb 2019 09:56:48 -0800 Subject: [PATCH 096/200] chore: Remove trailing whitespace --- types/url-parse/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/url-parse/index.d.ts b/types/url-parse/index.d.ts index e9dbd83208..cb3bc75dd5 100644 --- a/types/url-parse/index.d.ts +++ b/types/url-parse/index.d.ts @@ -23,7 +23,7 @@ declare namespace URLParse { | 'username'; type QueryParser = (query: string) => object; - + type StringifyQuery = (query: object) => string; } From 8e29287b7970702dff5583239c7b622d628b9445 Mon Sep 17 00:00:00 2001 From: Tiger Oakes <contact@tigeroakes.com> Date: Tue, 5 Feb 2019 10:22:59 -0800 Subject: [PATCH 097/200] Support koa-joi-router 5.2 --- types/koa-joi-router/index.d.ts | 24 ++++++++++++-------- types/koa-joi-router/koa-joi-router-tests.ts | 3 ++- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/types/koa-joi-router/index.d.ts b/types/koa-joi-router/index.d.ts index b767984d73..54cf148240 100644 --- a/types/koa-joi-router/index.d.ts +++ b/types/koa-joi-router/index.d.ts @@ -1,14 +1,16 @@ -// Type definitions for koa-joi-router 5.1 +// Type definitions for koa-joi-router 5.2 // Project: https://github.com/koajs/joi-router // Definitions by: Matthew Bull <https://github.com/wingsbob> // Dave Welsh <https://github.com/move-zig> // Hiroshi Ioka <https://github.com/hirochachacha> +// Tiger Oakes <https://github.com/NotWoods> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as Koa from 'koa'; import * as Joi from 'joi'; import * as KoaRouter from 'koa-router'; +import * as CoBody from 'co-body'; declare module "koa" { interface Request { @@ -23,10 +25,9 @@ interface createRouter { } declare namespace createRouter { - type PartialHandler = (ctx: Koa.Context) => any; type FullHandler = (ctx: Koa.Context, next: () => Promise<any>) => any; - interface NestedHandler extends ReadonlyArray<PartialHandler|FullHandler|NestedHandler> {} - type Handler = PartialHandler | FullHandler| NestedHandler; + interface NestedHandler extends ReadonlyArray<Handler> {} + type Handler = FullHandler | NestedHandler; type Method = (path: string|RegExp, handlerOrConfig: Handler | object, ...handlers: Handler[]) => Router; @@ -34,17 +35,22 @@ declare namespace createRouter { method: string|string[]; path: string|RegExp; handler: Handler; + pre?: Handler; validate?: { - header?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; - query?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; - params?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; - body?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + header?: Joi.SchemaLike; + query?: Joi.SchemaLike; + params?: Joi.SchemaLike; + body?: Joi.SchemaLike; maxBody?: number; failure?: number; type?: 'form'|'json'|'multipart'; - output?: {[status: number]: Joi.AnySchema}; + formOptions?: CoBody.Options; + jsonOptions?: CoBody.Options; + multipartOptions?: CoBody.Options; + output?: {[status: string]: Joi.SchemaLike}; continueOnError?: boolean; }; + meta?: any; } interface Router { diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts index 6ff956c2ef..67340a5a8d 100644 --- a/types/koa-joi-router/koa-joi-router-tests.ts +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -41,6 +41,7 @@ const spec4: router.Spec = { type: 'json', output: { 201: Joi.object(), + '400,404': Joi.object(), } }, handler: (ctx: koa.Context) => { @@ -54,7 +55,7 @@ router().route(spec4); const spec5: router.Spec = { method: 'PUT', path: '/user', - handler: (ctx: koa.Context) => { + handler: (ctx) => { ctx.status = 201; ctx.body = ctx.request.body; }, From 86ca25c6fa02028ffe4b8c2a0589eb132240e4e7 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume <kocal@live.fr> Date: Sun, 3 Feb 2019 19:43:24 +0100 Subject: [PATCH 098/200] feat: add type for "rollup-plugin-buble" --- types/rollup-plugin-buble/index.d.ts | 18 ++++++ types/rollup-plugin-buble/package.json | 6 ++ .../rollup-plugin-buble-tests.ts | 57 +++++++++++++++++++ types/rollup-plugin-buble/tsconfig.json | 23 ++++++++ types/rollup-plugin-buble/tslint.json | 1 + 5 files changed, 105 insertions(+) create mode 100644 types/rollup-plugin-buble/index.d.ts create mode 100644 types/rollup-plugin-buble/package.json create mode 100644 types/rollup-plugin-buble/rollup-plugin-buble-tests.ts create mode 100644 types/rollup-plugin-buble/tsconfig.json create mode 100644 types/rollup-plugin-buble/tslint.json diff --git a/types/rollup-plugin-buble/index.d.ts b/types/rollup-plugin-buble/index.d.ts new file mode 100644 index 0000000000..d6e3414346 --- /dev/null +++ b/types/rollup-plugin-buble/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for rollup-plugin-buble 0.19 +// Project: https://github.com/rollup/rollup-plugin-buble#readme +// Definitions by: Hugo Alliaume <https://github.com/Kocal> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// <reference types="node" /> + +import { Plugin } from 'rollup'; +import { TransformOptions } from 'buble'; + +export interface Options extends TransformOptions { + // Every files will be parsed by default, but you can specify which files to include or exclude + include?: Array<string | RegExp> | string | RegExp | null; + exclude?: Array<string | RegExp> | string | RegExp | null; +} + +export default function buble(options?: Options): Plugin; diff --git a/types/rollup-plugin-buble/package.json b/types/rollup-plugin-buble/package.json new file mode 100644 index 0000000000..ee69ca3cd2 --- /dev/null +++ b/types/rollup-plugin-buble/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "rollup": "^0.63.4" + } +} diff --git a/types/rollup-plugin-buble/rollup-plugin-buble-tests.ts b/types/rollup-plugin-buble/rollup-plugin-buble-tests.ts new file mode 100644 index 0000000000..d020539f8b --- /dev/null +++ b/types/rollup-plugin-buble/rollup-plugin-buble-tests.ts @@ -0,0 +1,57 @@ +import buble from 'rollup-plugin-buble'; + +// No options (default) +(() => { + // $ExpectType Plugin + buble(); +})(); + +// With every options +(() => { + // $ExpectType Plugin + buble({ + target: { + chrome: 71, + firefox: 64, + }, + objectAssign: true, + transforms: { + arrow: true, + classes: false, + collections: true, + computedProperty: false, + conciseMethodProperty: true, + constLoop: false, + dangerousForOf: true, + dangerousTaggedTemplateString: false, + defaultParameter: true, + destructuring: false, + forOf: true, + generator: false, + letConst: true, + modules: false, + numericLiteral: true, + parameterDestructuring: false, + reservedProperties: true, + spreadRest: false, + stickyRegExp: true, + templateString: false, + unicodeRegExp: true, + } + }); +})(); + +// Filter files +(() => { + // $ExpectType Plugin + buble({ + include: '*.js', + exclude: '*.js', + }); + + // $ExpectType Plugin + buble({ + include: /.js$/, + exclude: ['foo.js', 'bar.js'], + }); +})(); diff --git a/types/rollup-plugin-buble/tsconfig.json b/types/rollup-plugin-buble/tsconfig.json new file mode 100644 index 0000000000..80dec6b110 --- /dev/null +++ b/types/rollup-plugin-buble/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rollup-plugin-buble-tests.ts" + ] +} diff --git a/types/rollup-plugin-buble/tslint.json b/types/rollup-plugin-buble/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rollup-plugin-buble/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 321969d161fefb598a24254e7f55213a5dea2a9d Mon Sep 17 00:00:00 2001 From: Anthony Dionise <dionisea@frib.msu.edu> Date: Tue, 5 Feb 2019 15:25:51 -0500 Subject: [PATCH 099/200] Non empty namespce --- .../index.d.ts | 47 ++++++++++--------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/types/connect-history-api-fallback-exclusions/index.d.ts b/types/connect-history-api-fallback-exclusions/index.d.ts index fa69b20e17..afbe7aa6a6 100644 --- a/types/connect-history-api-fallback-exclusions/index.d.ts +++ b/types/connect-history-api-fallback-exclusions/index.d.ts @@ -10,27 +10,28 @@ import { Url } from 'url'; import * as core from "express-serve-static-core"; -declare function historyApiFallback(options?: Options): core.RequestHandler; -declare namespace historyApiFallback {} +declare function historyApiFallback(options?: historyApiFallback.Options): core.RequestHandler; + +declare namespace historyApiFallback { + interface Options { + exclusions?: string[]; + disableDotRule?: true; + htmlAcceptHeaders?: string[]; + index?: string; + logger?: typeof console.log; + rewrites?: Rewrite[]; + verbose?: boolean; + } + + interface Context { + match: RegExpMatchArray; + parsedUrl: Url; + } + type RewriteTo = (context: Context) => string; + + interface Rewrite { + from: RegExp; + to: string | RegExp | RewriteTo; + } +} export = historyApiFallback; - -interface Options { - exclusions?: string[]; - disableDotRule?: true; - htmlAcceptHeaders?: string[]; - index?: string; - logger?: typeof console.log; - rewrites?: Rewrite[]; - verbose?: boolean; -} - -interface Context { - match: RegExpMatchArray; - parsedUrl: Url; -} -type RewriteTo = (context: Context) => string; - -interface Rewrite { - from: RegExp; - to: string | RegExp | RewriteTo; -} From 376eb731770ce9d11aa0a215db3b86ddab1131f3 Mon Sep 17 00:00:00 2001 From: Anthony Dionise <dionisea@frib.msu.edu> Date: Tue, 5 Feb 2019 15:37:19 -0500 Subject: [PATCH 100/200] Remove trailing whitespace for Travis --- types/connect-history-api-fallback-exclusions/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/connect-history-api-fallback-exclusions/index.d.ts b/types/connect-history-api-fallback-exclusions/index.d.ts index afbe7aa6a6..c83335203a 100644 --- a/types/connect-history-api-fallback-exclusions/index.d.ts +++ b/types/connect-history-api-fallback-exclusions/index.d.ts @@ -22,13 +22,13 @@ declare namespace historyApiFallback { rewrites?: Rewrite[]; verbose?: boolean; } - + interface Context { match: RegExpMatchArray; parsedUrl: Url; } type RewriteTo = (context: Context) => string; - + interface Rewrite { from: RegExp; to: string | RegExp | RewriteTo; From 342d8a0a22b6f7d3882a8d8e6de80b6f4fc6ea9a Mon Sep 17 00:00:00 2001 From: Kyra <kyradiscord@gmail.com> Date: Tue, 5 Feb 2019 22:06:15 +0100 Subject: [PATCH 101/200] fix: Added missing properties for FetchError Ref: https://github.com/bitinn/node-fetch/blob/e996bdab73baf996cf2dbf25643c8fe2698c3249/src/fetch-error.js#L20-L25 --- types/node-fetch/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/node-fetch/index.d.ts b/types/node-fetch/index.d.ts index 1177e8da25..03ae639d26 100644 --- a/types/node-fetch/index.d.ts +++ b/types/node-fetch/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Torsten Werner <https://github.com/torstenwerner> // Niklas Lindgren <https://github.com/nikcorg> // Vinay Bedre <https://github.com/vinaybedre> +// Antonio Román <https://github.com/kyranet> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> @@ -134,6 +135,9 @@ export class Body { export class FetchError extends Error { name: "FetchError"; constructor(message: string, type: string, systemError: string); + type: string; + code?: string; + errno?: string; } export class Response extends Body { From 8aa0f3f0e0459cdeee0d5511f88dca5d877843aa Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 20:30:41 +0100 Subject: [PATCH 102/200] Removed HostStatic and HostMapStatic Those classes are not exposed and can not be instantiated from user code --- types/cassandra-driver/index.d.ts | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 02853c66ba..446cd0f7fb 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -499,8 +499,6 @@ export namespace types { } export let Client: ClientStatic; -export let Host: HostStatic; -export let HostMap: HostMapStatic; export let Encoder: EncoderStatic; export interface ClientOptions { @@ -611,14 +609,10 @@ export interface Client extends events.EventEmitter { stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): NodeJS.ReadableStream; } -export interface HostStatic { - new (address: string, protocolVersion: number, options: ClientOptions): Host; -} - export interface Host extends events.EventEmitter { address: string; cassandraVersion: string; - dataCenter: string; + datacenter: string; rack: string; tokens: string[]; @@ -627,10 +621,6 @@ export interface Host extends events.EventEmitter { isUp(): boolean; } -export interface HostMapStatic { - new (): HostMap; -} - export interface HostMap extends events.EventEmitter { length: number; From ea43dcfd5c15a50235c3b908a329ce2e446565c7 Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 21:35:18 +0100 Subject: [PATCH 103/200] Fixed metadata namespace Removed constructors for internal classes Added missing Metadata functions Added Promise returning overloads for Metadata functions --- types/cassandra-driver/index.d.ts | 108 ++++++++++++++++++------------ 1 file changed, 66 insertions(+), 42 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 446cd0f7fb..264d5ddec8 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -732,19 +732,10 @@ export namespace errors { } export namespace metadata { - let Aggregate: AggregateStatic; - let Index: IndexStatic; - let MaterializedView: MaterializedViewStatic; let Metadata: MetadataStatic; - let SchemaFunction: SchemaFunctionStatic; - let TableMetadata: TableMetadataStatic; type caching = "all" | "keys_only" | "rows_only" | "none"; - interface AggregateStatic { - new (): Aggregate; - } - interface Aggregate { argumentTypes: Array<{ code: number, info: any }>; finalFunction: string; @@ -756,10 +747,6 @@ export namespace metadata { stateType: string; } - interface ClientStateStatic { - new (): ClientState; - } - interface ClientState { getConnectedHosts(): Host[]; getInFlightQueries(host: Host): number; @@ -812,13 +799,6 @@ export namespace metadata { composites } - interface IndexStatic { - new (name: string, target: string, kind: string | IndexType, options: object): Index; - - fromRows(indexRows: types.Row[]): Index[]; - fromColumnRows(columnRows: types.Row[], columnsByName: { [key: string]: ColumnInfo }): Index[]; - } - interface Index { kind: IndexType; name: string; @@ -830,11 +810,43 @@ export namespace metadata { isKeysKind(): boolean; } - interface MaterializedViewStatic { - new (name: string): MaterializedView; + interface MaterializedView extends DataCollection { } + + class Token { + getType(): types.dataTypes; + getValue(): any; + compare(other: Token): number; + equals(other: Token): boolean; } - interface MaterializedView extends DataCollection { } + interface TokenRange { + start: Token; + end: Token; + + splitEvenly(numberOfSplits: number): TokenRange[]; + isEmpty(): boolean; + isWrappedAround(): boolean; + unwrap(): TokenRange[]; + contains(token: Token): boolean; + equals(other: TokenRange): boolean; + compare(other: TokenRange): number; + } + + class ByteOrderedToken extends Token {} + class Murmur3Token extends Token {} + class BytRandomToken extends Token {} + + interface QueryTrace { + requestType: any; + coordinator: any; + parameters: any; + startedAt: any; + duration: any; + clientAddress: any; + events: Array<{ id: any; activity: any; source: any; elapsed: any; thread: any }>; + } + + type MetadataCallback<T> = (err: any, retVal: T) => void; interface MetadataStatic { new (options: ClientOptions, controlConnection: any): Metadata; @@ -843,21 +855,37 @@ export namespace metadata { interface Metadata { clearPrepared(): void; - getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: Callback): void; - getAggregates(keyspaceName: string, name: string, callback: Callback): void; - getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: Callback): void; - getFunctions(keyspaceName: string, name: string, callback: Callback): void; - getMaterializedView(keyspaceName: string, name: string, callback: Callback): void; - getReplicas(keyspaceName: string, tokenBuffer: Buffer): any[]; - getTable(keyspaceName: string, name: string, callback: Callback): void; - getTrace(traceId: types.Uuid, callback: Callback): void; - getUdt(keyspaceName: string, name: string, callback: Callback): void; - refreshKeyspace(name: string, callback?: Callback): void; - refreshKeyspaces(callback?: Callback): void; - } - - interface SchemaFunctionStatic { - new (): SchemaFunction; + getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: MetadataCallback<Aggregate>): void; + getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise<Aggregate>; + getAggregates(keyspaceName: string, name: string, callback: MetadataCallback<Aggregate[]>): void; + getAggregates(keyspaceName: string, name: string): Promise<Aggregate[]>; + getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: MetadataCallback<SchemaFunction>): void; + getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise<SchemaFunction>; + getFunctions(keyspaceName: string, name: string, callback: MetadataCallback<SchemaFunction[]>): void; + getFunctions(keyspaceName: string, name: string): Promise<SchemaFunction[]>; + getMaterializedView(keyspaceName: string, name: string, callback: MetadataCallback<MaterializedView>): void; + getMaterializedView(keyspaceName: string, name: string, callback: Callback): Promise<MaterializedView>; + getReplicas(keyspaceName: string, token: Buffer | Token | TokenRange): any[]; // TODO + getTable(keyspaceName: string, name: string, callback: MetadataCallback<TableMetadata>): void; + getTable(keyspaceName: string, name: string): Promise<TableMetadata>; + getTokenRanges(): Set<TokenRange>; + getTokenRangesForHost(keyspaceName: string, host: Host): Set<TokenRange> | null; + getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: MetadataCallback<QueryTrace>): void; + getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: Callback): Promise<QueryTrace>; + getTrace(traceId: types.Uuid, callback: MetadataCallback<QueryTrace>): void; + getTrace(traceId: types.Uuid): Promise<QueryTrace>; + getUdt(keyspaceName: string, name: string, callback: MetadataCallback<any>): void; // TODO + getUdt(keyspaceName: string, name: string): Promise<any>; // TODO + newToken(components: Buffer[] | Buffer | string): Token; + newTokenRange(start: Token, end: Token): TokenRange; + refreshKeyspace(name: string, callback: Callback): void; + refreshKeyspace(name: string): Promise<void>; + refreshKeyspaces(waitReconnect: () => boolean, callback: Callback): void; + refreshKeyspaces(waitReconnect: () => boolean): Promise<void>; + refreshKeyspaces(waitReconnect: boolean, callback: Callback): void; + refreshKeyspaces(waitReconnect: boolean): Promise<void>; + refreshKeyspaces(callback: Callback): void; + refreshKeyspaces(): Promise<void>; } interface SchemaFunction { @@ -872,10 +900,6 @@ export namespace metadata { signature: string[]; } - interface TableMetadataStatic { - new (name: string): TableMetadata; - } - interface TableMetadata extends DataCollection { indexes: Index[]; indexInterval?: number; From 623449259ff9424bec6b6d2dfabcbb2232ece1c4 Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 22:01:21 +0100 Subject: [PATCH 104/200] Added missing top-level exports token namespace ExecutionProfile constructor defaultOptions function version const --- types/cassandra-driver/index.d.ts | 72 +++++++++++++++++++------------ 1 file changed, 44 insertions(+), 28 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 264d5ddec8..81941afde0 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -812,29 +812,6 @@ export namespace metadata { interface MaterializedView extends DataCollection { } - class Token { - getType(): types.dataTypes; - getValue(): any; - compare(other: Token): number; - equals(other: Token): boolean; - } - - interface TokenRange { - start: Token; - end: Token; - - splitEvenly(numberOfSplits: number): TokenRange[]; - isEmpty(): boolean; - isWrappedAround(): boolean; - unwrap(): TokenRange[]; - contains(token: Token): boolean; - equals(other: TokenRange): boolean; - compare(other: TokenRange): number; - } - - class ByteOrderedToken extends Token {} - class Murmur3Token extends Token {} - class BytRandomToken extends Token {} interface QueryTrace { requestType: any; @@ -865,19 +842,19 @@ export namespace metadata { getFunctions(keyspaceName: string, name: string): Promise<SchemaFunction[]>; getMaterializedView(keyspaceName: string, name: string, callback: MetadataCallback<MaterializedView>): void; getMaterializedView(keyspaceName: string, name: string, callback: Callback): Promise<MaterializedView>; - getReplicas(keyspaceName: string, token: Buffer | Token | TokenRange): any[]; // TODO + getReplicas(keyspaceName: string, token: Buffer | token.Token | token.TokenRange): any[]; // TODO getTable(keyspaceName: string, name: string, callback: MetadataCallback<TableMetadata>): void; getTable(keyspaceName: string, name: string): Promise<TableMetadata>; - getTokenRanges(): Set<TokenRange>; - getTokenRangesForHost(keyspaceName: string, host: Host): Set<TokenRange> | null; + getTokenRanges(): Set<token.TokenRange>; + getTokenRangesForHost(keyspaceName: string, host: Host): Set<token.TokenRange> | null; getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: MetadataCallback<QueryTrace>): void; getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: Callback): Promise<QueryTrace>; getTrace(traceId: types.Uuid, callback: MetadataCallback<QueryTrace>): void; getTrace(traceId: types.Uuid): Promise<QueryTrace>; getUdt(keyspaceName: string, name: string, callback: MetadataCallback<any>): void; // TODO getUdt(keyspaceName: string, name: string): Promise<any>; // TODO - newToken(components: Buffer[] | Buffer | string): Token; - newTokenRange(start: Token, end: Token): TokenRange; + newToken(components: Buffer[] | Buffer | string): token.Token; + newTokenRange(start: token.Token, end: token.Token): token.TokenRange; refreshKeyspace(name: string, callback: Callback): void; refreshKeyspace(name: string): Promise<void>; refreshKeyspaces(waitReconnect: () => boolean, callback: Callback): void; @@ -941,6 +918,7 @@ export interface ExecutionOptions { } export let ExecutionOptions: ExecutionOptionsStatic; +export let ExecutionProfile: ExecutionProfileStatic; export namespace mapping { let Mapper: MapperStatic; @@ -1150,3 +1128,41 @@ export namespace metrics { } interface DefaultMetrics extends ClientMetrics {} } + +export namespace token { + interface Tokenizer { + hash(value: Buffer | number[]): Token; + parse(value: string): Token; + minToken(): Token; + split(start: Token, end: Token, numberOfSplits: number): TokenRange[]; + splitBase(start: number, end: number, ringEnd: number, ringLength: number, numberOfSplits: number): number[]; + stringify(token: Token): string; + } + + class Token { + constructor(value: any); + + getType(): { code: number, info: any }; + getValue(): any; + compare(other: Token): number; + equals(other: Token): boolean; + } + + class TokenRange { + start: Token; + end: Token; + + constructor(start: Token, end: Token, tokenizer: Tokenizer); + + splitEvenly(numberOfSplits: number): TokenRange[]; + isEmpty(): boolean; + isWrappedAround(): boolean; + unwrap(): TokenRange[]; + contains(token: Token): boolean; + equals(other: TokenRange): boolean; + compare(other: TokenRange): number; + } +} + +export const defaultOptions: () => ClientOptions; +export const version: string; \ No newline at end of file From 941c30484d0b411deeb4a87bfcaf08055365253d Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 22:15:57 +0100 Subject: [PATCH 105/200] Rewritten policies.loadBalancing namespace to use classes So it allows writing own policies by extending LoadBalancingPolicy --- types/cassandra-driver/index.d.ts | 38 ++++++++++--------------------- 1 file changed, 12 insertions(+), 26 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 81941afde0..70da1c9ce5 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -34,43 +34,29 @@ export namespace policies { } namespace loadBalancing { - let DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; - let RoundRobinPolicy: RoundRobinPolicyStatic; - let TokenAwarePolicy: TokenAwarePolicyStatic; - let WhiteListPolicy: WhiteListPolicyStatic; - - interface LoadBalancingPolicy { + class LoadBalancingPolicy { init(client: Client, hosts: HostMap, callback: Callback): void; getDistance(host: Host): types.distance; newQueryPlan(keyspace: string, queryOptions: ExecutionOptions | null, callback: Callback): void; + getOptions(): Map<string, any>; } - interface DCAwareRoundRobinPolicyStatic { - new (localDc?: string): DCAwareRoundRobinPolicy; - } - - interface DCAwareRoundRobinPolicy extends LoadBalancingPolicy { + class DCAwareRoundRobinPolicy extends LoadBalancingPolicy { + localDc: string; localHostsArray: Host[]; - remoteHostsArray: Host[]; + + constructor(localDc?: string); } - interface RoundRobinPolicyStatic { - new (): RoundRobinPolicy; + class RoundRobinPolicy extends LoadBalancingPolicy {} + + class TokenAwarePolicy extends LoadBalancingPolicy { + constructor(childPolicy: LoadBalancingPolicy); } - interface RoundRobinPolicy extends LoadBalancingPolicy { } - - interface TokenAwarePolicyStatic { - new (childPolicy: LoadBalancingPolicy): TokenAwarePolicy; + class WhiteListPolicy extends LoadBalancingPolicy { + constructor(childPolicy: LoadBalancingPolicy, whiteList: string[]); } - - interface TokenAwarePolicy extends LoadBalancingPolicy { } - - interface WhiteListPolicyStatic { - new (childPolicy: LoadBalancingPolicy, whiteList: string[]): WhiteListPolicy; - } - - interface WhiteListPolicy extends LoadBalancingPolicy { } } namespace reconnection { From e2935590f3c0a49b185d5a8402333ac0656a1706 Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 22:46:51 +0100 Subject: [PATCH 106/200] Fixed specification after testing + linter fixes --- types/cassandra-driver/index.d.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 70da1c9ce5..18527ed8c5 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -798,7 +798,6 @@ export namespace metadata { interface MaterializedView extends DataCollection { } - interface QueryTrace { requestType: any; coordinator: any; @@ -843,12 +842,9 @@ export namespace metadata { newTokenRange(start: token.Token, end: token.Token): token.TokenRange; refreshKeyspace(name: string, callback: Callback): void; refreshKeyspace(name: string): Promise<void>; - refreshKeyspaces(waitReconnect: () => boolean, callback: Callback): void; - refreshKeyspaces(waitReconnect: () => boolean): Promise<void>; refreshKeyspaces(waitReconnect: boolean, callback: Callback): void; - refreshKeyspaces(waitReconnect: boolean): Promise<void>; + refreshKeyspaces(waitReconnect?: boolean): Promise<void>; refreshKeyspaces(callback: Callback): void; - refreshKeyspaces(): Promise<void>; } interface SchemaFunction { @@ -1150,5 +1146,5 @@ export namespace token { } } -export const defaultOptions: () => ClientOptions; -export const version: string; \ No newline at end of file +export function defaultOptions(): ClientOptions; +export const version: string; From b99f36cd7e36391506c6d2c15cf943bf5ba2cf6a Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 22:47:05 +0100 Subject: [PATCH 107/200] Updated and extended tests after changes --- .../cassandra-driver-tests.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/types/cassandra-driver/cassandra-driver-tests.ts b/types/cassandra-driver/cassandra-driver-tests.ts index 3e203837b7..b4f850c315 100644 --- a/types/cassandra-driver/cassandra-driver-tests.ts +++ b/types/cassandra-driver/cassandra-driver-tests.ts @@ -102,3 +102,35 @@ const mapper = new cassandra.mapping.Mapper( const videoMapper = mapper.forModel('Video'); videoMapper.insert({ videoId: 'uuid', addedDate: new Date(), userId: 'uuid', name: 'My video', description: 'My desc' }); videoMapper.find({ videoId: 'uuid' }).then(results => results.first()); + +console.log(cassandra.version); + +const metadata = new cassandra.metadata.Metadata(cassandra.defaultOptions(), undefined); +let refreshFinished: Promise<void> = metadata.refreshKeyspaces(); +refreshFinished = metadata.refreshKeyspaces(true); +metadata.refreshKeyspaces(() => {}); +metadata.refreshKeyspaces(true, () => {}); + +const start: cassandra.token.Token = new cassandra.token.Token("x"); +const end: cassandra.token.Token = new cassandra.token.Token("z"); + +const tokenizer: cassandra.token.Tokenizer = { + hash: (value: Buffer | number[]) => new cassandra.token.Token("x"), + parse: (value: string) => new cassandra.token.Token("x"), + minToken: () => new cassandra.token.Token("x"), + split: (start: cassandra.token.Token, end: cassandra.token.Token, numberOfSplits: number) => [], + splitBase: (start: number, end: number, ringEnd: number, ringLength: number, numberOfSplits: number): number[] => [1], + stringify: (token: cassandra.token.Token): string => "asd" +}; + +const range: cassandra.token.TokenRange = new cassandra.token.TokenRange(start, end, tokenizer); + +class MyLoadBalancingPolicy extends cassandra.policies.loadBalancing.LoadBalancingPolicy { + getDistance() { + return cassandra.types.distance.ignored; + } +} + +const myPolicy: cassandra.policies.loadBalancing.LoadBalancingPolicy = new MyLoadBalancingPolicy(); +let existingPolicy: cassandra.policies.loadBalancing.LoadBalancingPolicy = new cassandra.policies.loadBalancing.DCAwareRoundRobinPolicy(); +existingPolicy = new cassandra.policies.loadBalancing.DCAwareRoundRobinPolicy("dc"); From 7a7ee210a16dcfb3b769cf3e60fc0caffb7953cd Mon Sep 17 00:00:00 2001 From: Tiger Oakes <contact@tigeroakes.com> Date: Tue, 5 Feb 2019 14:16:16 -0800 Subject: [PATCH 108/200] Add tests for pre, meta, and options --- types/koa-joi-router/koa-joi-router-tests.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts index 67340a5a8d..160c3834c1 100644 --- a/types/koa-joi-router/koa-joi-router-tests.ts +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -30,6 +30,7 @@ const spec3: router.Spec = { body: Joi.any(), }, handler: (ctx: koa.Context) => ctx.status = 201, + pre: (_ctx, next) => next(), }; router().route(spec3); @@ -42,9 +43,12 @@ const spec4: router.Spec = { output: { 201: Joi.object(), '400,404': Joi.object(), + }, + jsonOptions: { + limit: '10kb' } }, - handler: (ctx: koa.Context) => { + handler(ctx) { ctx.status = 201; ctx.body = {}; }, @@ -59,6 +63,7 @@ const spec5: router.Spec = { ctx.status = 201; ctx.body = ctx.request.body; }, + meta: 'meta data', }; router().route(spec5); From 3f6d89f42b3347d63993695e6e8d4e8162465f3c Mon Sep 17 00:00:00 2001 From: arichter83 <ar@5mm.de> Date: Wed, 6 Feb 2019 00:01:02 +0100 Subject: [PATCH 109/200] Added result.customOption for allowNew items See https://github.com/ericgio/react-bootstrap-typeahead/blob/4537b2522854431f67732c9cbddd9ce5bffbc958/src/containers/typeaheadContainer.js#L142 --- types/react-bootstrap-typeahead/index.d.ts | 6 ++++-- .../react-bootstrap-typeahead-tests.tsx | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/types/react-bootstrap-typeahead/index.d.ts b/types/react-bootstrap-typeahead/index.d.ts index 2f1ad8b7be..c4cc65f66a 100644 --- a/types/react-bootstrap-typeahead/index.d.ts +++ b/types/react-bootstrap-typeahead/index.d.ts @@ -107,6 +107,8 @@ export interface TypeaheadContainerProps<T extends TypeaheadModel> { text: string; } +export type TypeaheadResult<T extends TypeaheadModel> = T & { customOption: boolean } + export interface TypeaheadProps<T extends TypeaheadModel> { /* For localized accessibility: Should return a string indicating the number of results for screen readers. Receives the current results. */ @@ -252,10 +254,10 @@ export interface TypeaheadProps<T extends TypeaheadModel> { placeholder?: string; /* Callback for custom menu rendering. */ - renderMenu?: (results: T[], menuProps: any) => React.ReactNode; + renderMenu?: (results: TypeaheadResult<T>[], menuProps: any) => React.ReactNode; /* Provides a hook for customized rendering of menu item contents. */ - renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode; + renderMenuItemChildren?: (option: TypeaheadResult<T>, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode; /* Provides a hook for customized rendering of tokens when multiple selections are enabled. */ renderToken?: (selectedItem: T, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode; diff --git a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx index 7e2c3a29a6..f331752cbb 100644 --- a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx +++ b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx @@ -107,6 +107,21 @@ class BasicExample extends React.Component { </Highlighter> } /> + <Typeahead + labelKey="name" + options={options} + placeholder="Choose a state..." + renderMenu={(results, menuProps) => ( + <Menu {...menuProps}> + { results.map((result, index) => ( + <MenuItem option={result} position={index} key={index}> + { result.customOption && 'New: ' } + <Highlighter search={menuProps.text}>{result.name}</Highlighter> + </MenuItem> + )) } + </Menu> + )} + /> <Typeahead labelKey="name" options={options} From c537e44b72f430376856fe2d279ae11e32da1d3a Mon Sep 17 00:00:00 2001 From: arichter83 <ar@5mm.de> Date: Wed, 6 Feb 2019 00:07:07 +0100 Subject: [PATCH 110/200] Fix linting --- types/react-bootstrap-typeahead/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-bootstrap-typeahead/index.d.ts b/types/react-bootstrap-typeahead/index.d.ts index c4cc65f66a..93fa2c9c6a 100644 --- a/types/react-bootstrap-typeahead/index.d.ts +++ b/types/react-bootstrap-typeahead/index.d.ts @@ -107,7 +107,7 @@ export interface TypeaheadContainerProps<T extends TypeaheadModel> { text: string; } -export type TypeaheadResult<T extends TypeaheadModel> = T & { customOption: boolean } +export type TypeaheadResult<T extends TypeaheadModel> = T & { customOption: boolean }; export interface TypeaheadProps<T extends TypeaheadModel> { /* For localized accessibility: Should return a string indicating the number of results for screen readers. @@ -254,7 +254,7 @@ export interface TypeaheadProps<T extends TypeaheadModel> { placeholder?: string; /* Callback for custom menu rendering. */ - renderMenu?: (results: TypeaheadResult<T>[], menuProps: any) => React.ReactNode; + renderMenu?: (results: Array<TypeaheadResult<T>>, menuProps: any) => React.ReactNode; /* Provides a hook for customized rendering of menu item contents. */ renderMenuItemChildren?: (option: TypeaheadResult<T>, props: TypeaheadMenuProps<T>, index: number) => React.ReactNode; From 8803b9e34bcf2eb1de1903125405095648a87b9d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 5 Feb 2019 15:19:44 -0800 Subject: [PATCH 111/200] Update README with links to gitter and infrastructure Also reduce the expected time before NPM publishing to "a few minutes" and the allowed time to "an hour" instead of "an hour" and "24 hours". --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bbf2a6f16e..98d6f6ede4 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although This section tracks the health of the repository and publishing process. It may be helpful for contributors experiencing any issues with their PRs and packages. -* All packages are type-checking/linting cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) -* All packages are being published to npm in under 10,000 seconds: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) +* All packages are [type-checking/linting](https://github.com/Microsoft/dtslint) cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) +* All packages are being [published to npm](https://github.com/Microsoft/types-publisher) in under an hour: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) * [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [![Activity Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped). @@ -229,7 +229,7 @@ It depends, but most pull requests will be merged within a week. PRs that have b #### My PR is merged; when will the `@types` NPM package be updated? -NPM packages should update within a few hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR to investigate. +NPM packages should update within a few minutes. If it's been more than an hour, mention the PR number on [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped) and the current maintainer will get the correct team member to investigate. #### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import? From a436f6c83f021c9f7f8f31f8377eeffe1c43a32a Mon Sep 17 00:00:00 2001 From: Jonathan Viney <jonathan.viney@gmail.com> Date: Wed, 6 Feb 2019 12:22:33 +1300 Subject: [PATCH 112/200] [video.js]: add player readyState() --- types/video.js/index.d.ts | 14 ++++++++++++++ types/video.js/video.js-tests.ts | 2 ++ 2 files changed, 16 insertions(+) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 62bbf83362..7f64f16b7a 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -3713,6 +3713,14 @@ declare namespace videojs { new (player: Player, options?: ComponentOptions): MouseTimeDisplay }; + enum ReadyState { + HaveNothing = 0, + HaveMetadata = 1, + HaveCurrentData = 2, + HaveFutureData = 3, + HaveEnoughData = 4 + } + /** * An instance of the `Player` class is created when any of the Video.js setup methods * are used to initialize a video. @@ -4342,6 +4350,12 @@ declare namespace videojs { */ preload(value?: boolean): string; + /** + * Returns a value that expresses the current state of the element + * with respect to rendering the current playback position. + */ + readyState(): ReadyState; + /** * Calculates how much time is left in the video. Not part * of the native video API. diff --git a/types/video.js/video.js-tests.ts b/types/video.js/video.js-tests.ts index 378a7150f3..910085557a 100644 --- a/types/video.js/video.js-tests.ts +++ b/types/video.js/video.js-tests.ts @@ -57,6 +57,8 @@ videojs("example_video_1").ready(function() { this.height(480); + const readyState: videojs.ReadyState = this.readyState(); + this.requestFullscreen(); testEvents(this); From 471af18e9f7332a9cd2cb115942c37b0caecc14f Mon Sep 17 00:00:00 2001 From: Jonathan Viney <jonathan.viney@gmail.com> Date: Wed, 6 Feb 2019 12:25:26 +1300 Subject: [PATCH 113/200] [video.js]: add player inactivityTimeout option --- types/video.js/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 62bbf83362..a85081be66 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -4609,6 +4609,7 @@ declare namespace videojs { fluid?: boolean; height?: number; html5?: any; + inactivityTimeout?: number; language?: string; languages?: { [code: string]: LanguageTranslations }; loop?: boolean; From e731bb5edf8d72fccfbf215f5360cc3c643d5170 Mon Sep 17 00:00:00 2001 From: arichter83 <ar@5mm.de> Date: Wed, 6 Feb 2019 00:45:54 +0100 Subject: [PATCH 114/200] Fix $addToSet --- types/meteor/mongo.d.ts | 2 +- types/meteor/test/meteor-tests.ts | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/types/meteor/mongo.d.ts b/types/meteor/mongo.d.ts index 84b2d53528..079bf6272d 100644 --- a/types/meteor/mongo.d.ts +++ b/types/meteor/mongo.d.ts @@ -96,7 +96,7 @@ declare module "meteor/mongo" { { $each?: T[P], $position?: number, $slice?: number, $sort?: 1 | -1 | Dictionary<number> } } type ArraysOrEach<T> = { - [P in keyof T]?: OnlyArrays<T[P]> | { $each: T[P] } + [P in keyof T]?: OnlyElementsOfArrays<T[P]> | { $each: T[P] } } type CurrentDateModifier = { $type: "timestamp" | "date" } | true type Modifier<T> = T | { diff --git a/types/meteor/test/meteor-tests.ts b/types/meteor/test/meteor-tests.ts index 8e14f39fb1..8a9a32ddde 100644 --- a/types/meteor/test/meteor-tests.ts +++ b/types/meteor/test/meteor-tests.ts @@ -246,7 +246,13 @@ Items.insert({ list: groceriesId, name: "Persimmons" }); /** * From Collections, collection.update section */ -var Players = new Mongo.Collection('Players'); + +interface Players { + score: number + badges: string[] +} + +var Players: Mongo.Collection<Players> = new Mongo.Collection('Players'); Template['adminDashboard'].events({ 'click .givePoints': function () { @@ -265,6 +271,17 @@ Meteor.methods({ } }); +/** + * Also from Collections, collection.update section + */ +Meteor.methods({ + declareWinners: function () { + Players.update({ score: { $gt: 10 } }, + { $addToSet: { badges: {$each: ["Winner", "Super"]} } }, + { multi: true }); + } +}); + /** * From Collections, collection.remove section */ From b4efd11169d93b38be16d3ce17984b41d1c33b51 Mon Sep 17 00:00:00 2001 From: Alex Jerabek <aljerabe@microsoft.com> Date: Tue, 5 Feb 2019 16:14:10 -0800 Subject: [PATCH 115/200] Fixing Application.load description --- types/office-js/index.d.ts | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 0b4346ef8b..d53bdedb79 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -20747,22 +20747,20 @@ declare namespace Excel { /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * + * @remarks + * + * In addition to this signature, this method has the following signatures: + * + * `load(option?: string | string[]): Excel.Application` - Where option is a comma-delimited string or an array of strings that specify the properties to load. + * + * `load(option?: { select?: string; expand?: string; }): Excel.Application` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. + * + * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Application` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. + * * @param options Provides options for which properties of the object to load. */ load(option?: Excel.Interfaces.ApplicationLoadOptions): Excel.Application; - /** - * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. - * - * @param options The names of the properties to load. - */ load(option?: string | string[]): Excel.Application; - /** - * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. - * - * @param options Provides options for which properties of the object to load. - * `option.select` is a comma-delimited string that specifies the properties to load, - * and `options.expand` is a comma-delimited string that specifies the navigation properties to load. - */ load(option?: { select?: string; expand?: string; From 219f33284fb726b557ad52d190f05dbbffd94fff Mon Sep 17 00:00:00 2001 From: Krantisinh Deshmukh <krantisinh@monjin.com> Date: Wed, 6 Feb 2019 10:08:43 +0530 Subject: [PATCH 116/200] [Ramda] - Added typings to support all combinations of curried versions of R.move --- types/ramda/index.d.ts | 5 ++++- types/ramda/ramda-tests.ts | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 05b629137d..459a351c33 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1583,7 +1583,10 @@ declare namespace R { */ move<T>(from: number, to: number, list: ReadonlyArray<T>): T[]; move(from: number, to: number): <T>(list: ReadonlyArray<T>) => T[]; - move(from: number): (<T>(to: number, list: ReadonlyArray<T>) => T[]); + move(from: number): { + <T>(to: number, list: ReadonlyArray<T>): T[]; + (to: number): <T>(list: ReadonlyArray<T>) => T[]; + }; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 6c568d4a56..e4039483da 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1126,6 +1126,10 @@ interface Obj { const moveCurried2 = R.move(0); moveCurried2<string>(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried3 = R.move(0); + const moveCurried4 = moveCurried3(2); + moveCurried4<string>(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] }; () => { From 8dc61af424b338d5829dcbe67a7615a577c16147 Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Tue, 5 Feb 2019 20:23:38 -0500 Subject: [PATCH 117/200] Allow for functional styles in victory Add missing VictoryLabel props --- types/victory/index.d.ts | 213 +++++++++++++++++++------------- types/victory/tslint.json | 7 +- types/victory/victory-tests.tsx | 67 +++++++--- 3 files changed, 177 insertions(+), 110 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index c6909a4886..c1a1a6f394 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -33,17 +33,19 @@ declare module "victory" { "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; // Many victory components accept string or number or callback which returns string or number - type StringOrNumberOrCallback = string | number | { (): string | number }; + type StringOrNumberOrCallback = + | string + | number + | ((datum: any, active: boolean) => string | number); type NumberOrCallback = ((datum: any, active: boolean) => number) | number; /** * Style interface used in components/themeing */ export interface VictoryStyleInterface { - parent?: React.CSSProperties; - data?: React.CSSProperties; - labels?: React.CSSProperties; - tickLabels?: React.CSSProperties; + parent?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + data?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + labels?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; } export interface VictoryAnimationProps { @@ -122,16 +124,19 @@ declare module "victory" { * Event handlers are currently only called with their corresponding events. */ events?: React.DOMAttributes<any>; - /** - * All Victory components will pass a text prop to their label component. - * This defines the content of the label when child nodes are absent. It will be ignored if children are provided. - */ - text?: StringOrNumberOrCallback; /** * The children of this component define the content of the label. * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. */ children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; /** * The lineHeight prop defines how much space a single line of text should take up. * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, @@ -141,10 +146,31 @@ declare module "victory" { * @default 1 */ lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ + origin?: { x: number, y: number }; + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; /** * The style prop applies CSS properties to the rendered `<text>` element. */ style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; /** * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. */ @@ -1002,65 +1028,67 @@ declare module "victory" { label?: string | { (data: any): string }; } - export interface VictoryAreaProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. - * Since VictoryArea only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. an area), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; - /** - * The interpolation prop determines how data points should be connected when plotting a line - * @default "linear" - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - * @default 50 - */ - samples?: number; - /** - * The style prop specifies styles for your VictoryArea. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; + export interface VictoryAreaProps + extends VictoryCommonProps, + VictoryDatableProps, + VictorySingleLabableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. + * Since VictoryArea only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. an area), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; + /** + * The interpolation prop determines how data points should be connected when plotting a line + * @default "linear" + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + * @default 50 + */ + samples?: number; + /** + * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; } /** @@ -1146,7 +1174,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; /** @@ -1198,20 +1225,40 @@ declare module "victory" { */ orientation?: "top" | "bottom" | "left" | "right"; /** - * The style prop specifies styles for your VictoryAxis. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {axis: {stroke: "#756f6a"}, grid: {stroke: "grey"}, ticks: {stroke: "grey"}, - * tickLabels: {fontSize: 10, padding: 5}, axisLabel: {fontSize: 16, padding: 20}} + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. */ style?: { parent?: React.CSSProperties; axis?: React.CSSProperties; axisLabel?: React.CSSProperties; - grid?: React.CSSProperties; - ticks?: React.CSSProperties; - tickLabels?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; }; /** * The tickComponent prop takes in an entire component which will be used @@ -1339,7 +1386,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** @@ -1449,7 +1495,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; /** @@ -1580,7 +1625,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; /** @@ -1685,7 +1729,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -1752,7 +1795,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** @@ -1995,7 +2037,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -2113,7 +2154,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -2220,7 +2260,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; /** diff --git a/types/victory/tslint.json b/types/victory/tslint.json index d100149dde..2fccde6e9b 100644 --- a/types/victory/tslint.json +++ b/types/victory/tslint.json @@ -5,15 +5,10 @@ "ban-types": false, "callable-types": false, "interface-over-type-literal": false, - "jsdoc-format": false, "no-any-union": false, "no-declare-current-package": false, "no-empty-interface": false, - "no-object-literal-type-assertion": false, "no-single-declare-module": false, - "no-unnecessary-generics": false, - "no-void-expression": false, - "strict-export-declare-modifiers": false, - "void-return": false + "strict-export-declare-modifiers": false } } diff --git a/types/victory/victory-tests.tsx b/types/victory/victory-tests.tsx index fc6ec678d4..fcd18571e3 100644 --- a/types/victory/victory-tests.tsx +++ b/types/victory/victory-tests.tsx @@ -53,6 +53,27 @@ test = <VictoryLabel x={50} y={10} {"data viz \n is \n fun!"} </VictoryLabel>; +test = ( + <VictoryLabel + text={datum => datum.label} + labelPlacement='perpendicular' + renderInPortal={true} + > + {"data viz \n is \n fun!"} + </VictoryLabel> +); + +test = ( + <VictoryLabel + text={['some', 'text', 'strings']} + labelPlacement='vertical' + renderInPortal={true} + lineHeight={'12'} + > + {"data viz \n is \n fun!"} + </VictoryLabel> +); + // VictoryArea test test = ( <VictoryArea @@ -156,32 +177,37 @@ test = ( test = ( <VictoryAxis style={{ - axis: {stroke: "black"}, - grid: {strokeWidth: 2}, - ticks: {stroke: "red"}, - tickLabels: {fontSize: 12}, - axisLabel: {fontSize: 16} + axis: { stroke: "black" }, + grid: { strokeWidth: 2 }, + ticks: { stroke: "red" }, + tickLabels: { fontSize: 12 }, + axisLabel: { fontSize: 16 } }} label="Planets" tickValues={[ - "Mercury", - "Venus", - "Earth", - "Mars", - "Jupiter" - ]}/> + "Mercury", + "Venus", + "Earth", + "Mars", + "Jupiter" + ]} /> ); test = ( <VictoryAxis scale="time" + style={{ + grid: { strokeWidth: tick => tick.x }, + ticks: { stroke: tick => tick.color }, + tickLabels: { fontSize: tick => tick.y }, + }} tickValues={[ new Date(1980, 1, 1), new Date(1990, 1, 1), new Date(2000, 1, 1), new Date(2010, 1, 1), new Date(2020, 1, 1)]} - tickFormat={(x) => x.getFullYear()}/> + tickFormat={(x) => x.getFullYear()} /> ); test = ( @@ -577,12 +603,19 @@ test = ( test = ( <VictoryScatter data={[ - {amount: 1, yield: 1, error: 0.5}, - {amount: 2, yield: 2, error: 1.1}, - {amount: 3, yield: 3, error: 0}, - {amount: 4, yield: 2, error: 0.1}, - {amount: 5, yield: 1, error: 1.5} + { amount: 1, yield: 1, error: 0.5 }, + { amount: 2, yield: 2, error: 1.1 }, + { amount: 3, yield: 3, error: 0 }, + { amount: 4, yield: 2, error: 0.1 }, + { amount: 5, yield: 1, error: 1.5 } ]} + style={{ + data: { + fill: d => d.x, + stroke: (datum, active) => active ? datum.x : datum.y, + strokeWidth: 3 + } + }} x={"amount"} y={(data) => (data.yield + data.error)} /> From fe4db4f74ef8bc5181048bae50734cdd40e11310 Mon Sep 17 00:00:00 2001 From: arichter83 <ar@5mm.de> Date: Wed, 6 Feb 2019 09:13:59 +0100 Subject: [PATCH 118/200] Added Meteor.absoluteUrl.defaultOptions --- types/meteor/meteor.d.ts | 15 ++++++++++----- types/meteor/test/meteor-tests.ts | 7 +++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/types/meteor/meteor.d.ts b/types/meteor/meteor.d.ts index ca08c31c98..e1a51fe48e 100644 --- a/types/meteor/meteor.d.ts +++ b/types/meteor/meteor.d.ts @@ -63,11 +63,16 @@ declare module "meteor/meteor" { /** Method **/ /** Url **/ - function absoluteUrl(path?: string, options?: { - secure?: boolean; - replaceLocalhost?: boolean; - rootUrl?: string; - }): string; + var absoluteUrl: { + (path?: string, options?: absoluteUrlOptions): string; + defaultOptions: absoluteUrlOptions; + } + + interface absoluteUrlOptions { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + } /** Url **/ /** Timeout **/ diff --git a/types/meteor/test/meteor-tests.ts b/types/meteor/test/meteor-tests.ts index 8a9a32ddde..db6815caf2 100644 --- a/types/meteor/test/meteor-tests.ts +++ b/types/meteor/test/meteor-tests.ts @@ -812,3 +812,10 @@ const collectionWithoutConnection = new Mongo.Collection<MonkeyDAO>("monkey", { }); } // End of namespace + +// absoluteUrl +Meteor.absoluteUrl('/sub', {rootUrl: 'http://wonderful.com'}); +Meteor.absoluteUrl.defaultOptions = { + rootUrl: 'http://123.com', + secure: false +}; From f245a172eb7bffb6a4aebd3768a5a38297131ed1 Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 20:01:40 +0900 Subject: [PATCH 119/200] Fix react-event-listener for breaking change in ts@next Use newfound ts@3.1 powers to improve the types. --- types/react-event-listener/index.d.ts | 2 +- types/react-event-listener/package.json | 7 + .../react-event-listener-tests.tsx | 2 +- types/react-event-listener/ts3.1/index.d.ts | 220 ++++++++++++++++++ .../ts3.1/react-event-listener-tests.tsx | 9 + .../react-event-listener/ts3.1/tsconfig.json | 25 ++ types/react-event-listener/ts3.1/tslint.json | 1 + 7 files changed, 264 insertions(+), 2 deletions(-) create mode 100644 types/react-event-listener/package.json create mode 100644 types/react-event-listener/ts3.1/index.d.ts create mode 100644 types/react-event-listener/ts3.1/react-event-listener-tests.tsx create mode 100644 types/react-event-listener/ts3.1/tsconfig.json create mode 100644 types/react-event-listener/ts3.1/tslint.json diff --git a/types/react-event-listener/index.d.ts b/types/react-event-listener/index.d.ts index c3ff194394..c264735c08 100644 --- a/types/react-event-listener/index.d.ts +++ b/types/react-event-listener/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from "react"; +import React = require("react"); export interface EventOptions { /** diff --git a/types/react-event-listener/package.json b/types/react-event-listener/package.json new file mode 100644 index 0000000000..24c89a85ed --- /dev/null +++ b/types/react-event-listener/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} \ No newline at end of file diff --git a/types/react-event-listener/react-event-listener-tests.tsx b/types/react-event-listener/react-event-listener-tests.tsx index 8b9aae2c4d..e9a00dcc5f 100644 --- a/types/react-event-listener/react-event-listener-tests.tsx +++ b/types/react-event-listener/react-event-listener-tests.tsx @@ -1,4 +1,4 @@ -import * as React from "react"; +import React = require("react"); import EventListener, { withOptions } from "react-event-listener"; <EventListener target={document} onBeforeUnload={ev => { }} />; diff --git a/types/react-event-listener/ts3.1/index.d.ts b/types/react-event-listener/ts3.1/index.d.ts new file mode 100644 index 0000000000..b6e11bed31 --- /dev/null +++ b/types/react-event-listener/ts3.1/index.d.ts @@ -0,0 +1,220 @@ +import React = require("react"); + +export interface EventOptions extends Pick<AddEventListenerOptions, 'capture' | 'passive'> { } + +export function withOptions<T, TThis = any>(handler: (this: TThis, ev: T) => any, options: EventOptions): (this: TThis, ev: T) => any; + +export type EventListenerThisType<T extends EventTarget | WindowEventTargets> = T extends keyof Window ? Window[T] : T; + +export type OnErrorEventHandlerArgs = OnErrorEventHandlerNonNull extends (...args: infer A) => any ? A : []; + +export interface EventListenerProps<T extends EventTarget | WindowEventTargets> { + // Global events + onPointerCancel?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerCancelCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerDown?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerDownCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerEnter?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerEnterCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerLeave?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerLeaveCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerMove?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerMoveCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOut?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOutCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOver?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOverCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerUp?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerUpCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onWheel?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onWheelCapture?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onAbort?(this: EventListenerThisType<T>, ev: Event): any; + onAbortCapture?(this: EventListenerThisType<T>, ev: Event): any; + onAfterPrint?(this: EventListenerThisType<T>, ev: Event): any; + onAfterPrintCapture?(this: EventListenerThisType<T>, ev: Event): any; + onBeforePrint?(this: EventListenerThisType<T>, ev: Event): any; + onBeforePrintCapture?(this: EventListenerThisType<T>, ev: Event): any; + onBeforeUnload?(this: EventListenerThisType<T>, ev: BeforeUnloadEvent): any; + onBeforeUnloadCapture?(this: EventListenerThisType<T>, ev: BeforeUnloadEvent): any; + onBlur?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onBlurCapture?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onCanPlay?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayCapture?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayThrough?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayThroughCapture?(this: EventListenerThisType<T>, ev: Event): any; + onChange?(this: EventListenerThisType<T>, ev: Event): any; + onChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onClick?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onClickCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onCompassNeedsCalibration?(this: EventListenerThisType<T>, ev: Event): any; + onCompassNeedsCalibrationCapture?(this: EventListenerThisType<T>, ev: Event): any; + onContextMenu?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onContextMenuCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onDblClick?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onDblClickCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onDeviceMotion?(this: EventListenerThisType<T>, ev: DeviceMotionEvent): any; + onDeviceMotionCapture?(this: EventListenerThisType<T>, ev: DeviceMotionEvent): any; + onDeviceOrientation?(this: EventListenerThisType<T>, ev: DeviceOrientationEvent): any; + onDeviceOrientationCapture?(this: EventListenerThisType<T>, ev: DeviceOrientationEvent): any; + onDrag?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnd?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEndCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnter?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnterCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragLeave?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragLeaveCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragOver?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragOverCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragStart?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragStartCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDrop?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDropCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDurationChange?(this: EventListenerThisType<T>, ev: Event): any; + onDurationChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onEmptied?(this: EventListenerThisType<T>, ev: Event): any; + onEmptiedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onEnded?(this: EventListenerThisType<T>, ev: Event): any; + onEndedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onError?(this: EventListenerThisType<T>, ...args: OnErrorEventHandlerArgs): any; + onErrorCapture?(this: EventListenerThisType<T>, ...args: OnErrorEventHandlerArgs): any; + onFocus?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onFocusCapture?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onHashChange?(this: EventListenerThisType<T>, ev: HashChangeEvent): any; + onHashChangeCapture?(this: EventListenerThisType<T>, ev: HashChangeEvent): any; + onInput?(this: EventListenerThisType<T>, ev: Event): any; + onInputCapture?(this: EventListenerThisType<T>, ev: Event): any; + onKeyDown?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyDownCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyPress?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyPressCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyUp?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyUpCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onLoad?(this: EventListenerThisType<T>, ev: Event): any; + onLoadCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedData?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedDataCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedMetadata?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedMetadataCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadStart?(this: EventListenerThisType<T>, ev: Event): any; + onLoadStartCapture?(this: EventListenerThisType<T>, ev: Event): any; + onMessage?(this: EventListenerThisType<T>, ev: MessageEvent): any; + onMessageCapture?(this: EventListenerThisType<T>, ev: MessageEvent): any; + onMouseDown?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseDownCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseEnter?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseEnterCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseLeave?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseLeaveCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseMove?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseMoveCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOut?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOutCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOver?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOverCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseUp?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseUpCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseWheel?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onMouseWheelCapture?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onMsGestureChange?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureChangeCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureDoubleTap?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureDoubleTapCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureEnd?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureEndCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureHold?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureHoldCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureStart?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureStartCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureTap?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureTapCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsInertiaStart?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsInertiaStartCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsPointerCancel?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerCancelCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerDown?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerDownCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerEnter?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerEnterCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerLeave?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerLeaveCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerMove?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerMoveCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOut?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOutCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOver?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOverCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + oNmsPointerUp?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + oNmsPointerUpCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onOffline?(this: EventListenerThisType<T>, ev: Event): any; + onOfflineCapture?(this: EventListenerThisType<T>, ev: Event): any; + onOnline?(this: EventListenerThisType<T>, ev: Event): any; + onOnlineCapture?(this: EventListenerThisType<T>, ev: Event): any; + onOrientationChange?(this: EventListenerThisType<T>, ev: Event): any; + onOrientationChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPageHide?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageHideCapture?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageShow?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageShowCapture?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPause?(this: EventListenerThisType<T>, ev: Event): any; + onPauseCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPlay?(this: EventListenerThisType<T>, ev: Event): any; + onPlayCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPlaying?(this: EventListenerThisType<T>, ev: Event): any; + onPlayingCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPopState?(this: EventListenerThisType<T>, ev: PopStateEvent): any; + onPopStateCapture?(this: EventListenerThisType<T>, ev: PopStateEvent): any; + onProgress?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onProgressCapture?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onRateChange?(this: EventListenerThisType<T>, ev: Event): any; + onRateChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onReadyStateChange?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onReadyStateChangeCapture?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onReset?(this: EventListenerThisType<T>, ev: Event): any; + onResetCapture?(this: EventListenerThisType<T>, ev: Event): any; + onResize?(this: EventListenerThisType<T>, ev: UIEvent): any; + onResizeCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onScroll?(this: EventListenerThisType<T>, ev: UIEvent): any; + onScrollCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSeeked?(this: EventListenerThisType<T>, ev: Event): any; + onSeekedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSeeking?(this: EventListenerThisType<T>, ev: Event): any; + onSeekingCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSelect?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSelectCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSelectionChange?(this: EventListenerThisType<T>, ev: Event): any; + onSelectionChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onStalled?(this: EventListenerThisType<T>, ev: Event): any; + onStalledCapture?(this: EventListenerThisType<T>, ev: Event): any; + onStorage?(this: EventListenerThisType<T>, ev: StorageEvent): any; + onStorageCapture?(this: EventListenerThisType<T>, ev: StorageEvent): any; + onSubmit?(this: EventListenerThisType<T>, ev: Event): any; + onSubmitCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSuspend?(this: EventListenerThisType<T>, ev: Event): any; + onSuspendCapture?(this: EventListenerThisType<T>, ev: Event): any; + onTimeUpdate?(this: EventListenerThisType<T>, ev: Event): any; + onTimeUpdateCapture?(this: EventListenerThisType<T>, ev: Event): any; + onTouchCancel?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchCancelCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchEnd?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchEndCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchMove?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchMoveCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchStart?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchStartCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onUnload?(this: EventListenerThisType<T>, ev: Event): any; + onUnloadCapture?(this: EventListenerThisType<T>, ev: Event): any; + onVolumeChange?(this: EventListenerThisType<T>, ev: Event): any; + onVolumeChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onWaiting?(this: EventListenerThisType<T>, ev: Event): any; + onWaitingCapture?(this: EventListenerThisType<T>, ev: Event): any; + + /** + * Target (window or document) + */ + target: T; +} + +export type WindowEventTargets = {[K in keyof Window]: Window[K] extends EventTarget ? K : never}[keyof Window]; + +export default class EventListener<T extends EventTarget | WindowEventTargets> extends React.PureComponent<EventListenerProps<T>> { } diff --git a/types/react-event-listener/ts3.1/react-event-listener-tests.tsx b/types/react-event-listener/ts3.1/react-event-listener-tests.tsx new file mode 100644 index 0000000000..238b05237b --- /dev/null +++ b/types/react-event-listener/ts3.1/react-event-listener-tests.tsx @@ -0,0 +1,9 @@ +import React = require("react"); +import EventListener, { withOptions } from "react-event-listener"; + +<EventListener target={document} onBeforeUnload={ev => { }} />; +<EventListener target={window} onResize={withOptions((ev: UIEvent) => { }, { passive: true, capture: true })} />; +<EventListener target="window" onResize={() => { }}/>; +<EventListener target={document} onSelectionChange={ev => { }} />; +<EventListener target="document" onError={function() { this.documentElement; }} />; +<EventListener target={window} onBlurCapture={function() { this.pageXOffset; }} />; diff --git a/types/react-event-listener/ts3.1/tsconfig.json b/types/react-event-listener/ts3.1/tsconfig.json new file mode 100644 index 0000000000..8b6f2935ea --- /dev/null +++ b/types/react-event-listener/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-event-listener-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-event-listener/ts3.1/tslint.json b/types/react-event-listener/ts3.1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-event-listener/ts3.1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 58da7330ea25ead450a8ee3ec3e83b742f2d0a9e Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 18:30:44 +0900 Subject: [PATCH 120/200] Update react-dom, react-test-renderer to 16.8.0 --- types/react-dom/index.d.ts | 3 ++- types/react-dom/react-dom-tests.tsx | 14 ++++++++++++++ types/react-dom/test-utils/index.d.ts | 14 ++++++++++++++ types/react-dom/tsconfig.json | 2 +- types/react-test-renderer/index.d.ts | 17 ++++++++++++++++- .../react-test-renderer-tests.ts | 11 +++++++++-- 6 files changed, 56 insertions(+), 5 deletions(-) diff --git a/types/react-dom/index.d.ts b/types/react-dom/index.d.ts index 518c0c617c..a6ac5c9d11 100644 --- a/types/react-dom/index.d.ts +++ b/types/react-dom/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for React (react-dom) 16.0 +// Type definitions for React (react-dom) 16.8 // Project: http://facebook.github.io/react/ // Definitions by: Asana <https://asana.com> // AssureSign <http://www.assuresign.com> // Microsoft <https://microsoft.com> // MartynasZilinskas <https://github.com/MartynasZilinskas> // Josh Rutherford <https://github.com/theruther4d> +// Jessica Franco <https://github.com/Jessidhia> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index c7ccb0052d..e81c500f9c 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -178,4 +178,18 @@ describe('React dom test utils', () => { shallowRenderer.getRenderOutput(); }); }); + + describe('act', () => { + it('accepts a sync callback that is void', () => { + ReactTestUtils.act(() => {}); + }); + it('rejects an async callback even if void', () => { + // $ExpectError + ReactTestUtils.act(async () => {}); + }); + it('rejects a callback that returns null', () => { + // $ExpectError + ReactTestUtils.act(() => null); + }); + }); }); diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index f60d088515..f1eae65df6 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -278,3 +278,17 @@ export function findRenderedComponentWithType<T extends Component<any>, C extend * Call this in your tests to create a shallow renderer. */ export function createRenderer(): ShallowRenderer; + +/** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ +// the "void | undefined" is here to forbid any sneaky "Promise" returns. +export function act(callback: () => void | undefined): void; diff --git a/types/react-dom/tsconfig.json b/types/react-dom/tsconfig.json index f63325026f..6d7d943c8b 100644 --- a/types/react-dom/tsconfig.json +++ b/types/react-dom/tsconfig.json @@ -14,7 +14,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index c147d5c190..040ec3a513 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for react-test-renderer 16.0 +// Type definitions for react-test-renderer 16.8 // Project: https://facebook.github.io/react/ // Definitions by: Arvitaly <https://github.com/arvitaly> // Lochbrunner <https://github.com/lochbrunner> // John Reilly <https://github.com/johnnyreilly> // John Gozde <https://github.com/jgoz> +// Jessica Franco <https://github.com/Jessidhia> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -50,3 +51,17 @@ export interface TestRendererOptions { createNodeMock(element: ReactElement<any>): any; } export function create(nextElement: ReactElement<any>, options?: TestRendererOptions): ReactTestRenderer; + +/** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ +// the "void | undefined" is here to forbid any sneaky "Promise" returns. +export function act(callback: () => void | undefined): void; diff --git a/types/react-test-renderer/react-test-renderer-tests.ts b/types/react-test-renderer/react-test-renderer-tests.ts index 83dc510e2b..b7e23caf25 100644 --- a/types/react-test-renderer/react-test-renderer-tests.ts +++ b/types/react-test-renderer/react-test-renderer-tests.ts @@ -1,5 +1,5 @@ -import * as React from "react"; -import { create, ReactTestInstance } from "react-test-renderer"; +import React = require("react"); +import { act, create, ReactTestInstance } from "react-test-renderer"; import { createRenderer } from 'react-test-renderer/shallow'; class TestComponent extends React.Component { } @@ -66,3 +66,10 @@ const shallowRenderer = createRenderer(); shallowRenderer.render(component); shallowRenderer.getRenderOutput(); shallowRenderer.getMountedInstance(); + +// Only synchronous, void callbacks are acceptable for act() +act(() => {}); +// $ExpectError +act(async () => {}); +// $ExpectError +act(() => null); From 1755edd5fc18384333ed91db9b4d60098ee5e32c Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 18:39:55 +0900 Subject: [PATCH 121/200] Forbid returning non-void from the useEffect destructor too There is a runtime warning. --- types/react/index.d.ts | 16 +++++++++------- types/react/test/hooks.tsx | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 929a698775..9e46bc5ca9 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -783,11 +783,9 @@ declare namespace React { // TODO (TypeScript 3.0): ReadonlyArray<unknown> type DependencyList = ReadonlyArray<any>; - // NOTE: Currently, in alpha.0, the effect callbacks are actually allowed to return anything, - // but functions are treated specially. The next version published with hooks will warn if you actually - // return anything besides `void` or a callback. Async effects need to call an async function inside - // them. - type EffectCallback = () => (void | (() => void)); + // NOTE: callbacks are _only_ allowed to return either void, or a destructor. + // The destructor is itself only allowed to return void. + type EffectCallback = () => (void | (() => void | undefined)); interface MutableRefObject<T> { current: T; @@ -853,12 +851,16 @@ declare namespace React { * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#usereducer */ + // I'm not sure if I keep this 2-ary or if I make it (2,3)-ary; it's currently (2,3)-ary. // The Flow types do have an overload for 3-ary invocation with undefined initializer. - // NOTE: the documentation or any alphas aren't updated, this is current for master. - // NOTE 2: without the ReducerState indirection, TypeScript would reduce S to be the most common + + // NOTE: without the ReducerState indirection, TypeScript would reduce S to be the most common // supertype between the reducer's return type and the initialState (or the initializer's return type), // which would prevent autocompletion from ever working. + + // TODO: double-check if this weird overload logic is necessary. It is possible it's either a bug + // in older versions, or a regression in newer versions of the typescript completion service. function useReducer<R extends Reducer<any, any>>( reducer: R, initialState: ReducerState<R>, diff --git a/types/react/test/hooks.tsx b/types/react/test/hooks.tsx index 12fcc28222..26ff634e89 100644 --- a/types/react/test/hooks.tsx +++ b/types/react/test/hooks.tsx @@ -120,6 +120,23 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { setState(reducerState.age); }, []); + // effects are only allowed to either be actually void or return actually void functions + React.useEffect(() => () => {}); + // indistinguishable + React.useEffect(() => () => undefined); + // $ExpectError + React.useEffect(() => null); + // $ExpectError + React.useEffect(() => Math.random() ? null : undefined); + // $ExpectError + React.useEffect(() => () => null); + // $ExpectError + React.useEffect(() => () => Math.random() ? null : undefined); + // $ExpectError + React.useEffect(() => async () => {}); + // $ExpectError + React.useEffect(async () => () => {}); + React.useDebugValue(id, value => value.toFixed()); React.useDebugValue(id); From 8af624afbe50926ee476cbad993b80da2ce07802 Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 19:07:43 +0900 Subject: [PATCH 122/200] Use contrivances to present something close to act()'s real return type Make it harder to accidentally use it in contexts where a Promise may be expected. --- types/react-dom/react-dom-tests.tsx | 5 +++++ types/react-dom/test-utils/index.d.ts | 11 ++++++++++- types/react-test-renderer/index.d.ts | 11 ++++++++++- .../react-test-renderer/react-test-renderer-tests.ts | 2 ++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index e81c500f9c..46274e3ffd 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -191,5 +191,10 @@ describe('React dom test utils', () => { // $ExpectError ReactTestUtils.act(() => null); }); + it('returns a Promise-like that errors out on use', () => { + const result = ReactTestUtils.act(() => {}); + // $ExpectError + Promise.resolve(result); + }); }); }); diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index f1eae65df6..fb98181847 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -291,4 +291,13 @@ export function createRenderer(): ShallowRenderer; * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks */ // the "void | undefined" is here to forbid any sneaky "Promise" returns. -export function act(callback: () => void | undefined): void; +// the actual return value is always a "DebugPromiseLike", +// but having an "| {}" makes it harder to accidentally use. +export function act(callback: () => void | undefined): DebugPromiseLike | {}; + +// Intentionally doesn't extend PromiseLike<never>. +// Ideally this should be as hard to accidentally use as possible. +interface DebugPromiseLike { + // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. + then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; +} diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index 040ec3a513..34ddb2502c 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -64,4 +64,13 @@ export function create(nextElement: ReactElement<any>, options?: TestRendererOpt * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks */ // the "void | undefined" is here to forbid any sneaky "Promise" returns. -export function act(callback: () => void | undefined): void; +// the actual return value is always a "DebugPromiseLike", +// but having an "| {}" makes it harder to accidentally use. +export function act(callback: () => void | undefined): DebugPromiseLike | {}; + +// Intentionally doesn't extend PromiseLike<never>. +// Ideally this should be as hard to accidentally use as possible. +interface DebugPromiseLike { + // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. + then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; +} diff --git a/types/react-test-renderer/react-test-renderer-tests.ts b/types/react-test-renderer/react-test-renderer-tests.ts index b7e23caf25..48d861cf62 100644 --- a/types/react-test-renderer/react-test-renderer-tests.ts +++ b/types/react-test-renderer/react-test-renderer-tests.ts @@ -73,3 +73,5 @@ act(() => {}); act(async () => {}); // $ExpectError act(() => null); +// $ExpectError +Promise.resolve(act(() => {})); From 987f88cc20bd60a60a23640ab76f52fe1f7fca08 Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 19:53:52 +0900 Subject: [PATCH 123/200] Add missing export annotations --- types/react-dom/test-utils/index.d.ts | 2 +- types/react-test-renderer/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index fb98181847..8730dc9447 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -297,7 +297,7 @@ export function act(callback: () => void | undefined): DebugPromiseLike | {}; // Intentionally doesn't extend PromiseLike<never>. // Ideally this should be as hard to accidentally use as possible. -interface DebugPromiseLike { +export interface DebugPromiseLike { // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; } diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index 34ddb2502c..abdae1c908 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -70,7 +70,7 @@ export function act(callback: () => void | undefined): DebugPromiseLike | {}; // Intentionally doesn't extend PromiseLike<never>. // Ideally this should be as hard to accidentally use as possible. -interface DebugPromiseLike { +export interface DebugPromiseLike { // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; } From acd0e1cb6de77123798368dbcf48d62a9f1d5006 Mon Sep 17 00:00:00 2001 From: Erik Krogh Kristensen <erik@webbies.dk> Date: Wed, 6 Feb 2019 13:10:33 +0100 Subject: [PATCH 124/200] platform: The parse and toString methods are not maybe present, they are definitely present. --- types/platform/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/platform/index.d.ts b/types/platform/index.d.ts index b0f640d522..c1db7431f3 100644 --- a/types/platform/index.d.ts +++ b/types/platform/index.d.ts @@ -18,8 +18,8 @@ declare interface Platform { version?: string; toString(): string; }; - parse?(ua: string): Platform; - toString?(): string; + parse(ua: string): Platform; + toString(): string; } declare var platform: Platform; From 8ab3765a87c465c8273308ea09ace21281ee4c40 Mon Sep 17 00:00:00 2001 From: Erik Krogh Kristensen <erik@webbies.dk> Date: Wed, 6 Feb 2019 13:20:10 +0100 Subject: [PATCH 125/200] platform: fixed the tests --- types/platform/platform-tests.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/platform/platform-tests.ts b/types/platform/platform-tests.ts index 65433ffb13..ce8648e876 100644 --- a/types/platform/platform-tests.ts +++ b/types/platform/platform-tests.ts @@ -16,7 +16,8 @@ var tests: TestContainer = { prerelease: null, product: null, ua: "Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; HTC Sensation XE with Beats Audio Build/IML74K) AppleWebKit/535.7 (KHTML, like Gecko) CrMo/16.0.912.77 Mobile Safari/535.7", - version: "16.0.912.77" + version: "16.0.912.77", + parse: function () {throw new Error()} }, 'WebKit Nightly 528.4 (like Safari 4.x) on Mac OS X 10.4.11': { description: "WebKit Nightly 528.4 (like Safari 4.x) on Mac OS X 10.4.11", @@ -31,7 +32,8 @@ var tests: TestContainer = { prerelease: "alpha", product: null, ua: "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; tr) AppleWebKit/528.4+ (KHTML, like Gecko) Version/4.0dp1 Safari/526.11.2", - version: "528.4" + version: "528.4", + parse: function () {throw new Error()} } }; From 970fc9d48471d2834e24f327610ce56e3010477c Mon Sep 17 00:00:00 2001 From: Martin Probst <martin@probst.io> Date: Wed, 6 Feb 2019 14:08:06 +0100 Subject: [PATCH 126/200] Angular IPromise interop with platform Promise. Angular promises support `.then()` chaining of functions that return arbitrary `then()`able values. https://docs.angularjs.org/api/ng/service/$q#the-promise-api This change updates the definition of `ng.IPromise.then()` to match that by overloading the function to handle `PromiseLike` values. --- types/angular/angular-tests.ts | 8 ++++++++ types/angular/index.d.ts | 14 ++++++++++++++ types/angular/tsconfig.json | 5 +++-- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index b83a41a6df..7470fb08bb 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -294,6 +294,14 @@ foo.then((x) => { x.toFixed(); }); +namespace TestPromiseInterop { + declare const promiseInterop: ng.IPromise<number>; + const ngStringPromise: ng.IPromise<string> = + promiseInterop.then((num) => Promise.resolve(String(num))); + const caughtStringPromise: ng.IPromise<string|number> = + promiseInterop.catch((reason) => Promise.resolve('oh noes')); +} + // $q signature tests namespace TestQ { interface AbcObject { diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 4a8b26fba9..0c28ddbf27 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -1197,6 +1197,15 @@ declare namespace angular { * the `notifyCallback` method. The promise can not be resolved or rejected from the * `notifyCallback` method. */ + then<TResult1 = T, TResult2 = never>( + successCallback?: + | ((value: T) => PromiseLike<never> | PromiseLike<TResult1> | TResult1) + | null, + errorCallback?: + | ((reason: any) => PromiseLike<never> | PromiseLike<TResult2> | TResult2) + | null, + notifyCallback?: (state: any) => any + ): IPromise<TResult1 | TResult2>; then<TResult1 = T, TResult2 = never>( successCallback?: | ((value: T) => IPromise<never> | IPromise<TResult1> | TResult1) @@ -1210,6 +1219,11 @@ declare namespace angular { /** * Shorthand for promise.then(null, errorCallback) */ + catch<TResult = never>( + onRejected?: + | ((reason: any) => PromiseLike<never> | PromiseLike<TResult> | TResult) + | null + ): IPromise<T | TResult>; catch<TResult = never>( onRejected?: | ((reason: any) => IPromise<never> | IPromise<TResult> | TResult) diff --git a/types/angular/tsconfig.json b/types/angular/tsconfig.json index 46eeb69c7a..590c9c7798 100644 --- a/types/angular/tsconfig.json +++ b/types/angular/tsconfig.json @@ -11,7 +11,8 @@ "lib": [ "es5", "dom", - "es2015.iterable" + "es2015.iterable", + "es2015.promise" ], "noImplicitAny": false, "noImplicitThis": false, @@ -25,4 +26,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} From 89d2235d1d4d655f3f2a1584f41e7797029c6fc5 Mon Sep 17 00:00:00 2001 From: Kristoffer <hello@kristoffer.is> Date: Wed, 6 Feb 2019 14:32:30 +0100 Subject: [PATCH 127/200] Add addPrevSibling typing --- types/libxmljs/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index db37035f06..5ba3fc294f 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -116,6 +116,7 @@ export class Element extends Node { prevElement(): Element|null; nextElement(): Element|null; addNextSibling(siblingNode: Node): Node; + addPrevSibling(siblingNode: Node): Node; find(xpath: string, ns_uri?: string): Node[]; find(xpath: string, namespaces: StringMap): Node[]; From 7f68109ad68f2c4f68f7dd6461a4ba44249f6123 Mon Sep 17 00:00:00 2001 From: Paito Anderson <pj.paito@gmail.com> Date: Wed, 6 Feb 2019 09:28:43 -0500 Subject: [PATCH 128/200] Update react-native-popup-dialog --- types/react-native-popup-dialog/index.d.ts | 8 +++--- .../react-native-popup-dialog-tests.tsx | 25 +++++++++++++------ 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/types/react-native-popup-dialog/index.d.ts b/types/react-native-popup-dialog/index.d.ts index d0a9d22a4b..b81533a6bc 100644 --- a/types/react-native-popup-dialog/index.d.ts +++ b/types/react-native-popup-dialog/index.d.ts @@ -17,7 +17,7 @@ export interface DialogContentProps { style?: StyleProp<ViewStyle>; } -export interface DialogActionListProps { +export interface DialogFooterProps { bordered?: boolean; style?: StyleProp<ViewStyle>; } @@ -70,9 +70,7 @@ export interface DialogProps { onDismiss?: () => void; onTouchOutside?: () => void; onHardwareBackPress?: () => boolean; - actions?: any[]; - actionContainerStyle?: StyleProp<ViewStyle>; - actionsBordered?: boolean; + footer?: any; useNativeDriver?: boolean; } @@ -97,7 +95,7 @@ export class SlideAnimation { } export class DialogContent extends React.Component<DialogContentProps, any> { } -export class DialogActionList extends React.Component<DialogActionListProps, any> { } +export class DialogFooter extends React.Component<DialogFooterProps, any> { } export class DialogButton extends React.Component<DialogButtonProps, any> { } export class DialogTitle extends React.Component<DialogTitleProps, any> { } export class Overlay extends React.Component<OverlayProps, any> { } diff --git a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx index 55f979f506..2dc943d35b 100644 --- a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx +++ b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx @@ -7,6 +7,7 @@ import Dialog, { SlideAnimation, ScaleAnimation, FadeAnimation, + DialogFooter, } from 'react-native-popup-dialog'; const slideAnimation = new SlideAnimation({ slideFrom: 'bottom' }); @@ -50,14 +51,22 @@ class Test extends React.Component<any> { <Dialog ref={(popupDialog) => this.scalingPopupDialog = popupDialog} dialogTitle={<DialogTitle title="Popup Dialog - Scale Animation" />} dialogAnimation={scaleAnimation} - actions={[ - <DialogButton - text="CLOSE" - onPress={(event) => this.dismissPopupDialog(this.scalingPopupDialog)} - textStyle={{ color: "red" }} - key="button-1" - />, - ]} + footer={ + <DialogFooter> + <DialogButton + text="CLOSE" + onPress={(event) => this.dismissPopupDialog(this.scalingPopupDialog)} + textStyle={{ color: "red" }} + bordered + key="button-1" + /> + <DialogButton + text="OK" + onPress={() => {}} + key="button-2" + /> + </DialogFooter> + } /> <Dialog ref={(popupDialog) => this.slidingPopupDialog = popupDialog} dialogTitle={<DialogTitle title="Popup Dialog - Slide Animation" />} From 97fa13c0b88946d6d2bb9c97d5f6e432baa1c00e Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Wed, 6 Feb 2019 11:18:11 -0500 Subject: [PATCH 129/200] Extract functional style def to type Use type in box plot styles --- types/victory/index.d.ts | 3849 +++++++++++++++++++------------------- 1 file changed, 1925 insertions(+), 1924 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index c1a1a6f394..43bf4378e6 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -11,20 +11,20 @@ /// <reference types="react"/> declare module "victory" { - import * as React from "react"; + import * as React from "react"; - /** - * Single animation object to interpolate - */ + /** + * Single animation object to interpolate + */ export type AnimationStyle = { [key: string ]: string | number }; - /** - * Animation styles to interpolate - */ + /** + * Animation styles to interpolate + */ - export type AnimationData = AnimationStyle | AnimationStyle[]; + export type AnimationData = AnimationStyle | AnimationStyle[]; - export type AnimationEasing = + export type AnimationEasing = "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | @@ -32,793 +32,794 @@ declare module "victory" { "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; - // Many victory components accept string or number or callback which returns string or number - type StringOrNumberOrCallback = - | string - | number - | ((datum: any, active: boolean) => string | number); - type NumberOrCallback = ((datum: any, active: boolean) => number) | number; + // Many victory components accept string or number or callback which returns string or number + type StringOrNumberOrCallback = + | string + | number + | ((datum: any, active: boolean) => string | number); + type NumberOrCallback = ((datum: any, active: boolean) => number) | number; - /** - * Style interface used in components/themeing - */ - export interface VictoryStyleInterface { - parent?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; - data?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; - labels?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; - } + type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + /** + * Style interface used in components/themeing + */ + export interface VictoryStyleInterface { + parent?: VictoryStyleObject; + data?: VictoryStyleObject; + labels?: VictoryStyleObject; + } - export interface VictoryAnimationProps { - /** - * The child of should be a function that takes an object of tweened values and returns a component to render. - * @param style - */ - children?: (style: AnimationStyle) => React.ReactElement<any>; - /** - * The number of milliseconds the animation should take to complete. - * @default 1000 - */ - duration?: number; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - /** - * The delay prop specifies a delay in milliseconds before the animation begins. - * If multiple values are in the animation queue, it is the delay between each animation. - * @default 0 - */ - delay?: number; - /** - * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. - */ - onEnd?: () => void; - /** - * The data prop specifies the latest set of values to tween to. - * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. - * When given an array of values, VictoryAnimation will use it as an animation queue. - * @default {} - */ - data?: AnimationData; - } + export interface VictoryAnimationProps { + /** + * The child of should be a function that takes an object of tweened values and returns a component to render. + * @param style + */ + children?: (style: AnimationStyle) => React.ReactElement<any>; + /** + * The number of milliseconds the animation should take to complete. + * @default 1000 + */ + duration?: number; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + /** + * The delay prop specifies a delay in milliseconds before the animation begins. + * If multiple values are in the animation queue, it is the delay between each animation. + * @default 0 + */ + delay?: number; + /** + * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. + */ + onEnd?: () => void; + /** + * The data prop specifies the latest set of values to tween to. + * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. + * When given an array of values, VictoryAnimation will use it as an animation queue. + * @default {} + */ + data?: AnimationData; + } - /** - * VictoryAnimation animates prop changes for any React component. - * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. - */ + /** + * VictoryAnimation animates prop changes for any React component. + * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. + */ export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} - /** - * Text anchor type - */ - type TextAnchorType = "start" | "middle" | "end" | "inherit"; + /** + * Text anchor type + */ + type TextAnchorType = "start" | "middle" | "end" | "inherit"; - /** - * Vertical anchor type - */ - type VerticalAnchorType = "start" | "middle" | "end"; + /** + * Vertical anchor type + */ + type VerticalAnchorType = "start" | "middle" | "end"; - export interface VictoryLabelProps { - /** - * Specifies the angle to rotate the text by. - */ - angle?: string | number; - /** - * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. - * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. - * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. - * @default "0.71em" - */ - capHeight?: StringOrNumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text - */ - datum?: {}; - /** - * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. - */ - data?: any[]; - /** - * The events prop attaches arbitrary event handlers to the label component. - * Event handlers are currently only called with their corresponding events. - */ - events?: React.DOMAttributes<any>; - /** - * The children of this component define the content of the label. - * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. - */ - children?: StringOrNumberOrCallback; - /** - * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. - * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar - * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. - * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label - * placement will be used for cartesian charts. - */ - labelPlacement?: "parallel" | "perpendicular" | "vertical"; - /** - * The lineHeight prop defines how much space a single line of text should take up. - * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, - * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. - * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. - * If given a unitless number, it is assumed to be ems. - * @default 1 - */ - lineHeight?: StringOrNumberOrCallback; - /** - * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. - * **This prop should not be set manually.** - */ + export interface VictoryLabelProps { + /** + * Specifies the angle to rotate the text by. + */ + angle?: string | number; + /** + * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. + * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. + * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. + * @default "0.71em" + */ + capHeight?: StringOrNumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text + */ + datum?: {}; + /** + * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. + */ + data?: any[]; + /** + * The events prop attaches arbitrary event handlers to the label component. + * Event handlers are currently only called with their corresponding events. + */ + events?: React.DOMAttributes<any>; + /** + * The children of this component define the content of the label. + * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. + */ + children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; + /** + * The lineHeight prop defines how much space a single line of text should take up. + * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, + * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. + * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. + * If given a unitless number, it is assumed to be ems. + * @default 1 + */ + lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ origin?: { x: number, y: number }; - /** - * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. - * **This prop should not be set manually.** - */ - polar?: boolean; - /** - * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. - * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, - * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate - * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. - */ - text?: string[] | StringOrNumberOrCallback; - /** - * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. - */ - textAnchor?: TextAnchorType | { (): TextAnchorType }; - /** - * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. - */ - verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; - /** - * The transform prop applies a transform to the rendered `<text>` element. - * In addition to being a string, it can be an object containing transform definitions for easier authoring. - */ - transform?: string | {} | { (): string | {} }; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - /** - * The dx prop defines a horizontal shift from the `x` coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the `y` coordinate. - * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. - */ - dy?: StringOrNumberOrCallback; - } + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; + /** + * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. + */ + textAnchor?: TextAnchorType | { (): TextAnchorType }; + /** + * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. + */ + verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; + /** + * The transform prop applies a transform to the rendered `<text>` element. + * In addition to being a string, it can be an object containing transform definitions for easier authoring. + */ + transform?: string | {} | { (): string | {} }; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + /** + * The dx prop defines a horizontal shift from the `x` coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the `y` coordinate. + * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. + */ + dy?: StringOrNumberOrCallback; + } - /** - * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. - */ - export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} + /** + * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. + */ + export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} - export interface VictoryContainerProps { - /** - * The responsive prop specifies whether the rendered container should be a responsive container - * with a viewBox attribute, or a static container with absolute width and height. - * @default true - */ - responsive?: boolean; - /** - * The style prop specifies styles for your VictoryContainer. Any valid inline style properties - * will be applied. Height and width should be specified via the height - * and width props, as they are used to calculate the alignment of - * components within the container. Styles from the child component will - * also be passed, if any exist. - * @examples {border: 1px solid red} - */ - style?: React.CSSProperties; - /** - * The height props specifies the height the svg viewBox of the container. - * This value should be given as a number of pixels. If no height prop - * is given, the height prop from the child component passed will be used. - */ - height?: number; - /** - * The width props specifies the width of the svg viewBox of the container - * This value should be given as a number of pixels. If no width prop - * is given, the width prop from the child component passed will be used. - */ - width?: number; - /** - * The events prop attaches arbitrary event handlers to the container component. - * Event handlers passed from other Victory components are called with their - * corresponding events as well as scale, style, width, height, and data when - * applicable. Use the invert method to convert event coordinate information to - * data. `scale.x.invert(evt.offsetX)`. - * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} - */ - events?: React.DOMAttributes<any>; - /** - * The title prop specifies the title to be applied to the SVG to assist - * accessibility for screen readers. The more descriptive this title is, the more - * useful it will be. If no title prop is passed, it will default to Victory Chart. - * @example "Popularity of Dog Breeds by Percentage" - * @default "Victory Chart" - */ - title?: string; - /** - * The desc prop specifies the description of the chart/SVG to assist with - * accessibility for screen readers. The more info about the chart provided in - * the description, the more usable it will be for people using screen readers. - * This prop defaults to an empty string. - * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are - * not represented above 5% each." - * @default "" - */ - desc?: string; - } + export interface VictoryContainerProps { + /** + * The responsive prop specifies whether the rendered container should be a responsive container + * with a viewBox attribute, or a static container with absolute width and height. + * @default true + */ + responsive?: boolean; + /** + * The style prop specifies styles for your VictoryContainer. Any valid inline style properties + * will be applied. Height and width should be specified via the height + * and width props, as they are used to calculate the alignment of + * components within the container. Styles from the child component will + * also be passed, if any exist. + * @examples {border: 1px solid red} + */ + style?: React.CSSProperties; + /** + * The height props specifies the height the svg viewBox of the container. + * This value should be given as a number of pixels. If no height prop + * is given, the height prop from the child component passed will be used. + */ + height?: number; + /** + * The width props specifies the width of the svg viewBox of the container + * This value should be given as a number of pixels. If no width prop + * is given, the width prop from the child component passed will be used. + */ + width?: number; + /** + * The events prop attaches arbitrary event handlers to the container component. + * Event handlers passed from other Victory components are called with their + * corresponding events as well as scale, style, width, height, and data when + * applicable. Use the invert method to convert event coordinate information to + * data. `scale.x.invert(evt.offsetX)`. + * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} + */ + events?: React.DOMAttributes<any>; + /** + * The title prop specifies the title to be applied to the SVG to assist + * accessibility for screen readers. The more descriptive this title is, the more + * useful it will be. If no title prop is passed, it will default to Victory Chart. + * @example "Popularity of Dog Breeds by Percentage" + * @default "Victory Chart" + */ + title?: string; + /** + * The desc prop specifies the description of the chart/SVG to assist with + * accessibility for screen readers. The more info about the chart provided in + * the description, the more usable it will be for people using screen readers. + * This prop defaults to an empty string. + * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are + * not represented above 5% each." + * @default "" + */ + desc?: string; + } export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} - type CursorData = { - x: number; - y: number; - }; + type CursorData = { + x: number; + y: number; + }; - export interface VictoryCursorContainerProps extends VictoryContainerProps { - /** - * The cursorComponent prop takes a component instance which will be used to render a cursor element. - * The new element created will be supplied with x1, y1, x2 and y2 positioning props. - * If a cursorComponent is not supplied, a new Line component will be rendered. - * @default cursorComponent={<Line/>} - */ - cursorComponent?: React.ReactElement<any>; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example cursorDimension="x" - */ + export interface VictoryCursorContainerProps extends VictoryContainerProps { + /** + * The cursorComponent prop takes a component instance which will be used to render a cursor element. + * The new element created will be supplied with x1, y1, x2 and y2 positioning props. + * If a cursorComponent is not supplied, a new Line component will be rendered. + * @default cursorComponent={<Line/>} + */ + cursorComponent?: React.ReactElement<any>; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example cursorDimension="x" + */ cursorDimension?: 'x' | 'y'; - /** - * The cursorLabel prop defines the label that will appear next to the cursor. - * A label will only appear if cursorLabel is set. This prop should be given as a - * function of a point (an Object with x and y properties). - * @example cursorLabel={(point) => point.x} - */ - cursorLabel?: (point: CursorData) => void; - /** - * The cursorLabelComponent prop takes a component instance which will be - * used to render a label for the cursor. The new element created from the passed - * cursorLabelComponent will be supplied with the following props: x, y, - * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. - * @default cursorLabelComponent={<VictoryLabel/>} - */ - cursorLabelComponent?: React.ReactElement<any>; - /** - * The cursorLabelOffset prop determines the pixel offset of the cursor label - * from the cursor point. This prop should be an Object with x and y properties, or a - * number to be used for both dimensions. - * @default "{ x: 5, y: -10 }" - */ - cursorLabelOffset?: number | CursorData; - /** - * Whenever the mouse is not over the chart, the cursor will not be displayed. - * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. - * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. - * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} - */ - defaultCursorValue?: number | CursorData; - /** - * When the disable prop is set to true, VictoryCursorContainer events will not fire. - */ - disable?: boolean; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example onChange={(value, props) => this.setState({cursorValue: value})} - */ + /** + * The cursorLabel prop defines the label that will appear next to the cursor. + * A label will only appear if cursorLabel is set. This prop should be given as a + * function of a point (an Object with x and y properties). + * @example cursorLabel={(point) => point.x} + */ + cursorLabel?: (point: CursorData) => void; + /** + * The cursorLabelComponent prop takes a component instance which will be + * used to render a label for the cursor. The new element created from the passed + * cursorLabelComponent will be supplied with the following props: x, y, + * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. + * @default cursorLabelComponent={<VictoryLabel/>} + */ + cursorLabelComponent?: React.ReactElement<any>; + /** + * The cursorLabelOffset prop determines the pixel offset of the cursor label + * from the cursor point. This prop should be an Object with x and y properties, or a + * number to be used for both dimensions. + * @default "{ x: 5, y: -10 }" + */ + cursorLabelOffset?: number | CursorData; + /** + * Whenever the mouse is not over the chart, the cursor will not be displayed. + * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. + * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. + * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} + */ + defaultCursorValue?: number | CursorData; + /** + * When the disable prop is set to true, VictoryCursorContainer events will not fire. + */ + disable?: boolean; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example onChange={(value, props) => this.setState({cursorValue: value})} + */ onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; - } + } export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} - export interface VictoryBrushContainerProps extends VictoryContainerProps { - /** - * The optional allowDrag prop accepts a boolean that enables dragging behavior - * for the highlighted brush area. Resizing will still be enabled when the allowDrag - * prop is set to false. - * @default true - */ - allowDrag?: boolean; - /** - * The optional allowResize prop accepts a boolean that enables resizing the - * highlighted brush area. Dragging will still be enabled when the allowResize - * prop is set to false, but the dimensions of the brush area will be fixed. - * @default true - */ - allowResize?: boolean; - /** - * The brushComponent prop specifies the component to be rendered for the - * highlighted area. This component will be supplied with the following props: x, y, - * width, height, and style. When this prop is not specified, a <rect/> will be rendered. - * @default brushComponent={<rect/>} - */ - brushComponent?: React.ReactElement<any>; - /** - * When the brushDimension prop is set, brushing will only be specific to the to - * the given dimension (either "x" or "y"), and the entire domain of the other - * dimension will be highlighted. When this prop is not specified, highlighting will - * occur along both dimensions. - * @example brushDimension="x" - */ + export interface VictoryBrushContainerProps extends VictoryContainerProps { + /** + * The optional allowDrag prop accepts a boolean that enables dragging behavior + * for the highlighted brush area. Resizing will still be enabled when the allowDrag + * prop is set to false. + * @default true + */ + allowDrag?: boolean; + /** + * The optional allowResize prop accepts a boolean that enables resizing the + * highlighted brush area. Dragging will still be enabled when the allowResize + * prop is set to false, but the dimensions of the brush area will be fixed. + * @default true + */ + allowResize?: boolean; + /** + * The brushComponent prop specifies the component to be rendered for the + * highlighted area. This component will be supplied with the following props: x, y, + * width, height, and style. When this prop is not specified, a <rect/> will be rendered. + * @default brushComponent={<rect/>} + */ + brushComponent?: React.ReactElement<any>; + /** + * When the brushDimension prop is set, brushing will only be specific to the to + * the given dimension (either "x" or "y"), and the entire domain of the other + * dimension will be highlighted. When this prop is not specified, highlighting will + * occur along both dimensions. + * @example brushDimension="x" + */ brushDimension?: 'x' | 'y'; - /** - * The optional brushDomain prop describes the highlighted state. This prop is an - * object that specifies separate arrays for x and y. Each array is a tuple that - * describes the minimum and maximum values to render. If this prop is not provided - * initially, the chart will render with the entire domain highlighted. When this prop - * changes, the chart will render with a new highlighted domain. - * @example brushDomain={{ x: [50, 100], y: [0, 100] }} - */ - brushDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ + /** + * The optional brushDomain prop describes the highlighted state. This prop is an + * object that specifies separate arrays for x and y. Each array is a tuple that + * describes the minimum and maximum values to render. If this prop is not provided + * initially, the chart will render with the entire domain highlighted. When this prop + * changes, the chart will render with a new highlighted domain. + * @example brushDomain={{ x: [50, 100], y: [0, 100] }} + */ + brushDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * The handleComponent prop specifies the component to be rendered for each - * handle for the highlighted area. This component will be supplied with the following - * props: x, y, width, height, cursor, and style. When this prop is not - * specified, a <rect/> will be rendered. - * @default handleComponent={<rect/>} - */ - handleComponent?: React.ReactElement<any>; - /** - * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. - * - * Handles refer to the region on each highlighted area where the area may be - * expanded. Only handles relevant to the given dimension will be rendered. For - * example, when brushDimension="x" only "left" and "right" handles will be - * rendered. Handles are automatically styled with cursors appropriate to their orientation. - * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" - */ - handleStyle?: React.CSSProperties; - /** - * The optional onBrushDomainChange prop accepts an function to be called on - * each update to the highlighted domain. The function accepts the parameters of - * domain (the updated domain), and props (the props used by VictoryBrushContainer). - * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * The handleComponent prop specifies the component to be rendered for each + * handle for the highlighted area. This component will be supplied with the following + * props: x, y, width, height, cursor, and style. When this prop is not + * specified, a <rect/> will be rendered. + * @default handleComponent={<rect/>} + */ + handleComponent?: React.ReactElement<any>; + /** + * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. + * + * Handles refer to the region on each highlighted area where the area may be + * expanded. Only handles relevant to the given dimension will be rendered. For + * example, when brushDimension="x" only "left" and "right" handles will be + * rendered. Handles are automatically styled with cursors appropriate to their orientation. + * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" + */ + handleStyle?: React.CSSProperties; + /** + * The optional onBrushDomainChange prop accepts an function to be called on + * each update to the highlighted domain. The function accepts the parameters of + * domain (the updated domain), and props (the props used by VictoryBrushContainer). + * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; - } + } export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} - export interface VictoryZoomContainerProps extends VictoryContainerProps { - /** - * The optional allowPan prop accepts a boolean that enables the panning - * functionality. Zooming will still be enabled when the allowPan prop is set to false. - * @default true - */ - allowPan?: boolean; - /** - * The optional allowZoom prop accepts a boolean that enables the zoom - * functionality. Panning will still be enabled when the allowZoom prop is set to false. - * @default true - */ - allowZoom?: boolean; - /** - * VictoryZoomContainer works by clipping data outside of a given domain. - * VictoryZoomContainer uses VictoryClipContainer by default. - * This prop should not be replaced with a custom component, but you may want to set - * props on VictoryClipContainer, such as clipPadding. - * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} - */ - clipContainerComponent?: React.ReactElement<any>; - /** - * When the zoomDimension prop is set, panning and zooming will be restricted to - * the given dimension (either x or y), and the domain of the other dimension will - * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. - * @example zoomDimension="x" - */ + export interface VictoryZoomContainerProps extends VictoryContainerProps { + /** + * The optional allowPan prop accepts a boolean that enables the panning + * functionality. Zooming will still be enabled when the allowPan prop is set to false. + * @default true + */ + allowPan?: boolean; + /** + * The optional allowZoom prop accepts a boolean that enables the zoom + * functionality. Panning will still be enabled when the allowZoom prop is set to false. + * @default true + */ + allowZoom?: boolean; + /** + * VictoryZoomContainer works by clipping data outside of a given domain. + * VictoryZoomContainer uses VictoryClipContainer by default. + * This prop should not be replaced with a custom component, but you may want to set + * props on VictoryClipContainer, such as clipPadding. + * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} + */ + clipContainerComponent?: React.ReactElement<any>; + /** + * When the zoomDimension prop is set, panning and zooming will be restricted to + * the given dimension (either x or y), and the domain of the other dimension will + * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. + * @example zoomDimension="x" + */ zoomDimension?: 'x' | 'y'; - /** - * The zoomDomain prop describes the zoomed state. This prop is an object that - * specifies separate arrays for x and y. Each array is a tuple that describes the - * minimum and maximum values to render. If this prop is not provided initially, the - * chart will render without an initial zoom, displaying the entire dataset. Updates to - * zoomDomain will trigger a re-render of the chart with the new domain. - * @example zoomDomain={{x: [0, 100]}} - */ - zoomDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ + /** + * The zoomDomain prop describes the zoomed state. This prop is an object that + * specifies separate arrays for x and y. Each array is a tuple that describes the + * minimum and maximum values to render. If this prop is not provided initially, the + * chart will render without an initial zoom, displaying the entire dataset. Updates to + * zoomDomain will trigger a re-render of the chart with the new domain. + * @example zoomDomain={{x: [0, 100]}} + */ + zoomDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * When the disable prop is set to true, VictoryZoomContainer events will not fire. - */ - downsample?: number | boolean; - /** - * The minimumZoom prop sets a minimum domain extent for the zoomed chart. - * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom - * in either dimension, the component will stop responding to events that would normally trigger zooming in. - * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum - * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object - * with numeric values for x and y. - * @example minimumZoom={{x: 1, y: 0.01}} - */ - minimumZoom?: CursorData; - /** - * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. - * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). - * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * When the disable prop is set to true, VictoryZoomContainer events will not fire. + */ + downsample?: number | boolean; + /** + * The minimumZoom prop sets a minimum domain extent for the zoomed chart. + * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom + * in either dimension, the component will stop responding to events that would normally trigger zooming in. + * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum + * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object + * with numeric values for x and y. + * @example minimumZoom={{x: 1, y: 0.01}} + */ + minimumZoom?: CursorData; + /** + * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. + * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). + * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; - } + } export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} - // Note: Many SVG attributes are missed in CSSProperties interface - export interface VictoryThemeDefinition { - area?: VictoryStyleInterface; - axis?: { - axis: React.CSSProperties; - axisLabel: React.CSSProperties; - grid: React.CSSProperties; - ticks: React.CSSProperties; - tickLabels: React.CSSProperties; - }; - bar?: VictoryStyleInterface; - candlestick?: VictoryStyleInterface & { - props: { - width: number; - height: number; - candleColors: { - positive: string; - negative: string; + // Note: Many SVG attributes are missed in CSSProperties interface + export interface VictoryThemeDefinition { + area?: VictoryStyleInterface; + axis?: { + axis: React.CSSProperties; + axisLabel: React.CSSProperties; + grid: React.CSSProperties; + ticks: React.CSSProperties; + tickLabels: React.CSSProperties; }; - }; - }; - line?: VictoryStyleInterface; - pie?: { - props: { - width: number; - height: number; - colorScale: string[]; - }; - style: VictoryStyleInterface; - }; - scatter?: VictoryStyleInterface; - props?: { - width: number; - height: number; - colorScale: string[]; - }; - } + bar?: VictoryStyleInterface; + candlestick?: VictoryStyleInterface & { + props: { + width: number; + height: number; + candleColors: { + positive: string; + negative: string; + }; + }; + }; + line?: VictoryStyleInterface; + pie?: { + props: { + width: number; + height: number; + colorScale: string[]; + }; + style: VictoryStyleInterface; + }; + scatter?: VictoryStyleInterface; + props?: { + width: number; + height: number; + colorScale: string[]; + }; + } - interface VictoryThemeInterface { - /** - * Default theme - */ - grayscale: VictoryThemeDefinition; - material: VictoryThemeDefinition; - } + interface VictoryThemeInterface { + /** + * Default theme + */ + grayscale: VictoryThemeDefinition; + material: VictoryThemeDefinition; + } - /** - * Available themes - */ - export const VictoryTheme: VictoryThemeInterface; + /** + * Available themes + */ + export const VictoryTheme: VictoryThemeInterface; - type OrientationTypes = "top" | "bottom" | "left" | "right"; + type OrientationTypes = "top" | "bottom" | "left" | "right"; - export interface VictoryTooltipProps { - /** - * The active prop specifies whether the tooltip component should be displayed. - */ - active?: boolean; - /** - * When true, tooltip events will set the active prop on both data and label elements. - * @default false - */ - activateData?: boolean; - /** - * The angle prop specifies the angle to rotate the tooltip around its origin point. - */ - angle?: string | number; - /** - * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. - */ - cornerRadius?: NumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. - */ - datum?: {}; - /** - * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. - */ - data?: any[]; - /** - * The dx prop defines a horizontal shift from the x coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the y coordinate. - */ - dy?: StringOrNumberOrCallback; - /** - * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. - * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. - * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} - */ - events?: {}; - /** - * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. - */ - flyoutStyle?: React.CSSProperties; - /** - * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. - * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, - * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If flyoutComponent is omitted, a default Flyout component will be created with props described above. - * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} - * @default <Flyout/> - */ - flyoutComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. - * @default groupComponent={<g/>} - */ - groupComponent?: React.ReactElement<any>; - /** - * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - height?: NumberOrCallback; - /** - * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. - * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. - * negative values result in a left orientation and positive values will result in a right orientation by default. - */ - horizontal?: boolean; - /** - * The index prop represents the index of the datum in the data array. - */ - index?: number | string; - /** - * The labelComponent prop takes a component instance which will be used to render each tooltip label. - * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. - * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. - * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. - * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. - */ - orientation?: OrientationTypes; - /** - * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerLength?: NumberOrCallback; - /** - * The pointerWidth prop determines the width of the base of the triangular pointer extending from - * the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerWidth?: NumberOrCallback; - /** - * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element - * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. - * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. - */ - text?: StringOrNumberOrCallback | string[] | number[]; - /** - * VictoryAxis uses the standard theme prop. Read about it here - * @default VictoryTheme.grayscale - */ - theme?: VictoryThemeDefinition; - /** - * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - width?: NumberOrCallback; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - } + export interface VictoryTooltipProps { + /** + * The active prop specifies whether the tooltip component should be displayed. + */ + active?: boolean; + /** + * When true, tooltip events will set the active prop on both data and label elements. + * @default false + */ + activateData?: boolean; + /** + * The angle prop specifies the angle to rotate the tooltip around its origin point. + */ + angle?: string | number; + /** + * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. + */ + cornerRadius?: NumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. + */ + datum?: {}; + /** + * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. + */ + data?: any[]; + /** + * The dx prop defines a horizontal shift from the x coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the y coordinate. + */ + dy?: StringOrNumberOrCallback; + /** + * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. + * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. + * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} + */ + events?: {}; + /** + * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. + */ + flyoutStyle?: VictoryStyleObject; + /** + * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. + * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, + * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If flyoutComponent is omitted, a default Flyout component will be created with props described above. + * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} + * @default <Flyout/> + */ + flyoutComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. + * @default groupComponent={<g/>} + */ + groupComponent?: React.ReactElement<any>; + /** + * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + height?: NumberOrCallback; + /** + * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. + * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. + * negative values result in a left orientation and positive values will result in a right orientation by default. + */ + horizontal?: boolean; + /** + * The index prop represents the index of the datum in the data array. + */ + index?: number | string; + /** + * The labelComponent prop takes a component instance which will be used to render each tooltip label. + * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. + * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. + * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. + * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. + */ + orientation?: OrientationTypes; + /** + * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerLength?: NumberOrCallback; + /** + * The pointerWidth prop determines the width of the base of the triangular pointer extending from + * the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerWidth?: NumberOrCallback; + /** + * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element + * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. + * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. + */ + text?: StringOrNumberOrCallback | string[] | number[]; + /** + * VictoryAxis uses the standard theme prop. Read about it here + * @default VictoryTheme.grayscale + */ + theme?: VictoryThemeDefinition; + /** + * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + width?: NumberOrCallback; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + } - /** - * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label - * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. - * VictoryTooltip renders text as well as a configurable Flyout container. - */ - export class VictoryTooltip extends React.Component< - VictoryTooltipProps, - any + /** + * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label + * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. + * VictoryTooltip renders text as well as a configurable Flyout container. + */ + export class VictoryTooltip extends React.Component< + VictoryTooltipProps, + any > {} - /** - * Animate object used in components - */ - export interface AnimatePropTypeInterface { /** - * Animation duration + * Animate object used in components */ - duration: number; - /** - * Animation end callback - */ - onEnd?: () => void; - /** - * Animation exit transition configuration - */ - onExit?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - }; - /** - * Animation enter transition configuration - */ - onEnter?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * Animation load transition configuration - */ - onLoad?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - } + export interface AnimatePropTypeInterface { + /** + * Animation duration + */ + duration: number; + /** + * Animation end callback + */ + onEnd?: () => void; + /** + * Animation exit transition configuration + */ + onExit?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + }; + /** + * Animation enter transition configuration + */ + onEnter?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * Animation load transition configuration + */ + onLoad?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + } - /** - * Return value for eventHandlers values - */ - interface EventCallbackInterface<TTarget, TEventKey> { /** - * Use only in: - * - VictoryChart - * - VictoryStack + * Return value for eventHandlers values */ - childName?: string; - target?: TTarget; - eventKey?: TEventKey; - /** - * Will be called with the calculated props for the individual selected element and result will override - * props of selected element via object assignment - * @param props - */ - mutation: (props: any) => any; - } + interface EventCallbackInterface<TTarget, TEventKey> { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + target?: TTarget; + eventKey?: TEventKey; + /** + * Will be called with the calculated props for the individual selected element and result will override + * props of selected element via object assignment + * @param props + */ + mutation: (props: any) => any; + } - export interface EventPropTypeInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - /** - * Targets may be any valid style namespace for a given component - */ - target: TTarget; + export interface EventPropTypeInterface<TTarget, TEventKey> { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + /** + * Targets may be any valid style namespace for a given component + */ + target: TTarget; - eventKey?: TEventKey; - /** - * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks - */ - eventHandlers: { + eventKey?: TEventKey; + /** + * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks + */ + eventHandlers: { [key: string]: { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] - } - }; - } + } + }; + } - /** - * Data domain type - */ - type DomainTuple = [number, number] | [Date, Date]; + /** + * Data domain type + */ + type DomainTuple = [number, number] | [Date, Date]; type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; - /** - * Domain padding - */ + /** + * Domain padding + */ type DomainPaddingPropType = number | { x?: number | [ number, number]; y?: number | [ number, number]; - }; + }; - /** - * D3 scale function shape. Don't want to introduce typing dependency to d3 - */ - interface D3Scale { - domain: () => any; - range: () => any; - copy: () => any; - } + /** + * D3 scale function shape. Don't want to introduce typing dependency to d3 + */ + interface D3Scale { + domain: () => any; + range: () => any; + copy: () => any; + } - /** - * Acceptable scale types - */ - type ScalePropType = "linear" | "time" | "log" | "sqrt"; + /** + * Acceptable scale types + */ + type ScalePropType = "linear" | "time" | "log" | "sqrt"; - /** - * Category prop type - */ + /** + * Category prop type + */ type CategoryPropType = string[] | { x: string[] y: string[] - }; + }; - /** - * Data getter property type - */ + /** + * Data getter property type + */ type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | @@ -829,606 +830,606 @@ declare module "victory" { type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; - /** - * Common properties - */ - interface VictoryCommonProps { /** - * The animate prop specifies props for VictoryAnimation to use. - * The animate prop should also be used to specify enter and exit - * transition configurations with the `onExit` and `onEnter` namespaces respectively. - * @example - * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} - */ - animate?: AnimatePropTypeInterface; - /** - * The name prop is used to reference a component instance when defining shared events. - */ - name?: string; - /** - * The height props specifies the height the svg viewBox of the chart container. - * This value should be given as a number of pixels - */ - height?: number; - /** - * The padding props specifies the amount of padding in number of pixels between - * the edge of the chart and any rendered child components. This prop can be given - * as a number or as an object with padding specified for top, bottom, left - * and right. - * @default 50 + * Common properties */ + interface VictoryCommonProps { + /** + * The animate prop specifies props for VictoryAnimation to use. + * The animate prop should also be used to specify enter and exit + * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * @example + * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + */ + animate?: AnimatePropTypeInterface; + /** + * The name prop is used to reference a component instance when defining shared events. + */ + name?: string; + /** + * The height props specifies the height the svg viewBox of the chart container. + * This value should be given as a number of pixels + */ + height?: number; + /** + * The padding props specifies the amount of padding in number of pixels between + * the edge of the chart and any rendered child components. This prop can be given + * as a number or as an object with padding specified for top, bottom, left + * and right. + * @default 50 + */ padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The scale prop determines which scales your chart should use. This prop can be - * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), - * as a d3 scale function, or as an object with scales specified for x and y - * @example d3Scale.time(), {x: "linear", y: "log"} - * @default "linear" - */ + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The scale prop determines which scales your chart should use. This prop can be + * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), + * as a d3 scale function, or as an object with scales specified for x and y + * @example d3Scale.time(), {x: "linear", y: "log"} + * @default "linear" + */ scale?: ScalePropType | D3Scale | { - x?: ScalePropType | D3Scale; - y?: ScalePropType | D3Scale; - }; - /** - * The standalone prop determines whether the component will render a standalone svg - * or a <g> tag that will be included in an external svg. Set standalone to false to - * compose VictoryAxis with other components within an enclosing <svg> tag. - * @default true - */ - standalone?: boolean; - /** - * The width props specifies the width of the svg viewBox of the chart container - * This value should be given as a number of pixels - */ - width?: number; - /** - * The containerComponent prop takes an entire component which will be used to - * create a container element for standalone charts. - * The new element created from the passed containerComponent wil be provided with - * these props from VictoryArea: height, width, children - * (the chart itself) and style. Props that are not provided by the - * child chart component include title and desc, both of which - * are intended to add accessibility to Victory components. The more descriptive these props - * are, the more accessible your data will be for people using screen readers. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use the default VictoryContainer component. - * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * The theme prop takes a style object with nested data, labels, and parent objects. - * You can create this object yourself, or you can use a theme provided by Victory. - * When using VictoryArea as a solo component, implement the theme directly on - * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or - * VictoryGroup, please call the theme on the outermost wrapper component instead. - * @example theme={VictoryTheme.material} - * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js - */ - theme?: VictoryThemeDefinition; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; - } + x?: ScalePropType | D3Scale; + y?: ScalePropType | D3Scale; + }; + /** + * The standalone prop determines whether the component will render a standalone svg + * or a <g> tag that will be included in an external svg. Set standalone to false to + * compose VictoryAxis with other components within an enclosing <svg> tag. + * @default true + */ + standalone?: boolean; + /** + * The width props specifies the width of the svg viewBox of the chart container + * This value should be given as a number of pixels + */ + width?: number; + /** + * The containerComponent prop takes an entire component which will be used to + * create a container element for standalone charts. + * The new element created from the passed containerComponent wil be provided with + * these props from VictoryArea: height, width, children + * (the chart itself) and style. Props that are not provided by the + * child chart component include title and desc, both of which + * are intended to add accessibility to Victory components. The more descriptive these props + * are, the more accessible your data will be for people using screen readers. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use the default VictoryContainer component. + * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * The theme prop takes a style object with nested data, labels, and parent objects. + * You can create this object yourself, or you can use a theme provided by Victory. + * When using VictoryArea as a solo component, implement the theme directly on + * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or + * VictoryGroup, please call the theme on the outermost wrapper component instead. + * @example theme={VictoryTheme.material} + * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js + */ + theme?: VictoryThemeDefinition; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; + } - /** - * Common properties for all data components - */ - interface VictoryDatableProps { /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these arrays of values specified for x and y. If this prop is not set, - * categorical data will be plotted in the order it was given in the data array - * @example ["dogs", "cats", "mice"] + * Common properties for all data components */ - categories?: CategoryPropType; - /** - * The data prop specifies the data to be plotted. Data should be in the form of an array - * of data points, or an array of arrays of data points for multiple datasets. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire component which will be used to create an area. - * The new element created from the passed dataComponent will be provided with the - * following properties calculated by VictoryArea: a scale, style, events, interpolation, - * and an array of modified data objects (including x, y, and calculated y0 and y1). - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use its default Area component. - * @default <Area/> - */ - dataComponent?: React.ReactElement<any>; - /** - * The domain prop describes the range of values your chart will cover. This prop can be - * given as a array of the minimum and maximum expected values for your bar chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - * @default "x" - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - * @default "y" - */ - y?: DataGetterPropType; - } + interface VictoryDatableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these arrays of values specified for x and y. If this prop is not set, + * categorical data will be plotted in the order it was given in the data array + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The data prop specifies the data to be plotted. Data should be in the form of an array + * of data points, or an array of arrays of data points for multiple datasets. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire component which will be used to create an area. + * The new element created from the passed dataComponent will be provided with the + * following properties calculated by VictoryArea: a scale, style, events, interpolation, + * and an array of modified data objects (including x, y, and calculated y0 and y1). + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use its default Area component. + * @default <Area/> + */ + dataComponent?: React.ReactElement<any>; + /** + * The domain prop describes the range of values your chart will cover. This prop can be + * given as a array of the minimum and maximum expected values for your bar chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + * @default "x" + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + * @default "y" + */ + y?: DataGetterPropType; + } - // Common labable interface - interface VictoryLabableProps { - /** - * The labelComponent prop takes in an entire label component which will be used - * to create a label for the area. The new element created from the passed labelComponent - * will be supplied with the following properties: x, y, index, data, verticalAnchor, - * textAnchor, angle, style, text, and events. any of these props may be overridden - * by passing in props to the supplied component, or modified or ignored within - * the custom component itself. If labelComponent is omitted, a new VictoryLabel - * will be created with props described above. This labelComponent prop should be used to - * provide a series label for VictoryArea. If individual labels are required for each - * data point, they should be created by composing VictoryArea with VictoryScatter - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - } + // Common labable interface + interface VictoryLabableProps { + /** + * The labelComponent prop takes in an entire label component which will be used + * to create a label for the area. The new element created from the passed labelComponent + * will be supplied with the following properties: x, y, index, data, verticalAnchor, + * textAnchor, angle, style, text, and events. any of these props may be overridden + * by passing in props to the supplied component, or modified or ignored within + * the custom component itself. If labelComponent is omitted, a new VictoryLabel + * will be created with props described above. This labelComponent prop should be used to + * provide a series label for VictoryArea. If individual labels are required for each + * data point, they should be created by composing VictoryArea with VictoryScatter + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + } - interface VictoryMultiLabeableProps extends VictoryLabableProps { - /** - * The labels prop defines labels that will appear above each bar in your chart. - * This prop should be given as an array of values or as a function of data. - * If given as an array, the number of elements in the array should be equal to - * the length of the data array. Labels may also be added directly to the data object - * like data={[{x: 1, y: 1, label: "first"}]}. - * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title - */ - labels?: string[] | { (data: any): string }; - } + interface VictoryMultiLabeableProps extends VictoryLabableProps { + /** + * The labels prop defines labels that will appear above each bar in your chart. + * This prop should be given as an array of values or as a function of data. + * If given as an array, the number of elements in the array should be equal to + * the length of the data array. Labels may also be added directly to the data object + * like data={[{x: 1, y: 1, label: "first"}]}. + * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title + */ + labels?: string[] | { (data: any): string }; + } - interface VictorySingleLabableProps extends VictoryLabableProps { - /** - * The label prop defines the label that will appear at the edge of the area. - * This prop should be given a string or as a function of data. If individual - * labels are required for each data point, they should be created by composing - * VictoryArea with VictoryScatter - * @example: "Series 1", (data) => `${data.length} points` - */ - label?: string | { (data: any): string }; - } + interface VictorySingleLabableProps extends VictoryLabableProps { + /** + * The label prop defines the label that will appear at the edge of the area. + * This prop should be given a string or as a function of data. If individual + * labels are required for each data point, they should be created by composing + * VictoryArea with VictoryScatter + * @example: "Series 1", (data) => `${data.length} points` + */ + label?: string | { (data: any): string }; + } - export interface VictoryAreaProps - extends VictoryCommonProps, - VictoryDatableProps, - VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. - * Since VictoryArea only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. an area), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; - /** - * The interpolation prop determines how data points should be connected when plotting a line - * @default "linear" - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - * @default 50 - */ - samples?: number; - /** - * The style prop specifies styles for your VictoryArea. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - } + export interface VictoryAreaProps + extends VictoryCommonProps, + VictoryDatableProps, + VictorySingleLabableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. + * Since VictoryArea only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. an area), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; + /** + * The interpolation prop determines how data points should be connected when plotting a line + * @default "linear" + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + * @default 50 + */ + samples?: number; + /** + * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } - /** - * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. - * Add VictoryArea as a child of VictoryChart for a complete chart. - */ - export class VictoryArea extends React.Component<VictoryAreaProps, any> {} + /** + * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. + * Add VictoryArea as a child of VictoryChart for a complete chart. + */ + export class VictoryArea extends React.Component<VictoryAreaProps, any> {} - export interface VictoryAxisProps extends VictoryCommonProps { - /** - * The axisComponent prop takes in an entire component which will be used - * to create the axis line. The new element created from the passed axisComponent - * will be supplied with the following properties: x1, y1, x2, y2, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If an axisComponent - * is not supplied, VictoryAxis will render its default AxisLine component. - * @default <AxisLine/> - */ - axisComponent?: React.ReactElement<any>; - /** - * The axisLabelComponent prop takes in an entire component which will be used - * to create the axis label. The new element created from the passed axisLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, transform, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an axisLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - axisLabelComponent?: React.ReactElement<any>; - /** - * This prop specifies whether a given axis is intended to cross another axis. - */ - crossAxis?: boolean; - /** - * The dependentAxis prop specifies whether the axis corresponds to the - * dependent variable (usually y). This prop is useful when composing axis - * with other components to form a chart. - */ - dependentAxis?: boolean; - /** - * The domain prop describes the range of values your axis will include. This prop should be - * given as a array of the minimum and maximum expected values for your axis. - * If this value is not given it will be calculated based on the scale or tickValues. - * @examples [-1, 1] - */ - domain?: DomainPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are - * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a - * single element by index rather than an entire set. The eventHandlers object - * should be given as an object whose keys are standard event names (i.e. onClick) - * and whose values are event callbacks. The return value of an event handler - * be used to modify other elemnts. The return value should be given as an object or - * an array of objects with optional target and eventKey keys, and a mutation - * key whose value is a function. The target and eventKey keys will default to those - * corresponding to the element the event handler was attached to. The mutation - * function will be called with the calculated props for the individual selected - * element (i.e. a single tick), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "grid", - * eventKey: 2, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "tickLabels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + export interface VictoryAxisProps extends VictoryCommonProps { + /** + * The axisComponent prop takes in an entire component which will be used + * to create the axis line. The new element created from the passed axisComponent + * will be supplied with the following properties: x1, y1, x2, y2, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If an axisComponent + * is not supplied, VictoryAxis will render its default AxisLine component. + * @default <AxisLine/> + */ + axisComponent?: React.ReactElement<any>; + /** + * The axisLabelComponent prop takes in an entire component which will be used + * to create the axis label. The new element created from the passed axisLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, transform, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an axisLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + axisLabelComponent?: React.ReactElement<any>; + /** + * This prop specifies whether a given axis is intended to cross another axis. + */ + crossAxis?: boolean; + /** + * The dependentAxis prop specifies whether the axis corresponds to the + * dependent variable (usually y). This prop is useful when composing axis + * with other components to form a chart. + */ + dependentAxis?: boolean; + /** + * The domain prop describes the range of values your axis will include. This prop should be + * given as a array of the minimum and maximum expected values for your axis. + * If this value is not given it will be calculated based on the scale or tickValues. + * @examples [-1, 1] + */ + domain?: DomainPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are + * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a + * single element by index rather than an entire set. The eventHandlers object + * should be given as an object whose keys are standard event names (i.e. onClick) + * and whose values are event callbacks. The return value of an event handler + * be used to modify other elemnts. The return value should be given as an object or + * an array of objects with optional target and eventKey keys, and a mutation + * key whose value is a function. The target and eventKey keys will default to those + * corresponding to the element the event handler was attached to. The mutation + * function will be called with the calculated props for the individual selected + * element (i.e. a single tick), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "grid", + * eventKey: 2, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "tickLabels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; - /** - * When true, this prop reduces the number of tick labels to fit the length of the axis. - * Labels are removed at approximately even intervals from the original array of labels. - * This feature only works well for labels that are approximately evenly spaced. - * @default false - */ - fixLabelOverlap?: boolean; - /** - * The gridComponent prop takes in an entire component which will be used - * to create grid lines. The new element created from the passed gridComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a gridComponent - * is not supplied, VictoryAxis will render its default GridLine component. - * @default <GridLine/> - */ - gridComponent?: React.ReactElement<any>; - /** - * If true, this value will flip the domain of a given axis. - */ - invertAxis?: boolean; - /** - * The label prop defines the label that will appear along the axis. This - * prop should be given as a value or an entire, HTML-complete label - * component. If a label component is given, it will be cloned. The new - * element's properties x, y, textAnchor, verticalAnchor, and transform - * will have defaults provided by the axis; styles filled out with - * defaults provided by the axis, and overrides from the label component. - * If a value is given, a new VictoryLabel will be created with props and - * styles from the axis. - */ - label?: any; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the x-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetX?: number; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the y-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetY?: number; - /** - * The orientation prop specifies the position and orientation of your axis. - */ - orientation?: "top" | "bottom" | "left" | "right"; - /** - * The style prop defines the style of the component. The style prop should be given as an object - * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg - * styles are supported, but width, height, and padding should be specified via props as they - * determine relative layout for components in VictoryChart. Functional styles may be defined for - * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. - * - * note: When a component is rendered as a child of another Victory component, or within a custom - * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. - * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. - * - * note: custom angle and verticalAnchor properties may be included in labels styles. - */ - style?: { - parent?: React.CSSProperties; - axis?: React.CSSProperties; - axisLabel?: React.CSSProperties; - grid?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - ticks?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - tickLabels?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - }; - /** - * The tickComponent prop takes in an entire component which will be used - * to create tick lines. The new element created from the passed tickComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a tickComponent - * is not supplied, VictoryAxis will render its default Tick component. - * @default <Tick/> - */ - tickComponent?: React.ReactElement<any>; - /** - * The tickCount prop specifies approximately how many ticks should be drawn on the axis if - * tickValues are not explicitly provided. This value is calculated by d3 scale and - * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. - * If you need an exact number of ticks, please specify them via the tickValues prop. - * This prop must have a value greater than zero. - * @default 5 - */ - tickCount?: number; - /** - * The tickLabelComponent prop takes in an entire component which will be used - * to create the tick labels. The new element created from the passed tickLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, tick, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an tickLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - tickLabelComponent?: React.ReactElement<any>; - /** - * The tickFormat prop specifies how tick values should be expressed visually. - * tickFormat can be given as a function to be applied to every tickValue, or as - * an array of display values for each tickValue. - * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] - */ + /** + * When true, this prop reduces the number of tick labels to fit the length of the axis. + * Labels are removed at approximately even intervals from the original array of labels. + * This feature only works well for labels that are approximately evenly spaced. + * @default false + */ + fixLabelOverlap?: boolean; + /** + * The gridComponent prop takes in an entire component which will be used + * to create grid lines. The new element created from the passed gridComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a gridComponent + * is not supplied, VictoryAxis will render its default GridLine component. + * @default <GridLine/> + */ + gridComponent?: React.ReactElement<any>; + /** + * If true, this value will flip the domain of a given axis. + */ + invertAxis?: boolean; + /** + * The label prop defines the label that will appear along the axis. This + * prop should be given as a value or an entire, HTML-complete label + * component. If a label component is given, it will be cloned. The new + * element's properties x, y, textAnchor, verticalAnchor, and transform + * will have defaults provided by the axis; styles filled out with + * defaults provided by the axis, and overrides from the label component. + * If a value is given, a new VictoryLabel will be created with props and + * styles from the axis. + */ + label?: any; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the x-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetX?: number; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the y-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetY?: number; + /** + * The orientation prop specifies the position and orientation of your axis. + */ + orientation?: "top" | "bottom" | "left" | "right"; + /** + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. + */ + style?: { + parent?: React.CSSProperties; + axis?: React.CSSProperties; + axisLabel?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + }; + /** + * The tickComponent prop takes in an entire component which will be used + * to create tick lines. The new element created from the passed tickComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a tickComponent + * is not supplied, VictoryAxis will render its default Tick component. + * @default <Tick/> + */ + tickComponent?: React.ReactElement<any>; + /** + * The tickCount prop specifies approximately how many ticks should be drawn on the axis if + * tickValues are not explicitly provided. This value is calculated by d3 scale and + * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. + * If you need an exact number of ticks, please specify them via the tickValues prop. + * This prop must have a value greater than zero. + * @default 5 + */ + tickCount?: number; + /** + * The tickLabelComponent prop takes in an entire component which will be used + * to create the tick labels. The new element created from the passed tickLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, tick, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an tickLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + tickLabelComponent?: React.ReactElement<any>; + /** + * The tickFormat prop specifies how tick values should be expressed visually. + * tickFormat can be given as a function to be applied to every tickValue, or as + * an array of display values for each tickValue. + * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] + */ tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; - /** - * The tickValues prop explicitly specifies which tick values to draw on the axis. - * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] - */ - tickValues?: any[]; - } + /** + * The tickValues prop explicitly specifies which tick values to draw on the axis. + * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] + */ + tickValues?: any[]; + } - /** - * VictoryAxis draws an SVG chart axis with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} + /** + * VictoryAxis draws an SVG chart axis with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. + */ + export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The alignment prop specifies how bars should be aligned relative to their data points. - * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, - * bars will have “middle” alignment relative to their data points. - */ - alignment?: "start" | "middle" | "end"; - /** - * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. - * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will - * be used to calculate a default width for each bar given the total number of bars in the data series - * and the overall width of the chart. - */ - barRatio?: number; - /** - * The barWidth prop is used to specify the width of each bar. This prop may be given as - * a number of pixels or as a function that returns a number. When this prop is given as - * a function, it will be evaluated with the arguments datum, and active. When this value - * is not given, a default value will be calculated based on the overall dimensions of - * the chart, and the number of bars. - */ - barWidth?: NumberOrCallback; - /** - * The cornerRadius prop specifies a radius to apply to each bar. - * If this prop is given as a single number, the radius will only be applied to the top of each bar. - * When this prop is given as a function, it will be evaluated with the arguments datum, and active. - */ + /** + * The alignment prop specifies how bars should be aligned relative to their data points. + * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, + * bars will have “middle” alignment relative to their data points. + */ + alignment?: "start" | "middle" | "end"; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; + /** + * The cornerRadius prop specifies a radius to apply to each bar. + * If this prop is given as a single number, the radius will only be applied to the top of each bar. + * When this prop is given as a function, it will be evaluated with the arguments datum, and active. + */ cornerRadius?: NumberOrCallback - | { + | { top?: number | (NumberOrCallback), topLeft?: number | (NumberOrCallback), topRight?: number | (NumberOrCallback), bottom?: number | (NumberOrCallback), bottomLeft?: number | (NumberOrCallback), bottomRight?: number | (NumberOrCallback) - }; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. - * The eventKey may optionally be used to select a single element by index rather than an entire - * set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + }; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. + * The eventKey may optionally be used to select a single element by index rather than an entire + * set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your VictoryBar. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - } + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your VictoryBar. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } - /** - * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes - * Check out VictoryChart for complete bar charts and more. - */ - export class VictoryBar extends React.Component<VictoryBarProps, any> {} + /** + * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes + * Check out VictoryChart for complete bar charts and more. + */ + export class VictoryBar extends React.Component<VictoryBarProps, any> {} export interface VictoryBoxPlotStyleInterface extends VictoryStyleInterface { - max?: React.CSSProperties; - maxLabels?: React.CSSProperties; - min?: React.CSSProperties; - minLabels?: React.CSSProperties; - median?: React.CSSProperties; - medianLabels?: React.CSSProperties; - q1?: React.CSSProperties; - q1Labels?: React.CSSProperties; - q3?: React.CSSProperties; - q3Labels?: React.CSSProperties; + max?: VictoryStyleObject; + maxLabels?: VictoryStyleObject; + min?: VictoryStyleObject; + minLabels?: VictoryStyleObject; + median?: VictoryStyleObject; + medianLabels?: VictoryStyleObject; + q1?: VictoryStyleObject; + q1Labels?: VictoryStyleObject; + q3?: VictoryStyleObject; + q3Labels?: VictoryStyleObject; } export interface VictoryBoxPlotProps @@ -1655,179 +1656,179 @@ declare module "victory" { export class VictoryChart extends React.Component<VictoryChartProps, any> {} export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or categorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryGroup, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or categorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryGroup, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The offset prop determines the number of pixels each element in a group should - * be offset from its original position of the on the independent axis. In the - * case of groups of bars, this number should be equal to the width of the bar - * plus the desired spacing between bars. - */ - offset?: number; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The offset prop determines the number of pixels each element in a group should + * be offset from its original position of the on the independent axis. In the + * case of groups of bars, this number should be equal to the width of the bar + * plus the desired spacing between bars. + */ + offset?: number; + /** + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children + */ + style?: VictoryStyleInterface; } export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. - * Since VictoryLine only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a line), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. + * Since VictoryLine only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a line), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * The interpolation prop determines how data points should be connected - * when plotting a line - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The labels prop defines the labels that will appear above each point. - * This prop should be given as an array or as a function of data. - */ + /** + * The interpolation prop determines how data points should be connected + * when plotting a line + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The labels prop defines the labels that will appear above each point. + * This prop should be given as an array or as a function of data. + */ labels?: string[]|number[]|Function; - /** - * Use the sortKey prop to indicate how data should be sorted. This prop - * is given directly to the lodash sortBy function to be executed on the - * final dataset. - */ + /** + * Use the sortKey prop to indicate how data should be sorted. This prop + * is given directly to the lodash sortBy function to be executed on the + * final dataset. + */ sortKey?: string|string[]|Function; - /** - * The style prop specifies styles for your VictoryLine. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. in addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; + /** + * The style prop specifies styles for your VictoryLine. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. in addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; } /** @@ -1837,152 +1838,152 @@ declare module "victory" { export class VictoryLine extends React.Component<VictoryLineProps, any> {} export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The colorScale prop defines a color scale to be applied to each data - * symbol in VictoryLegend. This prop should be given as an array of CSS - * colors, or as a string corresponding to one of the built in color - * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", - * "green", "blue". VictoryLegend will assign a color to each symbol by - * index, unless they are explicitly specified in the data object. - * Colors will repeat when there are more symbols than colors in the - * provided colorScale. - */ - colorScale?: ColorScalePropType; - /** - * The style prop defines the style of the VictoryLegend component. - * The style prop should be given as an object with styles defined for data, labels and - * parent. Any valid svg styles are supported, but width, height, and - * padding should be specified via props as they determine relative - * layout for components in VictoryLegend. - */ - style?: VictoryStyleInterface; - /** - * The containerComponent prop takes a component instance which will be - * used to create a container element for standalone legends. The new - * element created from the passed containerComponent will be provided - * with the following props: height, width, children (the legend itself) - * and style. If a containerComponent is not provided, the default - * VictoryContainer component will be used. VictoryContainer supports - * title and desc props, which are intended to add accessibility to - * Victory components. The more descriptive these props are, the more - * accessible your data will be for people using screen readers. These - * props may be set by passing them directly to the supplied component. - * By default, VictoryContainer renders a responsive svg using the - * viewBox attribute. To render a static container, set - * responsive={false} directly on the instance of VictoryContainer - * supplied via the containerComponent prop. VictoryContainer also - * renders a Portal element that may be used in conjunction with - * VictoryPortal to force components to render above other children. - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * Specify data via the data prop. VictoryLegend expects data as an - * array of objects with name (required), symbol, and labels properties. - * The data prop must be given as an array. - */ - data?: Array<{ - name?: string; - symbol?: { - fill?: string; - type?: string; - }; - }>; - /** - * The itemsPerRow prop determines how many items to render in each row - * of a horizontal legend, or in each column of a vertical legend. This - * prop should be given as an integer. When this prop is not given, - * legend items will be rendered in a single row or column. - */ - itemsPerRow?: number; - /** - * The dataComponent prop takes a component instance which will be - * responsible for rendering a data element used to associate a symbol - * or color with each data series. The new element created from the - * passed dataComponent will be provided with the following properties - * calculated by VictoryLegend: x, y, size, style, and symbol. Any of - * these props may be overridden by passing in props to the supplied - * component, or modified or ignored within the custom component itself. - * If a dataComponent is not provided, VictoryLegend will use its - * default Point component. - */ - dataComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; - /** - * The gutter prop defines the number of pixels between legend rows or - * columns, depending on orientation. When orientation is horizontal, - * gutters are between columns. When orientation is vertical, gutters - * are the space between rows. - */ - gutter?: number; - /** - * The labelComponent prop takes a component instance which will be used - * to render each legend label. The new element created from the passed - * labelComponent will be supplied with the following properties: x, y, - * style, and text. Any of these props may be overridden by passing in - * props to the supplied component, or modified or ignored within the - * custom component itself. If labelComponent is omitted, a new - * VictoryLabel will be created with the props described above. - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop takes a string that defines whether legend data - * are displayed in a row or column. When orientation is "horizontal", - * legend items will be displayed in a single row. When orientation is - * "vertical", legend items will be displayed in a single column. Line - * and text-wrapping is not currently supported, so "vertical" - * orientation is both the default setting and recommended for - * displaying many series of data. - * @default 'vertical' - */ + /** + * The colorScale prop defines a color scale to be applied to each data + * symbol in VictoryLegend. This prop should be given as an array of CSS + * colors, or as a string corresponding to one of the built in color + * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", + * "green", "blue". VictoryLegend will assign a color to each symbol by + * index, unless they are explicitly specified in the data object. + * Colors will repeat when there are more symbols than colors in the + * provided colorScale. + */ + colorScale?: ColorScalePropType; + /** + * The style prop defines the style of the VictoryLegend component. + * The style prop should be given as an object with styles defined for data, labels and + * parent. Any valid svg styles are supported, but width, height, and + * padding should be specified via props as they determine relative + * layout for components in VictoryLegend. + */ + style?: VictoryStyleInterface; + /** + * The containerComponent prop takes a component instance which will be + * used to create a container element for standalone legends. The new + * element created from the passed containerComponent will be provided + * with the following props: height, width, children (the legend itself) + * and style. If a containerComponent is not provided, the default + * VictoryContainer component will be used. VictoryContainer supports + * title and desc props, which are intended to add accessibility to + * Victory components. The more descriptive these props are, the more + * accessible your data will be for people using screen readers. These + * props may be set by passing them directly to the supplied component. + * By default, VictoryContainer renders a responsive svg using the + * viewBox attribute. To render a static container, set + * responsive={false} directly on the instance of VictoryContainer + * supplied via the containerComponent prop. VictoryContainer also + * renders a Portal element that may be used in conjunction with + * VictoryPortal to force components to render above other children. + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * Specify data via the data prop. VictoryLegend expects data as an + * array of objects with name (required), symbol, and labels properties. + * The data prop must be given as an array. + */ + data?: Array<{ + name?: string; + symbol?: { + fill?: string; + type?: string; + }; + }>; + /** + * The itemsPerRow prop determines how many items to render in each row + * of a horizontal legend, or in each column of a vertical legend. This + * prop should be given as an integer. When this prop is not given, + * legend items will be rendered in a single row or column. + */ + itemsPerRow?: number; + /** + * The dataComponent prop takes a component instance which will be + * responsible for rendering a data element used to associate a symbol + * or color with each data series. The new element created from the + * passed dataComponent will be provided with the following properties + * calculated by VictoryLegend: x, y, size, style, and symbol. Any of + * these props may be overridden by passing in props to the supplied + * component, or modified or ignored within the custom component itself. + * If a dataComponent is not provided, VictoryLegend will use its + * default Point component. + */ + dataComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; + /** + * The gutter prop defines the number of pixels between legend rows or + * columns, depending on orientation. When orientation is horizontal, + * gutters are between columns. When orientation is vertical, gutters + * are the space between rows. + */ + gutter?: number; + /** + * The labelComponent prop takes a component instance which will be used + * to render each legend label. The new element created from the passed + * labelComponent will be supplied with the following properties: x, y, + * style, and text. Any of these props may be overridden by passing in + * props to the supplied component, or modified or ignored within the + * custom component itself. If labelComponent is omitted, a new + * VictoryLabel will be created with the props described above. + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop takes a string that defines whether legend data + * are displayed in a row or column. When orientation is "horizontal", + * legend items will be displayed in a single row. When orientation is + * "vertical", legend items will be displayed in a single column. Line + * and text-wrapping is not currently supported, so "vertical" + * orientation is both the default setting and recommended for + * displaying many series of data. + * @default 'vertical' + */ orientation?: 'horizontal'|'vertical'; - /** - * The padding prop specifies the amount of padding in pixels between - * the edge of the legend and any rendered child components. This prop - * can be given as a number or as an object with padding specified for - * top, bottom, left and right. As with width and height, the absolute - * padding will depend on whether the component is rendered in a - * responsive container. When a component is nested within - * VictoryLegend, setting padding on the child component will have no - * effect. - */ + /** + * The padding prop specifies the amount of padding in pixels between + * the edge of the legend and any rendered child components. This prop + * can be given as a number or as an object with padding specified for + * top, bottom, left and right. As with width and height, the absolute + * padding will depend on whether the component is rendered in a + * responsive container. When a component is nested within + * VictoryLegend, setting padding on the child component will have no + * effect. + */ padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The standalone props specifies whether the component should be - * rendered in an independent <svg> element or in a <g> tag. This prop - * defaults to true, and renders an svg. - */ - standalone?: boolean; - /** - * The symbolSpacer prop defines the number of pixels between data - * components and label components. - */ - symbolSpacer?: number; - /** - * The width and height props define the width and height of the legend. - * These props may be given as positive numbers or functions of data. If - * these props are not set, width and height will be determined based on - * an approximate text size calculated from the text and style props - * provided to VictoryLegend. - */ - width?: number; - height?: number; - /** - * The x and y props define the base position of the legend element. - */ - x?: number; - y?: number; + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The standalone props specifies whether the component should be + * rendered in an independent <svg> element or in a <g> tag. This prop + * defaults to true, and renders an svg. + */ + standalone?: boolean; + /** + * The symbolSpacer prop defines the number of pixels between data + * components and label components. + */ + symbolSpacer?: number; + /** + * The width and height props define the width and height of the legend. + * These props may be given as positive numbers or functions of data. If + * these props are not set, width and height will be determined based on + * an approximate text size calculated from the text and style props + * provided to VictoryLegend. + */ + width?: number; + height?: number; + /** + * The x and y props define the base position of the legend element. + */ + x?: number; + y?: number; } /** @@ -1993,84 +1994,84 @@ declare module "victory" { type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The bubbleProperty prop indicates which property of the data object should be used - * to scale data points in a bubble chart - */ - bubbleProperty?: string; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryScatter - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The bubbleProperty prop indicates which property of the data object should be used + * to scale data points in a bubble chart + */ + bubbleProperty?: string; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryScatter + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart - */ - maxBubbleSize?: number; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The size prop determines how to scale each data point - */ - size?: number | { (data: any): number }; - /** - * The style prop specifies styles for your VictoryScatter. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - /** - * The symbol prop determines which symbol should be drawn to represent data points. - */ - symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart + */ + maxBubbleSize?: number; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The size prop determines how to scale each data point + */ + size?: number | { (data: any): number }; + /** + * The style prop specifies styles for your VictoryScatter. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + /** + * The symbol prop determines which symbol should be drawn to represent data points. + */ + symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; } /** @@ -2080,248 +2081,248 @@ declare module "victory" { export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or catigorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryStack, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or catigorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryStack, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; - /** - * The xOffset prop is used for grouping stacks of bars. This prop will be set - * by the VictoryGroup component wrapper, or can be set manually. - */ - xOffset?: number; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children + */ + style?: VictoryStyleInterface; + /** + * The xOffset prop is used for grouping stacks of bars. This prop will be set + * by the VictoryGroup component wrapper, or can be set manually. + */ + xOffset?: number; } export class VictoryStack extends React.Component<VictoryStackProps, any> {} export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The colorScale prop is an optional prop that defines the color scale the pie - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryPie will automatically assign - * values from this color scale to the pie slices unless colors are explicitly provided in the - * data object - */ - colorScale?: ColorScalePropType; - /** - * The data prop specifies the data to be plotted, - * where data X-value is the slice label (string or number), - * and Y-value is the corresponding number value represented by the slice - * Data should be in the form of an array of data points. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire, HTML-complete data component which will be used to - * create slices for each datum in the pie chart. The new element created from the passed - * dataComponent will have the property datum set by the pie chart for the point it renders; - * properties style and pathFunction calculated by VictoryPie; an index property set - * corresponding to the location of the datum in the data provided to the pie; events bound to - * the VictoryPie; and the d3 compatible slice object. - * If a dataComponent is not provided, VictoryPie's Slice component will be used. - */ - dataComponent?: React.ReactElement<any>; - /** - * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. - * If this prop is not set, the label radius will default to the radius of the pie + label padding. - */ - labelRadius?: number; - /** - * The overall end angle of the pie in degrees. This prop is used in conjunction with - * startAngle to create a pie that spans only a segment of a circle. - */ - endAngle?: number; - /** - * The event prop takes an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryPie - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: 1, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: 2, - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: 2, - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The colorScale prop is an optional prop that defines the color scale the pie + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryPie will automatically assign + * values from this color scale to the pie slices unless colors are explicitly provided in the + * data object + */ + colorScale?: ColorScalePropType; + /** + * The data prop specifies the data to be plotted, + * where data X-value is the slice label (string or number), + * and Y-value is the corresponding number value represented by the slice + * Data should be in the form of an array of data points. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire, HTML-complete data component which will be used to + * create slices for each datum in the pie chart. The new element created from the passed + * dataComponent will have the property datum set by the pie chart for the point it renders; + * properties style and pathFunction calculated by VictoryPie; an index property set + * corresponding to the location of the datum in the data provided to the pie; events bound to + * the VictoryPie; and the d3 compatible slice object. + * If a dataComponent is not provided, VictoryPie's Slice component will be used. + */ + dataComponent?: React.ReactElement<any>; + /** + * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. + * If this prop is not set, the label radius will default to the radius of the pie + label padding. + */ + labelRadius?: number; + /** + * The overall end angle of the pie in degrees. This prop is used in conjunction with + * startAngle to create a pie that spans only a segment of a circle. + */ + endAngle?: number; + /** + * The event prop takes an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryPie + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: 1, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: 2, + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: 2, + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * Specifies the radius of the chart. If this property is not provided it is computed - * from width, height, and padding props - * - */ - radius?: number; - /** - * When creating a donut chart, this prop determines the number of pixels between - * the center of the chart and the inner edge of a donut. When this prop is set to zero - * a regular pie chart is rendered. - */ - innerRadius?: number; - /** - * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie - */ - cornerRadius?: number; - /** - * The padAngle prop determines the amount of separation between adjacent data slices - * in number of degrees - */ - padAngle?: number; - /** - * The overall start angle of the pie in degrees. This prop is used in conjunction with - * endAngle to create a pie that spans only a segment of a circle. - */ - startAngle?: number; - /** - * The style prop specifies styles for your pie. VictoryPie relies on Radium, - * so valid Radium style objects should work for this prop. Height, width, and - * padding should be specified via the height, width, and padding props. - * @example {data: {stroke: "black"}, label: {fontSize: 10}} - */ - style?: VictoryStyleInterface; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - */ - y?: DataGetterPropType; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * Specifies the radius of the chart. If this property is not provided it is computed + * from width, height, and padding props + * + */ + radius?: number; + /** + * When creating a donut chart, this prop determines the number of pixels between + * the center of the chart and the inner edge of a donut. When this prop is set to zero + * a regular pie chart is rendered. + */ + innerRadius?: number; + /** + * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie + */ + cornerRadius?: number; + /** + * The padAngle prop determines the amount of separation between adjacent data slices + * in number of degrees + */ + padAngle?: number; + /** + * The overall start angle of the pie in degrees. This prop is used in conjunction with + * endAngle to create a pie that spans only a segment of a circle. + */ + startAngle?: number; + /** + * The style prop specifies styles for your pie. VictoryPie relies on Radium, + * so valid Radium style objects should work for this prop. Height, width, and + * padding should be specified via the height, width, and padding props. + * @example {data: {stroke: "black"}, label: {fontSize: 10}} + */ + style?: VictoryStyleInterface; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + */ + y?: DataGetterPropType; } /** @@ -2330,4 +2331,4 @@ declare module "victory" { * Data changes are animated with VictoryAnimation. */ export class VictoryPie extends React.Component<VictoryPieProps, any> {} - } +} From bd167704d48dfc551d2eb367a727ba0b5ff52879 Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Wed, 6 Feb 2019 11:29:40 -0500 Subject: [PATCH 130/200] Revert prettier whitespace changes --- types/victory/index.d.ts | 3013 +++++++++++++++++++------------------- 1 file changed, 1507 insertions(+), 1506 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 43bf4378e6..c3468151ba 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -12,33 +12,33 @@ declare module "victory" { import * as React from "react"; - + /** * Single animation object to interpolate */ - export type AnimationStyle = { [key: string ]: string | number }; - + export type AnimationStyle = { [key: string ]: string | number }; + /** * Animation styles to interpolate */ - + export type AnimationData = AnimationStyle | AnimationStyle[]; - + export type AnimationEasing = - "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | - "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | - "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | - "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | - "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | - "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; - + "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | + "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | + "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | + "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | + "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | + "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; + // Many victory components accept string or number or callback which returns string or number type StringOrNumberOrCallback = - | string - | number - | ((datum: any, active: boolean) => string | number); + | string + | number + | ((datum: any, active: boolean) => string | number); type NumberOrCallback = ((datum: any, active: boolean) => number) | number; - + type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; /** * Style interface used in components/themeing @@ -48,987 +48,987 @@ declare module "victory" { data?: VictoryStyleObject; labels?: VictoryStyleObject; } - + export interface VictoryAnimationProps { - /** - * The child of should be a function that takes an object of tweened values and returns a component to render. - * @param style - */ - children?: (style: AnimationStyle) => React.ReactElement<any>; - /** - * The number of milliseconds the animation should take to complete. - * @default 1000 - */ - duration?: number; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - /** - * The delay prop specifies a delay in milliseconds before the animation begins. - * If multiple values are in the animation queue, it is the delay between each animation. - * @default 0 - */ - delay?: number; - /** - * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. - */ - onEnd?: () => void; - /** - * The data prop specifies the latest set of values to tween to. - * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. - * When given an array of values, VictoryAnimation will use it as an animation queue. - * @default {} - */ - data?: AnimationData; + /** + * The child of should be a function that takes an object of tweened values and returns a component to render. + * @param style + */ + children?: (style: AnimationStyle) => React.ReactElement<any>; + /** + * The number of milliseconds the animation should take to complete. + * @default 1000 + */ + duration?: number; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + /** + * The delay prop specifies a delay in milliseconds before the animation begins. + * If multiple values are in the animation queue, it is the delay between each animation. + * @default 0 + */ + delay?: number; + /** + * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. + */ + onEnd?: () => void; + /** + * The data prop specifies the latest set of values to tween to. + * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. + * When given an array of values, VictoryAnimation will use it as an animation queue. + * @default {} + */ + data?: AnimationData; } - + /** * VictoryAnimation animates prop changes for any React component. * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. */ - export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} - + export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} + /** * Text anchor type */ type TextAnchorType = "start" | "middle" | "end" | "inherit"; - + /** * Vertical anchor type */ type VerticalAnchorType = "start" | "middle" | "end"; - + export interface VictoryLabelProps { - /** - * Specifies the angle to rotate the text by. - */ - angle?: string | number; - /** - * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. - * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. - * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. - * @default "0.71em" - */ - capHeight?: StringOrNumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text - */ - datum?: {}; - /** - * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. - */ - data?: any[]; - /** - * The events prop attaches arbitrary event handlers to the label component. - * Event handlers are currently only called with their corresponding events. - */ - events?: React.DOMAttributes<any>; - /** - * The children of this component define the content of the label. - * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. - */ - children?: StringOrNumberOrCallback; - /** - * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. - * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar - * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. - * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label - * placement will be used for cartesian charts. - */ - labelPlacement?: "parallel" | "perpendicular" | "vertical"; - /** - * The lineHeight prop defines how much space a single line of text should take up. - * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, - * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. - * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. - * If given a unitless number, it is assumed to be ems. - * @default 1 - */ - lineHeight?: StringOrNumberOrCallback; - /** - * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. - * **This prop should not be set manually.** - */ - origin?: { x: number, y: number }; - /** - * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. - * **This prop should not be set manually.** - */ - polar?: boolean; - /** - * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. - * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, - * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate - * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. - */ - text?: string[] | StringOrNumberOrCallback; - /** - * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. - */ - textAnchor?: TextAnchorType | { (): TextAnchorType }; - /** - * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. - */ - verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; - /** - * The transform prop applies a transform to the rendered `<text>` element. - * In addition to being a string, it can be an object containing transform definitions for easier authoring. - */ - transform?: string | {} | { (): string | {} }; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - /** - * The dx prop defines a horizontal shift from the `x` coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the `y` coordinate. - * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. - */ - dy?: StringOrNumberOrCallback; + /** + * Specifies the angle to rotate the text by. + */ + angle?: string | number; + /** + * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. + * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. + * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. + * @default "0.71em" + */ + capHeight?: StringOrNumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text + */ + datum?: {}; + /** + * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. + */ + data?: any[]; + /** + * The events prop attaches arbitrary event handlers to the label component. + * Event handlers are currently only called with their corresponding events. + */ + events?: React.DOMAttributes<any>; + /** + * The children of this component define the content of the label. + * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. + */ + children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; + /** + * The lineHeight prop defines how much space a single line of text should take up. + * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, + * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. + * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. + * If given a unitless number, it is assumed to be ems. + * @default 1 + */ + lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ + origin?: { x: number, y: number }; + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; + /** + * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. + */ + textAnchor?: TextAnchorType | { (): TextAnchorType }; + /** + * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. + */ + verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; + /** + * The transform prop applies a transform to the rendered `<text>` element. + * In addition to being a string, it can be an object containing transform definitions for easier authoring. + */ + transform?: string | {} | { (): string | {} }; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + /** + * The dx prop defines a horizontal shift from the `x` coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the `y` coordinate. + * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. + */ + dy?: StringOrNumberOrCallback; } - + /** * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. */ export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} - + export interface VictoryContainerProps { - /** - * The responsive prop specifies whether the rendered container should be a responsive container - * with a viewBox attribute, or a static container with absolute width and height. - * @default true - */ - responsive?: boolean; - /** - * The style prop specifies styles for your VictoryContainer. Any valid inline style properties - * will be applied. Height and width should be specified via the height - * and width props, as they are used to calculate the alignment of - * components within the container. Styles from the child component will - * also be passed, if any exist. - * @examples {border: 1px solid red} - */ - style?: React.CSSProperties; - /** - * The height props specifies the height the svg viewBox of the container. - * This value should be given as a number of pixels. If no height prop - * is given, the height prop from the child component passed will be used. - */ - height?: number; - /** - * The width props specifies the width of the svg viewBox of the container - * This value should be given as a number of pixels. If no width prop - * is given, the width prop from the child component passed will be used. - */ - width?: number; - /** - * The events prop attaches arbitrary event handlers to the container component. - * Event handlers passed from other Victory components are called with their - * corresponding events as well as scale, style, width, height, and data when - * applicable. Use the invert method to convert event coordinate information to - * data. `scale.x.invert(evt.offsetX)`. - * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} - */ - events?: React.DOMAttributes<any>; - /** - * The title prop specifies the title to be applied to the SVG to assist - * accessibility for screen readers. The more descriptive this title is, the more - * useful it will be. If no title prop is passed, it will default to Victory Chart. - * @example "Popularity of Dog Breeds by Percentage" - * @default "Victory Chart" - */ - title?: string; - /** - * The desc prop specifies the description of the chart/SVG to assist with - * accessibility for screen readers. The more info about the chart provided in - * the description, the more usable it will be for people using screen readers. - * This prop defaults to an empty string. - * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are - * not represented above 5% each." - * @default "" - */ - desc?: string; + /** + * The responsive prop specifies whether the rendered container should be a responsive container + * with a viewBox attribute, or a static container with absolute width and height. + * @default true + */ + responsive?: boolean; + /** + * The style prop specifies styles for your VictoryContainer. Any valid inline style properties + * will be applied. Height and width should be specified via the height + * and width props, as they are used to calculate the alignment of + * components within the container. Styles from the child component will + * also be passed, if any exist. + * @examples {border: 1px solid red} + */ + style?: React.CSSProperties; + /** + * The height props specifies the height the svg viewBox of the container. + * This value should be given as a number of pixels. If no height prop + * is given, the height prop from the child component passed will be used. + */ + height?: number; + /** + * The width props specifies the width of the svg viewBox of the container + * This value should be given as a number of pixels. If no width prop + * is given, the width prop from the child component passed will be used. + */ + width?: number; + /** + * The events prop attaches arbitrary event handlers to the container component. + * Event handlers passed from other Victory components are called with their + * corresponding events as well as scale, style, width, height, and data when + * applicable. Use the invert method to convert event coordinate information to + * data. `scale.x.invert(evt.offsetX)`. + * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} + */ + events?: React.DOMAttributes<any>; + /** + * The title prop specifies the title to be applied to the SVG to assist + * accessibility for screen readers. The more descriptive this title is, the more + * useful it will be. If no title prop is passed, it will default to Victory Chart. + * @example "Popularity of Dog Breeds by Percentage" + * @default "Victory Chart" + */ + title?: string; + /** + * The desc prop specifies the description of the chart/SVG to assist with + * accessibility for screen readers. The more info about the chart provided in + * the description, the more usable it will be for people using screen readers. + * This prop defaults to an empty string. + * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are + * not represented above 5% each." + * @default "" + */ + desc?: string; } - - export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} - + + export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} + type CursorData = { - x: number; - y: number; + x: number; + y: number; }; - + export interface VictoryCursorContainerProps extends VictoryContainerProps { - /** - * The cursorComponent prop takes a component instance which will be used to render a cursor element. - * The new element created will be supplied with x1, y1, x2 and y2 positioning props. - * If a cursorComponent is not supplied, a new Line component will be rendered. - * @default cursorComponent={<Line/>} - */ - cursorComponent?: React.ReactElement<any>; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example cursorDimension="x" - */ - cursorDimension?: 'x' | 'y'; - /** - * The cursorLabel prop defines the label that will appear next to the cursor. - * A label will only appear if cursorLabel is set. This prop should be given as a - * function of a point (an Object with x and y properties). - * @example cursorLabel={(point) => point.x} - */ - cursorLabel?: (point: CursorData) => void; - /** - * The cursorLabelComponent prop takes a component instance which will be - * used to render a label for the cursor. The new element created from the passed - * cursorLabelComponent will be supplied with the following props: x, y, - * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. - * @default cursorLabelComponent={<VictoryLabel/>} - */ - cursorLabelComponent?: React.ReactElement<any>; - /** - * The cursorLabelOffset prop determines the pixel offset of the cursor label - * from the cursor point. This prop should be an Object with x and y properties, or a - * number to be used for both dimensions. - * @default "{ x: 5, y: -10 }" - */ - cursorLabelOffset?: number | CursorData; - /** - * Whenever the mouse is not over the chart, the cursor will not be displayed. - * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. - * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. - * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} - */ - defaultCursorValue?: number | CursorData; - /** - * When the disable prop is set to true, VictoryCursorContainer events will not fire. - */ - disable?: boolean; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example onChange={(value, props) => this.setState({cursorValue: value})} - */ - onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; + /** + * The cursorComponent prop takes a component instance which will be used to render a cursor element. + * The new element created will be supplied with x1, y1, x2 and y2 positioning props. + * If a cursorComponent is not supplied, a new Line component will be rendered. + * @default cursorComponent={<Line/>} + */ + cursorComponent?: React.ReactElement<any>; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example cursorDimension="x" + */ + cursorDimension?: 'x' | 'y'; + /** + * The cursorLabel prop defines the label that will appear next to the cursor. + * A label will only appear if cursorLabel is set. This prop should be given as a + * function of a point (an Object with x and y properties). + * @example cursorLabel={(point) => point.x} + */ + cursorLabel?: (point: CursorData) => void; + /** + * The cursorLabelComponent prop takes a component instance which will be + * used to render a label for the cursor. The new element created from the passed + * cursorLabelComponent will be supplied with the following props: x, y, + * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. + * @default cursorLabelComponent={<VictoryLabel/>} + */ + cursorLabelComponent?: React.ReactElement<any>; + /** + * The cursorLabelOffset prop determines the pixel offset of the cursor label + * from the cursor point. This prop should be an Object with x and y properties, or a + * number to be used for both dimensions. + * @default "{ x: 5, y: -10 }" + */ + cursorLabelOffset?: number | CursorData; + /** + * Whenever the mouse is not over the chart, the cursor will not be displayed. + * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. + * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. + * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} + */ + defaultCursorValue?: number | CursorData; + /** + * When the disable prop is set to true, VictoryCursorContainer events will not fire. + */ + disable?: boolean; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example onChange={(value, props) => this.setState({cursorValue: value})} + */ + onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; } - - export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} - + + export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} + export interface VictoryBrushContainerProps extends VictoryContainerProps { - /** - * The optional allowDrag prop accepts a boolean that enables dragging behavior - * for the highlighted brush area. Resizing will still be enabled when the allowDrag - * prop is set to false. - * @default true - */ - allowDrag?: boolean; - /** - * The optional allowResize prop accepts a boolean that enables resizing the - * highlighted brush area. Dragging will still be enabled when the allowResize - * prop is set to false, but the dimensions of the brush area will be fixed. - * @default true - */ - allowResize?: boolean; - /** - * The brushComponent prop specifies the component to be rendered for the - * highlighted area. This component will be supplied with the following props: x, y, - * width, height, and style. When this prop is not specified, a <rect/> will be rendered. - * @default brushComponent={<rect/>} - */ - brushComponent?: React.ReactElement<any>; - /** - * When the brushDimension prop is set, brushing will only be specific to the to - * the given dimension (either "x" or "y"), and the entire domain of the other - * dimension will be highlighted. When this prop is not specified, highlighting will - * occur along both dimensions. - * @example brushDimension="x" - */ - brushDimension?: 'x' | 'y'; - /** - * The optional brushDomain prop describes the highlighted state. This prop is an - * object that specifies separate arrays for x and y. Each array is a tuple that - * describes the minimum and maximum values to render. If this prop is not provided - * initially, the chart will render with the entire domain highlighted. When this prop - * changes, the chart will render with a new highlighted domain. - * @example brushDomain={{ x: [50, 100], y: [0, 100] }} - */ - brushDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ - defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * The handleComponent prop specifies the component to be rendered for each - * handle for the highlighted area. This component will be supplied with the following - * props: x, y, width, height, cursor, and style. When this prop is not - * specified, a <rect/> will be rendered. - * @default handleComponent={<rect/>} - */ - handleComponent?: React.ReactElement<any>; - /** - * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. - * - * Handles refer to the region on each highlighted area where the area may be - * expanded. Only handles relevant to the given dimension will be rendered. For - * example, when brushDimension="x" only "left" and "right" handles will be - * rendered. Handles are automatically styled with cursors appropriate to their orientation. - * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" - */ - handleStyle?: React.CSSProperties; - /** - * The optional onBrushDomainChange prop accepts an function to be called on - * each update to the highlighted domain. The function accepts the parameters of - * domain (the updated domain), and props (the props used by VictoryBrushContainer). - * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ - onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; + /** + * The optional allowDrag prop accepts a boolean that enables dragging behavior + * for the highlighted brush area. Resizing will still be enabled when the allowDrag + * prop is set to false. + * @default true + */ + allowDrag?: boolean; + /** + * The optional allowResize prop accepts a boolean that enables resizing the + * highlighted brush area. Dragging will still be enabled when the allowResize + * prop is set to false, but the dimensions of the brush area will be fixed. + * @default true + */ + allowResize?: boolean; + /** + * The brushComponent prop specifies the component to be rendered for the + * highlighted area. This component will be supplied with the following props: x, y, + * width, height, and style. When this prop is not specified, a <rect/> will be rendered. + * @default brushComponent={<rect/>} + */ + brushComponent?: React.ReactElement<any>; + /** + * When the brushDimension prop is set, brushing will only be specific to the to + * the given dimension (either "x" or "y"), and the entire domain of the other + * dimension will be highlighted. When this prop is not specified, highlighting will + * occur along both dimensions. + * @example brushDimension="x" + */ + brushDimension?: 'x' | 'y'; + /** + * The optional brushDomain prop describes the highlighted state. This prop is an + * object that specifies separate arrays for x and y. Each array is a tuple that + * describes the minimum and maximum values to render. If this prop is not provided + * initially, the chart will render with the entire domain highlighted. When this prop + * changes, the chart will render with a new highlighted domain. + * @example brushDomain={{ x: [50, 100], y: [0, 100] }} + */ + brushDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ + defaultBrushArea?: 'all' | 'none' | 'disable'; + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * The handleComponent prop specifies the component to be rendered for each + * handle for the highlighted area. This component will be supplied with the following + * props: x, y, width, height, cursor, and style. When this prop is not + * specified, a <rect/> will be rendered. + * @default handleComponent={<rect/>} + */ + handleComponent?: React.ReactElement<any>; + /** + * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. + * + * Handles refer to the region on each highlighted area where the area may be + * expanded. Only handles relevant to the given dimension will be rendered. For + * example, when brushDimension="x" only "left" and "right" handles will be + * rendered. Handles are automatically styled with cursors appropriate to their orientation. + * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" + */ + handleStyle?: React.CSSProperties; + /** + * The optional onBrushDomainChange prop accepts an function to be called on + * each update to the highlighted domain. The function accepts the parameters of + * domain (the updated domain), and props (the props used by VictoryBrushContainer). + * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ + onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; } - - export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} - + + export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} + export interface VictoryZoomContainerProps extends VictoryContainerProps { - /** - * The optional allowPan prop accepts a boolean that enables the panning - * functionality. Zooming will still be enabled when the allowPan prop is set to false. - * @default true - */ - allowPan?: boolean; - /** - * The optional allowZoom prop accepts a boolean that enables the zoom - * functionality. Panning will still be enabled when the allowZoom prop is set to false. - * @default true - */ - allowZoom?: boolean; - /** - * VictoryZoomContainer works by clipping data outside of a given domain. - * VictoryZoomContainer uses VictoryClipContainer by default. - * This prop should not be replaced with a custom component, but you may want to set - * props on VictoryClipContainer, such as clipPadding. - * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} - */ - clipContainerComponent?: React.ReactElement<any>; - /** - * When the zoomDimension prop is set, panning and zooming will be restricted to - * the given dimension (either x or y), and the domain of the other dimension will - * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. - * @example zoomDimension="x" - */ - zoomDimension?: 'x' | 'y'; - /** - * The zoomDomain prop describes the zoomed state. This prop is an object that - * specifies separate arrays for x and y. Each array is a tuple that describes the - * minimum and maximum values to render. If this prop is not provided initially, the - * chart will render without an initial zoom, displaying the entire dataset. Updates to - * zoomDomain will trigger a re-render of the chart with the new domain. - * @example zoomDomain={{x: [0, 100]}} - */ - zoomDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ - defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * When the disable prop is set to true, VictoryZoomContainer events will not fire. - */ - downsample?: number | boolean; - /** - * The minimumZoom prop sets a minimum domain extent for the zoomed chart. - * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom - * in either dimension, the component will stop responding to events that would normally trigger zooming in. - * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum - * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object - * with numeric values for x and y. - * @example minimumZoom={{x: 1, y: 0.01}} - */ - minimumZoom?: CursorData; - /** - * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. - * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). - * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ - onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; + /** + * The optional allowPan prop accepts a boolean that enables the panning + * functionality. Zooming will still be enabled when the allowPan prop is set to false. + * @default true + */ + allowPan?: boolean; + /** + * The optional allowZoom prop accepts a boolean that enables the zoom + * functionality. Panning will still be enabled when the allowZoom prop is set to false. + * @default true + */ + allowZoom?: boolean; + /** + * VictoryZoomContainer works by clipping data outside of a given domain. + * VictoryZoomContainer uses VictoryClipContainer by default. + * This prop should not be replaced with a custom component, but you may want to set + * props on VictoryClipContainer, such as clipPadding. + * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} + */ + clipContainerComponent?: React.ReactElement<any>; + /** + * When the zoomDimension prop is set, panning and zooming will be restricted to + * the given dimension (either x or y), and the domain of the other dimension will + * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. + * @example zoomDimension="x" + */ + zoomDimension?: 'x' | 'y'; + /** + * The zoomDomain prop describes the zoomed state. This prop is an object that + * specifies separate arrays for x and y. Each array is a tuple that describes the + * minimum and maximum values to render. If this prop is not provided initially, the + * chart will render without an initial zoom, displaying the entire dataset. Updates to + * zoomDomain will trigger a re-render of the chart with the new domain. + * @example zoomDomain={{x: [0, 100]}} + */ + zoomDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ + defaultBrushArea?: 'all' | 'none' | 'disable'; + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * When the disable prop is set to true, VictoryZoomContainer events will not fire. + */ + downsample?: number | boolean; + /** + * The minimumZoom prop sets a minimum domain extent for the zoomed chart. + * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom + * in either dimension, the component will stop responding to events that would normally trigger zooming in. + * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum + * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object + * with numeric values for x and y. + * @example minimumZoom={{x: 1, y: 0.01}} + */ + minimumZoom?: CursorData; + /** + * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. + * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). + * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ + onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; } - - export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} - + + export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} + // Note: Many SVG attributes are missed in CSSProperties interface export interface VictoryThemeDefinition { - area?: VictoryStyleInterface; - axis?: { - axis: React.CSSProperties; - axisLabel: React.CSSProperties; - grid: React.CSSProperties; - ticks: React.CSSProperties; - tickLabels: React.CSSProperties; + area?: VictoryStyleInterface; + axis?: { + axis: React.CSSProperties; + axisLabel: React.CSSProperties; + grid: React.CSSProperties; + ticks: React.CSSProperties; + tickLabels: React.CSSProperties; + }; + bar?: VictoryStyleInterface; + candlestick?: VictoryStyleInterface & { + props: { + width: number; + height: number; + candleColors: { + positive: string; + negative: string; + }; }; - bar?: VictoryStyleInterface; - candlestick?: VictoryStyleInterface & { - props: { - width: number; - height: number; - candleColors: { - positive: string; - negative: string; - }; - }; - }; - line?: VictoryStyleInterface; - pie?: { - props: { - width: number; - height: number; - colorScale: string[]; - }; - style: VictoryStyleInterface; - }; - scatter?: VictoryStyleInterface; - props?: { - width: number; - height: number; - colorScale: string[]; + }; + line?: VictoryStyleInterface; + pie?: { + props: { + width: number; + height: number; + colorScale: string[]; }; + style: VictoryStyleInterface; + }; + scatter?: VictoryStyleInterface; + props?: { + width: number; + height: number; + colorScale: string[]; + }; } - + interface VictoryThemeInterface { - /** - * Default theme - */ - grayscale: VictoryThemeDefinition; - material: VictoryThemeDefinition; + /** + * Default theme + */ + grayscale: VictoryThemeDefinition; + material: VictoryThemeDefinition; } - + /** * Available themes */ export const VictoryTheme: VictoryThemeInterface; - + type OrientationTypes = "top" | "bottom" | "left" | "right"; - + export interface VictoryTooltipProps { - /** - * The active prop specifies whether the tooltip component should be displayed. - */ - active?: boolean; - /** - * When true, tooltip events will set the active prop on both data and label elements. - * @default false - */ - activateData?: boolean; - /** - * The angle prop specifies the angle to rotate the tooltip around its origin point. - */ - angle?: string | number; - /** - * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. - */ - cornerRadius?: NumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. - */ - datum?: {}; - /** - * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. - */ - data?: any[]; - /** - * The dx prop defines a horizontal shift from the x coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the y coordinate. - */ - dy?: StringOrNumberOrCallback; - /** - * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. - * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. - * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} - */ - events?: {}; - /** - * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. - */ - flyoutStyle?: VictoryStyleObject; - /** - * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. - * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, - * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If flyoutComponent is omitted, a default Flyout component will be created with props described above. - * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} - * @default <Flyout/> - */ - flyoutComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. - * @default groupComponent={<g/>} - */ - groupComponent?: React.ReactElement<any>; - /** - * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - height?: NumberOrCallback; - /** - * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. - * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. - * negative values result in a left orientation and positive values will result in a right orientation by default. - */ - horizontal?: boolean; - /** - * The index prop represents the index of the datum in the data array. - */ - index?: number | string; - /** - * The labelComponent prop takes a component instance which will be used to render each tooltip label. - * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. - * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. - * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. - * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. - */ - orientation?: OrientationTypes; - /** - * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerLength?: NumberOrCallback; - /** - * The pointerWidth prop determines the width of the base of the triangular pointer extending from - * the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerWidth?: NumberOrCallback; - /** - * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element - * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. - * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. - */ - text?: StringOrNumberOrCallback | string[] | number[]; - /** - * VictoryAxis uses the standard theme prop. Read about it here - * @default VictoryTheme.grayscale - */ - theme?: VictoryThemeDefinition; - /** - * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - width?: NumberOrCallback; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; + /** + * The active prop specifies whether the tooltip component should be displayed. + */ + active?: boolean; + /** + * When true, tooltip events will set the active prop on both data and label elements. + * @default false + */ + activateData?: boolean; + /** + * The angle prop specifies the angle to rotate the tooltip around its origin point. + */ + angle?: string | number; + /** + * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. + */ + cornerRadius?: NumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. + */ + datum?: {}; + /** + * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. + */ + data?: any[]; + /** + * The dx prop defines a horizontal shift from the x coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the y coordinate. + */ + dy?: StringOrNumberOrCallback; + /** + * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. + * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. + * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} + */ + events?: {}; + /** + * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. + */ + flyoutStyle?: VictoryStyleObject; + /** + * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. + * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, + * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If flyoutComponent is omitted, a default Flyout component will be created with props described above. + * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} + * @default <Flyout/> + */ + flyoutComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. + * @default groupComponent={<g/>} + */ + groupComponent?: React.ReactElement<any>; + /** + * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + height?: NumberOrCallback; + /** + * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. + * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. + * negative values result in a left orientation and positive values will result in a right orientation by default. + */ + horizontal?: boolean; + /** + * The index prop represents the index of the datum in the data array. + */ + index?: number | string; + /** + * The labelComponent prop takes a component instance which will be used to render each tooltip label. + * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. + * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. + * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. + * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. + */ + orientation?: OrientationTypes; + /** + * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerLength?: NumberOrCallback; + /** + * The pointerWidth prop determines the width of the base of the triangular pointer extending from + * the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerWidth?: NumberOrCallback; + /** + * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element + * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. + * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. + */ + text?: StringOrNumberOrCallback | string[] | number[]; + /** + * VictoryAxis uses the standard theme prop. Read about it here + * @default VictoryTheme.grayscale + */ + theme?: VictoryThemeDefinition; + /** + * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + width?: NumberOrCallback; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; } - + /** * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. * VictoryTooltip renders text as well as a configurable Flyout container. */ export class VictoryTooltip extends React.Component< - VictoryTooltipProps, - any - > {} - + VictoryTooltipProps, + any + > {} + /** * Animate object used in components */ export interface AnimatePropTypeInterface { - /** - * Animation duration - */ - duration: number; - /** - * Animation end callback - */ - onEnd?: () => void; - /** - * Animation exit transition configuration - */ - onExit?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - }; - /** - * Animation enter transition configuration - */ - onEnter?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * Animation load transition configuration - */ - onLoad?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; + /** + * Animation duration + */ + duration: number; + /** + * Animation end callback + */ + onEnd?: () => void; + /** + * Animation exit transition configuration + */ + onExit?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + }; + /** + * Animation enter transition configuration + */ + onEnter?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * Animation load transition configuration + */ + onLoad?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; } - + /** * Return value for eventHandlers values */ interface EventCallbackInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - target?: TTarget; - eventKey?: TEventKey; - /** - * Will be called with the calculated props for the individual selected element and result will override - * props of selected element via object assignment - * @param props - */ - mutation: (props: any) => any; + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + target?: TTarget; + eventKey?: TEventKey; + /** + * Will be called with the calculated props for the individual selected element and result will override + * props of selected element via object assignment + * @param props + */ + mutation: (props: any) => any; } - + export interface EventPropTypeInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - /** - * Targets may be any valid style namespace for a given component - */ - target: TTarget; - - eventKey?: TEventKey; - /** - * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks - */ - eventHandlers: { - [key: string]: { - (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | - { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] - } - }; + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + /** + * Targets may be any valid style namespace for a given component + */ + target: TTarget; + + eventKey?: TEventKey; + /** + * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks + */ + eventHandlers: { + [key: string]: { + (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | + { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] + } + }; } - + /** * Data domain type */ type DomainTuple = [number, number] | [Date, Date]; - - type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; - + + type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; + /** * Domain padding */ - type DomainPaddingPropType = number | { - x?: number | [ number, number]; - y?: number | [ number, number]; - }; - + type DomainPaddingPropType = number | { + x?: number | [ number, number]; + y?: number | [ number, number]; + }; + /** * D3 scale function shape. Don't want to introduce typing dependency to d3 */ interface D3Scale { - domain: () => any; - range: () => any; - copy: () => any; + domain: () => any; + range: () => any; + copy: () => any; } - + /** * Acceptable scale types */ type ScalePropType = "linear" | "time" | "log" | "sqrt"; - + /** * Category prop type */ - type CategoryPropType = string[] | { - x: string[] - y: string[] - }; - + type CategoryPropType = string[] | { + x: string[] + y: string[] + }; + /** * Data getter property type */ - type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; - - type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | - "cardinal" | "cardinalClosed" | "cardinalOpen" | - "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | - "linear" | "linearClosed" | "monotoneX" | "monotoneY" | - "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; - - type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; - + type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; + + type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | + "cardinal" | "cardinalClosed" | "cardinalOpen" | + "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | + "linear" | "linearClosed" | "monotoneX" | "monotoneY" | + "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; + + type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; + /** * Common properties */ interface VictoryCommonProps { - /** - * The animate prop specifies props for VictoryAnimation to use. - * The animate prop should also be used to specify enter and exit - * transition configurations with the `onExit` and `onEnter` namespaces respectively. - * @example - * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} - */ - animate?: AnimatePropTypeInterface; - /** - * The name prop is used to reference a component instance when defining shared events. - */ - name?: string; - /** - * The height props specifies the height the svg viewBox of the chart container. - * This value should be given as a number of pixels - */ - height?: number; - /** - * The padding props specifies the amount of padding in number of pixels between - * the edge of the chart and any rendered child components. This prop can be given - * as a number or as an object with padding specified for top, bottom, left - * and right. - * @default 50 - */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The scale prop determines which scales your chart should use. This prop can be - * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), - * as a d3 scale function, or as an object with scales specified for x and y - * @example d3Scale.time(), {x: "linear", y: "log"} - * @default "linear" - */ - scale?: ScalePropType | D3Scale | { - x?: ScalePropType | D3Scale; - y?: ScalePropType | D3Scale; - }; - /** - * The standalone prop determines whether the component will render a standalone svg - * or a <g> tag that will be included in an external svg. Set standalone to false to - * compose VictoryAxis with other components within an enclosing <svg> tag. - * @default true - */ - standalone?: boolean; - /** - * The width props specifies the width of the svg viewBox of the chart container - * This value should be given as a number of pixels - */ - width?: number; - /** - * The containerComponent prop takes an entire component which will be used to - * create a container element for standalone charts. - * The new element created from the passed containerComponent wil be provided with - * these props from VictoryArea: height, width, children - * (the chart itself) and style. Props that are not provided by the - * child chart component include title and desc, both of which - * are intended to add accessibility to Victory components. The more descriptive these props - * are, the more accessible your data will be for people using screen readers. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use the default VictoryContainer component. - * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * The theme prop takes a style object with nested data, labels, and parent objects. - * You can create this object yourself, or you can use a theme provided by Victory. - * When using VictoryArea as a solo component, implement the theme directly on - * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or - * VictoryGroup, please call the theme on the outermost wrapper component instead. - * @example theme={VictoryTheme.material} - * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js - */ - theme?: VictoryThemeDefinition; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; + /** + * The animate prop specifies props for VictoryAnimation to use. + * The animate prop should also be used to specify enter and exit + * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * @example + * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + */ + animate?: AnimatePropTypeInterface; + /** + * The name prop is used to reference a component instance when defining shared events. + */ + name?: string; + /** + * The height props specifies the height the svg viewBox of the chart container. + * This value should be given as a number of pixels + */ + height?: number; + /** + * The padding props specifies the amount of padding in number of pixels between + * the edge of the chart and any rendered child components. This prop can be given + * as a number or as an object with padding specified for top, bottom, left + * and right. + * @default 50 + */ + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The scale prop determines which scales your chart should use. This prop can be + * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), + * as a d3 scale function, or as an object with scales specified for x and y + * @example d3Scale.time(), {x: "linear", y: "log"} + * @default "linear" + */ + scale?: ScalePropType | D3Scale | { + x?: ScalePropType | D3Scale; + y?: ScalePropType | D3Scale; + }; + /** + * The standalone prop determines whether the component will render a standalone svg + * or a <g> tag that will be included in an external svg. Set standalone to false to + * compose VictoryAxis with other components within an enclosing <svg> tag. + * @default true + */ + standalone?: boolean; + /** + * The width props specifies the width of the svg viewBox of the chart container + * This value should be given as a number of pixels + */ + width?: number; + /** + * The containerComponent prop takes an entire component which will be used to + * create a container element for standalone charts. + * The new element created from the passed containerComponent wil be provided with + * these props from VictoryArea: height, width, children + * (the chart itself) and style. Props that are not provided by the + * child chart component include title and desc, both of which + * are intended to add accessibility to Victory components. The more descriptive these props + * are, the more accessible your data will be for people using screen readers. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use the default VictoryContainer component. + * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * The theme prop takes a style object with nested data, labels, and parent objects. + * You can create this object yourself, or you can use a theme provided by Victory. + * When using VictoryArea as a solo component, implement the theme directly on + * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or + * VictoryGroup, please call the theme on the outermost wrapper component instead. + * @example theme={VictoryTheme.material} + * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js + */ + theme?: VictoryThemeDefinition; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; } - + /** * Common properties for all data components */ interface VictoryDatableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these arrays of values specified for x and y. If this prop is not set, - * categorical data will be plotted in the order it was given in the data array - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The data prop specifies the data to be plotted. Data should be in the form of an array - * of data points, or an array of arrays of data points for multiple datasets. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire component which will be used to create an area. - * The new element created from the passed dataComponent will be provided with the - * following properties calculated by VictoryArea: a scale, style, events, interpolation, - * and an array of modified data objects (including x, y, and calculated y0 and y1). - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use its default Area component. - * @default <Area/> - */ - dataComponent?: React.ReactElement<any>; - /** - * The domain prop describes the range of values your chart will cover. This prop can be - * given as a array of the minimum and maximum expected values for your bar chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - * @default "x" - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - * @default "y" - */ - y?: DataGetterPropType; + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these arrays of values specified for x and y. If this prop is not set, + * categorical data will be plotted in the order it was given in the data array + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The data prop specifies the data to be plotted. Data should be in the form of an array + * of data points, or an array of arrays of data points for multiple datasets. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire component which will be used to create an area. + * The new element created from the passed dataComponent will be provided with the + * following properties calculated by VictoryArea: a scale, style, events, interpolation, + * and an array of modified data objects (including x, y, and calculated y0 and y1). + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use its default Area component. + * @default <Area/> + */ + dataComponent?: React.ReactElement<any>; + /** + * The domain prop describes the range of values your chart will cover. This prop can be + * given as a array of the minimum and maximum expected values for your bar chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + * @default "x" + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + * @default "y" + */ + y?: DataGetterPropType; } - + // Common labable interface interface VictoryLabableProps { - /** - * The labelComponent prop takes in an entire label component which will be used - * to create a label for the area. The new element created from the passed labelComponent - * will be supplied with the following properties: x, y, index, data, verticalAnchor, - * textAnchor, angle, style, text, and events. any of these props may be overridden - * by passing in props to the supplied component, or modified or ignored within - * the custom component itself. If labelComponent is omitted, a new VictoryLabel - * will be created with props described above. This labelComponent prop should be used to - * provide a series label for VictoryArea. If individual labels are required for each - * data point, they should be created by composing VictoryArea with VictoryScatter - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; + /** + * The labelComponent prop takes in an entire label component which will be used + * to create a label for the area. The new element created from the passed labelComponent + * will be supplied with the following properties: x, y, index, data, verticalAnchor, + * textAnchor, angle, style, text, and events. any of these props may be overridden + * by passing in props to the supplied component, or modified or ignored within + * the custom component itself. If labelComponent is omitted, a new VictoryLabel + * will be created with props described above. This labelComponent prop should be used to + * provide a series label for VictoryArea. If individual labels are required for each + * data point, they should be created by composing VictoryArea with VictoryScatter + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; } - + interface VictoryMultiLabeableProps extends VictoryLabableProps { - /** - * The labels prop defines labels that will appear above each bar in your chart. - * This prop should be given as an array of values or as a function of data. - * If given as an array, the number of elements in the array should be equal to - * the length of the data array. Labels may also be added directly to the data object - * like data={[{x: 1, y: 1, label: "first"}]}. - * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title - */ - labels?: string[] | { (data: any): string }; + /** + * The labels prop defines labels that will appear above each bar in your chart. + * This prop should be given as an array of values or as a function of data. + * If given as an array, the number of elements in the array should be equal to + * the length of the data array. Labels may also be added directly to the data object + * like data={[{x: 1, y: 1, label: "first"}]}. + * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title + */ + labels?: string[] | { (data: any): string }; } - + interface VictorySingleLabableProps extends VictoryLabableProps { - /** - * The label prop defines the label that will appear at the edge of the area. - * This prop should be given a string or as a function of data. If individual - * labels are required for each data point, they should be created by composing - * VictoryArea with VictoryScatter - * @example: "Series 1", (data) => `${data.length} points` - */ - label?: string | { (data: any): string }; + /** + * The label prop defines the label that will appear at the edge of the area. + * This prop should be given a string or as a function of data. If individual + * labels are required for each data point, they should be created by composing + * VictoryArea with VictoryScatter + * @example: "Series 1", (data) => `${data.length} points` + */ + label?: string | { (data: any): string }; } - + export interface VictoryAreaProps extends VictoryCommonProps, VictoryDatableProps, @@ -1091,571 +1091,571 @@ declare module "victory" { */ style?: VictoryStyleInterface; } - + /** * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. * Add VictoryArea as a child of VictoryChart for a complete chart. */ export class VictoryArea extends React.Component<VictoryAreaProps, any> {} - + export interface VictoryAxisProps extends VictoryCommonProps { - /** - * The axisComponent prop takes in an entire component which will be used - * to create the axis line. The new element created from the passed axisComponent - * will be supplied with the following properties: x1, y1, x2, y2, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If an axisComponent - * is not supplied, VictoryAxis will render its default AxisLine component. - * @default <AxisLine/> - */ - axisComponent?: React.ReactElement<any>; - /** - * The axisLabelComponent prop takes in an entire component which will be used - * to create the axis label. The new element created from the passed axisLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, transform, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an axisLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - axisLabelComponent?: React.ReactElement<any>; - /** - * This prop specifies whether a given axis is intended to cross another axis. - */ - crossAxis?: boolean; - /** - * The dependentAxis prop specifies whether the axis corresponds to the - * dependent variable (usually y). This prop is useful when composing axis - * with other components to form a chart. - */ - dependentAxis?: boolean; - /** - * The domain prop describes the range of values your axis will include. This prop should be - * given as a array of the minimum and maximum expected values for your axis. - * If this value is not given it will be calculated based on the scale or tickValues. - * @examples [-1, 1] - */ - domain?: DomainPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are - * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a - * single element by index rather than an entire set. The eventHandlers object - * should be given as an object whose keys are standard event names (i.e. onClick) - * and whose values are event callbacks. The return value of an event handler - * be used to modify other elemnts. The return value should be given as an object or - * an array of objects with optional target and eventKey keys, and a mutation - * key whose value is a function. The target and eventKey keys will default to those - * corresponding to the element the event handler was attached to. The mutation - * function will be called with the calculated props for the individual selected - * element (i.e. a single tick), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "grid", - * eventKey: 2, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "tickLabels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; - /** - * When true, this prop reduces the number of tick labels to fit the length of the axis. - * Labels are removed at approximately even intervals from the original array of labels. - * This feature only works well for labels that are approximately evenly spaced. - * @default false - */ - fixLabelOverlap?: boolean; - /** - * The gridComponent prop takes in an entire component which will be used - * to create grid lines. The new element created from the passed gridComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a gridComponent - * is not supplied, VictoryAxis will render its default GridLine component. - * @default <GridLine/> - */ - gridComponent?: React.ReactElement<any>; - /** - * If true, this value will flip the domain of a given axis. - */ - invertAxis?: boolean; - /** - * The label prop defines the label that will appear along the axis. This - * prop should be given as a value or an entire, HTML-complete label - * component. If a label component is given, it will be cloned. The new - * element's properties x, y, textAnchor, verticalAnchor, and transform - * will have defaults provided by the axis; styles filled out with - * defaults provided by the axis, and overrides from the label component. - * If a value is given, a new VictoryLabel will be created with props and - * styles from the axis. - */ - label?: any; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the x-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetX?: number; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the y-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetY?: number; - /** - * The orientation prop specifies the position and orientation of your axis. - */ - orientation?: "top" | "bottom" | "left" | "right"; - /** - * The style prop defines the style of the component. The style prop should be given as an object - * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg - * styles are supported, but width, height, and padding should be specified via props as they - * determine relative layout for components in VictoryChart. Functional styles may be defined for - * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. - * - * note: When a component is rendered as a child of another Victory component, or within a custom - * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. - * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. - * - * note: custom angle and verticalAnchor properties may be included in labels styles. - */ - style?: { - parent?: React.CSSProperties; - axis?: React.CSSProperties; - axisLabel?: React.CSSProperties; - grid?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - ticks?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - tickLabels?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; + /** + * The axisComponent prop takes in an entire component which will be used + * to create the axis line. The new element created from the passed axisComponent + * will be supplied with the following properties: x1, y1, x2, y2, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If an axisComponent + * is not supplied, VictoryAxis will render its default AxisLine component. + * @default <AxisLine/> + */ + axisComponent?: React.ReactElement<any>; + /** + * The axisLabelComponent prop takes in an entire component which will be used + * to create the axis label. The new element created from the passed axisLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, transform, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an axisLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + axisLabelComponent?: React.ReactElement<any>; + /** + * This prop specifies whether a given axis is intended to cross another axis. + */ + crossAxis?: boolean; + /** + * The dependentAxis prop specifies whether the axis corresponds to the + * dependent variable (usually y). This prop is useful when composing axis + * with other components to form a chart. + */ + dependentAxis?: boolean; + /** + * The domain prop describes the range of values your axis will include. This prop should be + * given as a array of the minimum and maximum expected values for your axis. + * If this value is not given it will be calculated based on the scale or tickValues. + * @examples [-1, 1] + */ + domain?: DomainPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are + * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a + * single element by index rather than an entire set. The eventHandlers object + * should be given as an object whose keys are standard event names (i.e. onClick) + * and whose values are event callbacks. The return value of an event handler + * be used to modify other elemnts. The return value should be given as an object or + * an array of objects with optional target and eventKey keys, and a mutation + * key whose value is a function. The target and eventKey keys will default to those + * corresponding to the element the event handler was attached to. The mutation + * function will be called with the calculated props for the individual selected + * element (i.e. a single tick), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "grid", + * eventKey: 2, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "tickLabels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; + /** + * When true, this prop reduces the number of tick labels to fit the length of the axis. + * Labels are removed at approximately even intervals from the original array of labels. + * This feature only works well for labels that are approximately evenly spaced. + * @default false + */ + fixLabelOverlap?: boolean; + /** + * The gridComponent prop takes in an entire component which will be used + * to create grid lines. The new element created from the passed gridComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a gridComponent + * is not supplied, VictoryAxis will render its default GridLine component. + * @default <GridLine/> + */ + gridComponent?: React.ReactElement<any>; + /** + * If true, this value will flip the domain of a given axis. + */ + invertAxis?: boolean; + /** + * The label prop defines the label that will appear along the axis. This + * prop should be given as a value or an entire, HTML-complete label + * component. If a label component is given, it will be cloned. The new + * element's properties x, y, textAnchor, verticalAnchor, and transform + * will have defaults provided by the axis; styles filled out with + * defaults provided by the axis, and overrides from the label component. + * If a value is given, a new VictoryLabel will be created with props and + * styles from the axis. + */ + label?: any; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the x-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetX?: number; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the y-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetY?: number; + /** + * The orientation prop specifies the position and orientation of your axis. + */ + orientation?: "top" | "bottom" | "left" | "right"; + /** + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. + */ + style?: { + parent?: React.CSSProperties; + axis?: React.CSSProperties; + axisLabel?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) }; - /** - * The tickComponent prop takes in an entire component which will be used - * to create tick lines. The new element created from the passed tickComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a tickComponent - * is not supplied, VictoryAxis will render its default Tick component. - * @default <Tick/> - */ - tickComponent?: React.ReactElement<any>; - /** - * The tickCount prop specifies approximately how many ticks should be drawn on the axis if - * tickValues are not explicitly provided. This value is calculated by d3 scale and - * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. - * If you need an exact number of ticks, please specify them via the tickValues prop. - * This prop must have a value greater than zero. - * @default 5 - */ - tickCount?: number; - /** - * The tickLabelComponent prop takes in an entire component which will be used - * to create the tick labels. The new element created from the passed tickLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, tick, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an tickLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - tickLabelComponent?: React.ReactElement<any>; - /** - * The tickFormat prop specifies how tick values should be expressed visually. - * tickFormat can be given as a function to be applied to every tickValue, or as - * an array of display values for each tickValue. - * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] - */ - tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; - /** - * The tickValues prop explicitly specifies which tick values to draw on the axis. - * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] - */ - tickValues?: any[]; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + }; + /** + * The tickComponent prop takes in an entire component which will be used + * to create tick lines. The new element created from the passed tickComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a tickComponent + * is not supplied, VictoryAxis will render its default Tick component. + * @default <Tick/> + */ + tickComponent?: React.ReactElement<any>; + /** + * The tickCount prop specifies approximately how many ticks should be drawn on the axis if + * tickValues are not explicitly provided. This value is calculated by d3 scale and + * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. + * If you need an exact number of ticks, please specify them via the tickValues prop. + * This prop must have a value greater than zero. + * @default 5 + */ + tickCount?: number; + /** + * The tickLabelComponent prop takes in an entire component which will be used + * to create the tick labels. The new element created from the passed tickLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, tick, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an tickLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + tickLabelComponent?: React.ReactElement<any>; + /** + * The tickFormat prop specifies how tick values should be expressed visually. + * tickFormat can be given as a function to be applied to every tickValue, or as + * an array of display values for each tickValue. + * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] + */ + tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; + /** + * The tickValues prop explicitly specifies which tick values to draw on the axis. + * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] + */ + tickValues?: any[]; } - + /** * VictoryAxis draws an SVG chart axis with React. * Styles and data can be customized by passing in your own values as properties to the component. * Data changes are animated with VictoryAnimation. */ export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} - - export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The alignment prop specifies how bars should be aligned relative to their data points. - * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, - * bars will have “middle” alignment relative to their data points. - */ - alignment?: "start" | "middle" | "end"; - /** - * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. - * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will - * be used to calculate a default width for each bar given the total number of bars in the data series - * and the overall width of the chart. - */ - barRatio?: number; - /** - * The barWidth prop is used to specify the width of each bar. This prop may be given as - * a number of pixels or as a function that returns a number. When this prop is given as - * a function, it will be evaluated with the arguments datum, and active. When this value - * is not given, a default value will be calculated based on the overall dimensions of - * the chart, and the number of bars. - */ - barWidth?: NumberOrCallback; - /** - * The cornerRadius prop specifies a radius to apply to each bar. - * If this prop is given as a single number, the radius will only be applied to the top of each bar. - * When this prop is given as a function, it will be evaluated with the arguments datum, and active. - */ - cornerRadius?: NumberOrCallback - | { - top?: number | (NumberOrCallback), - topLeft?: number | (NumberOrCallback), - topRight?: number | (NumberOrCallback), - bottom?: number | (NumberOrCallback), - bottomLeft?: number | (NumberOrCallback), - bottomRight?: number | (NumberOrCallback) - }; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. - * The eventKey may optionally be used to select a single element by index rather than an entire - * set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your VictoryBar. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; + + export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The alignment prop specifies how bars should be aligned relative to their data points. + * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, + * bars will have “middle” alignment relative to their data points. + */ + alignment?: "start" | "middle" | "end"; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; + /** + * The cornerRadius prop specifies a radius to apply to each bar. + * If this prop is given as a single number, the radius will only be applied to the top of each bar. + * When this prop is given as a function, it will be evaluated with the arguments datum, and active. + */ + cornerRadius?: NumberOrCallback + | { + top?: number | (NumberOrCallback), + topLeft?: number | (NumberOrCallback), + topRight?: number | (NumberOrCallback), + bottom?: number | (NumberOrCallback), + bottomLeft?: number | (NumberOrCallback), + bottomRight?: number | (NumberOrCallback) + }; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. + * The eventKey may optionally be used to select a single element by index rather than an entire + * set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your VictoryBar. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; } - + /** * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes * Check out VictoryChart for complete bar charts and more. */ export class VictoryBar extends React.Component<VictoryBarProps, any> {} - - export interface VictoryBoxPlotStyleInterface - extends VictoryStyleInterface { - max?: VictoryStyleObject; - maxLabels?: VictoryStyleObject; - min?: VictoryStyleObject; - minLabels?: VictoryStyleObject; - median?: VictoryStyleObject; - medianLabels?: VictoryStyleObject; - q1?: VictoryStyleObject; - q1Labels?: VictoryStyleObject; - q3?: VictoryStyleObject; - q3Labels?: VictoryStyleObject; - } - - export interface VictoryBoxPlotProps - extends VictoryCommonProps, - VictoryDatableProps { - /** - * The boxWidth prop specifies how wide each box should be. If the whiskerWidth - * prop is not set, this prop will also determine the width of the whisker crosshair. - */ - boxWidth?: number; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The labelOrientation prop determines where labels are placed relative to their - * corresponding data. If this prop is not set, it will be set to “top” for - * horizontal charts, and “right” for vertical charts. - */ - labelOrientation?: "top" | "bottom" | "left" | "right"; - /** - * When the boolean labels prop is set to true, the values for min, max, median, - * q1, and q3 will be displayed for each box. For more granular label control, use - * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. - */ - labels?: boolean; - /** - * Use the max data accessor prop to define the max value of a box plot. - */ - max?: StringOrNumberOrCallback; - /** - * Use the median data accessor prop to define the median value of a box plot. - */ - median?: StringOrNumberOrCallback; - /** - * Use the min data accessor prop to define the min value of a box plot. - */ - min?: StringOrNumberOrCallback; - /** - * Use the q1 data accessor prop to define the q1 value of a box plot. - */ - q1?: StringOrNumberOrCallback; - /** - * Use the q3 data accessor prop to define the q1 value of a box plot. - */ - q3?: StringOrNumberOrCallback; - /** - * The style prop defines the style of the component. The style prop - * should be given as an object with styles defined for parent, max, - * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, - * q3Labels. Any valid svg styles are supported, but width, height, a - * nd padding should be specified via props as they determine relative - * layout for components in VictoryChart. Functional styles may be - * defined for style properties, and they will be evaluated with each datum. - */ - style?: VictoryBoxPlotStyleInterface; - /** - * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the - * whiskerWidth prop is not set, the width of the whisker crosshair will match - * the width of the box. - */ - whiskerWidth?: number; - } - - /** - * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for - * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), - * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. - */ - export class VictoryBoxPlot extends React.Component< - VictoryBoxPlotProps, - any - > {} - - export interface VictoryChartProps extends VictoryCommonProps { - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The style prop specifies styles for your chart. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} - */ - style?: Pick<VictoryStyleInterface, 'parent'>; - } - - /** - * A flexible charting component for React. - * VictoryChart composes other Victory components into reusable charts. - * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, - * and provides a set of sensible defaults. This component works with: - * - VictoryAxis - * - VictoryLine - * - VictoryScatter - * - VictoryBar - */ - export class VictoryChart extends React.Component<VictoryChartProps, any> {} - - export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { + + export interface VictoryBoxPlotStyleInterface + extends VictoryStyleInterface { + max?: VictoryStyleObject; + maxLabels?: VictoryStyleObject; + min?: VictoryStyleObject; + minLabels?: VictoryStyleObject; + median?: VictoryStyleObject; + medianLabels?: VictoryStyleObject; + q1?: VictoryStyleObject; + q1Labels?: VictoryStyleObject; + q3?: VictoryStyleObject; + q3Labels?: VictoryStyleObject; + } + + export interface VictoryBoxPlotProps + extends VictoryCommonProps, + VictoryDatableProps { + /** + * The boxWidth prop specifies how wide each box should be. If the whiskerWidth + * prop is not set, this prop will also determine the width of the whisker crosshair. + */ + boxWidth?: number; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The labelOrientation prop determines where labels are placed relative to their + * corresponding data. If this prop is not set, it will be set to “top” for + * horizontal charts, and “right” for vertical charts. + */ + labelOrientation?: "top" | "bottom" | "left" | "right"; + /** + * When the boolean labels prop is set to true, the values for min, max, median, + * q1, and q3 will be displayed for each box. For more granular label control, use + * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. + */ + labels?: boolean; + /** + * Use the max data accessor prop to define the max value of a box plot. + */ + max?: StringOrNumberOrCallback; + /** + * Use the median data accessor prop to define the median value of a box plot. + */ + median?: StringOrNumberOrCallback; + /** + * Use the min data accessor prop to define the min value of a box plot. + */ + min?: StringOrNumberOrCallback; + /** + * Use the q1 data accessor prop to define the q1 value of a box plot. + */ + q1?: StringOrNumberOrCallback; + /** + * Use the q3 data accessor prop to define the q1 value of a box plot. + */ + q3?: StringOrNumberOrCallback; + /** + * The style prop defines the style of the component. The style prop + * should be given as an object with styles defined for parent, max, + * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, + * q3Labels. Any valid svg styles are supported, but width, height, a + * nd padding should be specified via props as they determine relative + * layout for components in VictoryChart. Functional styles may be + * defined for style properties, and they will be evaluated with each datum. + */ + style?: VictoryBoxPlotStyleInterface; + /** + * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the + * whiskerWidth prop is not set, the width of the whisker crosshair will match + * the width of the box. + */ + whiskerWidth?: number; + } + + /** + * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for + * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), + * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. + */ + export class VictoryBoxPlot extends React.Component< + VictoryBoxPlotProps, + any + > {} + + export interface VictoryChartProps extends VictoryCommonProps { + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The style prop specifies styles for your chart. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} + */ + style?: Pick<VictoryStyleInterface, 'parent'>; + } + + /** + * A flexible charting component for React. + * VictoryChart composes other Victory components into reusable charts. + * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, + * and provides a set of sensible defaults. This component works with: + * - VictoryAxis + * - VictoryLine + * - VictoryScatter + * - VictoryBar + */ + export class VictoryChart extends React.Component<VictoryChartProps, any> {} + + export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The categories prop specifies how categorical data for a chart should be ordered. * This prop should be given as an array of string values, or an object with @@ -1731,7 +1731,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -1755,11 +1755,11 @@ declare module "victory" { * applied to all grouped children */ style?: VictoryStyleInterface; - } - - export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} - - export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + } + + export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} + + export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The event prop take an array of event objects. Event objects are composed of * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace @@ -1797,7 +1797,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** * The interpolation prop determines how data points should be connected * when plotting a line @@ -1812,13 +1812,13 @@ declare module "victory" { * The labels prop defines the labels that will appear above each point. * This prop should be given as an array or as a function of data. */ - labels?: string[]|number[]|Function; + labels?: string[]|number[]|Function; /** * Use the sortKey prop to indicate how data should be sorted. This prop * is given directly to the lodash sortBy function to be executed on the * final dataset. */ - sortKey?: string|string[]|Function; + sortKey?: string|string[]|Function; /** * The style prop specifies styles for your VictoryLine. Any valid inline style properties * will be applied. Height, width, and padding should be specified via the height, @@ -1829,15 +1829,15 @@ declare module "victory" { * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} */ style?: VictoryStyleInterface; - } - - /** - * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use line charts and more. - */ - export class VictoryLine extends React.Component<VictoryLineProps, any> {} - - export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + } + + /** + * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use line charts and more. + */ + export class VictoryLine extends React.Component<VictoryLineProps, any> {} + + export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The colorScale prop defines a color scale to be applied to each data * symbol in VictoryLegend. This prop should be given as an array of CSS @@ -1883,11 +1883,11 @@ declare module "victory" { * The data prop must be given as an array. */ data?: Array<{ - name?: string; - symbol?: { - fill?: string; - type?: string; - }; + name?: string; + symbol?: { + fill?: string; + type?: string; + }; }>; /** * The itemsPerRow prop determines how many items to render in each row @@ -1942,7 +1942,7 @@ declare module "victory" { * displaying many series of data. * @default 'vertical' */ - orientation?: 'horizontal'|'vertical'; + orientation?: 'horizontal'|'vertical'; /** * The padding prop specifies the amount of padding in pixels between * the edge of the legend and any rendered child components. This prop @@ -1953,12 +1953,12 @@ declare module "victory" { * VictoryLegend, setting padding on the child component will have no * effect. */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; /** * The standalone props specifies whether the component should be * rendered in an independent <svg> element or in a <g> tag. This prop @@ -1984,16 +1984,16 @@ declare module "victory" { */ x?: number; y?: number; - } - - /** - * VictoryLegend renders a chart legend component. - */ - export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} - - type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; - - export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + } + + /** + * VictoryLegend renders a chart legend component. + */ + export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} + + type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; + + export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { /** * The bubbleProperty prop indicates which property of the data object should be used * to scale data points in a bubble chart @@ -2039,7 +2039,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -2072,15 +2072,15 @@ declare module "victory" { * The symbol prop determines which symbol should be drawn to represent data points. */ symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; - } - - /** - * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use scatter plots and more. - */ - export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} - - export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { + } + + /** + * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use scatter plots and more. + */ + export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} + + export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The categories prop specifies how categorical data for a chart should be ordered. * This prop should be given as an array of string values, or an object with @@ -2156,7 +2156,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -2178,11 +2178,11 @@ declare module "victory" { * by the VictoryGroup component wrapper, or can be set manually. */ xOffset?: number; - } - - export class VictoryStack extends React.Component<VictoryStackProps, any> {} - - export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { + } + + export class VictoryStack extends React.Component<VictoryStackProps, any> {} + + export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The colorScale prop is an optional prop that defines the color scale the pie * will be created on. This prop should be given as an array of CSS colors, or as a string @@ -2262,7 +2262,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -2323,12 +2323,13 @@ declare module "victory" { * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) */ y?: DataGetterPropType; + } + + /** + * victory-pie draws an SVG pie or donut chart with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. + */ + export class VictoryPie extends React.Component<VictoryPieProps, any> {} } - - /** - * victory-pie draws an SVG pie or donut chart with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryPie extends React.Component<VictoryPieProps, any> {} -} + \ No newline at end of file From 54766514fa90919b8238abc6728a4edb66cf7b59 Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Wed, 6 Feb 2019 11:43:12 -0500 Subject: [PATCH 131/200] Second try and reverting bad whitespace fix --- types/victory/index.d.ts | 4313 +++++++++++++++++++------------------- 1 file changed, 2156 insertions(+), 2157 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index c3468151ba..e2f1cb8111 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -11,1054 +11,1481 @@ /// <reference types="react"/> declare module "victory" { - import * as React from "react"; - + import * as React from "react"; + + /** + * Single animation object to interpolate + */ + export type AnimationStyle = { [key: string ]: string | number }; + + /** + * Animation styles to interpolate + */ + + export type AnimationData = AnimationStyle | AnimationStyle[]; + + export type AnimationEasing = + "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | + "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | + "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | + "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | + "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | + "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; + + // Many victory components accept string or number or callback which returns string or number + type StringOrNumberOrCallback = + | string + | number + | ((datum: any, active: boolean) => string | number); + type NumberOrCallback = ((datum: any, active: boolean) => number) | number; + + type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + /** + * Style interface used in components/themeing + */ + export interface VictoryStyleInterface { + parent?: VictoryStyleObject; + data?: VictoryStyleObject; + labels?: VictoryStyleObject; + } + + export interface VictoryAnimationProps { /** - * Single animation object to interpolate + * The child of should be a function that takes an object of tweened values and returns a component to render. + * @param style */ - export type AnimationStyle = { [key: string ]: string | number }; - + children?: (style: AnimationStyle) => React.ReactElement<any>; /** - * Animation styles to interpolate + * The number of milliseconds the animation should take to complete. + * @default 1000 */ - - export type AnimationData = AnimationStyle | AnimationStyle[]; - - export type AnimationEasing = - "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | - "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | - "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | - "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | - "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | - "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; - - // Many victory components accept string or number or callback which returns string or number - type StringOrNumberOrCallback = - | string - | number - | ((datum: any, active: boolean) => string | number); - type NumberOrCallback = ((datum: any, active: boolean) => number) | number; - - type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + duration?: number; /** - * Style interface used in components/themeing + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" */ - export interface VictoryStyleInterface { - parent?: VictoryStyleObject; - data?: VictoryStyleObject; - labels?: VictoryStyleObject; - } - - export interface VictoryAnimationProps { - /** - * The child of should be a function that takes an object of tweened values and returns a component to render. - * @param style - */ - children?: (style: AnimationStyle) => React.ReactElement<any>; - /** - * The number of milliseconds the animation should take to complete. - * @default 1000 - */ - duration?: number; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - /** - * The delay prop specifies a delay in milliseconds before the animation begins. - * If multiple values are in the animation queue, it is the delay between each animation. - * @default 0 - */ - delay?: number; - /** - * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. - */ - onEnd?: () => void; - /** - * The data prop specifies the latest set of values to tween to. - * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. - * When given an array of values, VictoryAnimation will use it as an animation queue. - * @default {} - */ - data?: AnimationData; - } - + easing?: AnimationEasing; /** - * VictoryAnimation animates prop changes for any React component. - * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. + * The delay prop specifies a delay in milliseconds before the animation begins. + * If multiple values are in the animation queue, it is the delay between each animation. + * @default 0 */ - export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} - + delay?: number; /** - * Text anchor type + * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. */ - type TextAnchorType = "start" | "middle" | "end" | "inherit"; - + onEnd?: () => void; /** - * Vertical anchor type + * The data prop specifies the latest set of values to tween to. + * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. + * When given an array of values, VictoryAnimation will use it as an animation queue. + * @default {} */ - type VerticalAnchorType = "start" | "middle" | "end"; - - export interface VictoryLabelProps { - /** - * Specifies the angle to rotate the text by. - */ - angle?: string | number; - /** - * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. - * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. - * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. - * @default "0.71em" - */ - capHeight?: StringOrNumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text - */ - datum?: {}; - /** - * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. - */ - data?: any[]; - /** - * The events prop attaches arbitrary event handlers to the label component. - * Event handlers are currently only called with their corresponding events. - */ - events?: React.DOMAttributes<any>; - /** - * The children of this component define the content of the label. - * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. - */ - children?: StringOrNumberOrCallback; - /** - * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. - * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar - * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. - * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label - * placement will be used for cartesian charts. - */ - labelPlacement?: "parallel" | "perpendicular" | "vertical"; - /** - * The lineHeight prop defines how much space a single line of text should take up. - * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, - * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. - * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. - * If given a unitless number, it is assumed to be ems. - * @default 1 - */ - lineHeight?: StringOrNumberOrCallback; - /** - * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. - * **This prop should not be set manually.** - */ - origin?: { x: number, y: number }; - /** - * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. - * **This prop should not be set manually.** - */ - polar?: boolean; - /** - * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. - * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, - * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate - * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. - */ - text?: string[] | StringOrNumberOrCallback; - /** - * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. - */ - textAnchor?: TextAnchorType | { (): TextAnchorType }; - /** - * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. - */ - verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; - /** - * The transform prop applies a transform to the rendered `<text>` element. - * In addition to being a string, it can be an object containing transform definitions for easier authoring. - */ - transform?: string | {} | { (): string | {} }; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - /** - * The dx prop defines a horizontal shift from the `x` coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the `y` coordinate. - * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. - */ - dy?: StringOrNumberOrCallback; - } - + data?: AnimationData; + } + + /** + * VictoryAnimation animates prop changes for any React component. + * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. + */ + export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} + + /** + * Text anchor type + */ + type TextAnchorType = "start" | "middle" | "end" | "inherit"; + + /** + * Vertical anchor type + */ + type VerticalAnchorType = "start" | "middle" | "end"; + + export interface VictoryLabelProps { /** - * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. + * Specifies the angle to rotate the text by. */ - export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} - - export interface VictoryContainerProps { - /** - * The responsive prop specifies whether the rendered container should be a responsive container - * with a viewBox attribute, or a static container with absolute width and height. - * @default true - */ - responsive?: boolean; - /** - * The style prop specifies styles for your VictoryContainer. Any valid inline style properties - * will be applied. Height and width should be specified via the height - * and width props, as they are used to calculate the alignment of - * components within the container. Styles from the child component will - * also be passed, if any exist. - * @examples {border: 1px solid red} - */ - style?: React.CSSProperties; - /** - * The height props specifies the height the svg viewBox of the container. - * This value should be given as a number of pixels. If no height prop - * is given, the height prop from the child component passed will be used. - */ - height?: number; - /** - * The width props specifies the width of the svg viewBox of the container - * This value should be given as a number of pixels. If no width prop - * is given, the width prop from the child component passed will be used. - */ - width?: number; - /** - * The events prop attaches arbitrary event handlers to the container component. - * Event handlers passed from other Victory components are called with their - * corresponding events as well as scale, style, width, height, and data when - * applicable. Use the invert method to convert event coordinate information to - * data. `scale.x.invert(evt.offsetX)`. - * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} - */ - events?: React.DOMAttributes<any>; - /** - * The title prop specifies the title to be applied to the SVG to assist - * accessibility for screen readers. The more descriptive this title is, the more - * useful it will be. If no title prop is passed, it will default to Victory Chart. - * @example "Popularity of Dog Breeds by Percentage" - * @default "Victory Chart" - */ - title?: string; - /** - * The desc prop specifies the description of the chart/SVG to assist with - * accessibility for screen readers. The more info about the chart provided in - * the description, the more usable it will be for people using screen readers. - * This prop defaults to an empty string. - * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are - * not represented above 5% each." - * @default "" - */ - desc?: string; - } - - export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} - - type CursorData = { - x: number; - y: number; + angle?: string | number; + /** + * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. + * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. + * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. + * @default "0.71em" + */ + capHeight?: StringOrNumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text + */ + datum?: {}; + /** + * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. + */ + data?: any[]; + /** + * The events prop attaches arbitrary event handlers to the label component. + * Event handlers are currently only called with their corresponding events. + */ + events?: React.DOMAttributes<any>; + /** + * The children of this component define the content of the label. + * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. + */ + children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; + /** + * The lineHeight prop defines how much space a single line of text should take up. + * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, + * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. + * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. + * If given a unitless number, it is assumed to be ems. + * @default 1 + */ + lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ + origin?: { x: number, y: number }; + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; + /** + * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. + */ + textAnchor?: TextAnchorType | { (): TextAnchorType }; + /** + * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. + */ + verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; + /** + * The transform prop applies a transform to the rendered `<text>` element. + * In addition to being a string, it can be an object containing transform definitions for easier authoring. + */ + transform?: string | {} | { (): string | {} }; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + /** + * The dx prop defines a horizontal shift from the `x` coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the `y` coordinate. + * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. + */ + dy?: StringOrNumberOrCallback; + } + + /** + * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. + */ + export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} + + export interface VictoryContainerProps { + /** + * The responsive prop specifies whether the rendered container should be a responsive container + * with a viewBox attribute, or a static container with absolute width and height. + * @default true + */ + responsive?: boolean; + /** + * The style prop specifies styles for your VictoryContainer. Any valid inline style properties + * will be applied. Height and width should be specified via the height + * and width props, as they are used to calculate the alignment of + * components within the container. Styles from the child component will + * also be passed, if any exist. + * @examples {border: 1px solid red} + */ + style?: React.CSSProperties; + /** + * The height props specifies the height the svg viewBox of the container. + * This value should be given as a number of pixels. If no height prop + * is given, the height prop from the child component passed will be used. + */ + height?: number; + /** + * The width props specifies the width of the svg viewBox of the container + * This value should be given as a number of pixels. If no width prop + * is given, the width prop from the child component passed will be used. + */ + width?: number; + /** + * The events prop attaches arbitrary event handlers to the container component. + * Event handlers passed from other Victory components are called with their + * corresponding events as well as scale, style, width, height, and data when + * applicable. Use the invert method to convert event coordinate information to + * data. `scale.x.invert(evt.offsetX)`. + * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} + */ + events?: React.DOMAttributes<any>; + /** + * The title prop specifies the title to be applied to the SVG to assist + * accessibility for screen readers. The more descriptive this title is, the more + * useful it will be. If no title prop is passed, it will default to Victory Chart. + * @example "Popularity of Dog Breeds by Percentage" + * @default "Victory Chart" + */ + title?: string; + /** + * The desc prop specifies the description of the chart/SVG to assist with + * accessibility for screen readers. The more info about the chart provided in + * the description, the more usable it will be for people using screen readers. + * This prop defaults to an empty string. + * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are + * not represented above 5% each." + * @default "" + */ + desc?: string; + } + + export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} + + type CursorData = { + x: number; + y: number; + }; + + export interface VictoryCursorContainerProps extends VictoryContainerProps { + /** + * The cursorComponent prop takes a component instance which will be used to render a cursor element. + * The new element created will be supplied with x1, y1, x2 and y2 positioning props. + * If a cursorComponent is not supplied, a new Line component will be rendered. + * @default cursorComponent={<Line/>} + */ + cursorComponent?: React.ReactElement<any>; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example cursorDimension="x" + */ + cursorDimension?: 'x' | 'y'; + /** + * The cursorLabel prop defines the label that will appear next to the cursor. + * A label will only appear if cursorLabel is set. This prop should be given as a + * function of a point (an Object with x and y properties). + * @example cursorLabel={(point) => point.x} + */ + cursorLabel?: (point: CursorData) => void; + /** + * The cursorLabelComponent prop takes a component instance which will be + * used to render a label for the cursor. The new element created from the passed + * cursorLabelComponent will be supplied with the following props: x, y, + * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. + * @default cursorLabelComponent={<VictoryLabel/>} + */ + cursorLabelComponent?: React.ReactElement<any>; + /** + * The cursorLabelOffset prop determines the pixel offset of the cursor label + * from the cursor point. This prop should be an Object with x and y properties, or a + * number to be used for both dimensions. + * @default "{ x: 5, y: -10 }" + */ + cursorLabelOffset?: number | CursorData; + /** + * Whenever the mouse is not over the chart, the cursor will not be displayed. + * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. + * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. + * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} + */ + defaultCursorValue?: number | CursorData; + /** + * When the disable prop is set to true, VictoryCursorContainer events will not fire. + */ + disable?: boolean; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example onChange={(value, props) => this.setState({cursorValue: value})} + */ + onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; + } + + export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} + + export interface VictoryBrushContainerProps extends VictoryContainerProps { + /** + * The optional allowDrag prop accepts a boolean that enables dragging behavior + * for the highlighted brush area. Resizing will still be enabled when the allowDrag + * prop is set to false. + * @default true + */ + allowDrag?: boolean; + /** + * The optional allowResize prop accepts a boolean that enables resizing the + * highlighted brush area. Dragging will still be enabled when the allowResize + * prop is set to false, but the dimensions of the brush area will be fixed. + * @default true + */ + allowResize?: boolean; + /** + * The brushComponent prop specifies the component to be rendered for the + * highlighted area. This component will be supplied with the following props: x, y, + * width, height, and style. When this prop is not specified, a <rect/> will be rendered. + * @default brushComponent={<rect/>} + */ + brushComponent?: React.ReactElement<any>; + /** + * When the brushDimension prop is set, brushing will only be specific to the to + * the given dimension (either "x" or "y"), and the entire domain of the other + * dimension will be highlighted. When this prop is not specified, highlighting will + * occur along both dimensions. + * @example brushDimension="x" + */ + brushDimension?: 'x' | 'y'; + /** + * The optional brushDomain prop describes the highlighted state. This prop is an + * object that specifies separate arrays for x and y. Each array is a tuple that + * describes the minimum and maximum values to render. If this prop is not provided + * initially, the chart will render with the entire domain highlighted. When this prop + * changes, the chart will render with a new highlighted domain. + * @example brushDomain={{ x: [50, 100], y: [0, 100] }} + */ + brushDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ + defaultBrushArea?: 'all' | 'none' | 'disable'; + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * The handleComponent prop specifies the component to be rendered for each + * handle for the highlighted area. This component will be supplied with the following + * props: x, y, width, height, cursor, and style. When this prop is not + * specified, a <rect/> will be rendered. + * @default handleComponent={<rect/>} + */ + handleComponent?: React.ReactElement<any>; + /** + * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. + * + * Handles refer to the region on each highlighted area where the area may be + * expanded. Only handles relevant to the given dimension will be rendered. For + * example, when brushDimension="x" only "left" and "right" handles will be + * rendered. Handles are automatically styled with cursors appropriate to their orientation. + * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" + */ + handleStyle?: React.CSSProperties; + /** + * The optional onBrushDomainChange prop accepts an function to be called on + * each update to the highlighted domain. The function accepts the parameters of + * domain (the updated domain), and props (the props used by VictoryBrushContainer). + * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ + onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; + } + + export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} + + export interface VictoryZoomContainerProps extends VictoryContainerProps { + /** + * The optional allowPan prop accepts a boolean that enables the panning + * functionality. Zooming will still be enabled when the allowPan prop is set to false. + * @default true + */ + allowPan?: boolean; + /** + * The optional allowZoom prop accepts a boolean that enables the zoom + * functionality. Panning will still be enabled when the allowZoom prop is set to false. + * @default true + */ + allowZoom?: boolean; + /** + * VictoryZoomContainer works by clipping data outside of a given domain. + * VictoryZoomContainer uses VictoryClipContainer by default. + * This prop should not be replaced with a custom component, but you may want to set + * props on VictoryClipContainer, such as clipPadding. + * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} + */ + clipContainerComponent?: React.ReactElement<any>; + /** + * When the zoomDimension prop is set, panning and zooming will be restricted to + * the given dimension (either x or y), and the domain of the other dimension will + * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. + * @example zoomDimension="x" + */ + zoomDimension?: 'x' | 'y'; + /** + * The zoomDomain prop describes the zoomed state. This prop is an object that + * specifies separate arrays for x and y. Each array is a tuple that describes the + * minimum and maximum values to render. If this prop is not provided initially, the + * chart will render without an initial zoom, displaying the entire dataset. Updates to + * zoomDomain will trigger a re-render of the chart with the new domain. + * @example zoomDomain={{x: [0, 100]}} + */ + zoomDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ + defaultBrushArea?: 'all' | 'none' | 'disable'; + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * When the disable prop is set to true, VictoryZoomContainer events will not fire. + */ + downsample?: number | boolean; + /** + * The minimumZoom prop sets a minimum domain extent for the zoomed chart. + * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom + * in either dimension, the component will stop responding to events that would normally trigger zooming in. + * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum + * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object + * with numeric values for x and y. + * @example minimumZoom={{x: 1, y: 0.01}} + */ + minimumZoom?: CursorData; + /** + * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. + * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). + * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ + onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; + } + + export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} + + // Note: Many SVG attributes are missed in CSSProperties interface + export interface VictoryThemeDefinition { + area?: VictoryStyleInterface; + axis?: { + axis: React.CSSProperties; + axisLabel: React.CSSProperties; + grid: React.CSSProperties; + ticks: React.CSSProperties; + tickLabels: React.CSSProperties; }; - - export interface VictoryCursorContainerProps extends VictoryContainerProps { - /** - * The cursorComponent prop takes a component instance which will be used to render a cursor element. - * The new element created will be supplied with x1, y1, x2 and y2 positioning props. - * If a cursorComponent is not supplied, a new Line component will be rendered. - * @default cursorComponent={<Line/>} - */ - cursorComponent?: React.ReactElement<any>; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example cursorDimension="x" - */ - cursorDimension?: 'x' | 'y'; - /** - * The cursorLabel prop defines the label that will appear next to the cursor. - * A label will only appear if cursorLabel is set. This prop should be given as a - * function of a point (an Object with x and y properties). - * @example cursorLabel={(point) => point.x} - */ - cursorLabel?: (point: CursorData) => void; - /** - * The cursorLabelComponent prop takes a component instance which will be - * used to render a label for the cursor. The new element created from the passed - * cursorLabelComponent will be supplied with the following props: x, y, - * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. - * @default cursorLabelComponent={<VictoryLabel/>} - */ - cursorLabelComponent?: React.ReactElement<any>; - /** - * The cursorLabelOffset prop determines the pixel offset of the cursor label - * from the cursor point. This prop should be an Object with x and y properties, or a - * number to be used for both dimensions. - * @default "{ x: 5, y: -10 }" - */ - cursorLabelOffset?: number | CursorData; - /** - * Whenever the mouse is not over the chart, the cursor will not be displayed. - * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. - * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. - * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} - */ - defaultCursorValue?: number | CursorData; - /** - * When the disable prop is set to true, VictoryCursorContainer events will not fire. - */ - disable?: boolean; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example onChange={(value, props) => this.setState({cursorValue: value})} - */ - onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; - } - - export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} - - export interface VictoryBrushContainerProps extends VictoryContainerProps { - /** - * The optional allowDrag prop accepts a boolean that enables dragging behavior - * for the highlighted brush area. Resizing will still be enabled when the allowDrag - * prop is set to false. - * @default true - */ - allowDrag?: boolean; - /** - * The optional allowResize prop accepts a boolean that enables resizing the - * highlighted brush area. Dragging will still be enabled when the allowResize - * prop is set to false, but the dimensions of the brush area will be fixed. - * @default true - */ - allowResize?: boolean; - /** - * The brushComponent prop specifies the component to be rendered for the - * highlighted area. This component will be supplied with the following props: x, y, - * width, height, and style. When this prop is not specified, a <rect/> will be rendered. - * @default brushComponent={<rect/>} - */ - brushComponent?: React.ReactElement<any>; - /** - * When the brushDimension prop is set, brushing will only be specific to the to - * the given dimension (either "x" or "y"), and the entire domain of the other - * dimension will be highlighted. When this prop is not specified, highlighting will - * occur along both dimensions. - * @example brushDimension="x" - */ - brushDimension?: 'x' | 'y'; - /** - * The optional brushDomain prop describes the highlighted state. This prop is an - * object that specifies separate arrays for x and y. Each array is a tuple that - * describes the minimum and maximum values to render. If this prop is not provided - * initially, the chart will render with the entire domain highlighted. When this prop - * changes, the chart will render with a new highlighted domain. - * @example brushDomain={{ x: [50, 100], y: [0, 100] }} - */ - brushDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ - defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * The handleComponent prop specifies the component to be rendered for each - * handle for the highlighted area. This component will be supplied with the following - * props: x, y, width, height, cursor, and style. When this prop is not - * specified, a <rect/> will be rendered. - * @default handleComponent={<rect/>} - */ - handleComponent?: React.ReactElement<any>; - /** - * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. - * - * Handles refer to the region on each highlighted area where the area may be - * expanded. Only handles relevant to the given dimension will be rendered. For - * example, when brushDimension="x" only "left" and "right" handles will be - * rendered. Handles are automatically styled with cursors appropriate to their orientation. - * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" - */ - handleStyle?: React.CSSProperties; - /** - * The optional onBrushDomainChange prop accepts an function to be called on - * each update to the highlighted domain. The function accepts the parameters of - * domain (the updated domain), and props (the props used by VictoryBrushContainer). - * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ - onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; - } - - export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} - - export interface VictoryZoomContainerProps extends VictoryContainerProps { - /** - * The optional allowPan prop accepts a boolean that enables the panning - * functionality. Zooming will still be enabled when the allowPan prop is set to false. - * @default true - */ - allowPan?: boolean; - /** - * The optional allowZoom prop accepts a boolean that enables the zoom - * functionality. Panning will still be enabled when the allowZoom prop is set to false. - * @default true - */ - allowZoom?: boolean; - /** - * VictoryZoomContainer works by clipping data outside of a given domain. - * VictoryZoomContainer uses VictoryClipContainer by default. - * This prop should not be replaced with a custom component, but you may want to set - * props on VictoryClipContainer, such as clipPadding. - * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} - */ - clipContainerComponent?: React.ReactElement<any>; - /** - * When the zoomDimension prop is set, panning and zooming will be restricted to - * the given dimension (either x or y), and the domain of the other dimension will - * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. - * @example zoomDimension="x" - */ - zoomDimension?: 'x' | 'y'; - /** - * The zoomDomain prop describes the zoomed state. This prop is an object that - * specifies separate arrays for x and y. Each array is a tuple that describes the - * minimum and maximum values to render. If this prop is not provided initially, the - * chart will render without an initial zoom, displaying the entire dataset. Updates to - * zoomDomain will trigger a re-render of the chart with the new domain. - * @example zoomDomain={{x: [0, 100]}} - */ - zoomDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ - defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * When the disable prop is set to true, VictoryZoomContainer events will not fire. - */ - downsample?: number | boolean; - /** - * The minimumZoom prop sets a minimum domain extent for the zoomed chart. - * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom - * in either dimension, the component will stop responding to events that would normally trigger zooming in. - * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum - * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object - * with numeric values for x and y. - * @example minimumZoom={{x: 1, y: 0.01}} - */ - minimumZoom?: CursorData; - /** - * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. - * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). - * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ - onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; - } - - export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} - - // Note: Many SVG attributes are missed in CSSProperties interface - export interface VictoryThemeDefinition { - area?: VictoryStyleInterface; - axis?: { - axis: React.CSSProperties; - axisLabel: React.CSSProperties; - grid: React.CSSProperties; - ticks: React.CSSProperties; - tickLabels: React.CSSProperties; - }; - bar?: VictoryStyleInterface; - candlestick?: VictoryStyleInterface & { - props: { - width: number; - height: number; - candleColors: { - positive: string; - negative: string; - }; + bar?: VictoryStyleInterface; + candlestick?: VictoryStyleInterface & { + props: { + width: number; + height: number; + candleColors: { + positive: string; + negative: string; }; }; - line?: VictoryStyleInterface; - pie?: { - props: { - width: number; - height: number; - colorScale: string[]; - }; - style: VictoryStyleInterface; - }; - scatter?: VictoryStyleInterface; - props?: { + }; + line?: VictoryStyleInterface; + pie?: { + props: { width: number; height: number; colorScale: string[]; }; - } - - interface VictoryThemeInterface { - /** - * Default theme - */ - grayscale: VictoryThemeDefinition; - material: VictoryThemeDefinition; - } - - /** - * Available themes - */ - export const VictoryTheme: VictoryThemeInterface; - - type OrientationTypes = "top" | "bottom" | "left" | "right"; - - export interface VictoryTooltipProps { - /** - * The active prop specifies whether the tooltip component should be displayed. - */ - active?: boolean; - /** - * When true, tooltip events will set the active prop on both data and label elements. - * @default false - */ - activateData?: boolean; - /** - * The angle prop specifies the angle to rotate the tooltip around its origin point. - */ - angle?: string | number; - /** - * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. - */ - cornerRadius?: NumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. - */ - datum?: {}; - /** - * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. - */ - data?: any[]; - /** - * The dx prop defines a horizontal shift from the x coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the y coordinate. - */ - dy?: StringOrNumberOrCallback; - /** - * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. - * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. - * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} - */ - events?: {}; - /** - * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. - */ - flyoutStyle?: VictoryStyleObject; - /** - * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. - * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, - * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If flyoutComponent is omitted, a default Flyout component will be created with props described above. - * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} - * @default <Flyout/> - */ - flyoutComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. - * @default groupComponent={<g/>} - */ - groupComponent?: React.ReactElement<any>; - /** - * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - height?: NumberOrCallback; - /** - * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. - * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. - * negative values result in a left orientation and positive values will result in a right orientation by default. - */ - horizontal?: boolean; - /** - * The index prop represents the index of the datum in the data array. - */ - index?: number | string; - /** - * The labelComponent prop takes a component instance which will be used to render each tooltip label. - * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. - * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. - * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. - * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. - */ - orientation?: OrientationTypes; - /** - * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerLength?: NumberOrCallback; - /** - * The pointerWidth prop determines the width of the base of the triangular pointer extending from - * the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerWidth?: NumberOrCallback; - /** - * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element - * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. - * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. - */ - text?: StringOrNumberOrCallback | string[] | number[]; - /** - * VictoryAxis uses the standard theme prop. Read about it here - * @default VictoryTheme.grayscale - */ - theme?: VictoryThemeDefinition; - /** - * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - width?: NumberOrCallback; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - } - - /** - * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label - * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. - * VictoryTooltip renders text as well as a configurable Flyout container. - */ - export class VictoryTooltip extends React.Component< - VictoryTooltipProps, - any - > {} - - /** - * Animate object used in components - */ - export interface AnimatePropTypeInterface { - /** - * Animation duration - */ - duration: number; - /** - * Animation end callback - */ - onEnd?: () => void; - /** - * Animation exit transition configuration - */ - onExit?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - }; - /** - * Animation enter transition configuration - */ - onEnter?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * Animation load transition configuration - */ - onLoad?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - } - - /** - * Return value for eventHandlers values - */ - interface EventCallbackInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - target?: TTarget; - eventKey?: TEventKey; - /** - * Will be called with the calculated props for the individual selected element and result will override - * props of selected element via object assignment - * @param props - */ - mutation: (props: any) => any; - } - - export interface EventPropTypeInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - /** - * Targets may be any valid style namespace for a given component - */ - target: TTarget; - - eventKey?: TEventKey; - /** - * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks - */ - eventHandlers: { - [key: string]: { - (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | - { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] - } - }; - } - - /** - * Data domain type - */ - type DomainTuple = [number, number] | [Date, Date]; - - type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; - - /** - * Domain padding - */ - type DomainPaddingPropType = number | { - x?: number | [ number, number]; - y?: number | [ number, number]; + style: VictoryStyleInterface; }; - - /** - * D3 scale function shape. Don't want to introduce typing dependency to d3 - */ - interface D3Scale { - domain: () => any; - range: () => any; - copy: () => any; - } - - /** - * Acceptable scale types - */ - type ScalePropType = "linear" | "time" | "log" | "sqrt"; - - /** - * Category prop type - */ - type CategoryPropType = string[] | { - x: string[] - y: string[] + scatter?: VictoryStyleInterface; + props?: { + width: number; + height: number; + colorScale: string[]; }; - + } + + interface VictoryThemeInterface { /** - * Data getter property type + * Default theme */ - type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; - - type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | - "cardinal" | "cardinalClosed" | "cardinalOpen" | - "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | - "linear" | "linearClosed" | "monotoneX" | "monotoneY" | - "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; - - type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; - + grayscale: VictoryThemeDefinition; + material: VictoryThemeDefinition; + } + + /** + * Available themes + */ + export const VictoryTheme: VictoryThemeInterface; + + type OrientationTypes = "top" | "bottom" | "left" | "right"; + + export interface VictoryTooltipProps { /** - * Common properties + * The active prop specifies whether the tooltip component should be displayed. */ - interface VictoryCommonProps { + active?: boolean; + /** + * When true, tooltip events will set the active prop on both data and label elements. + * @default false + */ + activateData?: boolean; + /** + * The angle prop specifies the angle to rotate the tooltip around its origin point. + */ + angle?: string | number; + /** + * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. + */ + cornerRadius?: NumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. + */ + datum?: {}; + /** + * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. + */ + data?: any[]; + /** + * The dx prop defines a horizontal shift from the x coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the y coordinate. + */ + dy?: StringOrNumberOrCallback; + /** + * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. + * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. + * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} + */ + events?: {}; + /** + * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. + */ + flyoutStyle?: VictoryStyleObject; + /** + * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. + * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, + * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If flyoutComponent is omitted, a default Flyout component will be created with props described above. + * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} + * @default <Flyout/> + */ + flyoutComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. + * @default groupComponent={<g/>} + */ + groupComponent?: React.ReactElement<any>; + /** + * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + height?: NumberOrCallback; + /** + * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. + * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. + * negative values result in a left orientation and positive values will result in a right orientation by default. + */ + horizontal?: boolean; + /** + * The index prop represents the index of the datum in the data array. + */ + index?: number | string; + /** + * The labelComponent prop takes a component instance which will be used to render each tooltip label. + * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. + * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. + * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. + * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. + */ + orientation?: OrientationTypes; + /** + * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerLength?: NumberOrCallback; + /** + * The pointerWidth prop determines the width of the base of the triangular pointer extending from + * the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerWidth?: NumberOrCallback; + /** + * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element + * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. + * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. + */ + text?: StringOrNumberOrCallback | string[] | number[]; + /** + * VictoryAxis uses the standard theme prop. Read about it here + * @default VictoryTheme.grayscale + */ + theme?: VictoryThemeDefinition; + /** + * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + width?: NumberOrCallback; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + } + + /** + * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label + * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. + * VictoryTooltip renders text as well as a configurable Flyout container. + */ + export class VictoryTooltip extends React.Component< + VictoryTooltipProps, + any + > {} + + /** + * Animate object used in components + */ + export interface AnimatePropTypeInterface { + /** + * Animation duration + */ + duration: number; + /** + * Animation end callback + */ + onEnd?: () => void; + /** + * Animation exit transition configuration + */ + onExit?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + }; + /** + * Animation enter transition configuration + */ + onEnter?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * Animation load transition configuration + */ + onLoad?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + } + + /** + * Return value for eventHandlers values + */ + interface EventCallbackInterface<TTarget, TEventKey> { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + target?: TTarget; + eventKey?: TEventKey; + /** + * Will be called with the calculated props for the individual selected element and result will override + * props of selected element via object assignment + * @param props + */ + mutation: (props: any) => any; + } + + export interface EventPropTypeInterface<TTarget, TEventKey> { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + /** + * Targets may be any valid style namespace for a given component + */ + target: TTarget; + + eventKey?: TEventKey; + /** + * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks + */ + eventHandlers: { + [key: string]: { + (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | + { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] + } + }; + } + + /** + * Data domain type + */ + type DomainTuple = [number, number] | [Date, Date]; + + type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; + + /** + * Domain padding + */ + type DomainPaddingPropType = number | { + x?: number | [ number, number]; + y?: number | [ number, number]; + }; + + /** + * D3 scale function shape. Don't want to introduce typing dependency to d3 + */ + interface D3Scale { + domain: () => any; + range: () => any; + copy: () => any; + } + + /** + * Acceptable scale types + */ + type ScalePropType = "linear" | "time" | "log" | "sqrt"; + + /** + * Category prop type + */ + type CategoryPropType = string[] | { + x: string[] + y: string[] + }; + + /** + * Data getter property type + */ + type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; + + type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | + "cardinal" | "cardinalClosed" | "cardinalOpen" | + "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | + "linear" | "linearClosed" | "monotoneX" | "monotoneY" | + "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; + + type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; + + /** + * Common properties + */ + interface VictoryCommonProps { + /** + * The animate prop specifies props for VictoryAnimation to use. + * The animate prop should also be used to specify enter and exit + * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * @example + * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + */ + animate?: AnimatePropTypeInterface; + /** + * The name prop is used to reference a component instance when defining shared events. + */ + name?: string; + /** + * The height props specifies the height the svg viewBox of the chart container. + * This value should be given as a number of pixels + */ + height?: number; + /** + * The padding props specifies the amount of padding in number of pixels between + * the edge of the chart and any rendered child components. This prop can be given + * as a number or as an object with padding specified for top, bottom, left + * and right. + * @default 50 + */ + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The scale prop determines which scales your chart should use. This prop can be + * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), + * as a d3 scale function, or as an object with scales specified for x and y + * @example d3Scale.time(), {x: "linear", y: "log"} + * @default "linear" + */ + scale?: ScalePropType | D3Scale | { + x?: ScalePropType | D3Scale; + y?: ScalePropType | D3Scale; + }; + /** + * The standalone prop determines whether the component will render a standalone svg + * or a <g> tag that will be included in an external svg. Set standalone to false to + * compose VictoryAxis with other components within an enclosing <svg> tag. + * @default true + */ + standalone?: boolean; + /** + * The width props specifies the width of the svg viewBox of the chart container + * This value should be given as a number of pixels + */ + width?: number; + /** + * The containerComponent prop takes an entire component which will be used to + * create a container element for standalone charts. + * The new element created from the passed containerComponent wil be provided with + * these props from VictoryArea: height, width, children + * (the chart itself) and style. Props that are not provided by the + * child chart component include title and desc, both of which + * are intended to add accessibility to Victory components. The more descriptive these props + * are, the more accessible your data will be for people using screen readers. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use the default VictoryContainer component. + * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * The theme prop takes a style object with nested data, labels, and parent objects. + * You can create this object yourself, or you can use a theme provided by Victory. + * When using VictoryArea as a solo component, implement the theme directly on + * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or + * VictoryGroup, please call the theme on the outermost wrapper component instead. + * @example theme={VictoryTheme.material} + * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js + */ + theme?: VictoryThemeDefinition; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; + } + + /** + * Common properties for all data components + */ + interface VictoryDatableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these arrays of values specified for x and y. If this prop is not set, + * categorical data will be plotted in the order it was given in the data array + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The data prop specifies the data to be plotted. Data should be in the form of an array + * of data points, or an array of arrays of data points for multiple datasets. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire component which will be used to create an area. + * The new element created from the passed dataComponent will be provided with the + * following properties calculated by VictoryArea: a scale, style, events, interpolation, + * and an array of modified data objects (including x, y, and calculated y0 and y1). + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use its default Area component. + * @default <Area/> + */ + dataComponent?: React.ReactElement<any>; + /** + * The domain prop describes the range of values your chart will cover. This prop can be + * given as a array of the minimum and maximum expected values for your bar chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + * @default "x" + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + * @default "y" + */ + y?: DataGetterPropType; + } + + // Common labable interface + interface VictoryLabableProps { + /** + * The labelComponent prop takes in an entire label component which will be used + * to create a label for the area. The new element created from the passed labelComponent + * will be supplied with the following properties: x, y, index, data, verticalAnchor, + * textAnchor, angle, style, text, and events. any of these props may be overridden + * by passing in props to the supplied component, or modified or ignored within + * the custom component itself. If labelComponent is omitted, a new VictoryLabel + * will be created with props described above. This labelComponent prop should be used to + * provide a series label for VictoryArea. If individual labels are required for each + * data point, they should be created by composing VictoryArea with VictoryScatter + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + } + + interface VictoryMultiLabeableProps extends VictoryLabableProps { + /** + * The labels prop defines labels that will appear above each bar in your chart. + * This prop should be given as an array of values or as a function of data. + * If given as an array, the number of elements in the array should be equal to + * the length of the data array. Labels may also be added directly to the data object + * like data={[{x: 1, y: 1, label: "first"}]}. + * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title + */ + labels?: string[] | { (data: any): string }; + } + + interface VictorySingleLabableProps extends VictoryLabableProps { + /** + * The label prop defines the label that will appear at the edge of the area. + * This prop should be given a string or as a function of data. If individual + * labels are required for each data point, they should be created by composing + * VictoryArea with VictoryScatter + * @example: "Series 1", (data) => `${data.length} points` + */ + label?: string | { (data: any): string }; + } + + export interface VictoryAreaProps + extends VictoryCommonProps, + VictoryDatableProps, + VictorySingleLabableProps { /** - * The animate prop specifies props for VictoryAnimation to use. - * The animate prop should also be used to specify enter and exit - * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. + * Since VictoryArea only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. an area), and the object returned from the mutation function + * will override the props of the selected element via object assignment. * @example - * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} */ - animate?: AnimatePropTypeInterface; + events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; /** - * The name prop is used to reference a component instance when defining shared events. - */ - name?: string; - /** - * The height props specifies the height the svg viewBox of the chart container. - * This value should be given as a number of pixels - */ - height?: number; - /** - * The padding props specifies the amount of padding in number of pixels between - * the edge of the chart and any rendered child components. This prop can be given - * as a number or as an object with padding specified for top, bottom, left - * and right. - * @default 50 - */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The scale prop determines which scales your chart should use. This prop can be - * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), - * as a d3 scale function, or as an object with scales specified for x and y - * @example d3Scale.time(), {x: "linear", y: "log"} + * The interpolation prop determines how data points should be connected when plotting a line * @default "linear" */ - scale?: ScalePropType | D3Scale | { - x?: ScalePropType | D3Scale; - y?: ScalePropType | D3Scale; - }; + interpolation?: InterpolationPropType; /** - * The standalone prop determines whether the component will render a standalone svg - * or a <g> tag that will be included in an external svg. Set standalone to false to - * compose VictoryAxis with other components within an enclosing <svg> tag. - * @default true + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + * @default 50 */ - standalone?: boolean; + samples?: number; /** - * The width props specifies the width of the svg viewBox of the chart container - * This value should be given as a number of pixels + * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} */ - width?: number; - /** - * The containerComponent prop takes an entire component which will be used to - * create a container element for standalone charts. - * The new element created from the passed containerComponent wil be provided with - * these props from VictoryArea: height, width, children - * (the chart itself) and style. Props that are not provided by the - * child chart component include title and desc, both of which - * are intended to add accessibility to Victory components. The more descriptive these props - * are, the more accessible your data will be for people using screen readers. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use the default VictoryContainer component. - * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * The theme prop takes a style object with nested data, labels, and parent objects. - * You can create this object yourself, or you can use a theme provided by Victory. - * When using VictoryArea as a solo component, implement the theme directly on - * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or - * VictoryGroup, please call the theme on the outermost wrapper component instead. - * @example theme={VictoryTheme.material} - * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js - */ - theme?: VictoryThemeDefinition; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; - } - + style?: VictoryStyleInterface; + } + + /** + * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. + * Add VictoryArea as a child of VictoryChart for a complete chart. + */ + export class VictoryArea extends React.Component<VictoryAreaProps, any> {} + + export interface VictoryAxisProps extends VictoryCommonProps { /** - * Common properties for all data components + * The axisComponent prop takes in an entire component which will be used + * to create the axis line. The new element created from the passed axisComponent + * will be supplied with the following properties: x1, y1, x2, y2, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If an axisComponent + * is not supplied, VictoryAxis will render its default AxisLine component. + * @default <AxisLine/> */ - interface VictoryDatableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these arrays of values specified for x and y. If this prop is not set, - * categorical data will be plotted in the order it was given in the data array - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The data prop specifies the data to be plotted. Data should be in the form of an array - * of data points, or an array of arrays of data points for multiple datasets. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire component which will be used to create an area. - * The new element created from the passed dataComponent will be provided with the - * following properties calculated by VictoryArea: a scale, style, events, interpolation, - * and an array of modified data objects (including x, y, and calculated y0 and y1). - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use its default Area component. - * @default <Area/> - */ - dataComponent?: React.ReactElement<any>; - /** - * The domain prop describes the range of values your chart will cover. This prop can be - * given as a array of the minimum and maximum expected values for your bar chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - * @default "x" - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - * @default "y" - */ - y?: DataGetterPropType; + axisComponent?: React.ReactElement<any>; + /** + * The axisLabelComponent prop takes in an entire component which will be used + * to create the axis label. The new element created from the passed axisLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, transform, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an axisLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + axisLabelComponent?: React.ReactElement<any>; + /** + * This prop specifies whether a given axis is intended to cross another axis. + */ + crossAxis?: boolean; + /** + * The dependentAxis prop specifies whether the axis corresponds to the + * dependent variable (usually y). This prop is useful when composing axis + * with other components to form a chart. + */ + dependentAxis?: boolean; + /** + * The domain prop describes the range of values your axis will include. This prop should be + * given as a array of the minimum and maximum expected values for your axis. + * If this value is not given it will be calculated based on the scale or tickValues. + * @examples [-1, 1] + */ + domain?: DomainPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are + * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a + * single element by index rather than an entire set. The eventHandlers object + * should be given as an object whose keys are standard event names (i.e. onClick) + * and whose values are event callbacks. The return value of an event handler + * be used to modify other elemnts. The return value should be given as an object or + * an array of objects with optional target and eventKey keys, and a mutation + * key whose value is a function. The target and eventKey keys will default to those + * corresponding to the element the event handler was attached to. The mutation + * function will be called with the calculated props for the individual selected + * element (i.e. a single tick), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "grid", + * eventKey: 2, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "tickLabels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; + /** + * When true, this prop reduces the number of tick labels to fit the length of the axis. + * Labels are removed at approximately even intervals from the original array of labels. + * This feature only works well for labels that are approximately evenly spaced. + * @default false + */ + fixLabelOverlap?: boolean; + /** + * The gridComponent prop takes in an entire component which will be used + * to create grid lines. The new element created from the passed gridComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a gridComponent + * is not supplied, VictoryAxis will render its default GridLine component. + * @default <GridLine/> + */ + gridComponent?: React.ReactElement<any>; + /** + * If true, this value will flip the domain of a given axis. + */ + invertAxis?: boolean; + /** + * The label prop defines the label that will appear along the axis. This + * prop should be given as a value or an entire, HTML-complete label + * component. If a label component is given, it will be cloned. The new + * element's properties x, y, textAnchor, verticalAnchor, and transform + * will have defaults provided by the axis; styles filled out with + * defaults provided by the axis, and overrides from the label component. + * If a value is given, a new VictoryLabel will be created with props and + * styles from the axis. + */ + label?: any; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the x-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetX?: number; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the y-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetY?: number; + /** + * The orientation prop specifies the position and orientation of your axis. + */ + orientation?: "top" | "bottom" | "left" | "right"; + /** + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. + */ + style?: { + parent?: React.CSSProperties; + axis?: React.CSSProperties; + axisLabel?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + }; + /** + * The tickComponent prop takes in an entire component which will be used + * to create tick lines. The new element created from the passed tickComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a tickComponent + * is not supplied, VictoryAxis will render its default Tick component. + * @default <Tick/> + */ + tickComponent?: React.ReactElement<any>; + /** + * The tickCount prop specifies approximately how many ticks should be drawn on the axis if + * tickValues are not explicitly provided. This value is calculated by d3 scale and + * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. + * If you need an exact number of ticks, please specify them via the tickValues prop. + * This prop must have a value greater than zero. + * @default 5 + */ + tickCount?: number; + /** + * The tickLabelComponent prop takes in an entire component which will be used + * to create the tick labels. The new element created from the passed tickLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, tick, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an tickLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + tickLabelComponent?: React.ReactElement<any>; + /** + * The tickFormat prop specifies how tick values should be expressed visually. + * tickFormat can be given as a function to be applied to every tickValue, or as + * an array of display values for each tickValue. + * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] + */ + tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; + /** + * The tickValues prop explicitly specifies which tick values to draw on the axis. + * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] + */ + tickValues?: any[]; + } + + /** + * VictoryAxis draws an SVG chart axis with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. + */ + export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} + + export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The alignment prop specifies how bars should be aligned relative to their data points. + * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, + * bars will have “middle” alignment relative to their data points. + */ + alignment?: "start" | "middle" | "end"; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; + /** + * The cornerRadius prop specifies a radius to apply to each bar. + * If this prop is given as a single number, the radius will only be applied to the top of each bar. + * When this prop is given as a function, it will be evaluated with the arguments datum, and active. + */ + cornerRadius?: NumberOrCallback + | { + top?: number | (NumberOrCallback), + topLeft?: number | (NumberOrCallback), + topRight?: number | (NumberOrCallback), + bottom?: number | (NumberOrCallback), + bottomLeft?: number | (NumberOrCallback), + bottomRight?: number | (NumberOrCallback) + }; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. + * The eventKey may optionally be used to select a single element by index rather than an entire + * set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your VictoryBar. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } + + /** + * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes + * Check out VictoryChart for complete bar charts and more. + */ + export class VictoryBar extends React.Component<VictoryBarProps, any> {} + + export interface VictoryBoxPlotStyleInterface + extends VictoryStyleInterface { + max?: VictoryStyleObject; + maxLabels?: VictoryStyleObject; + min?: VictoryStyleObject; + minLabels?: VictoryStyleObject; + median?: VictoryStyleObject; + medianLabels?: VictoryStyleObject; + q1?: VictoryStyleObject; + q1Labels?: VictoryStyleObject; + q3?: VictoryStyleObject; + q3Labels?: VictoryStyleObject; } - - // Common labable interface - interface VictoryLabableProps { - /** - * The labelComponent prop takes in an entire label component which will be used - * to create a label for the area. The new element created from the passed labelComponent - * will be supplied with the following properties: x, y, index, data, verticalAnchor, - * textAnchor, angle, style, text, and events. any of these props may be overridden - * by passing in props to the supplied component, or modified or ignored within - * the custom component itself. If labelComponent is omitted, a new VictoryLabel - * will be created with props described above. This labelComponent prop should be used to - * provide a series label for VictoryArea. If individual labels are required for each - * data point, they should be created by composing VictoryArea with VictoryScatter - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - } - - interface VictoryMultiLabeableProps extends VictoryLabableProps { - /** - * The labels prop defines labels that will appear above each bar in your chart. - * This prop should be given as an array of values or as a function of data. - * If given as an array, the number of elements in the array should be equal to - * the length of the data array. Labels may also be added directly to the data object - * like data={[{x: 1, y: 1, label: "first"}]}. - * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title - */ - labels?: string[] | { (data: any): string }; - } - - interface VictorySingleLabableProps extends VictoryLabableProps { - /** - * The label prop defines the label that will appear at the edge of the area. - * This prop should be given a string or as a function of data. If individual - * labels are required for each data point, they should be created by composing - * VictoryArea with VictoryScatter - * @example: "Series 1", (data) => `${data.length} points` - */ - label?: string | { (data: any): string }; - } - - export interface VictoryAreaProps + + export interface VictoryBoxPlotProps extends VictoryCommonProps, - VictoryDatableProps, - VictorySingleLabableProps { + VictoryDatableProps { + /** + * The boxWidth prop specifies how wide each box should be. If the whiskerWidth + * prop is not set, this prop will also determine the width of the whisker crosshair. + */ + boxWidth?: number; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; /** * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. - * Since VictoryArea only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard * event names (i.e. onClick) and whose values are event callbacks. The return value * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys * will default to those corresponding to the element the event handler was attached to. * The mutation function will be called with the calculated props for the individual selected - * element (i.e. an area), and the object returned from the mutation function + * element (i.e. a single bar), and the object returned from the mutation function * will override the props of the selected element via object assignment. - * @example + * @examples * events={[ * { * target: "data", + * childName: "firstBar", * eventHandlers: { * onClick: () => { * return [ * { + * childName: "secondBar", * mutation: (props) => { * return {style: merge({}, props.style, {fill: "orange"})}; * } * }, { + * childName: "secondBar", * target: "labels", * mutation: () => { * return {text: "hey"}; @@ -1070,290 +1497,514 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; + events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; /** - * The interpolation prop determines how data points should be connected when plotting a line - * @default "linear" + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data */ - interpolation?: InterpolationPropType; + eventKey?: StringOrNumberOrCallback; /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - * @default 50 + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. */ - samples?: number; + horizontal?: boolean; /** - * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * The labelOrientation prop determines where labels are placed relative to their + * corresponding data. If this prop is not set, it will be set to “top” for + * horizontal charts, and “right” for vertical charts. + */ + labelOrientation?: "top" | "bottom" | "left" | "right"; + /** + * When the boolean labels prop is set to true, the values for min, max, median, + * q1, and q3 will be displayed for each box. For more granular label control, use + * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. + */ + labels?: boolean; + /** + * Use the max data accessor prop to define the max value of a box plot. + */ + max?: StringOrNumberOrCallback; + /** + * Use the median data accessor prop to define the median value of a box plot. + */ + median?: StringOrNumberOrCallback; + /** + * Use the min data accessor prop to define the min value of a box plot. + */ + min?: StringOrNumberOrCallback; + /** + * Use the q1 data accessor prop to define the q1 value of a box plot. + */ + q1?: StringOrNumberOrCallback; + /** + * Use the q3 data accessor prop to define the q1 value of a box plot. + */ + q3?: StringOrNumberOrCallback; + /** + * The style prop defines the style of the component. The style prop + * should be given as an object with styles defined for parent, max, + * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, + * q3Labels. Any valid svg styles are supported, but width, height, a + * nd padding should be specified via props as they determine relative + * layout for components in VictoryChart. Functional styles may be + * defined for style properties, and they will be evaluated with each datum. + */ + style?: VictoryBoxPlotStyleInterface; + /** + * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the + * whiskerWidth prop is not set, the width of the whisker crosshair will match + * the width of the box. + */ + whiskerWidth?: number; + } + + /** + * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for + * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), + * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. + */ + export class VictoryBoxPlot extends React.Component< + VictoryBoxPlotProps, + any + > {} + + export interface VictoryChartProps extends VictoryCommonProps { + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The style prop specifies styles for your chart. Any valid inline style properties * will be applied. Height, width, and padding should be specified via the height, * width, and padding props, as they are used to calculate the alignment of * components within chart. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} + * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} */ - style?: VictoryStyleInterface; + style?: Pick<VictoryStyleInterface, 'parent'>; } - + /** - * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. - * Add VictoryArea as a child of VictoryChart for a complete chart. + * A flexible charting component for React. + * VictoryChart composes other Victory components into reusable charts. + * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, + * and provides a set of sensible defaults. This component works with: + * - VictoryAxis + * - VictoryLine + * - VictoryScatter + * - VictoryBar */ - export class VictoryArea extends React.Component<VictoryAreaProps, any> {} - - export interface VictoryAxisProps extends VictoryCommonProps { + export class VictoryChart extends React.Component<VictoryChartProps, any> {} + + export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** - * The axisComponent prop takes in an entire component which will be used - * to create the axis line. The new element created from the passed axisComponent - * will be supplied with the following properties: x1, y1, x2, y2, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If an axisComponent - * is not supplied, VictoryAxis will render its default AxisLine component. - * @default <AxisLine/> + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or categorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] */ - axisComponent?: React.ReactElement<any>; + categories?: CategoryPropType; /** - * The axisLabelComponent prop takes in an entire component which will be used - * to create the axis label. The new element created from the passed axisLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, transform, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an axisLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. */ - axisLabelComponent?: React.ReactElement<any>; + colorScale?: ColorScalePropType; /** - * This prop specifies whether a given axis is intended to cross another axis. - */ - crossAxis?: boolean; - /** - * The dependentAxis prop specifies whether the axis corresponds to the - * dependent variable (usually y). This prop is useful when composing axis - * with other components to form a chart. - */ - dependentAxis?: boolean; - /** - * The domain prop describes the range of values your axis will include. This prop should be - * given as a array of the minimum and maximum expected values for your axis. - * If this value is not given it will be calculated based on the scale or tickValues. - * @examples [-1, 1] + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} */ domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; /** * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are - * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a - * single element by index rather than an entire set. The eventHandlers object - * should be given as an object whose keys are standard event names (i.e. onClick) - * and whose values are event callbacks. The return value of an event handler - * be used to modify other elemnts. The return value should be given as an object or - * an array of objects with optional target and eventKey keys, and a mutation - * key whose value is a function. The target and eventKey keys will default to those - * corresponding to the element the event handler was attached to. The mutation - * function will be called with the calculated props for the individual selected - * element (i.e. a single tick), and the object returned from the mutation function + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryGroup, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function * will override the props of the selected element via object assignment. * @examples * events={[ * { - * target: "grid", - * eventKey: 2, + * target: "data", + * childName: "firstBar", * eventHandlers: { * onClick: () => { * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "tickLabels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; * } * } * } * ]} */ - events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** - * When true, this prop reduces the number of tick labels to fit the length of the axis. - * Labels are removed at approximately even intervals from the original array of labels. - * This feature only works well for labels that are approximately evenly spaced. - * @default false + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data */ - fixLabelOverlap?: boolean; + eventKey?: StringOrNumberOrCallback; /** - * The gridComponent prop takes in an entire component which will be used - * to create grid lines. The new element created from the passed gridComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a gridComponent - * is not supplied, VictoryAxis will render its default GridLine component. - * @default <GridLine/> + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. */ - gridComponent?: React.ReactElement<any>; + horizontal?: boolean; /** - * If true, this value will flip the domain of a given axis. + * The offset prop determines the number of pixels each element in a group should + * be offset from its original position of the on the independent axis. In the + * case of groups of bars, this number should be equal to the width of the bar + * plus the desired spacing between bars. */ - invertAxis?: boolean; + offset?: number; /** - * The label prop defines the label that will appear along the axis. This - * prop should be given as a value or an entire, HTML-complete label - * component. If a label component is given, it will be cloned. The new - * element's properties x, y, textAnchor, verticalAnchor, and transform - * will have defaults provided by the axis; styles filled out with - * defaults provided by the axis, and overrides from the label component. - * If a value is given, a new VictoryLabel will be created with props and - * styles from the axis. + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children */ - label?: any; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the x-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetX?: number; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the y-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetY?: number; - /** - * The orientation prop specifies the position and orientation of your axis. - */ - orientation?: "top" | "bottom" | "left" | "right"; - /** - * The style prop defines the style of the component. The style prop should be given as an object - * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg - * styles are supported, but width, height, and padding should be specified via props as they - * determine relative layout for components in VictoryChart. Functional styles may be defined for - * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. - * - * note: When a component is rendered as a child of another Victory component, or within a custom - * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. - * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. - * - * note: custom angle and verticalAnchor properties may be included in labels styles. - */ - style?: { - parent?: React.CSSProperties; - axis?: React.CSSProperties; - axisLabel?: React.CSSProperties; - grid?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - ticks?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - tickLabels?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - }; - /** - * The tickComponent prop takes in an entire component which will be used - * to create tick lines. The new element created from the passed tickComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a tickComponent - * is not supplied, VictoryAxis will render its default Tick component. - * @default <Tick/> - */ - tickComponent?: React.ReactElement<any>; - /** - * The tickCount prop specifies approximately how many ticks should be drawn on the axis if - * tickValues are not explicitly provided. This value is calculated by d3 scale and - * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. - * If you need an exact number of ticks, please specify them via the tickValues prop. - * This prop must have a value greater than zero. - * @default 5 - */ - tickCount?: number; - /** - * The tickLabelComponent prop takes in an entire component which will be used - * to create the tick labels. The new element created from the passed tickLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, tick, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an tickLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - tickLabelComponent?: React.ReactElement<any>; - /** - * The tickFormat prop specifies how tick values should be expressed visually. - * tickFormat can be given as a function to be applied to every tickValue, or as - * an array of display values for each tickValue. - * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] - */ - tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; - /** - * The tickValues prop explicitly specifies which tick values to draw on the axis. - * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] - */ - tickValues?: any[]; + style?: VictoryStyleInterface; } - - /** - * VictoryAxis draws an SVG chart axis with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} - - export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The alignment prop specifies how bars should be aligned relative to their data points. - * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, - * bars will have “middle” alignment relative to their data points. - */ - alignment?: "start" | "middle" | "end"; - /** - * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. - * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will - * be used to calculate a default width for each bar given the total number of bars in the data series - * and the overall width of the chart. - */ - barRatio?: number; - /** - * The barWidth prop is used to specify the width of each bar. This prop may be given as - * a number of pixels or as a function that returns a number. When this prop is given as - * a function, it will be evaluated with the arguments datum, and active. When this value - * is not given, a default value will be calculated based on the overall dimensions of - * the chart, and the number of bars. - */ - barWidth?: NumberOrCallback; - /** - * The cornerRadius prop specifies a radius to apply to each bar. - * If this prop is given as a single number, the radius will only be applied to the top of each bar. - * When this prop is given as a function, it will be evaluated with the arguments datum, and active. - */ - cornerRadius?: NumberOrCallback - | { - top?: number | (NumberOrCallback), - topLeft?: number | (NumberOrCallback), - topRight?: number | (NumberOrCallback), - bottom?: number | (NumberOrCallback), - bottomLeft?: number | (NumberOrCallback), - bottomRight?: number | (NumberOrCallback) - }; + + export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} + + export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The event prop take an array of event objects. Event objects are composed of * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. - * The eventKey may optionally be used to select a single element by index rather than an entire - * set. The eventHandlers object should be given as an object whose keys are standard + * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. + * Since VictoryLine only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a line), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * The interpolation prop determines how data points should be connected + * when plotting a line + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The labels prop defines the labels that will appear above each point. + * This prop should be given as an array or as a function of data. + */ + labels?: string[]|number[]|Function; + /** + * Use the sortKey prop to indicate how data should be sorted. This prop + * is given directly to the lodash sortBy function to be executed on the + * final dataset. + */ + sortKey?: string|string[]|Function; + /** + * The style prop specifies styles for your VictoryLine. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. in addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } + + /** + * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use line charts and more. + */ + export class VictoryLine extends React.Component<VictoryLineProps, any> {} + + export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + /** + * The colorScale prop defines a color scale to be applied to each data + * symbol in VictoryLegend. This prop should be given as an array of CSS + * colors, or as a string corresponding to one of the built in color + * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", + * "green", "blue". VictoryLegend will assign a color to each symbol by + * index, unless they are explicitly specified in the data object. + * Colors will repeat when there are more symbols than colors in the + * provided colorScale. + */ + colorScale?: ColorScalePropType; + /** + * The style prop defines the style of the VictoryLegend component. + * The style prop should be given as an object with styles defined for data, labels and + * parent. Any valid svg styles are supported, but width, height, and + * padding should be specified via props as they determine relative + * layout for components in VictoryLegend. + */ + style?: VictoryStyleInterface; + /** + * The containerComponent prop takes a component instance which will be + * used to create a container element for standalone legends. The new + * element created from the passed containerComponent will be provided + * with the following props: height, width, children (the legend itself) + * and style. If a containerComponent is not provided, the default + * VictoryContainer component will be used. VictoryContainer supports + * title and desc props, which are intended to add accessibility to + * Victory components. The more descriptive these props are, the more + * accessible your data will be for people using screen readers. These + * props may be set by passing them directly to the supplied component. + * By default, VictoryContainer renders a responsive svg using the + * viewBox attribute. To render a static container, set + * responsive={false} directly on the instance of VictoryContainer + * supplied via the containerComponent prop. VictoryContainer also + * renders a Portal element that may be used in conjunction with + * VictoryPortal to force components to render above other children. + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * Specify data via the data prop. VictoryLegend expects data as an + * array of objects with name (required), symbol, and labels properties. + * The data prop must be given as an array. + */ + data?: Array<{ + name?: string; + symbol?: { + fill?: string; + type?: string; + }; + }>; + /** + * The itemsPerRow prop determines how many items to render in each row + * of a horizontal legend, or in each column of a vertical legend. This + * prop should be given as an integer. When this prop is not given, + * legend items will be rendered in a single row or column. + */ + itemsPerRow?: number; + /** + * The dataComponent prop takes a component instance which will be + * responsible for rendering a data element used to associate a symbol + * or color with each data series. The new element created from the + * passed dataComponent will be provided with the following properties + * calculated by VictoryLegend: x, y, size, style, and symbol. Any of + * these props may be overridden by passing in props to the supplied + * component, or modified or ignored within the custom component itself. + * If a dataComponent is not provided, VictoryLegend will use its + * default Point component. + */ + dataComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; + /** + * The gutter prop defines the number of pixels between legend rows or + * columns, depending on orientation. When orientation is horizontal, + * gutters are between columns. When orientation is vertical, gutters + * are the space between rows. + */ + gutter?: number; + /** + * The labelComponent prop takes a component instance which will be used + * to render each legend label. The new element created from the passed + * labelComponent will be supplied with the following properties: x, y, + * style, and text. Any of these props may be overridden by passing in + * props to the supplied component, or modified or ignored within the + * custom component itself. If labelComponent is omitted, a new + * VictoryLabel will be created with the props described above. + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop takes a string that defines whether legend data + * are displayed in a row or column. When orientation is "horizontal", + * legend items will be displayed in a single row. When orientation is + * "vertical", legend items will be displayed in a single column. Line + * and text-wrapping is not currently supported, so "vertical" + * orientation is both the default setting and recommended for + * displaying many series of data. + * @default 'vertical' + */ + orientation?: 'horizontal'|'vertical'; + /** + * The padding prop specifies the amount of padding in pixels between + * the edge of the legend and any rendered child components. This prop + * can be given as a number or as an object with padding specified for + * top, bottom, left and right. As with width and height, the absolute + * padding will depend on whether the component is rendered in a + * responsive container. When a component is nested within + * VictoryLegend, setting padding on the child component will have no + * effect. + */ + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The standalone props specifies whether the component should be + * rendered in an independent <svg> element or in a <g> tag. This prop + * defaults to true, and renders an svg. + */ + standalone?: boolean; + /** + * The symbolSpacer prop defines the number of pixels between data + * components and label components. + */ + symbolSpacer?: number; + /** + * The width and height props define the width and height of the legend. + * These props may be given as positive numbers or functions of data. If + * these props are not set, width and height will be determined based on + * an approximate text size calculated from the text and style props + * provided to VictoryLegend. + */ + width?: number; + height?: number; + /** + * The x and y props define the base position of the legend element. + */ + x?: number; + y?: number; + } + + /** + * VictoryLegend renders a chart legend component. + */ + export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} + + type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; + + export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The bubbleProperty prop indicates which property of the data object should be used + * to scale data points in a bubble chart + */ + bubbleProperty?: string; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryScatter + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard * event names (i.e. onClick) and whose values are event callbacks. The return value * of an event handler is used to modify elemnts. The return value should be given * as an object or an array of objects with optional target and eventKey keys, @@ -1362,7 +2013,7 @@ declare module "victory" { * The mutation function will be called with the calculated props for the individual selected * element (i.e. a single bar), and the object returned from the mutation function * will override the props of the selected element via object assignment. - * @example + * @examples * events={[ * { * target: "data", @@ -1388,7 +2039,124 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart + */ + maxBubbleSize?: number; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The size prop determines how to scale each data point + */ + size?: number | { (data: any): number }; + /** + * The style prop specifies styles for your VictoryScatter. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + /** + * The symbol prop determines which symbol should be drawn to represent data points. + */ + symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; + } + + /** + * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use scatter plots and more. + */ + export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} + + export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or catigorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryStack, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -1401,935 +2169,166 @@ declare module "victory" { */ horizontal?: boolean; /** - * The style prop specifies styles for your VictoryBar. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children */ style?: VictoryStyleInterface; + /** + * The xOffset prop is used for grouping stacks of bars. This prop will be set + * by the VictoryGroup component wrapper, or can be set manually. + */ + xOffset?: number; } - + + export class VictoryStack extends React.Component<VictoryStackProps, any> {} + + export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The colorScale prop is an optional prop that defines the color scale the pie + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryPie will automatically assign + * values from this color scale to the pie slices unless colors are explicitly provided in the + * data object + */ + colorScale?: ColorScalePropType; + /** + * The data prop specifies the data to be plotted, + * where data X-value is the slice label (string or number), + * and Y-value is the corresponding number value represented by the slice + * Data should be in the form of an array of data points. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire, HTML-complete data component which will be used to + * create slices for each datum in the pie chart. The new element created from the passed + * dataComponent will have the property datum set by the pie chart for the point it renders; + * properties style and pathFunction calculated by VictoryPie; an index property set + * corresponding to the location of the datum in the data provided to the pie; events bound to + * the VictoryPie; and the d3 compatible slice object. + * If a dataComponent is not provided, VictoryPie's Slice component will be used. + */ + dataComponent?: React.ReactElement<any>; + /** + * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. + * If this prop is not set, the label radius will default to the radius of the pie + label padding. + */ + labelRadius?: number; + /** + * The overall end angle of the pie in degrees. This prop is used in conjunction with + * startAngle to create a pie that spans only a segment of a circle. + */ + endAngle?: number; + /** + * The event prop takes an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryPie + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: 1, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: 2, + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: 2, + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * Specifies the radius of the chart. If this property is not provided it is computed + * from width, height, and padding props + * + */ + radius?: number; + /** + * When creating a donut chart, this prop determines the number of pixels between + * the center of the chart and the inner edge of a donut. When this prop is set to zero + * a regular pie chart is rendered. + */ + innerRadius?: number; + /** + * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie + */ + cornerRadius?: number; + /** + * The padAngle prop determines the amount of separation between adjacent data slices + * in number of degrees + */ + padAngle?: number; + /** + * The overall start angle of the pie in degrees. This prop is used in conjunction with + * endAngle to create a pie that spans only a segment of a circle. + */ + startAngle?: number; + /** + * The style prop specifies styles for your pie. VictoryPie relies on Radium, + * so valid Radium style objects should work for this prop. Height, width, and + * padding should be specified via the height, width, and padding props. + * @example {data: {stroke: "black"}, label: {fontSize: 10}} + */ + style?: VictoryStyleInterface; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + */ + y?: DataGetterPropType; + } + /** - * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes - * Check out VictoryChart for complete bar charts and more. + * victory-pie draws an SVG pie or donut chart with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. */ - export class VictoryBar extends React.Component<VictoryBarProps, any> {} - - export interface VictoryBoxPlotStyleInterface - extends VictoryStyleInterface { - max?: VictoryStyleObject; - maxLabels?: VictoryStyleObject; - min?: VictoryStyleObject; - minLabels?: VictoryStyleObject; - median?: VictoryStyleObject; - medianLabels?: VictoryStyleObject; - q1?: VictoryStyleObject; - q1Labels?: VictoryStyleObject; - q3?: VictoryStyleObject; - q3Labels?: VictoryStyleObject; - } - - export interface VictoryBoxPlotProps - extends VictoryCommonProps, - VictoryDatableProps { - /** - * The boxWidth prop specifies how wide each box should be. If the whiskerWidth - * prop is not set, this prop will also determine the width of the whisker crosshair. - */ - boxWidth?: number; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The labelOrientation prop determines where labels are placed relative to their - * corresponding data. If this prop is not set, it will be set to “top” for - * horizontal charts, and “right” for vertical charts. - */ - labelOrientation?: "top" | "bottom" | "left" | "right"; - /** - * When the boolean labels prop is set to true, the values for min, max, median, - * q1, and q3 will be displayed for each box. For more granular label control, use - * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. - */ - labels?: boolean; - /** - * Use the max data accessor prop to define the max value of a box plot. - */ - max?: StringOrNumberOrCallback; - /** - * Use the median data accessor prop to define the median value of a box plot. - */ - median?: StringOrNumberOrCallback; - /** - * Use the min data accessor prop to define the min value of a box plot. - */ - min?: StringOrNumberOrCallback; - /** - * Use the q1 data accessor prop to define the q1 value of a box plot. - */ - q1?: StringOrNumberOrCallback; - /** - * Use the q3 data accessor prop to define the q1 value of a box plot. - */ - q3?: StringOrNumberOrCallback; - /** - * The style prop defines the style of the component. The style prop - * should be given as an object with styles defined for parent, max, - * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, - * q3Labels. Any valid svg styles are supported, but width, height, a - * nd padding should be specified via props as they determine relative - * layout for components in VictoryChart. Functional styles may be - * defined for style properties, and they will be evaluated with each datum. - */ - style?: VictoryBoxPlotStyleInterface; - /** - * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the - * whiskerWidth prop is not set, the width of the whisker crosshair will match - * the width of the box. - */ - whiskerWidth?: number; - } - - /** - * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for - * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), - * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. - */ - export class VictoryBoxPlot extends React.Component< - VictoryBoxPlotProps, - any - > {} - - export interface VictoryChartProps extends VictoryCommonProps { - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The style prop specifies styles for your chart. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} - */ - style?: Pick<VictoryStyleInterface, 'parent'>; - } - - /** - * A flexible charting component for React. - * VictoryChart composes other Victory components into reusable charts. - * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, - * and provides a set of sensible defaults. This component works with: - * - VictoryAxis - * - VictoryLine - * - VictoryScatter - * - VictoryBar - */ - export class VictoryChart extends React.Component<VictoryChartProps, any> {} - - export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or categorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryGroup, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The offset prop determines the number of pixels each element in a group should - * be offset from its original position of the on the independent axis. In the - * case of groups of bars, this number should be equal to the width of the bar - * plus the desired spacing between bars. - */ - offset?: number; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; - } - - export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} - - export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. - * Since VictoryLine only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a line), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * The interpolation prop determines how data points should be connected - * when plotting a line - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The labels prop defines the labels that will appear above each point. - * This prop should be given as an array or as a function of data. - */ - labels?: string[]|number[]|Function; - /** - * Use the sortKey prop to indicate how data should be sorted. This prop - * is given directly to the lodash sortBy function to be executed on the - * final dataset. - */ - sortKey?: string|string[]|Function; - /** - * The style prop specifies styles for your VictoryLine. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. in addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - } - - /** - * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use line charts and more. - */ - export class VictoryLine extends React.Component<VictoryLineProps, any> {} - - export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The colorScale prop defines a color scale to be applied to each data - * symbol in VictoryLegend. This prop should be given as an array of CSS - * colors, or as a string corresponding to one of the built in color - * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", - * "green", "blue". VictoryLegend will assign a color to each symbol by - * index, unless they are explicitly specified in the data object. - * Colors will repeat when there are more symbols than colors in the - * provided colorScale. - */ - colorScale?: ColorScalePropType; - /** - * The style prop defines the style of the VictoryLegend component. - * The style prop should be given as an object with styles defined for data, labels and - * parent. Any valid svg styles are supported, but width, height, and - * padding should be specified via props as they determine relative - * layout for components in VictoryLegend. - */ - style?: VictoryStyleInterface; - /** - * The containerComponent prop takes a component instance which will be - * used to create a container element for standalone legends. The new - * element created from the passed containerComponent will be provided - * with the following props: height, width, children (the legend itself) - * and style. If a containerComponent is not provided, the default - * VictoryContainer component will be used. VictoryContainer supports - * title and desc props, which are intended to add accessibility to - * Victory components. The more descriptive these props are, the more - * accessible your data will be for people using screen readers. These - * props may be set by passing them directly to the supplied component. - * By default, VictoryContainer renders a responsive svg using the - * viewBox attribute. To render a static container, set - * responsive={false} directly on the instance of VictoryContainer - * supplied via the containerComponent prop. VictoryContainer also - * renders a Portal element that may be used in conjunction with - * VictoryPortal to force components to render above other children. - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * Specify data via the data prop. VictoryLegend expects data as an - * array of objects with name (required), symbol, and labels properties. - * The data prop must be given as an array. - */ - data?: Array<{ - name?: string; - symbol?: { - fill?: string; - type?: string; - }; - }>; - /** - * The itemsPerRow prop determines how many items to render in each row - * of a horizontal legend, or in each column of a vertical legend. This - * prop should be given as an integer. When this prop is not given, - * legend items will be rendered in a single row or column. - */ - itemsPerRow?: number; - /** - * The dataComponent prop takes a component instance which will be - * responsible for rendering a data element used to associate a symbol - * or color with each data series. The new element created from the - * passed dataComponent will be provided with the following properties - * calculated by VictoryLegend: x, y, size, style, and symbol. Any of - * these props may be overridden by passing in props to the supplied - * component, or modified or ignored within the custom component itself. - * If a dataComponent is not provided, VictoryLegend will use its - * default Point component. - */ - dataComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; - /** - * The gutter prop defines the number of pixels between legend rows or - * columns, depending on orientation. When orientation is horizontal, - * gutters are between columns. When orientation is vertical, gutters - * are the space between rows. - */ - gutter?: number; - /** - * The labelComponent prop takes a component instance which will be used - * to render each legend label. The new element created from the passed - * labelComponent will be supplied with the following properties: x, y, - * style, and text. Any of these props may be overridden by passing in - * props to the supplied component, or modified or ignored within the - * custom component itself. If labelComponent is omitted, a new - * VictoryLabel will be created with the props described above. - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop takes a string that defines whether legend data - * are displayed in a row or column. When orientation is "horizontal", - * legend items will be displayed in a single row. When orientation is - * "vertical", legend items will be displayed in a single column. Line - * and text-wrapping is not currently supported, so "vertical" - * orientation is both the default setting and recommended for - * displaying many series of data. - * @default 'vertical' - */ - orientation?: 'horizontal'|'vertical'; - /** - * The padding prop specifies the amount of padding in pixels between - * the edge of the legend and any rendered child components. This prop - * can be given as a number or as an object with padding specified for - * top, bottom, left and right. As with width and height, the absolute - * padding will depend on whether the component is rendered in a - * responsive container. When a component is nested within - * VictoryLegend, setting padding on the child component will have no - * effect. - */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The standalone props specifies whether the component should be - * rendered in an independent <svg> element or in a <g> tag. This prop - * defaults to true, and renders an svg. - */ - standalone?: boolean; - /** - * The symbolSpacer prop defines the number of pixels between data - * components and label components. - */ - symbolSpacer?: number; - /** - * The width and height props define the width and height of the legend. - * These props may be given as positive numbers or functions of data. If - * these props are not set, width and height will be determined based on - * an approximate text size calculated from the text and style props - * provided to VictoryLegend. - */ - width?: number; - height?: number; - /** - * The x and y props define the base position of the legend element. - */ - x?: number; - y?: number; - } - - /** - * VictoryLegend renders a chart legend component. - */ - export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} - - type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; - - export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The bubbleProperty prop indicates which property of the data object should be used - * to scale data points in a bubble chart - */ - bubbleProperty?: string; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryScatter - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart - */ - maxBubbleSize?: number; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The size prop determines how to scale each data point - */ - size?: number | { (data: any): number }; - /** - * The style prop specifies styles for your VictoryScatter. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - /** - * The symbol prop determines which symbol should be drawn to represent data points. - */ - symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; - } - - /** - * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use scatter plots and more. - */ - export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} - - export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or catigorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryStack, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; - /** - * The xOffset prop is used for grouping stacks of bars. This prop will be set - * by the VictoryGroup component wrapper, or can be set manually. - */ - xOffset?: number; - } - - export class VictoryStack extends React.Component<VictoryStackProps, any> {} - - export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The colorScale prop is an optional prop that defines the color scale the pie - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryPie will automatically assign - * values from this color scale to the pie slices unless colors are explicitly provided in the - * data object - */ - colorScale?: ColorScalePropType; - /** - * The data prop specifies the data to be plotted, - * where data X-value is the slice label (string or number), - * and Y-value is the corresponding number value represented by the slice - * Data should be in the form of an array of data points. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire, HTML-complete data component which will be used to - * create slices for each datum in the pie chart. The new element created from the passed - * dataComponent will have the property datum set by the pie chart for the point it renders; - * properties style and pathFunction calculated by VictoryPie; an index property set - * corresponding to the location of the datum in the data provided to the pie; events bound to - * the VictoryPie; and the d3 compatible slice object. - * If a dataComponent is not provided, VictoryPie's Slice component will be used. - */ - dataComponent?: React.ReactElement<any>; - /** - * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. - * If this prop is not set, the label radius will default to the radius of the pie + label padding. - */ - labelRadius?: number; - /** - * The overall end angle of the pie in degrees. This prop is used in conjunction with - * startAngle to create a pie that spans only a segment of a circle. - */ - endAngle?: number; - /** - * The event prop takes an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryPie - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: 1, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: 2, - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: 2, - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * Specifies the radius of the chart. If this property is not provided it is computed - * from width, height, and padding props - * - */ - radius?: number; - /** - * When creating a donut chart, this prop determines the number of pixels between - * the center of the chart and the inner edge of a donut. When this prop is set to zero - * a regular pie chart is rendered. - */ - innerRadius?: number; - /** - * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie - */ - cornerRadius?: number; - /** - * The padAngle prop determines the amount of separation between adjacent data slices - * in number of degrees - */ - padAngle?: number; - /** - * The overall start angle of the pie in degrees. This prop is used in conjunction with - * endAngle to create a pie that spans only a segment of a circle. - */ - startAngle?: number; - /** - * The style prop specifies styles for your pie. VictoryPie relies on Radium, - * so valid Radium style objects should work for this prop. Height, width, and - * padding should be specified via the height, width, and padding props. - * @example {data: {stroke: "black"}, label: {fontSize: 10}} - */ - style?: VictoryStyleInterface; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - */ - y?: DataGetterPropType; - } - - /** - * victory-pie draws an SVG pie or donut chart with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryPie extends React.Component<VictoryPieProps, any> {} - } - \ No newline at end of file + export class VictoryPie extends React.Component<VictoryPieProps, any> {} + } From 1e389cf9770e25872ff933aec5fc8f331d8d88ce Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Wed, 6 Feb 2019 11:02:02 -0600 Subject: [PATCH 132/200] Add types for @carbon/colors and update paths --- types/carbon__colors/carbon__colors-tests.ts | 3 + types/carbon__colors/index.d.ts | 491 +++++++++++++++++++ types/carbon__colors/tsconfig.json | 19 + types/carbon__colors/tslint.json | 1 + 4 files changed, 514 insertions(+) create mode 100644 types/carbon__colors/carbon__colors-tests.ts create mode 100644 types/carbon__colors/index.d.ts create mode 100644 types/carbon__colors/tsconfig.json create mode 100644 types/carbon__colors/tslint.json diff --git a/types/carbon__colors/carbon__colors-tests.ts b/types/carbon__colors/carbon__colors-tests.ts new file mode 100644 index 0000000000..1df2cea931 --- /dev/null +++ b/types/carbon__colors/carbon__colors-tests.ts @@ -0,0 +1,3 @@ +import { rgba } from "@carbon/colors"; + +rgba("TOTORO", 0.4); // $ExpectType string diff --git a/types/carbon__colors/index.d.ts b/types/carbon__colors/index.d.ts new file mode 100644 index 0000000000..33438d7c66 --- /dev/null +++ b/types/carbon__colors/index.d.ts @@ -0,0 +1,491 @@ +// Type definitions for @carbon/colors 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/colors +// Definitions by: Vince Picone <https://github.com/vpicone> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const black: string; + +export const black100: string; + +export const blue: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const blue10: string; + +export const blue100: string; + +export const blue20: string; + +export const blue30: string; + +export const blue40: string; + +export const blue50: string; + +export const blue60: string; + +export const blue70: string; + +export const blue80: string; + +export const blue90: string; + +export const colors: { + black: { + "100": string; + }; + blue: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + coolGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + cyan: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + gray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + green: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + magenta: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + orange: { + "40": string; + }; + purple: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + red: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + teal: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + warmGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + white: { + "0": string; + }; + yellow: { + "20": string; + }; +}; + +export const coolGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const coolGray10: string; + +export const coolGray100: string; + +export const coolGray20: string; + +export const coolGray30: string; + +export const coolGray40: string; + +export const coolGray50: string; + +export const coolGray60: string; + +export const coolGray70: string; + +export const coolGray80: string; + +export const coolGray90: string; + +export const cyan: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const cyan10: string; + +export const cyan100: string; + +export const cyan20: string; + +export const cyan30: string; + +export const cyan40: string; + +export const cyan50: string; + +export const cyan60: string; + +export const cyan70: string; + +export const cyan80: string; + +export const cyan90: string; + +export const gray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const gray10: string; + +export const gray100: string; + +export const gray20: string; + +export const gray30: string; + +export const gray40: string; + +export const gray50: string; + +export const gray60: string; + +export const gray70: string; + +export const gray80: string; + +export const gray90: string; + +export const green: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const green10: string; + +export const green100: string; + +export const green20: string; + +export const green30: string; + +export const green40: string; + +export const green50: string; + +export const green60: string; + +export const green70: string; + +export const green80: string; + +export const green90: string; + +export const magenta: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const magenta10: string; + +export const magenta100: string; + +export const magenta20: string; + +export const magenta30: string; + +export const magenta40: string; + +export const magenta50: string; + +export const magenta60: string; + +export const magenta70: string; + +export const magenta80: string; + +export const magenta90: string; + +export const orange: string; + +export const orange40: string; + +export const purple: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const purple10: string; + +export const purple100: string; + +export const purple20: string; + +export const purple30: string; + +export const purple40: string; + +export const purple50: string; + +export const purple60: string; + +export const purple70: string; + +export const purple80: string; + +export const purple90: string; + +export const red: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const red10: string; + +export const red100: string; + +export const red20: string; + +export const red30: string; + +export const red40: string; + +export const red50: string; + +export const red60: string; + +export const red70: string; + +export const red80: string; + +export const red90: string; + +export const teal: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const teal10: string; + +export const teal100: string; + +export const teal20: string; + +export const teal30: string; + +export const teal40: string; + +export const teal50: string; + +export const teal60: string; + +export const teal70: string; + +export const teal80: string; + +export const teal90: string; + +export const warmGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const warmGray10: string; + +export const warmGray100: string; + +export const warmGray20: string; + +export const warmGray30: string; + +export const warmGray40: string; + +export const warmGray50: string; + +export const warmGray60: string; + +export const warmGray70: string; + +export const warmGray80: string; + +export const warmGray90: string; + +export const white: string; + +export const white0: string; + +export const yellow: string; + +export const yellow20: string; + +export function rgba(hexcode: string, opacity: number): string; + +export namespace rgba { + const prototype: {}; +} diff --git a/types/carbon__colors/tsconfig.json b/types/carbon__colors/tsconfig.json new file mode 100644 index 0000000000..3b03be1aae --- /dev/null +++ b/types/carbon__colors/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "paths": { + "@carbon/colors": ["carbon__colors"] + } + }, + "files": ["index.d.ts", "carbon__colors-tests.ts"] +} diff --git a/types/carbon__colors/tslint.json b/types/carbon__colors/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__colors/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f86b9137fb1b01fb07e1d08eb454cd53e804d0b6 Mon Sep 17 00:00:00 2001 From: Anton Evzhakov <anton@evz.name> Date: Wed, 6 Feb 2019 16:57:30 +0200 Subject: [PATCH 133/200] Add definition for `isSchema()` method signature --- types/yup/index.d.ts | 1 + types/yup/yup-tests.ts | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 9f3cb687a2..88c4890b82 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -26,6 +26,7 @@ export function addMethod<T extends Schema<any>>( export function ref(path: string, options?: { contextPrefix: string }): Ref; export function lazy<T>(fn: (value: T) => Schema<T>): Lazy; export function setLocale(customLocale: LocaleObject): void; +export function isSchema(obj: any): obj is Schema<any>; export const mixed: MixedSchemaConstructor; export const string: StringSchemaConstructor; diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index a90a7df25d..f0404cf8bd 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -3,6 +3,7 @@ import * as yup from "yup"; // tslint:disable-next-line:no-duplicate-imports import { reach, + isSchema, date, Schema, ObjectSchema, @@ -24,6 +25,10 @@ const schema1 = yup.object().shape({ reach(schema1, "nested.arr.num"); reach(schema1, "nested.arr[].num"); +// isSchema function +const isSchemaResult1: boolean = isSchema(schema1); +const isSchemaResult2: boolean = isSchema({}); + // addMethod function yup.addMethod<NumberSchema>(yup.number, "minimum", function( this, From cfdcd0cb154f1abf23cf9b83c8feea1742596f05 Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 11:17:26 -0600 Subject: [PATCH 134/200] [kissfft-js]: add type declarations for kissfft-js --- types/kissfft-js/index.d.ts | 17 +++++++++++++++++ types/kissfft-js/kissfft-js-tests.ts | 12 ++++++++++++ types/kissfft-js/tsconfig.json | 22 ++++++++++++++++++++++ types/kissfft-js/tslint.json | 1 + 4 files changed, 52 insertions(+) create mode 100644 types/kissfft-js/index.d.ts create mode 100644 types/kissfft-js/kissfft-js-tests.ts create mode 100644 types/kissfft-js/tsconfig.json create mode 100644 types/kissfft-js/tslint.json diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts new file mode 100644 index 0000000000..11f41a3505 --- /dev/null +++ b/types/kissfft-js/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for kissfft-js 0.1 +// Project: https://github.com/j-funk/kissfft-js#readme +// Definitions by: racerhere <https://github.com/racerhere> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/types/kissfft-js + +declare abstract class AbstractKissFFT { + constructor(size: number); + forward(input: number[]): number[]; + inverse(input: number[]): number[]; + dispose(): void; +} + +export class FFT extends AbstractKissFFT { +} + +export class FFTR extends AbstractKissFFT { +} diff --git a/types/kissfft-js/kissfft-js-tests.ts b/types/kissfft-js/kissfft-js-tests.ts new file mode 100644 index 0000000000..76c0da2001 --- /dev/null +++ b/types/kissfft-js/kissfft-js-tests.ts @@ -0,0 +1,12 @@ +import {FFT} from "kissfft-js"; +import {FFTR} from "kissfft-js"; + +const fft = new FFT(0); // $ExpectType FFT +fft.forward([1, 2, 3]); // $ExpectType number[] +fft.inverse([1, 2, 3]); // $ExpectType number[] +fft.dispose(); // $ExpectType void + +const fftr = new FFTR(0); // $ExpectType FFTR +fftr.forward([1, 2, 3]); // $ExpectType number[] +fftr.inverse([1, 2, 3]); // $ExpectType number[] +fftr.dispose(); // $ExpectType void diff --git a/types/kissfft-js/tsconfig.json b/types/kissfft-js/tsconfig.json new file mode 100644 index 0000000000..5dfeddfade --- /dev/null +++ b/types/kissfft-js/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "kissfft-js-tests.ts" + ] +} diff --git a/types/kissfft-js/tslint.json b/types/kissfft-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/kissfft-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 24e05c755b45b7e2ba2ec60a37dd00c327ada8e5 Mon Sep 17 00:00:00 2001 From: Deadly0 <xdeadlyx@ya.ru> Date: Wed, 6 Feb 2019 20:27:24 +0300 Subject: [PATCH 135/200] More detailed typing for Meteor.methods(), fixed User model. --- types/meteor/globals/meteor.d.ts | 12 ++++++++++-- types/meteor/meteor.d.ts | 12 ++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/types/meteor/globals/meteor.d.ts b/types/meteor/globals/meteor.d.ts index 7a90b0611e..63f60df310 100644 --- a/types/meteor/globals/meteor.d.ts +++ b/types/meteor/globals/meteor.d.ts @@ -25,7 +25,7 @@ declare module Meteor { _id?: string; username?: string; emails?: UserEmail[]; - createdAt?: number; + createdAt?: Date; profile?: any; services?: any; } @@ -49,7 +49,15 @@ declare module Meteor { /** Error **/ /** Method **/ - function methods(methods: Object): void; + interface MethodThisType { + isSimulation: boolean; + userId: string | null; + connection: Connection | null; + setUserId(userId: string): void; + unblock(): void; + } + + function methods(methods: {[key: string]: (this: MethodThisType, ...args: any[]) => any}): void; function call(name: string, ...args: any[]): any; diff --git a/types/meteor/meteor.d.ts b/types/meteor/meteor.d.ts index ca08c31c98..141b1f7e61 100644 --- a/types/meteor/meteor.d.ts +++ b/types/meteor/meteor.d.ts @@ -26,7 +26,7 @@ declare module "meteor/meteor" { _id?: string; username?: string; emails?: UserEmail[]; - createdAt?: number; + createdAt?: Date; profile?: any; services?: any; } @@ -50,7 +50,15 @@ declare module "meteor/meteor" { /** Error **/ /** Method **/ - function methods(methods: Object): void; + interface MethodThisType { + isSimulation: boolean; + userId: string | null; + connection: Connection | null; + setUserId(userId: string): void; + unblock(): void; + } + + function methods(methods: {[key: string]: (this: MethodThisType, ...args: any[]) => any}): void; function call(name: string, ...args: any[]): any; From 14e3e2b16793f34e0e0525494a192a532ca5e540 Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 11:28:01 -0600 Subject: [PATCH 136/200] [kissfft-js] update tests --- types/kissfft-js/kissfft-js-tests.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/types/kissfft-js/kissfft-js-tests.ts b/types/kissfft-js/kissfft-js-tests.ts index 76c0da2001..7de3255660 100644 --- a/types/kissfft-js/kissfft-js-tests.ts +++ b/types/kissfft-js/kissfft-js-tests.ts @@ -1,12 +1,11 @@ -import {FFT} from "kissfft-js"; -import {FFTR} from "kissfft-js"; +import * as kissFFT from "kissfft-js"; -const fft = new FFT(0); // $ExpectType FFT +const fft = new kissFFT.FFT(0); // $ExpectType FFT fft.forward([1, 2, 3]); // $ExpectType number[] fft.inverse([1, 2, 3]); // $ExpectType number[] fft.dispose(); // $ExpectType void -const fftr = new FFTR(0); // $ExpectType FFTR +const fftr = new kissFFT.FFTR(0); // $ExpectType FFTR fftr.forward([1, 2, 3]); // $ExpectType number[] fftr.inverse([1, 2, 3]); // $ExpectType number[] fftr.dispose(); // $ExpectType void From 67d97feb29fa0dfbe86c7b831837997c385bf917 Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Wed, 6 Feb 2019 12:02:07 -0600 Subject: [PATCH 137/200] Add types for @carbon/themes --- types/carbon__themes/carbon__themes-tests.ts | 59 ++++++++++++++++ types/carbon__themes/index.d.ts | 74 ++++++++++++++++++++ types/carbon__themes/tsconfig.json | 19 +++++ types/carbon__themes/tslint.json | 1 + 4 files changed, 153 insertions(+) create mode 100644 types/carbon__themes/carbon__themes-tests.ts create mode 100644 types/carbon__themes/index.d.ts create mode 100644 types/carbon__themes/tsconfig.json create mode 100644 types/carbon__themes/tslint.json diff --git a/types/carbon__themes/carbon__themes-tests.ts b/types/carbon__themes/carbon__themes-tests.ts new file mode 100644 index 0000000000..7515742031 --- /dev/null +++ b/types/carbon__themes/carbon__themes-tests.ts @@ -0,0 +1,59 @@ +import ThemePackage from "@carbon/themes"; + +interface Theme { + active01: string; + activeDanger: string; + activePrimary: string; + activeSecondary: string; + activeTertiary: string; + activeUI: string; + brand01: string; + brand02: string; + brand03: string; + disabled01: string; + disabled02: string; + disabled03: string; + field01: string; + field02: string; + focus: string; + highlight: string; + hoverDanger: string; + hoverField: string; + hoverPrimary: string; + hoverPrimaryText: string; + hoverRow: string; + hoverSecondary: string; + hoverSelectedUI: string; + hoverTertiary: string; + hoverUI: string; + icon01: string; + icon02: string; + interactive01: string; + interactive02: string; + interactive03: string; + inverse01: string; + inverse02: string; + overlay01: string; + selectedUI: string; + support01: string; + support02: string; + support03: string; + support04: string; + text01: string; + text02: string; + text03: string; + text04: string; + ui01: string; + ui02: string; + ui03: string; + ui04: string; + ui05: string; + uiBackground: string; + visitedLink: string; +} + +const getDefaultTheme = (): Theme => { + return ThemePackage.white; +}; + +getDefaultTheme(); diff --git a/types/carbon__themes/index.d.ts b/types/carbon__themes/index.d.ts new file mode 100644 index 0000000000..e10f17f35c --- /dev/null +++ b/types/carbon__themes/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for @carbon/themes 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/themes +// Definitions by: Vince Picone <https://github.com/vpicone> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default carbon__themes; + +interface Theme { + active01: string; + activeDanger: string; + activePrimary: string; + activeSecondary: string; + activeTertiary: string; + activeUI: string; + brand01: string; + brand02: string; + brand03: string; + disabled01: string; + disabled02: string; + disabled03: string; + field01: string; + field02: string; + focus: string; + highlight: string; + hoverDanger: string; + hoverField: string; + hoverPrimary: string; + hoverPrimaryText: string; + hoverRow: string; + hoverSecondary: string; + hoverSelectedUI: string; + hoverTertiary: string; + hoverUI: string; + icon01: string; + icon02: string; + interactive01: string; + interactive02: string; + interactive03: string; + inverse01: string; + inverse02: string; + overlay01: string; + selectedUI: string; + support01: string; + support02: string; + support03: string; + support04: string; + text01: string; + text02: string; + text03: string; + text04: string; + ui01: string; + ui02: string; + ui03: string; + ui04: string; + ui05: string; + uiBackground: string; + visitedLink: string; +} + +// The default theme is included as a top level export +type ThemePackage = { + white: Theme; + g10: Theme; + g100: Theme; + g90: Theme; + themes: { + g10: Theme; + g100: Theme; + g90: Theme; + white: Theme; + }; +} & Theme; + +declare const carbon__themes: ThemePackage; diff --git a/types/carbon__themes/tsconfig.json b/types/carbon__themes/tsconfig.json new file mode 100644 index 0000000000..490b17648e --- /dev/null +++ b/types/carbon__themes/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/themes": ["carbon__themes"] + } + }, + "files": ["index.d.ts", "carbon__themes-tests.ts"] +} diff --git a/types/carbon__themes/tslint.json b/types/carbon__themes/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__themes/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 97515160efdb573a8e76ae4c73d49b17d817727c Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 12:46:54 -0600 Subject: [PATCH 138/200] [kissfft-js] enable strictFunctionTypes check --- types/kissfft-js/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/kissfft-js/tsconfig.json b/types/kissfft-js/tsconfig.json index 5dfeddfade..5164a8f4bd 100644 --- a/types/kissfft-js/tsconfig.json +++ b/types/kissfft-js/tsconfig.json @@ -13,7 +13,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true }, "files": [ "index.d.ts", From ff0e1f5aa0ddac9c1ae12797bcbcf0ab1fae98aa Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 12:50:22 -0600 Subject: [PATCH 139/200] [kissfft-js] fix lint rule strict-export-declare-modifiers --- types/kissfft-js/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts index 11f41a3505..14977f7aaa 100644 --- a/types/kissfft-js/index.d.ts +++ b/types/kissfft-js/index.d.ts @@ -15,3 +15,5 @@ export class FFT extends AbstractKissFFT { export class FFTR extends AbstractKissFFT { } + +export {} From fd72fae91ed6e896dbcf9802504aab3507dd02d8 Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 12:53:03 -0600 Subject: [PATCH 140/200] [kissfft-js] comply to strict-export-declare-modifiers lint rule --- types/kissfft-js/index.d.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts index 14977f7aaa..f03119e4f5 100644 --- a/types/kissfft-js/index.d.ts +++ b/types/kissfft-js/index.d.ts @@ -3,17 +3,16 @@ // Definitions by: racerhere <https://github.com/racerhere> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/types/kissfft-js -declare abstract class AbstractKissFFT { +export class FFT { constructor(size: number); forward(input: number[]): number[]; inverse(input: number[]): number[]; dispose(): void; } -export class FFT extends AbstractKissFFT { -} - -export class FFTR extends AbstractKissFFT { -} - -export {} +export class FFTR { + constructor(size: number); + forward(input: number[]): number[]; + inverse(input: number[]): number[]; + dispose(): void; +} \ No newline at end of file From b27226fdf1f5f87594d113ad695057a88eae1376 Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 12:54:31 -0600 Subject: [PATCH 141/200] [kissfft-js] comply to eofline lint rule --- types/kissfft-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts index f03119e4f5..dc745354ec 100644 --- a/types/kissfft-js/index.d.ts +++ b/types/kissfft-js/index.d.ts @@ -15,4 +15,4 @@ export class FFTR { forward(input: number[]): number[]; inverse(input: number[]): number[]; dispose(): void; -} \ No newline at end of file +} From 98149d72de09d1e5af3661a8c4b3f1fff8d9de5b Mon Sep 17 00:00:00 2001 From: John Slemmer <john.slemmer@gmail.com> Date: Wed, 6 Feb 2019 11:09:14 -0800 Subject: [PATCH 142/200] createError path and message optional from the documentation at https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema > this.createError(Object: { path: String, message: String }): create and return a validation error. Useful for dynamically setting the path, or more likely, the error message. *If either option is omitted it will use the current path, or default message*. --- types/yup/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 9f3cb687a2..8fc9461e85 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -227,7 +227,7 @@ export interface TestContext { parent: any; schema: Schema<any>; resolve: (value: any) => any; - createError: (params: { path: string; message: string }) => ValidationError; + createError: (params: { path?: string; message?: string }) => ValidationError; } export interface ValidateOptions { From 6783579dd5789957135d92fe2c9e2c1c8d8ac872 Mon Sep 17 00:00:00 2001 From: John Slemmer <john.slemmer@gmail.com> Date: Wed, 6 Feb 2019 11:16:47 -0800 Subject: [PATCH 143/200] Update yup-tests.ts --- types/yup/yup-tests.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index a90a7df25d..9e63952cc4 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -199,6 +199,12 @@ const testContext = function(this: TestContext) { this.resolve; // $ExpectType ValidationError this.createError({ path: "1", message: "1" }); + // $ExpectType ValidationError + this.createError({ message: "1" }); + // $ExpectType ValidationError + this.createError({ path: "1"}); + // $ExpectType ValidationError + this.createError(); return true; }; mixed.test("with-context", "it uses function context", testContext); From 9a5a7d1f4ac6cdb6e99ab41e2b6d321fb78be5f3 Mon Sep 17 00:00:00 2001 From: John Slemmer <john.slemmer@gmail.com> Date: Wed, 6 Feb 2019 11:42:46 -0800 Subject: [PATCH 144/200] make createError params optional entirely --- types/yup/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 8fc9461e85..b4a953410f 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -227,7 +227,7 @@ export interface TestContext { parent: any; schema: Schema<any>; resolve: (value: any) => any; - createError: (params: { path?: string; message?: string }) => ValidationError; + createError: (params?: { path?: string; message?: string }) => ValidationError; } export interface ValidateOptions { From 58203a3042527af4163fa34408e87eb19e7c1e39 Mon Sep 17 00:00:00 2001 From: Mischa MacLeod <mischa@singlesource.io> Date: Tue, 5 Feb 2019 12:04:59 +1300 Subject: [PATCH 145/200] keyFromPublic takes an object containing both x and y strings encoded as Hex --- types/elliptic/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts index fa8e19a2cf..722568a6f6 100644 --- a/types/elliptic/index.d.ts +++ b/types/elliptic/index.d.ts @@ -176,7 +176,7 @@ export class ec { keyPair(options: ec.KeyPairOptions): ec.KeyPair; keyFromPrivate(priv: Buffer | string | ec.KeyPair, enc?: string): ec.KeyPair; - keyFromPublic(pub: Buffer | string | ec.KeyPair, enc?: string): ec.KeyPair; + keyFromPublic(pub: Buffer | string | {x: string, y: string} | ec.KeyPair, enc?: string): ec.KeyPair; genKeyPair(options?: ec.GenKeyPairOptions): ec.KeyPair; sign(msg: BNInput, key: Buffer | ec.KeyPair, enc: string, options?: ec.SignOptions): ec.Signature; sign(msg: BNInput, key: Buffer | ec.KeyPair, options?: ec.SignOptions): ec.Signature; @@ -201,7 +201,7 @@ export namespace ec { } class KeyPair { - static fromPublic(ec: ec, pub: Buffer | string | KeyPair, enc?: string): KeyPair; + static fromPublic(ec: ec, pub: Buffer | string | {x: string, y: string} | KeyPair, enc?: string): KeyPair; static fromPrivate(ec: ec, priv: Buffer | string | KeyPair, enc?: string): KeyPair; ec: ec; From 5d016cee8f01b5307da196a6feca3583ec5a939c Mon Sep 17 00:00:00 2001 From: Kristoffer <hello@kristoffer.is> Date: Wed, 6 Feb 2019 22:18:13 +0100 Subject: [PATCH 146/200] libxmljs: Type all options --- types/libxmljs/index.d.ts | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index 5ba3fc294f..6540561a07 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -15,7 +15,40 @@ export const libxml_parser_version: string; interface StringMap { [key: string]: string; } // tslint:disable-next-line:strict-export-declare-modifiers -interface ParserOptions { [key: string]: boolean | string; } +interface ParserOptions { + recover?: boolean; + noent?: boolean; + dtdload?: boolean; + doctype?: boolean; + dtdattr?: any; + dtdvalid?: boolean; + noerror?: boolean; + errors?: boolean; + nowarning?: boolean; + warnings?: boolean; + pedantic?: boolean; + noblanks?: boolean; + blanks?: boolean; + sax1?: boolean; + xinclude?: boolean; + nonet?: boolean; + net?: boolean; + nodict?: boolean; + dict?: boolean; + nsclean?: boolean; + implied?: boolean; + nocdata?: boolean; + cdata?: boolean; + noxincnode?: boolean; + compact?: boolean; + old?: boolean; + nobasefix?: boolean; + basefix?: boolean; + huge?: boolean; + oldsax?: boolean; + ignore_enc?: boolean; + big_lines?: boolean; +} export function parseXml(source: string, options?: ParserOptions): Document; export function parseXmlString(source: string, options?: ParserOptions): Document; From 536174e4b335b716cd68c781cec2bf5e820109f3 Mon Sep 17 00:00:00 2001 From: Jonathan Viney <jonathan.viney@gmail.com> Date: Wed, 6 Feb 2019 12:16:29 +1300 Subject: [PATCH 147/200] [video.js]: add player networkState --- types/video.js/index.d.ts | 14 ++++++++++++++ types/video.js/video.js-tests.ts | 2 ++ 2 files changed, 16 insertions(+) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 9bcc8e858e..2c2457e3ea 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -3721,6 +3721,13 @@ declare namespace videojs { HaveEnoughData = 4 } + enum NetworkState { + Empty = 0, + Idle = 1, + Loading = 2, + NoSource = 3 + } + /** * An instance of the `Player` class is created when any of the Video.js setup methods * are used to initialize a video. @@ -4257,6 +4264,13 @@ declare namespace videojs { muted(): boolean; + /** + * Returns the current state of network activity for the element + * + * @return The current network state + */ + networkState(): NetworkState; + /** * Pause the video playback * @check diff --git a/types/video.js/video.js-tests.ts b/types/video.js/video.js-tests.ts index 910085557a..e21d7fe581 100644 --- a/types/video.js/video.js-tests.ts +++ b/types/video.js/video.js-tests.ts @@ -61,6 +61,8 @@ videojs("example_video_1").ready(function() { this.requestFullscreen(); + const networkState: videojs.NetworkState = this.networkState(); + testEvents(this); testComponents(this); From 9e0b1db4347a4357e7e3f11e06e744c93cf32219 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 6 Feb 2019 13:35:10 -0800 Subject: [PATCH 148/200] [jscodeshift] Use 'export =' and 'require' to be consistent with JS implementation --- types/jscodeshift/index.d.ts | 99 +---- types/jscodeshift/src/Collection.d.ts | 32 +- .../src/collections/JSXElement.d.ts | 19 +- types/jscodeshift/src/collections/Node.d.ts | 28 +- .../src/collections/VariableDeclarator.d.ts | 14 +- types/jscodeshift/src/core.d.ts | 363 ++++++++++++++++++ types/jscodeshift/src/template.d.ts | 28 +- .../bind-this-to-bind-expression.ts | 8 +- .../js-transforms/props-to-destructuring.ts | 2 +- types/jscodeshift/tsconfig.json | 1 + 10 files changed, 439 insertions(+), 155 deletions(-) create mode 100644 types/jscodeshift/src/core.d.ts diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index f4cee2db55..e19423d928 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -4,101 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 -import { ASTNode } from "ast-types/gen/nodes"; -import recast, { Builders, NamedTypes, NodePath, Options, Parser } from "recast"; -import { Collection, registerMethods } from "./src/Collection"; -import * as JSXElement from "./src/collections/JSXElement"; -import * as VariableDeclarator from "./src/collections/VariableDeclarator"; -import { Template } from "./src/template"; +import core = require("./src/core"); -export type ASTPath<N = ASTNode> = NodePath<N, N>; - -export interface Filters { - JSXElement: JSXElement.FilterMethods; - VariableDeclarator: VariableDeclarator.FilterMethods; -} - -export interface Mappings { - JSXElement: JSXElement.MappingMethods; -} - -export interface Plugin { - (core: Core): void; -} - -export interface FileInfo { - /** The absolute path to the current file. */ - path: string; - /** The source code of the current file. */ - source: string; -} - -export interface Stats { - /** - * Helper function to collect data during --dry runs. - * This function keeps a counter for how often it was called with a specific argument. - * The result is shown in the console. Useful for finding out how many files match a criterion. - */ - (name: string, quantity?: number): void; -} - -interface Core { - (source: string, options?: Options): Collection<any>; - (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection<any>; - - registerMethods: typeof registerMethods; - - types: typeof recast.types; - - match(path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode): boolean; - - /** template, bound to default parser */ - template: Template; - - filters: Filters; - - mappings: Mappings; - - /** - * Utility function for registering plugins. - * - * Plugins are simple functions that are passed the core jscodeshift instance. - * They should extend jscodeshift by calling `registerMethods`, etc. - * This method guards against repeated registrations (the plugin callback will only be called once). - */ - use(plugin: Plugin): void; - - /** - * Returns a version of the core jscodeshift function "bound" to a specific - * parser. - */ - withParser(parser: string | Parser): JSCodeshift; -} - -type JSCodeshift = Core & NamedTypes & Builders; - -declare const core: JSCodeshift; -export default core; - -export interface API { - j: JSCodeshift; - jscodeshift: JSCodeshift; - stats: Stats; - report: (msg: string) => void; -} - -export interface Options { - [option: string]: any; -} - -export interface Transform { - /** - * If a string is returned and it is different from passed source, the transform is considered to be successful. - * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. - * If nothing is returned, the file is not supposed to be transformed (which is ok). - */ - (file: FileInfo, api: API, options: Options): string | null | undefined | void; -} - -export * from "ast-types/gen/nodes"; -export { Collection, Parser }; +export = core; diff --git a/types/jscodeshift/src/Collection.d.ts b/types/jscodeshift/src/Collection.d.ts index 5ddf7b2bdc..2cab87b153 100644 --- a/types/jscodeshift/src/Collection.d.ts +++ b/types/jscodeshift/src/Collection.d.ts @@ -1,9 +1,9 @@ -import { ASTNode, NodePath, Options, Type } from "recast"; -import * as JSXElement from "./collections/JSXElement"; -import * as NodeCollection from "./collections/Node"; -import * as VariableDeclarator from "./collections/VariableDeclarator"; +import recast = require("recast"); +import JSXElement = require("./collections/JSXElement"); +import NodeCollection = require("./collections/Node"); +import VariableDeclarator = require("./collections/VariableDeclarator"); -type ASTPath<N> = NodePath<N, N>; +type ASTPath<N> = recast.NodePath<N, N>; export interface Collection<N> extends NodeCollection.TraversalMethods, @@ -18,7 +18,7 @@ export interface Collection<N> * @param types An array of types all the paths in the collection * have in common. If not passed, it will be inferred from the paths. */ - new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<Type<any>>): this; + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<recast.Type<any>>): this; /** * Returns a new collection containing the nodes for which the callback returns true. @@ -58,13 +58,13 @@ export interface Collection<N> * @param callback * @param type Force the new collection to be of a specific type */ - map<T = ASTNode>( + map<T = recast.ASTNode>( callback: ( path: ASTPath<N>, i: number, paths: Array<ASTPath<N>> ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, - type: Type<any> + type: recast.Type<any> ): Collection<T>; /** Returns the number of elements in this collection. */ @@ -85,7 +85,7 @@ export interface Collection<N> * Converts the AST back to a string, using recast. * @param options directly passed to recast's printer */ - toSource(options?: Options): string; + toSource(options?: recast.Options): string; /** * Returns a new collection containing only the element at position index. @@ -107,9 +107,13 @@ export interface Collection<N> /** * Returns true if this collection has the type 'type'. */ - isOfType(type: Type<any>): boolean; + isOfType(type: recast.Type<any>): boolean; } +export function fromPaths(...args: any[]): any; + +export function fromNodes(...args: any[]): any; + /** * This function adds the provided methods to the prototype of the corresponding * typed collection. If no type is passed, the methods are added to @@ -118,6 +122,10 @@ export interface Collection<N> * @param methods Methods to add to the prototype * @param type Optional type to add the methods to */ -export function registerMethods(methods: object, type?: Type<any>): void; +export function registerMethods(methods: object, type?: recast.Type<any>): void; -export { }; // to shut off automatic exporting +export function hasConflictingRegistration(...args: any[]): any; + +export function setDefaultCollectionType(...args: any[]): any; + +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/JSXElement.d.ts b/types/jscodeshift/src/collections/JSXElement.d.ts index 730c33ad90..0490e40f76 100644 --- a/types/jscodeshift/src/collections/JSXElement.d.ts +++ b/types/jscodeshift/src/collections/JSXElement.d.ts @@ -1,14 +1,15 @@ -import { JSXElement } from "ast-types/gen/nodes"; -import { NodePath } from "recast"; -import { Collection } from "../Collection"; +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); -type ASTPath<N> = NodePath<N, N>; +type ASTPath<N> = recast.NodePath<N, N>; +type JSXElement = nodes.JSXElement; export interface GlobalMethods { /** * Finds all JSXElements optionally filtered by name */ - findJSXElements(name?: string): Collection<JSXElement>; + findJSXElements(name?: string): Collection.Collection<JSXElement>; /** * Finds all JSXElements by module name. Given @@ -19,7 +20,7 @@ export interface GlobalMethods { * findJSXElementsByModuleName('Foo') will find <Bar />, without having to * know the variable name. */ - findJSXElementsByModuleName(moduleName: string): Collection<JSXElement>; + findJSXElementsByModuleName(moduleName: string): Collection.Collection<JSXElement>; } type Defined<T> = T extends undefined ? never : T; @@ -30,13 +31,13 @@ export interface TraversalMethods { * Returns all child nodes, including literals and expressions. * This method only applies to JSXElement typed collections. */ - childNodes(): Collection<JSXElementChild>; + childNodes(): Collection.Collection<JSXElementChild>; /** * Returns all children that are JSXElements. * This method only applies to JSXElement typed collections. */ - childElements(): Collection<JSXElement>; + childElements(): Collection.Collection<JSXElement>; } interface Filter { @@ -67,4 +68,4 @@ export function register(): void; export const filters: FilterMethods; export const mappings: MappingMethods; -export { }; // to shut off automatic exporting +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/Node.d.ts b/types/jscodeshift/src/collections/Node.d.ts index e596c8a8ab..d1e74f314d 100644 --- a/types/jscodeshift/src/collections/Node.d.ts +++ b/types/jscodeshift/src/collections/Node.d.ts @@ -1,34 +1,34 @@ -import { VariableDeclarator } from "ast-types/gen/nodes"; -import { ASTNode, NodePath, Type } from "recast"; -import { Collection } from "../Collection"; +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); -type ASTPath<N> = NodePath<N, N>; +type ASTPath<N> = recast.NodePath<N, N>; export interface TraversalMethods { /** * Find nodes of a specific type within the nodes of this collection. */ - find<T>(type: Type<T>, filter?: ((value: any) => boolean) | object): Collection<T>; + find<T>(type: recast.Type<T>, filter?: ((value: any) => boolean) | object): Collection.Collection<T>; /** * Returns a collection containing the paths that create the scope of the * currently selected paths. Dedupes the paths. */ - closestScope(): Collection<ASTNode>; + closestScope(): Collection.Collection<nodes.ASTNode>; /** * Traverse the AST up and finds the closest node of the provided type. */ - closest<T>(type: Type<T>, filter?: any): Collection<T>; + closest<T>(type: recast.Type<T>, filter?: any): Collection.Collection<T>; /** * Finds the declaration for each selected path. Useful for member expressions * or JSXElements. Expects a callback function that maps each path to the name * to look for. * - * If the callback returns a falsey value, the element is skipped. + * If the callback returns a falsy value, the element is skipped. */ - getVariableDeclarators(nameGetter: (...args: any[]) => any): Collection<VariableDeclarator>; + getVariableDeclarators(nameGetter: (...args: any[]) => any): Collection.Collection<nodes.VariableDeclarator>; } export interface MutationMethods<N> { @@ -37,21 +37,21 @@ export interface MutationMethods<N> { * is provided it is executed for every node and the node is replaced with the * functions return value. */ - replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection<T>; + replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection.Collection<T>; /** * Inserts a new node before the current one. */ - insertBefore(insert: any): Collection<N>; + insertBefore(insert: any): Collection.Collection<N>; /** * Inserts a new node after the current one. */ - insertAfter(insert: any): Collection<N>; + insertAfter(insert: any): Collection.Collection<N>; - remove(): Collection<N>; + remove(): Collection.Collection<N>; } export function register(): void; -export { }; // to shut off automatic exporting +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/VariableDeclarator.d.ts b/types/jscodeshift/src/collections/VariableDeclarator.d.ts index 8627b316db..eb7c8bcdfd 100644 --- a/types/jscodeshift/src/collections/VariableDeclarator.d.ts +++ b/types/jscodeshift/src/collections/VariableDeclarator.d.ts @@ -1,14 +1,14 @@ -import { VariableDeclarator } from "ast-types/gen/nodes"; -import { NodePath } from "recast"; -import { Collection } from "../Collection"; +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); -type ASTPath<N> = NodePath<N, N>; +type ASTPath<N> = recast.NodePath<N, N>; export interface GlobalMethods { /** * Finds all variable declarators, optionally filtered by name. */ - findVariableDeclarators(name?: string): Collection<VariableDeclarator>; + findVariableDeclarators(name?: string): Collection.Collection<nodes.VariableDeclarator>; } export interface TransformMethods<N> { @@ -16,7 +16,7 @@ export interface TransformMethods<N> { * Renames a variable and all its occurrences. * This method only applies to VariableDeclarator typed collections. */ - renameTo(newName: string): Collection<N>; + renameTo(newName: string): Collection.Collection<N>; } interface Filter { @@ -36,4 +36,4 @@ export interface FilterMethods { export function register(): void; export const filters: FilterMethods; -export { }; // to shut off automatic exporting +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/core.d.ts b/types/jscodeshift/src/core.d.ts new file mode 100644 index 0000000000..9b9f48305d --- /dev/null +++ b/types/jscodeshift/src/core.d.ts @@ -0,0 +1,363 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("./Collection"); +import template = require("./template"); +import VariableDeclarator = require("./collections/VariableDeclarator"); +import JSXElement = require("./collections/JSXElement"); + +declare namespace core { + type Parser = recast.Parser; + + interface Filters { + JSXElement: JSXElement.FilterMethods; + VariableDeclarator: VariableDeclarator.FilterMethods; + } + + interface Mappings { + JSXElement: JSXElement.MappingMethods; + } + + interface Plugin { + (core: Core): void; + } + + interface FileInfo { + /** The absolute path to the current file. */ + path: string; + /** The source code of the current file. */ + source: string; + } + + interface Stats { + /** + * Helper function to collect data during --dry runs. + * This function keeps a counter for how often it was called with a specific argument. + * The result is shown in the console. Useful for finding out how many files match a criterion. + */ + (name: string, quantity?: number): void; + } + + type ASTPath<N = ASTNode> = recast.NodePath<N, N>; + + interface Core { + (source: string, options?: Options): Collection.Collection<any>; + (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection.Collection<any>; + + registerMethods: typeof Collection.registerMethods; + + types: typeof recast.default.types; + + match( + path: ASTNode | ASTPath, + filter: ((path: ASTNode) => boolean) | ASTNode + ): boolean; + + /** template, bound to default parser */ + template: template.Template; + + filters: Filters; + + mappings: Mappings; + + /** + * Utility function for registering plugins. + * + * Plugins are simple functions that are passed the core jscodeshift instance. + * They should extend jscodeshift by calling `registerMethods`, etc. + * This method guards against repeated registrations (the plugin callback will only be called once). + */ + use(plugin: Plugin): void; + + /** + * Returns a version of the core jscodeshift function "bound" to a specific + * parser. + */ + withParser(parser: string | Parser): JSCodeshift; + } + + type JSCodeshift = Core & recast.NamedTypes & recast.Builders; + + interface API { + j: JSCodeshift; + jscodeshift: JSCodeshift; + stats: Stats; + report: (msg: string) => void; + } + + interface Options { + [option: string]: any; + } + + interface Transform { + /** + * If a string is returned and it is different from passed source, the transform is considered to be successful. + * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. + * If nothing is returned, the file is not supposed to be transformed (which is ok). + */ + (file: FileInfo, api: API, options: Options): string | null | undefined | void; + } + + type ASTNode = nodes.ASTNode; + + type AnyTypeAnnotation = nodes.AnyTypeAnnotation; + type ArrayExpression = nodes.ArrayExpression; + type ArrayPattern = nodes.ArrayPattern; + type ArrayTypeAnnotation = nodes.ArrayTypeAnnotation; + type ArrowFunctionExpression = nodes.ArrowFunctionExpression; + type AssignmentExpression = nodes.AssignmentExpression; + type AssignmentPattern = nodes.AssignmentPattern; + type AwaitExpression = nodes.AwaitExpression; + type BigIntLiteral = nodes.BigIntLiteral; + type BinaryExpression = nodes.BinaryExpression; + type BindExpression = nodes.BindExpression; + type Block = nodes.Block; + type BlockStatement = nodes.BlockStatement; + type BooleanLiteral = nodes.BooleanLiteral; + type BooleanLiteralTypeAnnotation = nodes.BooleanLiteralTypeAnnotation; + type BooleanTypeAnnotation = nodes.BooleanTypeAnnotation; + type BreakStatement = nodes.BreakStatement; + type CallExpression = nodes.CallExpression; + type CatchClause = nodes.CatchClause; + type ClassBody = nodes.ClassBody; + type ClassDeclaration = nodes.ClassDeclaration; + type ClassExpression = nodes.ClassExpression; + type ClassImplements = nodes.ClassImplements; + type ClassMethod = nodes.ClassMethod; + type ClassPrivateMethod = nodes.ClassPrivateMethod; + type ClassPrivateProperty = nodes.ClassPrivateProperty; + type ClassProperty = nodes.ClassProperty; + type ClassPropertyDefinition = nodes.ClassPropertyDefinition; + type Comment = nodes.Comment; + type CommentBlock = nodes.CommentBlock; + type CommentLine = nodes.CommentLine; + type ComprehensionBlock = nodes.ComprehensionBlock; + type ComprehensionExpression = nodes.ComprehensionExpression; + type ConditionalExpression = nodes.ConditionalExpression; + type ContinueStatement = nodes.ContinueStatement; + type DebuggerStatement = nodes.DebuggerStatement; + type Declaration = nodes.Declaration; + type DeclareClass = nodes.DeclareClass; + type DeclaredPredicate = nodes.DeclaredPredicate; + type DeclareExportAllDeclaration = nodes.DeclareExportAllDeclaration; + type DeclareExportDeclaration = nodes.DeclareExportDeclaration; + type DeclareFunction = nodes.DeclareFunction; + type DeclareInterface = nodes.DeclareInterface; + type DeclareModule = nodes.DeclareModule; + type DeclareModuleExports = nodes.DeclareModuleExports; + type DeclareOpaqueType = nodes.DeclareOpaqueType; + type DeclareTypeAlias = nodes.DeclareTypeAlias; + type DeclareVariable = nodes.DeclareVariable; + type Decorator = nodes.Decorator; + type Directive = nodes.Directive; + type DirectiveLiteral = nodes.DirectiveLiteral; + type DoExpression = nodes.DoExpression; + type DoWhileStatement = nodes.DoWhileStatement; + type EmptyStatement = nodes.EmptyStatement; + type EmptyTypeAnnotation = nodes.EmptyTypeAnnotation; + type ExistentialTypeParam = nodes.ExistentialTypeParam; + type ExistsTypeAnnotation = nodes.ExistsTypeAnnotation; + type ExportAllDeclaration = nodes.ExportAllDeclaration; + type ExportBatchSpecifier = nodes.ExportBatchSpecifier; + type ExportDeclaration = nodes.ExportDeclaration; + type ExportDefaultDeclaration = nodes.ExportDefaultDeclaration; + type ExportDefaultSpecifier = nodes.ExportDefaultSpecifier; + type ExportNamedDeclaration = nodes.ExportNamedDeclaration; + type ExportNamespaceSpecifier = nodes.ExportNamespaceSpecifier; + type ExportSpecifier = nodes.ExportSpecifier; + type Expression = nodes.Expression; + type ExpressionStatement = nodes.ExpressionStatement; + type File = nodes.File; + type Flow = nodes.Flow; + type FlowPredicate = nodes.FlowPredicate; + type FlowType = nodes.FlowType; + type ForAwaitStatement = nodes.ForAwaitStatement; + type ForInStatement = nodes.ForInStatement; + type ForOfStatement = nodes.ForOfStatement; + type ForStatement = nodes.ForStatement; + type Function = nodes.Function; + type FunctionDeclaration = nodes.FunctionDeclaration; + type FunctionExpression = nodes.FunctionExpression; + type FunctionTypeAnnotation = nodes.FunctionTypeAnnotation; + type FunctionTypeParam = nodes.FunctionTypeParam; + type GeneratorExpression = nodes.GeneratorExpression; + type GenericTypeAnnotation = nodes.GenericTypeAnnotation; + type Identifier = nodes.Identifier; + type IfStatement = nodes.IfStatement; + type Import = nodes.Import; + type ImportDeclaration = nodes.ImportDeclaration; + type ImportDefaultSpecifier = nodes.ImportDefaultSpecifier; + type ImportNamespaceSpecifier = nodes.ImportNamespaceSpecifier; + type ImportSpecifier = nodes.ImportSpecifier; + type InferredPredicate = nodes.InferredPredicate; + type InterfaceDeclaration = nodes.InterfaceDeclaration; + type InterfaceExtends = nodes.InterfaceExtends; + type InterfaceTypeAnnotation = nodes.InterfaceTypeAnnotation; + type InterpreterDirective = nodes.InterpreterDirective; + type IntersectionTypeAnnotation = nodes.IntersectionTypeAnnotation; + type JSXAttribute = nodes.JSXAttribute; + type JSXClosingElement = nodes.JSXClosingElement; + type JSXClosingFragment = nodes.JSXClosingFragment; + type JSXElement = nodes.JSXElement; + type JSXEmptyExpression = nodes.JSXEmptyExpression; + type JSXExpressionContainer = nodes.JSXExpressionContainer; + type JSXFragment = nodes.JSXFragment; + type JSXIdentifier = nodes.JSXIdentifier; + type JSXMemberExpression = nodes.JSXMemberExpression; + type JSXNamespacedName = nodes.JSXNamespacedName; + type JSXOpeningElement = nodes.JSXOpeningElement; + type JSXOpeningFragment = nodes.JSXOpeningFragment; + type JSXSpreadAttribute = nodes.JSXSpreadAttribute; + type JSXSpreadChild = nodes.JSXSpreadChild; + type JSXText = nodes.JSXText; + type LabeledStatement = nodes.LabeledStatement; + type Line = nodes.Line; + type Literal = nodes.Literal; + type LogicalExpression = nodes.LogicalExpression; + type MemberExpression = nodes.MemberExpression; + type MemberTypeAnnotation = nodes.MemberTypeAnnotation; + type MetaProperty = nodes.MetaProperty; + type MethodDefinition = nodes.MethodDefinition; + type MixedTypeAnnotation = nodes.MixedTypeAnnotation; + type ModuleSpecifier = nodes.ModuleSpecifier; + type NewExpression = nodes.NewExpression; + type Node = nodes.Node; + type Noop = nodes.Noop; + type NullableTypeAnnotation = nodes.NullableTypeAnnotation; + type NullLiteral = nodes.NullLiteral; + type NullLiteralTypeAnnotation = nodes.NullLiteralTypeAnnotation; + type NullTypeAnnotation = nodes.NullTypeAnnotation; + type NumberLiteralTypeAnnotation = nodes.NumberLiteralTypeAnnotation; + type NumberTypeAnnotation = nodes.NumberTypeAnnotation; + type NumericLiteral = nodes.NumericLiteral; + type NumericLiteralTypeAnnotation = nodes.NumericLiteralTypeAnnotation; + type ObjectExpression = nodes.ObjectExpression; + type ObjectMethod = nodes.ObjectMethod; + type ObjectPattern = nodes.ObjectPattern; + type ObjectProperty = nodes.ObjectProperty; + type ObjectTypeAnnotation = nodes.ObjectTypeAnnotation; + type ObjectTypeCallProperty = nodes.ObjectTypeCallProperty; + type ObjectTypeIndexer = nodes.ObjectTypeIndexer; + type ObjectTypeInternalSlot = nodes.ObjectTypeInternalSlot; + type ObjectTypeProperty = nodes.ObjectTypeProperty; + type ObjectTypeSpreadProperty = nodes.ObjectTypeSpreadProperty; + type OpaqueType = nodes.OpaqueType; + type OptionalCallExpression = nodes.OptionalCallExpression; + type OptionalMemberExpression = nodes.OptionalMemberExpression; + type ParenthesizedExpression = nodes.ParenthesizedExpression; + type Pattern = nodes.Pattern; + type Position = nodes.Position; + type Printable = nodes.Printable; + type PrivateName = nodes.PrivateName; + type Program = nodes.Program; + type Property = nodes.Property; + type PropertyPattern = nodes.PropertyPattern; + type QualifiedTypeIdentifier = nodes.QualifiedTypeIdentifier; + type RegExpLiteral = nodes.RegExpLiteral; + type RestElement = nodes.RestElement; + type RestProperty = nodes.RestProperty; + type ReturnStatement = nodes.ReturnStatement; + type SequenceExpression = nodes.SequenceExpression; + type SourceLocation = nodes.SourceLocation; + type Specifier = nodes.Specifier; + type SpreadElement = nodes.SpreadElement; + type SpreadElementPattern = nodes.SpreadElementPattern; + type SpreadProperty = nodes.SpreadProperty; + type SpreadPropertyPattern = nodes.SpreadPropertyPattern; + type Statement = nodes.Statement; + type StringLiteral = nodes.StringLiteral; + type StringLiteralTypeAnnotation = nodes.StringLiteralTypeAnnotation; + type StringTypeAnnotation = nodes.StringTypeAnnotation; + type Super = nodes.Super; + type SwitchCase = nodes.SwitchCase; + type SwitchStatement = nodes.SwitchStatement; + type TaggedTemplateExpression = nodes.TaggedTemplateExpression; + type TemplateElement = nodes.TemplateElement; + type TemplateLiteral = nodes.TemplateLiteral; + type ThisExpression = nodes.ThisExpression; + type ThisTypeAnnotation = nodes.ThisTypeAnnotation; + type ThrowStatement = nodes.ThrowStatement; + type TryStatement = nodes.TryStatement; + type TSAnyKeyword = nodes.TSAnyKeyword; + type TSArrayType = nodes.TSArrayType; + type TSAsExpression = nodes.TSAsExpression; + type TSBooleanKeyword = nodes.TSBooleanKeyword; + type TSCallSignatureDeclaration = nodes.TSCallSignatureDeclaration; + type TSConditionalType = nodes.TSConditionalType; + type TSConstructorType = nodes.TSConstructorType; + type TSConstructSignatureDeclaration = nodes.TSConstructSignatureDeclaration; + type TSDeclareFunction = nodes.TSDeclareFunction; + type TSDeclareMethod = nodes.TSDeclareMethod; + type TSEnumDeclaration = nodes.TSEnumDeclaration; + type TSEnumMember = nodes.TSEnumMember; + type TSExportAssignment = nodes.TSExportAssignment; + type TSExpressionWithTypeArguments = nodes.TSExpressionWithTypeArguments; + type TSExternalModuleReference = nodes.TSExternalModuleReference; + type TSFunctionType = nodes.TSFunctionType; + type TSHasOptionalTypeAnnotation = nodes.TSHasOptionalTypeAnnotation; + type TSHasOptionalTypeParameters = nodes.TSHasOptionalTypeParameters; + type TSImportEqualsDeclaration = nodes.TSImportEqualsDeclaration; + type TSIndexedAccessType = nodes.TSIndexedAccessType; + type TSIndexSignature = nodes.TSIndexSignature; + type TSInferType = nodes.TSInferType; + type TSInterfaceBody = nodes.TSInterfaceBody; + type TSInterfaceDeclaration = nodes.TSInterfaceDeclaration; + type TSIntersectionType = nodes.TSIntersectionType; + type TSLiteralType = nodes.TSLiteralType; + type TSMappedType = nodes.TSMappedType; + type TSMethodSignature = nodes.TSMethodSignature; + type TSModuleBlock = nodes.TSModuleBlock; + type TSModuleDeclaration = nodes.TSModuleDeclaration; + type TSNamespaceExportDeclaration = nodes.TSNamespaceExportDeclaration; + type TSNeverKeyword = nodes.TSNeverKeyword; + type TSNonNullExpression = nodes.TSNonNullExpression; + type TSNullKeyword = nodes.TSNullKeyword; + type TSNumberKeyword = nodes.TSNumberKeyword; + type TSObjectKeyword = nodes.TSObjectKeyword; + type TSOptionalType = nodes.TSOptionalType; + type TSParameterProperty = nodes.TSParameterProperty; + type TSParenthesizedType = nodes.TSParenthesizedType; + type TSPropertySignature = nodes.TSPropertySignature; + type TSQualifiedName = nodes.TSQualifiedName; + type TSRestType = nodes.TSRestType; + type TSStringKeyword = nodes.TSStringKeyword; + type TSSymbolKeyword = nodes.TSSymbolKeyword; + type TSThisType = nodes.TSThisType; + type TSTupleType = nodes.TSTupleType; + type TSType = nodes.TSType; + type TSTypeAliasDeclaration = nodes.TSTypeAliasDeclaration; + type TSTypeAnnotation = nodes.TSTypeAnnotation; + type TSTypeAssertion = nodes.TSTypeAssertion; + type TSTypeLiteral = nodes.TSTypeLiteral; + type TSTypeOperator = nodes.TSTypeOperator; + type TSTypeParameter = nodes.TSTypeParameter; + type TSTypeParameterDeclaration = nodes.TSTypeParameterDeclaration; + type TSTypeParameterInstantiation = nodes.TSTypeParameterInstantiation; + type TSTypePredicate = nodes.TSTypePredicate; + type TSTypeQuery = nodes.TSTypeQuery; + type TSTypeReference = nodes.TSTypeReference; + type TSUndefinedKeyword = nodes.TSUndefinedKeyword; + type TSUnionType = nodes.TSUnionType; + type TSUnknownKeyword = nodes.TSUnknownKeyword; + type TSVoidKeyword = nodes.TSVoidKeyword; + type TupleTypeAnnotation = nodes.TupleTypeAnnotation; + type TypeAlias = nodes.TypeAlias; + type TypeAnnotation = nodes.TypeAnnotation; + type TypeCastExpression = nodes.TypeCastExpression; + type TypeofTypeAnnotation = nodes.TypeofTypeAnnotation; + type TypeParameter = nodes.TypeParameter; + type TypeParameterDeclaration = nodes.TypeParameterDeclaration; + type TypeParameterInstantiation = nodes.TypeParameterInstantiation; + type UnaryExpression = nodes.UnaryExpression; + type UnionTypeAnnotation = nodes.UnionTypeAnnotation; + type UpdateExpression = nodes.UpdateExpression; + type VariableDeclaration = nodes.VariableDeclaration; + type VariableDeclarator = nodes.VariableDeclarator; + type Variance = nodes.Variance; + type VoidTypeAnnotation = nodes.VoidTypeAnnotation; + type WhileStatement = nodes.WhileStatement; + type WithStatement = nodes.WithStatement; + type YieldExpression = nodes.YieldExpression; +} + +declare const core: core.JSCodeshift; +export = core; diff --git a/types/jscodeshift/src/template.d.ts b/types/jscodeshift/src/template.d.ts index 44bfab9be3..cfc0a3c543 100644 --- a/types/jscodeshift/src/template.d.ts +++ b/types/jscodeshift/src/template.d.ts @@ -1,14 +1,18 @@ -import { Parser } from "recast"; +import recast = require("recast"); -export interface Template { - /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ - statements(...args: any[]): any; - /** Tagged template function. Parses the string as source and returns an Statement AST node. */ - statement(...args: any[]): any; - /** Tagged template function. Parses the string as source and returns an Expression AST node. */ - expression(...args: any[]): any; +export = template; + +declare const template: typeof withParser; + +declare function withParser(parser: recast.Parser): template.Template; + +declare namespace template { + interface Template { + /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ + statements(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Statement AST node. */ + statement(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Expression AST node. */ + expression(...args: any[]): any; + } } - -export default function withParser(parser: Parser): Template; - -export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts index 6bd9be1fc8..1c6d8cda56 100644 --- a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts @@ -8,9 +8,9 @@ * let x = ::this.foo; * */ -import { Transform, MemberExpression } from "jscodeshift"; +import j = require("jscodeshift"); -const transform: Transform = (file, api) => { +const transform: j.Transform = (file, api) => { const j = api.jscodeshift; return j(file.source) // Find stuff that looks like this.xyz.bind(this) @@ -18,6 +18,8 @@ const transform: Transform = (file, api) => { // Ensure that .bind() is being called with only one argument, and that argument is "this". .filter(p => p.value.arguments.length === 1 && p.value.arguments[0].type === "ThisExpression") // We can now replace it with ::this.xyz - .replaceWith(p => j.bindExpression(null, (p.value.callee as MemberExpression).object)) + .replaceWith(p => j.bindExpression(null, (p.value.callee as j.MemberExpression).object)) .toSource(); }; + +export = transform; diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts index 138d61a620..db4caff58c 100644 --- a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -20,7 +20,7 @@ * } * */ -import { Transform, VariableDeclarator, ObjectPattern, Identifier, BlockStatement } from "jscodeshift"; +import { Transform, VariableDeclarator, ObjectPattern, Identifier } from "jscodeshift"; // tslint:disable-next-line max-line-length const keywordsStr = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index a2c90ce266..5937bd483a 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "src/core.d.ts", "src/Collection.d.ts", "src/collections/JSXElement.d.ts", "src/collections/Node.d.ts", From 47ffe1a4ba623bc5c363aee2ddb725ecadbfb361 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 6 Feb 2019 13:41:12 -0800 Subject: [PATCH 149/200] [jscodeshift] Pin ast-types and recast --- types/jscodeshift/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jscodeshift/package.json b/types/jscodeshift/package.json index 6fd3d8b70f..a501c0f28d 100644 --- a/types/jscodeshift/package.json +++ b/types/jscodeshift/package.json @@ -1,7 +1,7 @@ { "private": true, "dependencies": { - "ast-types": "^0.12.1", - "recast": "^0.17.2" + "ast-types": "0.12.1", + "recast": "0.17.2" } } From 48bd3be95c1664a96cda70f0ce405932ba8f71d1 Mon Sep 17 00:00:00 2001 From: Faizan Virani <fvirani@lyft.com> Date: Wed, 6 Feb 2019 15:42:16 -0800 Subject: [PATCH 150/200] Fixed typo in configure description --- types/enzyme/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 58e5938a8f..d9f858d2a7 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -619,7 +619,7 @@ export class EnzymeAdapter { } /** - * Configure enzyme to use the correct adapter for the react verstion + * Configure enzyme to use the correct adapter for the react version * This is enabling the Enzyme configuration with adapters in TS */ export function configure(options: { From 77a6c2a9706e17d83a3623f2b1686aafa383e27b Mon Sep 17 00:00:00 2001 From: Ron Buckton <ron.buckton@microsoft.com> Date: Thu, 31 Jan 2019 18:03:21 -0800 Subject: [PATCH 151/200] Adds 'typesVersions' support to NodeJS definitions --- types/node/base.d.ts | 41 ++++++++++++++++ types/node/globals.d.ts | 26 ---------- types/node/index.d.ts | 88 ++++++++++++++++++---------------- types/node/node-tests.ts | 6 +-- types/node/package.json | 11 +++++ types/node/ts3.1/index.d.ts | 18 +++++++ types/node/ts3.1/node-tests.ts | 2 + types/node/ts3.1/tsconfig.json | 25 ++++++++++ types/node/ts3.1/tslint.json | 10 ++++ types/node/ts3.1/util.d.ts | 10 ++++ types/node/tsconfig.json | 1 + types/node/util.d.ts | 22 ++++----- 12 files changed, 176 insertions(+), 84 deletions(-) create mode 100644 types/node/base.d.ts create mode 100644 types/node/package.json create mode 100644 types/node/ts3.1/index.d.ts create mode 100644 types/node/ts3.1/node-tests.ts create mode 100644 types/node/ts3.1/tsconfig.json create mode 100644 types/node/ts3.1/tslint.json create mode 100644 types/node/ts3.1/util.d.ts diff --git a/types/node/base.d.ts b/types/node/base.d.ts new file mode 100644 index 0000000000..70983d9515 --- /dev/null +++ b/types/node/base.d.ts @@ -0,0 +1,41 @@ +// base definnitions for all NodeJS modules that are not specific to any version of TypeScript +/// <reference path="globals.d.ts" /> +/// <reference path="assert.d.ts" /> +/// <reference path="async_hooks.d.ts" /> +/// <reference path="buffer.d.ts" /> +/// <reference path="child_process.d.ts" /> +/// <reference path="cluster.d.ts" /> +/// <reference path="console.d.ts" /> +/// <reference path="constants.d.ts" /> +/// <reference path="crypto.d.ts" /> +/// <reference path="dgram.d.ts" /> +/// <reference path="dns.d.ts" /> +/// <reference path="domain.d.ts" /> +/// <reference path="events.d.ts" /> +/// <reference path="fs.d.ts" /> +/// <reference path="http.d.ts" /> +/// <reference path="http2.d.ts" /> +/// <reference path="https.d.ts" /> +/// <reference path="inspector.d.ts" /> +/// <reference path="module.d.ts" /> +/// <reference path="net.d.ts" /> +/// <reference path="os.d.ts" /> +/// <reference path="path.d.ts" /> +/// <reference path="perf_hooks.d.ts" /> +/// <reference path="process.d.ts" /> +/// <reference path="punycode.d.ts" /> +/// <reference path="querystring.d.ts" /> +/// <reference path="readline.d.ts" /> +/// <reference path="repl.d.ts" /> +/// <reference path="stream.d.ts" /> +/// <reference path="string_decoder.d.ts" /> +/// <reference path="timers.d.ts" /> +/// <reference path="tls.d.ts" /> +/// <reference path="trace_events.d.ts" /> +/// <reference path="tty.d.ts" /> +/// <reference path="url.d.ts" /> +/// <reference path="util.d.ts" /> +/// <reference path="v8.d.ts" /> +/// <reference path="vm.d.ts" /> +/// <reference path="worker_threads.d.ts" /> +/// <reference path="zlib.d.ts" /> diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index e4f6f40fd1..0c4215fe7b 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -142,34 +142,8 @@ interface ErrorConstructor { stackTraceLimit: number; } -// compat for TypeScript 1.8 and default es5 target -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } - -interface Set<T> {} -interface ReadonlySet<T> {} - -// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) -interface Iterable<T> { } -interface Iterator<T> { - next(value?: any): IteratorResult<T>; -} -interface IteratorResult<T> { } -interface IterableIterator<T> { } -interface AsyncIterableIterator<T> {} interface SymbolConstructor { readonly observable: symbol; - readonly iterator: symbol; - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; } // Node.js ESNEXT support diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 9126f5504b..a237502039 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -35,43 +35,51 @@ // Kyle Uehlein <https://github.com/kuehlein> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// <reference path="globals.d.ts" /> -/// <reference path="assert.d.ts" /> -/// <reference path="async_hooks.d.ts" /> -/// <reference path="buffer.d.ts" /> -/// <reference path="child_process.d.ts" /> -/// <reference path="cluster.d.ts" /> -/// <reference path="console.d.ts" /> -/// <reference path="constants.d.ts" /> -/// <reference path="crypto.d.ts" /> -/// <reference path="dgram.d.ts" /> -/// <reference path="dns.d.ts" /> -/// <reference path="domain.d.ts" /> -/// <reference path="events.d.ts" /> -/// <reference path="fs.d.ts" /> -/// <reference path="http.d.ts" /> -/// <reference path="http2.d.ts" /> -/// <reference path="https.d.ts" /> -/// <reference path="inspector.d.ts" /> -/// <reference path="module.d.ts" /> -/// <reference path="net.d.ts" /> -/// <reference path="os.d.ts" /> -/// <reference path="path.d.ts" /> -/// <reference path="perf_hooks.d.ts" /> -/// <reference path="process.d.ts" /> -/// <reference path="punycode.d.ts" /> -/// <reference path="querystring.d.ts" /> -/// <reference path="readline.d.ts" /> -/// <reference path="repl.d.ts" /> -/// <reference path="stream.d.ts" /> -/// <reference path="string_decoder.d.ts" /> -/// <reference path="timers.d.ts" /> -/// <reference path="tls.d.ts" /> -/// <reference path="trace_events.d.ts" /> -/// <reference path="tty.d.ts" /> -/// <reference path="url.d.ts" /> -/// <reference path="util.d.ts" /> -/// <reference path="v8.d.ts" /> -/// <reference path="vm.d.ts" /> -/// <reference path="worker_threads.d.ts" /> -/// <reference path="zlib.d.ts" /> +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides +// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.1, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// <reference path="base.d.ts" /> + +// TypeScript 2.1-specific augmentations: + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } +interface Set<T> {} +interface ReadonlySet<T> {} +interface IteratorResult<T> { } +interface Iterable<T> { } +interface Iterator<T> { + next(value?: any): IteratorResult<T>; +} +interface IterableIterator<T> { } +interface AsyncIterableIterator<T> {} +interface SymbolConstructor { + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } +} diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 3a8622802a..220de8ca8a 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -473,11 +473,7 @@ function bufferTests() { const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); - const sharedArrayBuffer: SharedArrayBuffer = { - byteLength: 10, - slice: (begin?: number, end?: number) => sharedArrayBuffer - }; - const buf7: Buffer = Buffer.from(sharedArrayBuffer); + const buf7: Buffer = Buffer.from(undefined as SharedArrayBuffer); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) diff --git a/types/node/package.json b/types/node/package.json new file mode 100644 index 0000000000..c1f0c68752 --- /dev/null +++ b/types/node/package.json @@ -0,0 +1,11 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} \ No newline at end of file diff --git a/types/node/ts3.1/index.d.ts b/types/node/ts3.1/index.d.ts new file mode 100644 index 0000000000..be36602300 --- /dev/null +++ b/types/node/ts3.1/index.d.ts @@ -0,0 +1,18 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// Reference required types from the default lib: +/// <reference lib="es2018" /> +/// <reference lib="esnext.asyncIterable" /> +/// <reference lib="esnext.intl" /> + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +// tslint:disable-next-line:no-bad-reference +/// <reference path="../base.d.ts" /> + +// TypeScript 3.1-specific augmentations: +/// <reference path="util.d.ts" /> diff --git a/types/node/ts3.1/node-tests.ts b/types/node/ts3.1/node-tests.ts new file mode 100644 index 0000000000..18db498871 --- /dev/null +++ b/types/node/ts3.1/node-tests.ts @@ -0,0 +1,2 @@ +// tslint:disable-next-line:no-bad-reference +import "../node-tests"; diff --git a/types/node/ts3.1/tsconfig.json b/types/node/ts3.1/tsconfig.json new file mode 100644 index 0000000000..e1a9ddb149 --- /dev/null +++ b/types/node/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "files": [ + "index.d.ts", + "node-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/node/ts3.1/tslint.json b/types/node/ts3.1/tslint.json new file mode 100644 index 0000000000..1a8ddd9863 --- /dev/null +++ b/types/node/ts3.1/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "unified-signatures": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "strict-export-declare-modifiers": false // http2 needs this + } +} diff --git a/types/node/ts3.1/util.d.ts b/types/node/ts3.1/util.d.ts new file mode 100644 index 0000000000..e35ef8d0f1 --- /dev/null +++ b/types/node/ts3.1/util.d.ts @@ -0,0 +1,10 @@ +// tslint:disable-next-line:no-bad-reference +/// <reference path="../util.d.ts" /> +declare module "util" { + namespace inspect { + const custom: unique symbol; + } + namespace promisify { + const custom: unique symbol; + } +} diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index 9675935b6a..37cfa4baed 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ "index.d.ts", + "base.d.ts", "globals.d.ts", "assert.d.ts", "async_hooks.d.ts", diff --git a/types/node/util.d.ts b/types/node/util.d.ts index f918286559..9da88fe9cb 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -12,18 +12,17 @@ declare module "util" { function print(...param: any[]): void; /** @deprecated since v0.11.3 - use a third party module instead. */ function log(string: string): void; - const inspect: { - (object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - (object: any, options: InspectOptions): string; - colors: { + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; + namespace inspect { + let colors: { [color: string]: [number, number] | undefined - } - styles: { + }; + let styles: { [style: string]: string | undefined - } - defaultOptions: InspectOptions; - custom: symbol; - }; + }; + let defaultOptions: InspectOptions; + } /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ function isArray(object: any): object is any[]; /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ @@ -108,9 +107,6 @@ declare module "util" { fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>; function promisify(fn: Function): Function; - namespace promisify { - const custom: symbol; - } namespace types { function isAnyArrayBuffer(object: any): boolean; From 0f1a0a5d6e20dbab8bbe4ee1eac23e7503908b66 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> Date: Wed, 6 Feb 2019 18:38:21 -0800 Subject: [PATCH 152/200] Update README.md --- README.md | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 650cecd1d5..faee7a4ee0 100644 --- a/README.md +++ b/README.md @@ -261,10 +261,10 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat _NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ Each DefinitelyTyped package is versioned when published to NPM. -The [automated tools](https://github.com/Microsoft/types-publisher) that publish type declaration packages to NPM will set the type declaration package's version using the version number listed in the first line of its `index.d.ts` file. -For example, below are the first few lines of the latest (as of late 2018) [node.js type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library versions `10.12.x`. +The [types-publisher](https://github.com/Microsoft/types-publisher) (the tool that publishes `@types` packages to npm) will set the declaration package's version by using the `major.minor` version number listed in the first line of its `index.d.ts` file. +For example, here are the first few lines of [Node's type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/node/index.d.ts) for version `10.12.x` at the time of writing: -```javascript +```js // Type definitions for Node.js 10.12 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript <https://github.com/Microsoft> @@ -272,21 +272,24 @@ For example, below are the first few lines of the latest (as of late 2018) [node // Alberto Schiabel <https://github.com/jkomyno> ``` -Because `10.12` is at the end the first line, the NPM version of the `@types/node` package will also be `10.12.x`. -Note that the first-line comment in the `index.d.ts` file should only contain major/minor versions (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). +Because `10.12` is at the end the first line, the npm version of the `@types/node` package will also be `10.12.x`. +Note that the first-line comment in the `index.d.ts` file should only contain the `major.minor` version (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). This is because only the major and minor release numbers are aligned between library packages and type declaration packages. The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. -Sometimes type declaration package versions and library package versions can get out of sync. -Below are a few common reasons why, in order of how much they inconvenience users of a library. +Sometimes type declaration package versions and library package versions can get out of sync. +Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. -* As noted above, the patch version of the type declaration package is unrelated to the library patch version. This allows DefinitelyTyped to safely update type declarations for the same major/minor version of a library. -* If a minor release adds new features that don't impact the type system, then there's no need to publish updated type declarations. In cases like this, updates are often skipped to the type declaration package. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the type declaration package version might remain `2.0.3` even as the library goes to `2.1.0`. -* Users who are updating type declarations for a library sometimes forget to increment the type declaration package's version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest type declaration package version, although it may be confusing for users because they might assume that a library update is missing types that are really present. It will also cause problems when libraries are (see below) updated to a new major release with breaking changes, because users won't know which type declaration package version is the right one to use for older versions of the library. -* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release. +* As noted above, the patch version of the type declaration package is unrelated to the library patch version. + This allows DefinitelyTyped to safely update type declarations for the same major/minor version of a library. +* If updating a package for new functionality, don't forget to update the version number to line up with that version of the library. + If users make sure versions correspond between JavaScript packages and their respective `@types` packages, then `npm update` should typically just work. +* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. + So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release. + If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member! -:exclamation:If you're updating type declarations for a library, always set the major/minor version in the first line of `index.d.ts` to match the library version that you're documenting!:exclamation: +:exclamation: If you're updating type declarations for a library, always set the `major.minor` version in the first line of `index.d.ts` to match the library version that you're documenting! :exclamation: #### If a library is updated to a new major version with breaking changes, how should I update its type declaration package? @@ -305,9 +308,8 @@ Because the root folder should always contain the type declarations for the late 2. Add path mapping rules to ensure that tests are running against the intended version. For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. -Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. -Therefore, a maintainer of the type declarations for this library added a `v2` folder inside the history repository that contains type declarations for the older version. -The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +Because many users still consumed the older `2.x` version, a maintainer who wanted to update the type declarations for this library to `3.x` added a `v2` folder inside the history repository that contains type declarations for the older version. +At the time of writing, the [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/history/v2/tsconfig.json) looks roughly like: ```json { From dda77e9c2af13607e6fa7be792d40a956c7c6be6 Mon Sep 17 00:00:00 2001 From: Joao Peixoto <joao.hartimer@gmail.com> Date: Wed, 6 Feb 2019 20:15:22 -0800 Subject: [PATCH 153/200] Make userHandle nullable instead of optional --- .../index.d.ts | 2 +- .../webappsec-credential-management-tests.ts | 45 ++++++++++--------- 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index c8fbf8ec60..ce3e7ef26c 100644 --- a/types/webappsec-credential-management/index.d.ts +++ b/types/webappsec-credential-management/index.d.ts @@ -494,7 +494,7 @@ interface AuthenticatorAttestationResponse extends AuthenticatorResponse { interface AuthenticatorAssertionResponse extends AuthenticatorResponse { readonly authenticatorData: ArrayBuffer; readonly signature: ArrayBuffer; - readonly userHandle?: ArrayBuffer; + readonly userHandle: ArrayBuffer | null; } /** diff --git a/types/webappsec-credential-management/webappsec-credential-management-tests.ts b/types/webappsec-credential-management/webappsec-credential-management-tests.ts index 1e0500dfce..15ae1c6b9e 100644 --- a/types/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/types/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -5,7 +5,7 @@ function passwordBasedSignInDeprecated() { return; } - navigator.credentials.get({password: true}).then((credential) => { + navigator.credentials.get({ password: true }).then((credential) => { if (!credential) { return; } @@ -117,7 +117,7 @@ function federatedSignIn() { navigator.credentials .get({ password: true, - federated: {providers: ['https://federation.com']} + federated: { providers: ['https://federation.com'] } }) .then((credential) => { if (!credential) return; @@ -141,7 +141,7 @@ function federatedSignIn() { const pwCred = credential as PasswordCredential; fetch( 'https://example.com/loginEndpoint', - {credentials: pwCred, method: 'POST'}); + { credentials: pwCred, method: 'POST' }); } }); } @@ -159,7 +159,7 @@ function passwordPostSignInConfirmation() { const formElem = (e.target as HTMLFormElement); const c = new PasswordCredential(formElem); - fetch(formElem.action, {method: 'POST', credentials: c}).then(r => { + fetch(formElem.action, { method: 'POST', credentials: c }).then(r => { if (r.status === 200) { navigator.credentials!.store(c); } @@ -172,7 +172,7 @@ function passwordPostSignInConfirmation() { function federationPostSignInConfirmation() { if (navigator.credentials) { navigator.credentials.store(new FederatedCredential( - {id: 'username', provider: 'https://federation.com'})); + { id: 'username', provider: 'https://federation.com' })); } } @@ -188,7 +188,7 @@ function existingFormPost(credential: PasswordCredential) { credential.passwordName = 'p'; fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } function additionalDataPost(credential: PasswordCredential, token: string) { @@ -196,14 +196,14 @@ function additionalDataPost(credential: PasswordCredential, token: string) { credential.additionalData.append('csrf', token); fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } function formEncodedPost(credential: PasswordCredential, token: string) { credential.additionalData = new URLSearchParams(); fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } // requireUserMediation example: not included in the spec, but included here @@ -236,7 +236,7 @@ function createPasswordCredential() { } navigator.credentials.create({ - password: {id: 'username', password: 'password'} + password: { id: 'username', password: 'password' } }).then((credential) => { // Credential created! }); @@ -266,7 +266,7 @@ function createFederatedCredential() { } navigator.credentials.create({ - federated: {id: 'username', provider: 'provider'} + federated: { id: 'username', provider: 'provider' } }).then((credential) => { // Credential created! }); @@ -293,7 +293,7 @@ function webauthnRegister() { }, challenge, pubKeyCredParams: [ - {type: 'public-key', alg: -7}, + { type: 'public-key', alg: -7 }, ], excludeCredentials: [ { @@ -329,16 +329,18 @@ function webauthnAuthenticate() { const challenge = new Uint8Array(32); window.crypto.getRandomValues(challenge); - const authPromise = navigator.credentials.get({publicKey: { - challenge, - timeout: 5000, - rpId: document.domain, - allowCredentials: [{ - type: "public-key", - id: credentialID, - transports: ['internal', 'ble', 'nfc', 'usb'] - }], - }}); + const authPromise = navigator.credentials.get({ + publicKey: { + challenge, + timeout: 5000, + rpId: document.domain, + allowCredentials: [{ + type: "public-key", + id: credentialID, + transports: ['internal', 'ble', 'nfc', 'usb'] + }], + } + }); authPromise.then((cred) => { if (cred === null) { @@ -362,6 +364,7 @@ function mockAuthenticatorAssertionResponse() { clientDataJSON: new ArrayBuffer(0), authenticatorData: new ArrayBuffer(0), signature: new ArrayBuffer(0), + userHandle: null, }; sampleResponse.userHandle === undefined; } From bc1eb3b28e41b2ed54865aecf134eae6c0b23add Mon Sep 17 00:00:00 2001 From: Mitchell Grice <mitchell.grice@polymathian.com> Date: Thu, 7 Feb 2019 15:11:18 +1000 Subject: [PATCH 154/200] Add moment-precise-range-plugin --- types/moment-precise-range-plugin/index.d.ts | 28 +++++++++++++++++++ .../moment-precise-range-plugin-tests.ts | 14 ++++++++++ .../moment-precise-range-plugin/package.json | 6 ++++ .../moment-precise-range-plugin/tsconfig.json | 23 +++++++++++++++ types/moment-precise-range-plugin/tslint.json | 1 + 5 files changed, 72 insertions(+) create mode 100644 types/moment-precise-range-plugin/index.d.ts create mode 100644 types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts create mode 100644 types/moment-precise-range-plugin/package.json create mode 100644 types/moment-precise-range-plugin/tsconfig.json create mode 100644 types/moment-precise-range-plugin/tslint.json diff --git a/types/moment-precise-range-plugin/index.d.ts b/types/moment-precise-range-plugin/index.d.ts new file mode 100644 index 0000000000..ad28b3d009 --- /dev/null +++ b/types/moment-precise-range-plugin/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for moment-precise-range 0.2 +// Project: https://github.com/codebox/moment-precise-range +// Definitions by: Mitchell Grice <https://github.com/gricey432> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import moment = require('moment'); + +export = moment; + +declare module "moment" { + interface PreciseRangeValueObject { + years: number; + months: number; + days: number; + hours: number; + minutes: number; + seconds: number; + firstDateWasLater: boolean; + } + + interface Moment { + preciseDiff(d2: Moment, returnValueObject?: false): string; + preciseDiff(d2: Moment, returnValueObject: true): PreciseRangeValueObject; + } + + function preciseDiff(d1: Moment, d2: Moment, returnValueObject?: false): string; + function preciseDiff(d1: Moment, d2: Moment, returnValueObject: true): PreciseRangeValueObject; +} diff --git a/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts b/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts new file mode 100644 index 0000000000..427d513fb9 --- /dev/null +++ b/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts @@ -0,0 +1,14 @@ +import moment = require("moment"); +import * as momentPreciseRange from "moment-precise-range-plugin"; + +// Static methods +const m1 = moment.utc(); +const m2 = moment.utc(); +moment.preciseDiff(m1, m2); +moment.preciseDiff(m1, m2, true); +moment.preciseDiff(m1, m2, false); + +// Instance methods +m1.preciseDiff(m2); +m1.preciseDiff(m2, true); +m1.preciseDiff(m2, false); diff --git a/types/moment-precise-range-plugin/package.json b/types/moment-precise-range-plugin/package.json new file mode 100644 index 0000000000..19e5fb0d14 --- /dev/null +++ b/types/moment-precise-range-plugin/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": ">=2.14.0" + } +} diff --git a/types/moment-precise-range-plugin/tsconfig.json b/types/moment-precise-range-plugin/tsconfig.json new file mode 100644 index 0000000000..cfb6dcbd4d --- /dev/null +++ b/types/moment-precise-range-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "moment-precise-range-plugin-tests.ts" + ] +} diff --git a/types/moment-precise-range-plugin/tslint.json b/types/moment-precise-range-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/moment-precise-range-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From af9d8f543526e27f7d0eaeb8c8646cd28fbce8ee Mon Sep 17 00:00:00 2001 From: Ray Booysen <ray@sumatro.co.uk> Date: Thu, 7 Feb 2019 14:39:11 +0800 Subject: [PATCH 155/200] Add bunyan-seq typings --- types/bunyan-seq/bunyan-seq-tests.ts | 2 ++ types/bunyan-seq/index.d.ts | 21 +++++++++++++++++++++ types/bunyan-seq/tsconfig.json | 23 +++++++++++++++++++++++ types/bunyan-seq/tslint.json | 1 + 4 files changed, 47 insertions(+) create mode 100644 types/bunyan-seq/bunyan-seq-tests.ts create mode 100644 types/bunyan-seq/index.d.ts create mode 100644 types/bunyan-seq/tsconfig.json create mode 100644 types/bunyan-seq/tslint.json diff --git a/types/bunyan-seq/bunyan-seq-tests.ts b/types/bunyan-seq/bunyan-seq-tests.ts new file mode 100644 index 0000000000..beeeb9d8ee --- /dev/null +++ b/types/bunyan-seq/bunyan-seq-tests.ts @@ -0,0 +1,2 @@ +import bunyanSeq = require("bunyan-seq"); +bunyanSeq.createStream({name: 'LoggerComponent', serverUrl: 'http://seq.com'}); diff --git a/types/bunyan-seq/index.d.ts b/types/bunyan-seq/index.d.ts new file mode 100644 index 0000000000..2520c93339 --- /dev/null +++ b/types/bunyan-seq/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for bunyan-blackhole 0.2 +// Project: https://github.com/datalust/bunyan-seq +// Definitions by: Ray Booysen <https://github.com/raybooysen> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// <reference types="node" /> +import * as Logger from "bunyan"; +export interface Configuration { + apiKey?: string; + batchSizeLimit?: number; + eventSizeLimit?: number; + level?: string; + maxBatchingTime?: number; + name?: string; + onError?: (e: Error) => void; + reemitErrorEvents?: boolean; + serverUrl?: string; +} + +export function createStream(config: Configuration): Logger.Stream; diff --git a/types/bunyan-seq/tsconfig.json b/types/bunyan-seq/tsconfig.json new file mode 100644 index 0000000000..bd77368148 --- /dev/null +++ b/types/bunyan-seq/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bunyan-seq-tests.ts" + ] +} diff --git a/types/bunyan-seq/tslint.json b/types/bunyan-seq/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bunyan-seq/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From add287a1d6eedf8d8ad9ccfac159ff5265970b1e Mon Sep 17 00:00:00 2001 From: Haroen Viaene <hello@haroen.me> Date: Thu, 7 Feb 2019 09:22:57 +0100 Subject: [PATCH 156/200] algoliasearch: add missing type for removeStopWords closes https://github.com/algolia/algoliasearch-client-javascript/issues/741 --- types/algoliasearch/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 04291996ba..633b681432 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1687,7 +1687,7 @@ declare namespace algoliasearch { * a list of language ISO codes (as a comma-separated string) for which stop words should be enable * https://github.com/algolia/algoliasearch-client-js#removestopwords */ - removeStopWords?: string[]; + removeStopWords?: boolean | string[]; /** * List of attributes on which you want to apply word-splitting ("decompounding") for * each of the languages supported (German, Dutch, and Finnish as of 05/2018) From 7203a2a86763485d1b6152a1dcac381ddc495bfe Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Thu, 7 Feb 2019 10:59:41 +0200 Subject: [PATCH 157/200] [@types/feathersjs__errors] Bumped version to 3.3. --- types/feathersjs__errors/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 01969de8a3..3a94e4cd50 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @feathersjs/errors 3.2 +// Type definitions for @feathersjs/errors 3.3 // Project: http://feathersjs.com/ // Definitions by: Jan Lohage <https://github.com/j2L4e> // RazzM13 <https://github.com/RazzM13> From a9259ab52140a3c0d35799d1c8072a86c34a7b78 Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Thu, 7 Feb 2019 11:04:29 +0200 Subject: [PATCH 158/200] [@types/feathersjs__errors] Made "FeathersError" specific properties readonly. --- types/feathersjs__errors/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 3a94e4cd50..ab7b1eae34 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -6,10 +6,10 @@ // TypeScript Version: 2.2 export class FeathersError extends Error { - code: number; - className: string; - data: any; - errors: any; + readonly code: number; + readonly className: string; + readonly data: any; + readonly errors: any; constructor(msg: string | Error, name: string, code: number, className: string, data: any); } From 12738483e6597664a21ab33ecb5ba3ac109bb433 Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Thu, 7 Feb 2019 11:09:17 +0200 Subject: [PATCH 159/200] [@types/feathersjs__errors] Added the missing "toJSON" function of the "FeathersError" base class that returns an object suitable for serialization. --- types/feathersjs__errors/index.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index ab7b1eae34..3994e2056c 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -5,12 +5,22 @@ // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.2 +export interface FeathersErrorJSON { + readonly name: string; + readonly message: string; + readonly code: number; + readonly className: string; + readonly data: any; + readonly errors: any; +} + export class FeathersError extends Error { readonly code: number; readonly className: string; readonly data: any; readonly errors: any; constructor(msg: string | Error, name: string, code: number, className: string, data: any); + toJSON(): FeathersErrorJSON; } export class BadRequest extends FeathersError { From 209ac2ff355b0e97b65ae29838c3d898322bab20 Mon Sep 17 00:00:00 2001 From: Loik Gaonach <dev.loikg@gmail.com> Date: Thu, 7 Feb 2019 10:52:54 +0100 Subject: [PATCH 160/200] add websocket integration props to APIGatewayEventRequestContext messageId is nullable on connection events --- types/aws-lambda/aws-lambda-tests.ts | 11 +++++++++++ types/aws-lambda/index.d.ts | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index ba6ebdc5ac..ad063c20b6 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -1,12 +1,14 @@ declare let str: string; declare let strOrNull: string | null; declare let strOrUndefined: string | undefined; +declare let strOrUndefinedOrNull: string | undefined | null; declare let date: Date; declare let anyObj: any; declare let num: number; declare let error: Error; declare let bool: boolean; declare let boolOrUndefined: boolean | undefined; +declare let numOrUndefined: number | undefined; declare let apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; declare let apiGwEvtReqCtxOpt: AWSLambda.APIGatewayEventRequestContext | null | undefined; declare let apiGwEvt: AWSLambda.APIGatewayEvent; @@ -80,6 +82,11 @@ declare const scheduledEvent: AWSLambda.ScheduledEvent; str = apiGwEvtReqCtx.accountId; str = apiGwEvtReqCtx.apiId; authResponseContextOpt = apiGwEvtReqCtx.authorizer; +numOrUndefined = apiGwEvtReqCtx.connectedAt; +strOrUndefined = apiGwEvtReqCtx.connectionId; +strOrUndefined = apiGwEvtReqCtx.domainName; +strOrUndefined = apiGwEvtReqCtx.eventType; +strOrUndefined = apiGwEvtReqCtx.extendedRequestId; str = apiGwEvtReqCtx.httpMethod; strOrNull = apiGwEvtReqCtx.identity.accessKey; strOrNull = apiGwEvtReqCtx.identity.accountId; @@ -94,11 +101,15 @@ str = apiGwEvtReqCtx.identity.sourceIp; strOrNull = apiGwEvtReqCtx.identity.user; strOrNull = apiGwEvtReqCtx.identity.userAgent; strOrNull = apiGwEvtReqCtx.identity.userArn; +strOrUndefined = apiGwEvtReqCtx.messageDirection; +strOrUndefinedOrNull = apiGwEvtReqCtx.messageId; str = apiGwEvtReqCtx.path; str = apiGwEvtReqCtx.stage; str = apiGwEvtReqCtx.requestId; +strOrUndefined = apiGwEvtReqCtx.requestTime; str = apiGwEvtReqCtx.resourceId; str = apiGwEvtReqCtx.resourcePath; +strOrUndefined = apiGwEvtReqCtx.routeKey; /* API Gateway Event */ strOrNull = apiGwEvt.body; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 52314529bc..3301feebb5 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -25,6 +25,7 @@ // Trevor Leach <https://github.com/trevor-leach> // James Gregory <https://github.com/jagregory> // Erik Dalén <https://github.com/dalen> +// Loïk Gaonac'h <https://github.com/loikg> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -33,6 +34,11 @@ export interface APIGatewayEventRequestContext { accountId: string; apiId: string; authorizer?: AuthResponseContext | null; + connectedAt: number; + connectionId?: string; + domainName?: string; + eventType?: string; + extendedRequestId?: string; httpMethod: string; identity: { accessKey: string | null; @@ -49,12 +55,16 @@ export interface APIGatewayEventRequestContext { userAgent: string | null; userArn: string | null; }; + messageDirection?: string; + messageId?: string | null; path: string; stage: string; requestId: string; + requestTime?: string; requestTimeEpoch: number; resourceId: string; resourcePath: string; + routeKey?: string; } // API Gateway "event" From d787437c0adac1fe12fe20af9b06859d6622656b Mon Sep 17 00:00:00 2001 From: Jason Gray <jason.gray@postcodelottery.co.uk> Date: Fri, 1 Feb 2019 14:45:40 +0000 Subject: [PATCH 161/200] add types for aws-param-store --- .../aws-param-store/aws-param-store-tests.ts | 78 +++++++++++++++++++ types/aws-param-store/index.d.ts | 48 ++++++++++++ types/aws-param-store/package.json | 6 ++ types/aws-param-store/tsconfig.json | 23 ++++++ types/aws-param-store/tslint.json | 1 + 5 files changed, 156 insertions(+) create mode 100644 types/aws-param-store/aws-param-store-tests.ts create mode 100644 types/aws-param-store/index.d.ts create mode 100644 types/aws-param-store/package.json create mode 100644 types/aws-param-store/tsconfig.json create mode 100644 types/aws-param-store/tslint.json diff --git a/types/aws-param-store/aws-param-store-tests.ts b/types/aws-param-store/aws-param-store-tests.ts new file mode 100644 index 0000000000..13ad6c0514 --- /dev/null +++ b/types/aws-param-store/aws-param-store-tests.ts @@ -0,0 +1,78 @@ +import { SSM } from 'aws-sdk'; +import { + ParameterQuery, + parameterQuery, + getParameter, + getParameters, + getParametersByPath, + getParameterSync, + getParametersSync, + getParametersByPathSync, +} from 'aws-param-store'; + +declare let bool: boolean; +declare let query: ParameterQuery; +declare let psName: SSM.Types.PSParameterName; +declare let psNames: SSM.Types.ParameterNameList; +declare let options: SSM.Types.ClientConfiguration; +declare let paramResult: SSM.Types.Parameter; +declare let paramsResult: SSM.Types.GetParametersResult; +declare let paramsByPathResult: SSM.Types.ParameterList; +declare let allParamResults: SSM.Types.Parameter | SSM.Types.GetParametersByPathResult | SSM.Types.ParameterList; +declare let promiseParamResult: Promise<SSM.Types.Parameter>; +declare let promiseParamsResult: Promise<SSM.Types.GetParametersResult>; +declare let promiseParamsByPathResult: Promise<SSM.Types.ParameterList>; +declare let promiseAllParamResults: Promise<typeof allParamResults>; + +query = parameterQuery(); + +query.path(psName); +query.named(psName); +query.named(psNames); +query.decryption(bool); +query.recursive(bool); + +promiseAllParamResults = query.execute(); +allParamResults = query.executeSync(); + +// test chaining +query = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool); + +promiseAllParamResults = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool) +.execute(); + +allParamResults = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool) +.executeSync(); + +promiseParamResult = getParameter(psName); +promiseParamResult = getParameter(psName, options); + +promiseParamsResult = getParameters(psNames); +promiseParamsResult = getParameters(psNames, options); + +promiseParamsByPathResult = getParametersByPath(psNames); +promiseParamsByPathResult = getParametersByPath(psNames, options); + +paramResult = getParameterSync(psName); +paramResult = getParameterSync(psName, options); + +paramsResult = getParametersSync(psNames); +paramsResult = getParametersSync(psNames, options); + +paramsByPathResult = getParametersByPathSync(psNames); +paramsByPathResult = getParametersByPathSync(psNames, options); diff --git a/types/aws-param-store/index.d.ts b/types/aws-param-store/index.d.ts new file mode 100644 index 0000000000..c35edef688 --- /dev/null +++ b/types/aws-param-store/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for aws-param-store 2.1 +// Project: https://github.com/vandium-io/aws-param-store#readme +// Definitions by: Jason Gray <https://github.com/jasonthomasgray> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// <reference types="node" /> +import { SSM } from 'aws-sdk'; + +export function getParameter( + name: SSM.Types.PSParameterName, + options?: SSM.Types.ClientConfiguration +): Promise<SSM.Types.Parameter>; + +export function getParameterSync( + name: SSM.Types.PSParameterName, + options?: SSM.Types.ClientConfiguration +): SSM.Types.Parameter; + +export function getParameters( + names: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): Promise<SSM.Types.GetParametersResult>; + +export function getParametersSync( + names: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): SSM.Types.GetParametersResult; + +export function getParametersByPath( + path: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): Promise<SSM.Types.ParameterList>; + +export function getParametersByPathSync( + path: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): SSM.Types.ParameterList; + +export interface ParameterQuery { + path(path: SSM.Types.PSParameterName): ParameterQuery; + named(nameOrNames: SSM.Types.PSParameterName | SSM.Types.ParameterNameList): ParameterQuery; + decryption(enabled: boolean): ParameterQuery; + recursive(enabled: boolean): ParameterQuery; + execute(): Promise<SSM.Types.ParameterList | SSM.Types.Parameter | SSM.Types.GetParametersResult>; + executeSync(): SSM.Types.ParameterList | SSM.Types.Parameter | SSM.Types.GetParametersResult; +} + +export function parameterQuery(options?: SSM.Types.ClientConfiguration): ParameterQuery; diff --git a/types/aws-param-store/package.json b/types/aws-param-store/package.json new file mode 100644 index 0000000000..abb680d4ac --- /dev/null +++ b/types/aws-param-store/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "aws-sdk": "^2.325.0" + } +} diff --git a/types/aws-param-store/tsconfig.json b/types/aws-param-store/tsconfig.json new file mode 100644 index 0000000000..2857e45680 --- /dev/null +++ b/types/aws-param-store/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aws-param-store-tests.ts" + ] +} diff --git a/types/aws-param-store/tslint.json b/types/aws-param-store/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/aws-param-store/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bfa57b661f5da696100751cb19cdac599213ad42 Mon Sep 17 00:00:00 2001 From: Jan Pesa <jan.pesa@gmail.com> Date: Thu, 7 Feb 2019 13:44:32 +0100 Subject: [PATCH 162/200] [utif] Add types --- types/utif/index.d.ts | 71 ++++++++++++++++++++++++++++++++++++++++ types/utif/tsconfig.json | 23 +++++++++++++ types/utif/tslint.json | 1 + types/utif/utif-tests.ts | 15 +++++++++ 4 files changed, 110 insertions(+) create mode 100644 types/utif/index.d.ts create mode 100644 types/utif/tsconfig.json create mode 100644 types/utif/tslint.json create mode 100644 types/utif/utif-tests.ts diff --git a/types/utif/index.d.ts b/types/utif/index.d.ts new file mode 100644 index 0000000000..569dfd949c --- /dev/null +++ b/types/utif/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for utif 2.0 +// Project: https://github.com/photopea/UTIF.js +// Definitions by: Jan Pesa <https://github.com/smajl> +// Naveen Kumar Sangi <https://github.com/nkprince007> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import 'node'; + +export as namespace UTIF; + +export type TiffTag = string[] | number[]; + +/** + * Each IFD is an object, keys are "tXYZ" (XYZ is a TIFF tag number), values are values of these tags. + * You can get the the dimension (and other properties, "metadata") of the image without decompressing pixel data. + * For more information on what each tag means, refer https://github.com/photopea/UTIF.js/blob/master/UTIF.js#L742 or TIFF 6 specification. + */ +// tslint:disable-next-line:interface-name +export interface IFD { + [property: string]: TiffTag | number | Uint8Array; + data: Uint8Array; + width: number; + height: number; +} + +/** + * Returns an array of "IFDs" (image file directories). + * + * @param buffer A Buffer or ArrayBuffer containing TIFF or EXIF data. + */ +export function decode(buffer: Buffer | ArrayBuffer): IFD[]; + +/** + * Loops through each IFD. If there is an image inside it, it is decoded and three new properties are added to the IFD: width, height and data. + * Note: TIFF files may have various number of channels and various color depth. The interpretation of data depends on many tags (see the TIFF 6 specification). + * + * @param buffer A Buffer or ArrayBuffer containing TIFF or EXIF data + * @param ifds An array of image file directories parsed via UTIF.decode() + */ +export function decodeImages(buffer: Buffer | ArrayBuffer, ifds: IFD[]): void; + +/** + * Returns Uint8Array of the image in RGBA format, 8 bits per channel (ready to use in context2d.putImageData() etc.) + * + * @param ifd An image file directory + */ +export function toRGBA8(ifd: IFD): Uint8Array; + +/** + * Returns an ArrayBuffer of the binary TIFF file. + * Note: No compression available right now. + * + * @param rgba A Uint8Array containing RGBA pixel data. + * @param w Width of the image. + * @param h Height of the image. + * @param metadata [optional] The image file directory which should be encoded. + */ +export function encodeImage(rgba: Uint8Array, w: number, h: number, metadata?: IFD): ArrayBuffer; + +/** + * Returns ArrayBuffer of binary data which can be used to encode EXIF data. + * + * @param ifds The array of IFDs (image file directories) to be encoded. + */ +export function encode(ifds: IFD[]): ArrayBuffer; + +/** + * Replaces all Image elements in the document with Canvas elements. + * The attributes "id", "class" and "style" will be copied from the original Image to the new Canvas. + */ +export function replaceIMG(): void; diff --git a/types/utif/tsconfig.json b/types/utif/tsconfig.json new file mode 100644 index 0000000000..cd4c8aa8fe --- /dev/null +++ b/types/utif/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "utif-tests.ts" + ] +} diff --git a/types/utif/tslint.json b/types/utif/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/utif/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/utif/utif-tests.ts b/types/utif/utif-tests.ts new file mode 100644 index 0000000000..66455e2f4a --- /dev/null +++ b/types/utif/utif-tests.ts @@ -0,0 +1,15 @@ +import * as UTIF from "utif"; + +// $ExpectType IFD[] +const IFDs = UTIF.decode(new ArrayBuffer(64)); +// $ExpectType Uint8Array +const rgba = UTIF.toRGBA8(IFDs[0]); + +// $ExpectType ArrayBuffer +UTIF.encodeImage(rgba, 8, 8); +// $ExpectType ArrayBuffer +UTIF.encode(IFDs); +// $ExpectType void +UTIF.decodeImages(new ArrayBuffer(64), IFDs); +// $ExpectType void +UTIF.replaceIMG(); From 8c819e3ff0ee063d24094de2226675f5d6dd8f9b Mon Sep 17 00:00:00 2001 From: "dominic.griesel" <d.griesel@gmx.net> Date: Thu, 7 Feb 2019 13:53:22 +0100 Subject: [PATCH 163/200] [ioBroker] Add `custom` property to ObjectCommon Fixes: ioBroker/adapter-core#3 --- types/iobroker/index.d.ts | 3 +++ types/iobroker/iobroker-tests.ts | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 6beeccb08f..fb5eb5661a 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -254,6 +254,9 @@ declare global { icon?: string; /** role of the object */ role?: string; + + /** Custom settings for this object */ + custom?: Record<string, any>; } interface StateCommon extends ObjectCommon { diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 01ab0c6fc4..40e48fe8e4 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -259,3 +259,13 @@ adapter.subscribeStatesAsync("*").catch(handleError); adapter.subscribeForeignStatesAsync("*").catch(handleError); adapter.unsubscribeStatesAsync("*").catch(handleError); adapter.unsubscribeForeignStatesAsync("*").catch(handleError); + +// Repro from https://github.com/ioBroker/adapter-core/issues/3 +const repro1: ioBroker.ObjectChangeHandler = (id, obj) => { + obj + && obj.common + && obj.common.custom + && obj.common.custom["adapter.0"] + && obj.common.custom["adapter.0"].enabled + ; +}; From 6b6bf4230bd3274486636a339b8cfe17f730023b Mon Sep 17 00:00:00 2001 From: "dominic.griesel" <d.griesel@gmx.net> Date: Thu, 7 Feb 2019 14:14:59 +0100 Subject: [PATCH 164/200] Add regression test for ioBroker/adapter-core#4 --- types/iobroker/iobroker-tests.ts | 39 +++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 40e48fe8e4..57d00e284b 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -209,8 +209,8 @@ switch (adapter.log.level) { adapter.sendTo("foo.0", "command", "message"); adapter.sendTo("foo.0", "message"); -adapter.sendTo("foo.0", "command", {msg: "message"}); -adapter.sendTo("foo.0", {msg: "message"}); +adapter.sendTo("foo.0", "command", { msg: "message" }); +adapter.sendTo("foo.0", { msg: "message" }); function handleMessageResponse(response?: ioBroker.Message) { if (!response) return; @@ -226,28 +226,28 @@ function handleMessageResponse(response?: ioBroker.Message) { } adapter.sendTo("foo.0", "command", "message", handleMessageResponse); adapter.sendTo("foo.0", "message", handleMessageResponse); -adapter.sendTo("foo.0", "command", {msg: "message"}, handleMessageResponse); -adapter.sendTo("foo.0", {msg: "message"}, handleMessageResponse); +adapter.sendTo("foo.0", "command", { msg: "message" }, handleMessageResponse); +adapter.sendTo("foo.0", { msg: "message" }, handleMessageResponse); adapter.sendToAsync("foo.0", "command", "message").then(handleMessageResponse); adapter.sendToAsync("foo.0", "message").then(handleMessageResponse); -adapter.sendToAsync("foo.0", "command", {msg: "message"}).then(handleMessageResponse); -adapter.sendToAsync("foo.0", {msg: "message"}).then(handleMessageResponse); +adapter.sendToAsync("foo.0", "command", { msg: "message" }).then(handleMessageResponse); +adapter.sendToAsync("foo.0", { msg: "message" }).then(handleMessageResponse); adapter.sendToHost("host-foo", "command", "message"); adapter.sendToHost("host-foo", "message"); -adapter.sendToHost("host-foo", "command", {msg: "message"}); -adapter.sendToHost("host-foo", {msg: "message"}); +adapter.sendToHost("host-foo", "command", { msg: "message" }); +adapter.sendToHost("host-foo", { msg: "message" }); adapter.sendToHost("host-foo", "command", "message", handleMessageResponse); adapter.sendToHost("host-foo", "message", handleMessageResponse); -adapter.sendToHost("host-foo", "command", {msg: "message"}, handleMessageResponse); -adapter.sendToHost("host-foo", {msg: "message"}, handleMessageResponse); +adapter.sendToHost("host-foo", "command", { msg: "message" }, handleMessageResponse); +adapter.sendToHost("host-foo", { msg: "message" }, handleMessageResponse); adapter.sendToHostAsync("host-foo", "command", "message").then(handleMessageResponse); adapter.sendToHostAsync("host-foo", "message").then(handleMessageResponse); -adapter.sendToHostAsync("host-foo", "command", {msg: "message"}).then(handleMessageResponse); -adapter.sendToHostAsync("host-foo", {msg: "message"}).then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", "command", { msg: "message" }).then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", { msg: "message" }).then(handleMessageResponse); function handleError(err?: string) { } adapter.subscribeStates("*", handleError); @@ -267,5 +267,18 @@ const repro1: ioBroker.ObjectChangeHandler = (id, obj) => { && obj.common.custom && obj.common.custom["adapter.0"] && obj.common.custom["adapter.0"].enabled - ; + ; }; + +// Repro from https://github.com/ioBroker/adapter-core/issues/4 +function repro2() { + // Prepare custom object + const obj = { + common: { + custom: { + "adapter.namespace": { start_day: null as any } + } + } + }; + adapter.extendForeignObject("obj.id", obj, (err) => { }); +} From 07b0e25aa55d23fae0768792262d16100ed78426 Mon Sep 17 00:00:00 2001 From: "dominic.griesel" <d.griesel@gmx.net> Date: Thu, 7 Feb 2019 14:42:21 +0100 Subject: [PATCH 165/200] Only allow `custom` in `StateCommon`, not the other common types --- types/iobroker/index.d.ts | 41 ++++++++++++++++++++++---------- types/iobroker/iobroker-tests.ts | 4 ++++ 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index fb5eb5661a..0075f8a273 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ioBroker/ioBroker // Definitions by: AlCalzone <https://github.com/AlCalzone> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 3.2 // Note: This is not the definition for the package `iobroker`, // which is just an installer, not a library. @@ -254,9 +254,6 @@ declare global { icon?: string; /** role of the object */ role?: string; - - /** Custom settings for this object */ - custom?: Record<string, any>; } interface StateCommon extends ObjectCommon { @@ -299,14 +296,28 @@ declare global { /** attached history information */ history?: any; + + /** Custom settings for this state */ + custom?: Record<string, any>; } interface ChannelCommon extends ObjectCommon { /** description of this channel */ desc?: string; + + // Only states can have common.custom + custom?: undefined; } - type OtherCommon = ObjectCommon & { + interface DeviceCommon extends ObjectCommon { + // Only states can have common.custom + custom?: undefined; + // TODO: any other definition for device? + } + interface OtherCommon extends ObjectCommon { [propName: string]: any; - }; + + // Only states can have common.custom + custom?: undefined; + } interface BaseObject { /** The ID of this object */ @@ -314,7 +325,7 @@ declare global { native: Record<string, any>; enums?: Record<string, string>; type: string; // specified in the derived interfaces - common: ObjectCommon; + common: StateCommon | ChannelCommon | DeviceCommon | OtherCommon; acl?: ObjectACL; } @@ -338,10 +349,10 @@ declare global { interface DeviceObject extends BaseObject { type: "device"; - common: ObjectCommon; // TODO: any definition for device? + common: DeviceCommon; } interface PartialDeviceObject extends Partial<Pick<DeviceObject, "_id" | "native" | "enums" | "type" | "acl">> { - common?: Partial<ObjectCommon>; + common?: Partial<DeviceCommon>; } interface OtherObject extends BaseObject { @@ -353,11 +364,15 @@ declare global { } type Object = StateObject | ChannelObject | DeviceObject | OtherObject; + + type SettableObjectWorker<T extends ioBroker.Object> = + Pick<T, Exclude<keyof T, "_id" | "acl">> & { + _id?: T["_id"]; + acl?: T["acl"]; + }; + // In set[Foreign]Object[NotExists] methods, the ID and acl of the object is optional - interface SettableObject extends Pick<ioBroker.Object, Exclude<keyof ioBroker.Object, "_id" | "acl">> { - _id?: ioBroker.Object["_id"]; - acl?: ioBroker.Object["acl"]; - } + type SettableObject = SettableObjectWorker<ioBroker.Object>; type PartialObject = PartialStateObject | PartialChannelObject | PartialDeviceObject | PartialOtherObject; /** Defines access rights for a single file */ diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 57d00e284b..a2c89cb893 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -262,6 +262,10 @@ adapter.unsubscribeForeignStatesAsync("*").catch(handleError); // Repro from https://github.com/ioBroker/adapter-core/issues/3 const repro1: ioBroker.ObjectChangeHandler = (id, obj) => { + if (!obj || !obj.common) return; + if (obj.common.custom) { + const test1: ioBroker.StateCommon = obj.common; + } obj && obj.common && obj.common.custom From ccb7c5dc16029909045607a02aee70da37ac5c03 Mon Sep 17 00:00:00 2001 From: Bradley Hill <brad.hill@jostens.com> Date: Thu, 7 Feb 2019 08:49:41 -0600 Subject: [PATCH 166/200] Fabricjs - missing color matrix definition (we only had matrix when charlie chaplin played Neo) --- types/fabric/fabric-impl.d.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 68c0a73efe..5cc59d0941 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -3774,7 +3774,18 @@ interface IAllFilters { */ fromObject(object: any): IBrightnessFilter }; - Convolute: { + ColorMatrix: { + new(options?: { + /** Filter matrix */ + matrix?: number[] + }): IColorMatrix; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IColorMatrix + }; + Convolute: { new(options?: { opaque?: boolean, /** Filter matrix */ @@ -3962,6 +3973,13 @@ interface IBrightnessFilter extends IBaseFilter { */ applyTo(canvasEl: HTMLCanvasElement): void; } +interface IColorMatrix extends IBaseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} interface IConvoluteFilter extends IBaseFilter { /** * Applies filter to canvas element From 6823bf50b489163a0604f8f0b1957678f2a5503e Mon Sep 17 00:00:00 2001 From: Jannik Keye <jannik.keye@gmail.com> Date: Thu, 7 Feb 2019 16:28:28 +0100 Subject: [PATCH 167/200] fix: remove fastify-static --- notNeededPackages.json | 6 +++ types/fastify-static/fastify-static-tests.ts | 16 -------- types/fastify-static/index.d.ts | 41 -------------------- types/fastify-static/package.json | 6 --- types/fastify-static/tsconfig.json | 16 -------- types/fastify-static/tslint.json | 1 - 6 files changed, 6 insertions(+), 80 deletions(-) delete mode 100644 types/fastify-static/fastify-static-tests.ts delete mode 100644 types/fastify-static/index.d.ts delete mode 100644 types/fastify-static/package.json delete mode 100644 types/fastify-static/tsconfig.json delete mode 100644 types/fastify-static/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 701978da24..db3d6b10d2 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -570,6 +570,12 @@ "sourceRepoURL": "https://github.com/fastify/fastify-jwt", "asOfVersion": "0.8.1" }, + { + "libraryName": "fastify-static", + "typingsPackageName": "fastify-static", + "sourceRepoURL": "https://github.com/fastify/fastify-static", + "asOfVersion": "2.2.0" + }, { "libraryName": "fecha", "typingsPackageName": "fecha", diff --git a/types/fastify-static/fastify-static-tests.ts b/types/fastify-static/fastify-static-tests.ts deleted file mode 100644 index 630fc0ef52..0000000000 --- a/types/fastify-static/fastify-static-tests.ts +++ /dev/null @@ -1,16 +0,0 @@ -import path = require("path"); -import fastify = require("fastify"); -import fastifyStatic = require("fastify-static"); - -const app = fastify(); - -app.register<fastifyStatic.FastifyStaticOptions>(fastifyStatic, { - root: path.join(__dirname, "public"), - prefix: "/public/", // optional: default '/' - immutable: true, - maxAge: 42 -}); - -app.get("/another/path", (req, reply) => { - reply.sendFile("myHtml.html"); // serving path.join(__dirname, 'public', 'myHtml.html') directly -}); diff --git a/types/fastify-static/index.d.ts b/types/fastify-static/index.d.ts deleted file mode 100644 index ef4eda1952..0000000000 --- a/types/fastify-static/index.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Type definitions for fastify-static 0.14 -// Project: https://github.com/fastify/fastify-static -// Definitions by: Leonhard Melzer <https://github.com/leomelzer> -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -import fastify = require("fastify"); - -import { Server, IncomingMessage, ServerResponse } from "http"; - -declare module "fastify" { - interface FastifyReply<HttpResponse> { - sendFile(filename: string): FastifyReply<HttpResponse>; - } -} - -declare function fastifyStatic(): void; - -declare namespace fastifyStatic { - interface FastifyStaticOptions { - root: string; - prefix?: string; - serve?: boolean; - decorateReply?: boolean; - schemaHide?: boolean; - setHeaders?: () => void; - - // Passed on to `send` - acceptRanges?: boolean; - cacheControl?: boolean; - dotfiles?: boolean; - etag?: boolean; - extensions?: string[]; - immutable?: boolean; - index?: string[]; - lastModified?: boolean; - maxAge?: string | number; - } -} - -export = fastifyStatic; diff --git a/types/fastify-static/package.json b/types/fastify-static/package.json deleted file mode 100644 index e8c68ab969..0000000000 --- a/types/fastify-static/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "private": true, - "dependencies": { - "fastify": "^1.11.2" - } -} diff --git a/types/fastify-static/tsconfig.json b/types/fastify-static/tsconfig.json deleted file mode 100644 index bdfa7d40c6..0000000000 --- a/types/fastify-static/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": ["es6"], - "noImplicitAny": true, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": ["../"], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": ["index.d.ts", "fastify-static-tests.ts"] -} diff --git a/types/fastify-static/tslint.json b/types/fastify-static/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/fastify-static/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } From a336ba83ae30b666f284dfd16c1b926f7ae03106 Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 09:45:58 -0600 Subject: [PATCH 168/200] Add @carbon/layout --- types/carbon__layout/carbon__layout-tests.ts | 20 +++++ types/carbon__layout/index.d.ts | 80 ++++++++++++++++++++ types/carbon__layout/tsconfig.json | 19 +++++ types/carbon__layout/tslint.json | 1 + 4 files changed, 120 insertions(+) create mode 100644 types/carbon__layout/carbon__layout-tests.ts create mode 100644 types/carbon__layout/index.d.ts create mode 100644 types/carbon__layout/tsconfig.json create mode 100644 types/carbon__layout/tslint.json diff --git a/types/carbon__layout/carbon__layout-tests.ts b/types/carbon__layout/carbon__layout-tests.ts new file mode 100644 index 0000000000..ef002f50ae --- /dev/null +++ b/types/carbon__layout/carbon__layout-tests.ts @@ -0,0 +1,20 @@ +import { + rem, + em, + px, + breakpoint, + breakpoints, + breakpointDown, + breakpointUp, + baseFontSize +} from "@carbon/layout"; + +const firstBreakpoint = Object.keys(breakpoints)[0]; + +rem(baseFontSize); // $ExpectType string +em(baseFontSize); // $ExpectType string +px(baseFontSize); // $ExpectType string + +breakpoint(firstBreakpoint); // $ExpectType string +breakpointUp(firstBreakpoint); // $ExpectType string +breakpointDown(firstBreakpoint); // $ExpectType string diff --git a/types/carbon__layout/index.d.ts b/types/carbon__layout/index.d.ts new file mode 100644 index 0000000000..1d7c7b4630 --- /dev/null +++ b/types/carbon__layout/index.d.ts @@ -0,0 +1,80 @@ +// Type definitions for @carbon/layout 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/layout +// Definitions by: Vince Picone <https://github.com/vpicone> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const baseFontSize: number; + +export const breakpoints: { + lg: { + columns: number; + margin: string; + width: string; + }; + max: { + columns: number; + margin: string; + width: string; + }; + md: { + columns: number; + margin: string; + width: string; + }; + sm: { + columns: number; + margin: string; + width: string; + }; + xlg: { + columns: number; + margin: string; + width: string; + }; +}; + +export const miniUnit: number; + +export const spacing: number[]; + +export function breakpoint(...args: any[]): string; + +export function breakpointDown(name: string): string; + +export function breakpointUp(name: string): string; + +export function em(px: number): string; + +export function miniUnits(count: number): string; + +export function px(value: number): string; + +export function rem(px: number): string; + +export namespace breakpoint { + const prototype: {}; +} + +export namespace breakpointDown { + const prototype: {}; +} + +export namespace breakpointUp { + const prototype: {}; +} + +export namespace em { + const prototype: {}; +} + +export namespace miniUnits { + const prototype: {}; +} + +export namespace px { + const prototype: {}; +} + +export namespace rem { + const prototype: {}; +} diff --git a/types/carbon__layout/tsconfig.json b/types/carbon__layout/tsconfig.json new file mode 100644 index 0000000000..10f832a631 --- /dev/null +++ b/types/carbon__layout/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/layout": ["carbon__layout"] + } + }, + "files": ["index.d.ts", "carbon__layout-tests.ts"] +} diff --git a/types/carbon__layout/tslint.json b/types/carbon__layout/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__layout/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 12e28d0e287d0a2fe41700639cb6e2f891c0ac0a Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 09:49:53 -0600 Subject: [PATCH 169/200] Add carbon motion --- types/carbon__motion/carbon__motion-tests.ts | 0 types/carbon__motion/index.d.ts | 28 ++++++++++++++++++++ types/carbon__motion/tsconfig.json | 19 +++++++++++++ types/carbon__motion/tslint.json | 1 + 4 files changed, 48 insertions(+) create mode 100644 types/carbon__motion/carbon__motion-tests.ts create mode 100644 types/carbon__motion/index.d.ts create mode 100644 types/carbon__motion/tsconfig.json create mode 100644 types/carbon__motion/tslint.json diff --git a/types/carbon__motion/carbon__motion-tests.ts b/types/carbon__motion/carbon__motion-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/carbon__motion/index.d.ts b/types/carbon__motion/index.d.ts new file mode 100644 index 0000000000..9570133327 --- /dev/null +++ b/types/carbon__motion/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for carbon__motion-ts 0.0 +// Project: https://github.com/baz/foo (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: My Self <https://github.com/me> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const easings: { + entrance: { + expressive: string; + productive: string; + }; + exit: { + expressive: string; + productive: string; + }; + standard: { + expressive: string; + productive: string; + }; +}; + +export function motion(name: any, mode: any): any; + +export namespace motion { + const prototype: { + }; + +} + diff --git a/types/carbon__motion/tsconfig.json b/types/carbon__motion/tsconfig.json new file mode 100644 index 0000000000..38245c7c9e --- /dev/null +++ b/types/carbon__motion/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/motion": ["carbon__motion"] + } + }, + "files": ["index.d.ts", "carbon__motion-tests.ts"] +} diff --git a/types/carbon__motion/tslint.json b/types/carbon__motion/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__motion/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6eea5834fa91716914c604464c4fd4d2ba032ac8 Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 09:56:03 -0600 Subject: [PATCH 170/200] add tests --- types/carbon__motion/carbon__motion-tests.ts | 8 ++++++++ types/carbon__motion/index.d.ts | 7 ++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/types/carbon__motion/carbon__motion-tests.ts b/types/carbon__motion/carbon__motion-tests.ts index e69de29bb2..6bcc820f5d 100644 --- a/types/carbon__motion/carbon__motion-tests.ts +++ b/types/carbon__motion/carbon__motion-tests.ts @@ -0,0 +1,8 @@ +import { easings, motion } from "@carbon/motion"; + +const easingNames = Object.keys(easings); + +const firstEasing = easingNames[0]; +const firstMode = Object.keys(firstEasing)[0]; + +motion(firstEasing, firstMode); diff --git a/types/carbon__motion/index.d.ts b/types/carbon__motion/index.d.ts index 9570133327..5027843174 100644 --- a/types/carbon__motion/index.d.ts +++ b/types/carbon__motion/index.d.ts @@ -18,11 +18,8 @@ export const easings: { }; }; -export function motion(name: any, mode: any): any; +export function motion(name: string, mode: string): string; export namespace motion { - const prototype: { - }; - + const prototype: {}; } - From c341f6378d8db86af3740a5f8c3b822e72184b29 Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 10:05:13 -0600 Subject: [PATCH 171/200] Add @carbon/type --- types/carbon__type/carbon__type-tests.ts | 0 types/carbon__type/index.d.ts | 717 +++++++++++++++++++++++ types/carbon__type/tsconfig.json | 19 + types/carbon__type/tslint.json | 1 + 4 files changed, 737 insertions(+) create mode 100644 types/carbon__type/carbon__type-tests.ts create mode 100644 types/carbon__type/index.d.ts create mode 100644 types/carbon__type/tsconfig.json create mode 100644 types/carbon__type/tslint.json diff --git a/types/carbon__type/carbon__type-tests.ts b/types/carbon__type/carbon__type-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/carbon__type/index.d.ts b/types/carbon__type/index.d.ts new file mode 100644 index 0000000000..af79ee812b --- /dev/null +++ b/types/carbon__type/index.d.ts @@ -0,0 +1,717 @@ +// Type definitions for @carbon/type 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/type +// Definitions by: Vince Picone <https://github.com/vpicone> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const bodyLong01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const bodyLong02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const bodyShort01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const bodyShort02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const caption01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const code01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const code02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const display01: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display02: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display03: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display04: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveHeading04: { + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveHeading05: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveParagraph01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lg: { + fontSize: string; + lineHeight: string; + }; + lineHeight: string; + max: { + fontSize: string; + lineHeight: string; + }; +}; + +export const fontFamilies: { + mono: string; + sans: string; + sansCondensed: string; + sansHebrew: string; + serif: string; +}; + +export const fontWeights: { + light: number; + regular: number; + semibold: number; +}; + +export const heading01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const heading02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const heading03: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const helperText01: { + fontFamily: string; + fontSize: string; + fontStyle: string; + letterSpacing: string; + lineHeight: string; +}; + +export const label01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const productiveHeading04: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const productiveHeading05: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const quotation01: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const quotation02: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const reset: { + body: { + "-moz-osx-font-smoothing": string; + "-webkit-font-smoothing": string; + fontFamily: string; + fontWeight: number; + textRendering: string; + }; + html: { + fontSize: string; + }; + strong: { + fontWeight: number; + }; +}; + +export const scale: number[]; + +export const spacing: { + layout01: string; + layout02: string; + layout03: string; + margin01: string; + margin02: string; + margin03: string; +}; + +export const styles: { + bodyLong01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + bodyLong02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + bodyShort01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + bodyShort02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + caption01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + code01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + code02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + display01: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display02: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display03: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display04: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveHeading04: { + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveHeading05: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveParagraph01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lg: { + fontSize: string; + lineHeight: string; + }; + lineHeight: string; + max: { + fontSize: string; + lineHeight: string; + }; + }; + heading01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + heading02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + heading03: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + helperText01: { + fontFamily: string; + fontSize: string; + fontStyle: string; + letterSpacing: string; + lineHeight: string; + }; + label01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + productiveHeading04: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + productiveHeading05: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + quotation01: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + quotation02: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; +}; + +export function fontFamily(name: any): any; + +export function fontWeight(weight: any): any; + +export function getTypeSize(step: any): any; + +export function print(block: any): any; + +export namespace fontFamily { + const prototype: {}; +} + +export namespace fontWeight { + const prototype: {}; +} + +export namespace getTypeSize { + const prototype: {}; +} + +export namespace print { + const prototype: {}; +} diff --git a/types/carbon__type/tsconfig.json b/types/carbon__type/tsconfig.json new file mode 100644 index 0000000000..7949e7ab22 --- /dev/null +++ b/types/carbon__type/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/type": ["carbon__type"] + } + }, + "files": ["index.d.ts", "carbon__type-tests.ts"] +} diff --git a/types/carbon__type/tslint.json b/types/carbon__type/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__type/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d69938c98f79fdf9f948e47fdd7f6ba68c42ccfe Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 10:06:01 -0600 Subject: [PATCH 172/200] fix headers --- types/carbon__motion/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/carbon__motion/index.d.ts b/types/carbon__motion/index.d.ts index 5027843174..173687d04c 100644 --- a/types/carbon__motion/index.d.ts +++ b/types/carbon__motion/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for carbon__motion-ts 0.0 -// Project: https://github.com/baz/foo (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) -// Definitions by: My Self <https://github.com/me> +// Type definitions for @carbon/motion 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/motion +// Definitions by: Vince Picone <https://github.com/vpicone> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export const easings: { From d4c5675d00e52c4cf99dcc88a5c0fea838d241eb Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 10:19:01 -0600 Subject: [PATCH 173/200] Add @carbon/type --- types/carbon__type/carbon__type-tests.ts | 6 ++++++ types/carbon__type/index.d.ts | 17 +++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/types/carbon__type/carbon__type-tests.ts b/types/carbon__type/carbon__type-tests.ts index e69de29bb2..a5d4cf7b8b 100644 --- a/types/carbon__type/carbon__type-tests.ts +++ b/types/carbon__type/carbon__type-tests.ts @@ -0,0 +1,6 @@ +import { fontFamily, fontWeight, getTypeSize, print } from "@carbon/type"; + +fontFamily("mono"); // $ExpectType { fontFamily: string; } +fontWeight("light"); // $ExpectType { fontWeight: number; } +print(fontFamily("mono")); // $ExpectType string +getTypeSize(2); // $ExpectType number diff --git a/types/carbon__type/index.d.ts b/types/carbon__type/index.d.ts index af79ee812b..7933f2e358 100644 --- a/types/carbon__type/index.d.ts +++ b/types/carbon__type/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/IBM/carbon-elements/tree/master/packages/type // Definitions by: Vince Picone <https://github.com/vpicone> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 export const bodyLong01: { fontFamily: string; @@ -692,13 +693,21 @@ export const styles: { }; }; -export function fontFamily(name: any): any; +export function fontFamily( + name: string +): { + fontFamily: string; +}; -export function fontWeight(weight: any): any; +export function fontWeight( + weight: string +): { + fontWeight: number; +}; -export function getTypeSize(step: any): any; +export function getTypeSize(step: number): number; -export function print(block: any): any; +export function print(block: object): string; export namespace fontFamily { const prototype: {}; From 95ea7a5148af9b2a643fcc5da7f3e7d0ae014f1d Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 09:19:21 -0800 Subject: [PATCH 174/200] [office-js] [office-js-preview] (Outlook) Remove inapplicable props --- types/office-js-preview/index.d.ts | 127 +---------------------------- types/office-js/index.d.ts | 127 +---------------------------- 2 files changed, 4 insertions(+), 250 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index ffb686b3d2..026701c4be 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of AttachmentDetail objects is returned as the attachments property of an Appointment or Message object. + * An array of `AttachmentDetails` objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -11765,32 +11765,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets or sets the date and time that the appointment is to end. * @@ -13622,32 +13596,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the type of item that an instance represents. * @@ -13676,29 +13624,6 @@ declare namespace Office { */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> - */ - recurrence: Recurrence; - /** * Gets the id of the series that an instance belongs to. * @@ -15234,32 +15159,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ conversationId: string; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the email address of the sender of a message. * @@ -15320,28 +15219,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - recurrence: Recurrence; /** * Gets the id of the series that an instance belongs to. * @@ -17779,7 +17656,7 @@ declare namespace Office { /** * Gets a string that was identified as a meeting suggestion. */ - meetingstring: string; + meetingString: string; /** * Gets the date and time that a suggested meeting is to begin. */ diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index d53bdedb79..b35620eeb1 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of AttachmentDetail objects is returned as the attachments property of an Appointment or Message object. + * An array of `AttachmentDetails` objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -11765,32 +11765,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets or sets the date and time that the appointment is to end. * @@ -13622,32 +13596,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the type of item that an instance represents. * @@ -13676,29 +13624,6 @@ declare namespace Office { */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> - */ - recurrence: Recurrence; - /** * Gets the id of the series that an instance belongs to. * @@ -15234,32 +15159,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ conversationId: string; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the email address of the sender of a message. * @@ -15320,28 +15219,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - recurrence: Recurrence; /** * Gets the id of the series that an instance belongs to. * @@ -17779,7 +17656,7 @@ declare namespace Office { /** * Gets a string that was identified as a meeting suggestion. */ - meetingstring: string; + meetingString: string; /** * Gets the date and time that a suggested meeting is to begin. */ From 8d7c359191857e2f72ffbf813bd17dfb1eaa24f4 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 09:24:47 -0800 Subject: [PATCH 175/200] Minor cleanup --- types/office-js-preview/index.d.ts | 8 ++++---- types/office-js/index.d.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 026701c4be..14838b162e 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -12849,7 +12849,7 @@ declare namespace Office { */ body: Body; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -12861,7 +12861,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * @@ -16205,7 +16205,7 @@ declare namespace Office { */ conversationId: string; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -16217,7 +16217,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index b35620eeb1..aa90caf5be 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -12849,7 +12849,7 @@ declare namespace Office { */ body: Body; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -12861,7 +12861,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * @@ -16205,7 +16205,7 @@ declare namespace Office { */ conversationId: string; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -16217,7 +16217,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * From 210e52da16ed7dbde6f6bda1a70f605f157cc4de Mon Sep 17 00:00:00 2001 From: Ethan Setnik <esetnik@gmail.com> Date: Thu, 7 Feb 2019 12:45:29 -0500 Subject: [PATCH 176/200] add startSubmit and stopSubmit --- types/redux-form/immutable/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/redux-form/immutable/index.d.ts b/types/redux-form/immutable/index.d.ts index 742027ccad..2ce6164232 100644 --- a/types/redux-form/immutable/index.d.ts +++ b/types/redux-form/immutable/index.d.ts @@ -24,5 +24,7 @@ export { isSubmitting, isAsyncValidating, isValid, - SubmissionError -} from "../"; + SubmissionError, + startSubmit, + stopSubmit, +} from '../'; From cc6741b1bf8c4e34d465fae748308f510dc40e41 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 09:53:12 -0800 Subject: [PATCH 177/200] Add link to OM page --- types/office-js-preview/index.d.ts | 24 ++++++++++++++++-------- types/office-js/index.d.ts | 24 ++++++++++++++++-------- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 14838b162e..e9586af4f1 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -11742,7 +11742,8 @@ declare namespace Office { * The subclass of {@link Office.Item} dealing with appointments. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Appointment extends Item { } @@ -11750,7 +11751,8 @@ declare namespace Office { * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentCompose extends Appointment, ItemCompose { /** @@ -12817,7 +12819,8 @@ declare namespace Office { * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of 'Office.context.mailbox.item'. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentRead extends Appointment, ItemRead { /** @@ -13876,7 +13879,8 @@ declare namespace Office { * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemCompose extends Item { /** @@ -14650,7 +14654,8 @@ declare namespace Office { * The read mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemRead extends Item { /** @@ -15069,7 +15074,8 @@ declare namespace Office { * A subclass of {@link Office.Item} for messages. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Message extends Item { /** @@ -15097,7 +15103,8 @@ declare namespace Office { * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageCompose extends Message, ItemCompose { /** @@ -16137,7 +16144,8 @@ declare namespace Office { * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageRead extends Message, ItemRead { /** diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index aa90caf5be..5a98b250ae 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -11742,7 +11742,8 @@ declare namespace Office { * The subclass of {@link Office.Item} dealing with appointments. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Appointment extends Item { } @@ -11750,7 +11751,8 @@ declare namespace Office { * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentCompose extends Appointment, ItemCompose { /** @@ -12817,7 +12819,8 @@ declare namespace Office { * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of 'Office.context.mailbox.item'. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentRead extends Appointment, ItemRead { /** @@ -13876,7 +13879,8 @@ declare namespace Office { * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemCompose extends Item { /** @@ -14650,7 +14654,8 @@ declare namespace Office { * The read mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemRead extends Item { /** @@ -15069,7 +15074,8 @@ declare namespace Office { * A subclass of {@link Office.Item} for messages. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Message extends Item { /** @@ -15097,7 +15103,8 @@ declare namespace Office { * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageCompose extends Message, ItemCompose { /** @@ -16137,7 +16144,8 @@ declare namespace Office { * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageRead extends Message, ItemRead { /** From ab8fc4f1508ed95007e858d7b5615bb928af3ff4 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 10:44:26 -0800 Subject: [PATCH 178/200] Bold Important and Note --- types/office-js-preview/index.d.ts | 286 ++++++++++++++--------------- types/office-js/index.d.ts | 286 ++++++++++++++--------------- 2 files changed, 286 insertions(+), 286 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index e9586af4f1..bbed11cdea 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -20,7 +20,7 @@ declare namespace Office { */ var Promise: IPromiseConstructor; - // Note: this is a copy of the PromiseConstructor object from + // **Note**: this is a copy of the PromiseConstructor object from // https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es2015.promise.d.ts // It is necessary so that even with targeting "ES5" and not specifying any libs, // developers will still get IntelliSense for "Office.Promise" just as they would with a regular Promise. @@ -628,7 +628,7 @@ declare namespace Office { * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the * `getSelectedDataAsync` and `setSelectedDataAsync` methods of the {@link Office.Document | Document} object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. + * **Note**: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. * To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. * * **Support details** @@ -1446,7 +1446,7 @@ declare namespace Office { /** * Specifies a table of sample data displayed in the prompt UI as an example of the kinds of fields (columns) that can be bound by your add-in. * The headers provided in the TableData object specify the labels used in the field selection UI. - * Note: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. + * **Note**: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. */ sampleData?: Office.TableData /** @@ -1781,43 +1781,43 @@ declare namespace Office { * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of * characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. * - * Note: Only applies to data in Excel and Word. + * **Note**: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. * - * Note: Only applies to data in Access, Excel, and Word. + * **Note**: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. * - * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * **Note**: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. * - * Note: Only applies to data in Word. + * **Note**: Only applies to data in Word. */ Ooxml, /** * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, * `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. * - * Note: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current + * **Note**: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current * slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ Image, /** * Data is returned or set as XML data containing an SVG image. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ XmlSvg } @@ -2523,7 +2523,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2654,7 +2654,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2825,7 +2825,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2835,7 +2835,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -2871,7 +2871,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2881,7 +2881,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -4542,7 +4542,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -4659,7 +4659,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -5151,7 +5151,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5177,7 +5177,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's resource collection. @@ -5202,7 +5202,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5228,7 +5228,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's task collection. @@ -5253,7 +5253,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5280,7 +5280,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5306,7 +5306,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5333,7 +5333,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5359,7 +5359,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5387,7 +5387,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5414,7 +5414,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5442,7 +5442,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5662,7 +5662,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5719,7 +5719,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5862,7 +5862,7 @@ declare namespace Office { /** * Removes the specified setting. * - * Important: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of + * **Important**: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of * the specified setting in the document, at some point after calling the Settings.remove method and before the add-in is closed, you must * call the Settings.saveAsync method. * @@ -5970,7 +5970,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6027,7 +6027,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6078,7 +6078,7 @@ declare namespace Office { /** * Sets or creates the specified setting. * - * Important: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. + * **Important**: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. * To make sure that additions or changes to settings will be available to your add-in the next time the document is opened, at some point * after calling the Settings.set method and before the add-in is closed, you must call the Settings.saveAsync method to persist settings in * the document. @@ -6128,7 +6128,7 @@ declare namespace Office { * The settingsChanged event was designed to let you to handle potential conflicts when two or more users are * attempting to save settings at the same time when your add-in is used in a shared (co-authored) document. * - * **Important:** Your add-in's code can register a handler for the settingsChanged event when the add-in + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in * is running with any Excel client, but the event will fire only when the add-in is loaded with a spreadsheet * that is opened in Excel Online, and more than one user is editing the spreadsheet (co-authoring). * Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. @@ -11741,7 +11741,7 @@ declare namespace Office { /** * The subclass of {@link Office.Item} dealing with appointments. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -11750,7 +11750,7 @@ declare namespace Office { /** * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -11880,9 +11880,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -11914,7 +11914,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -12271,7 +12271,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -12306,7 +12306,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -12566,11 +12566,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12610,11 +12610,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12643,11 +12643,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12677,11 +12677,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12818,7 +12818,7 @@ declare namespace Office { /** * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -12834,7 +12834,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * */ @@ -12874,7 +12874,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -12962,7 +12962,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -13064,9 +13064,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -13114,7 +13114,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. Before making REST API calls using this value, it * should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13209,7 +13209,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13234,7 +13234,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13252,7 +13252,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13281,7 +13281,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -13303,7 +13303,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13317,7 +13317,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13385,7 +13385,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13415,7 +13415,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13441,7 +13441,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13460,7 +13460,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13487,7 +13487,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13633,7 +13633,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13734,7 +13734,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13878,7 +13878,7 @@ declare namespace Office { /** * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -14166,7 +14166,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -14201,7 +14201,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -14396,11 +14396,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14442,11 +14442,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14475,11 +14475,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14510,11 +14510,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14653,7 +14653,7 @@ declare namespace Office { /** * The read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -14668,7 +14668,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -14718,7 +14718,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -14775,7 +14775,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14800,7 +14800,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14818,7 +14818,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14847,7 +14847,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14870,7 +14870,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14884,7 +14884,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14953,7 +14953,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14983,7 +14983,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15009,7 +15009,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15028,7 +15028,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15053,7 +15053,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15073,7 +15073,7 @@ declare namespace Office { /** * A subclass of {@link Office.Item} for messages. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -15102,7 +15102,7 @@ declare namespace Office { /** * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -15232,7 +15232,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -15592,7 +15592,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -15627,7 +15627,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -15891,11 +15891,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -15936,11 +15936,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -15968,11 +15968,11 @@ declare namespace Office { * Since appointments have no draft state, if saveAsync is called on an appointment in compose mode, the item will be saved as a normal * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16003,11 +16003,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16143,7 +16143,7 @@ declare namespace Office { /** * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -16159,7 +16159,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -16235,7 +16235,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -16244,7 +16244,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the from property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the from property is undefined. * * The from property returns an EmailAddressDetails object. * @@ -16329,7 +16329,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -16394,9 +16394,9 @@ declare namespace Office { * in a series. `null` is returned for single appointments and meeting requests of single appointments. * `undefined` is returned for messages that are not meeting requests. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment * and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -16414,7 +16414,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -16437,7 +16437,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the sender property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the sender property is undefined. * * [Api set: Mailbox 1.0] * @@ -16542,7 +16542,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16567,7 +16567,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16586,7 +16586,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -16616,7 +16616,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the * web for Office 365. * * [Api set: Mailbox Preview] @@ -16639,7 +16639,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16653,7 +16653,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16723,7 +16723,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16753,7 +16753,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16779,7 +16779,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16798,7 +16798,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -16825,7 +16825,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -17163,7 +17163,7 @@ declare namespace Office { * * The ewsUrl value can be used by a remote service to make EWS calls to the user's mailbox. For example, you can create a remote service to {@link https://docs.microsoft.com/outlook/add-ins/get-attachments-of-an-outlook-item | get attachments from the selected item}. * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ ewsUrl: string; /** @@ -17224,7 +17224,7 @@ declare namespace Office { * Item IDs retrieved via a REST API (such as the Outlook Mail API or the Microsoft Graph) use a different format than the format used by * Exchange Web Services (EWS). The convertToEwsId method converts a REST-formatted ID into the proper format for EWS. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17265,7 +17265,7 @@ declare namespace Office { /** * Converts an item ID formatted for EWS into REST format. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17316,7 +17316,7 @@ declare namespace Office { * If the specified item identifier does not identify an existing appointment, a blank pane opens on the client computer or device, and * no error message will be returned. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17342,7 +17342,7 @@ declare namespace Office { * Do not use the displayMessageForm with an itemId that represents an appointment. Use the displayAppointmentForm method to display * an existing appointment, and displayNewAppointmentForm to display a form to create a new appointment. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17371,7 +17371,7 @@ declare namespace Office { * * If any of the parameters exceed the specified size limits, or if an unknown parameter name is specified, an exception is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17453,7 +17453,7 @@ declare namespace Office { * * The add-in should use the ewsUrl property to determine the correct URL to use when making EWS calls. * - * Note: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. + * **Note**: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. * * [Api set: Mailbox 1.5] * @@ -17575,13 +17575,13 @@ declare namespace Office { * The XML result of the EWS call is provided as a string in the asyncResult.value property. * If the result exceeds 1 MB in size, an error message is returned instead. * - * Note: This method is not supported in the following scenarios: + * **Note**: This method is not supported in the following scenarios: * * - In Outlook for iOS or Outlook for Android. * * - When the add-in is loaded in a Gmail mailbox. * - * Note: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the + * **Note**: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the * makeEwsRequestAsync method to make EWS requests. * * *Version differences* @@ -18462,7 +18462,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18489,7 +18489,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18631,7 +18631,7 @@ declare namespace Office { * * The RoamingSettings object is accessible via the roamingSettings property in the Office.context namespace. * - * Important: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. + * **Important**: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. * For task panes, this means that it is only initialized when the task pane first opens. * If the task pane navigates to another page or reloads the current page, the in-memory object is reset to its initial values, even if * your add-in has persisted changes. The persisted changes will not be available until the task pane is closed and reopened. @@ -19271,7 +19271,7 @@ declare namespace Office { /** * Gets the account type of the user associated with the mailbox. * - * Note: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. + * **Note**: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. * * [Api set: Mailbox 1.6] * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 5a98b250ae..027a90d0c2 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -20,7 +20,7 @@ declare namespace Office { */ var Promise: IPromiseConstructor; - // Note: this is a copy of the PromiseConstructor object from + // **Note**: this is a copy of the PromiseConstructor object from // https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es2015.promise.d.ts // It is necessary so that even with targeting "ES5" and not specifying any libs, // developers will still get IntelliSense for "Office.Promise" just as they would with a regular Promise. @@ -628,7 +628,7 @@ declare namespace Office { * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the * `getSelectedDataAsync` and `setSelectedDataAsync` methods of the {@link Office.Document | Document} object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. + * **Note**: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. * To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. * * **Support details** @@ -1446,7 +1446,7 @@ declare namespace Office { /** * Specifies a table of sample data displayed in the prompt UI as an example of the kinds of fields (columns) that can be bound by your add-in. * The headers provided in the TableData object specify the labels used in the field selection UI. - * Note: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. + * **Note**: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. */ sampleData?: Office.TableData /** @@ -1781,43 +1781,43 @@ declare namespace Office { * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of * characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. * - * Note: Only applies to data in Excel and Word. + * **Note**: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. * - * Note: Only applies to data in Access, Excel, and Word. + * **Note**: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. * - * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * **Note**: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. * - * Note: Only applies to data in Word. + * **Note**: Only applies to data in Word. */ Ooxml, /** * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, * `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. * - * Note: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current + * **Note**: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current * slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ Image, /** * Data is returned or set as XML data containing an SVG image. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ XmlSvg } @@ -2523,7 +2523,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2654,7 +2654,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2825,7 +2825,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2835,7 +2835,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -2871,7 +2871,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2881,7 +2881,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -4542,7 +4542,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -4659,7 +4659,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -5151,7 +5151,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5177,7 +5177,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's resource collection. @@ -5202,7 +5202,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5228,7 +5228,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's task collection. @@ -5253,7 +5253,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5280,7 +5280,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5306,7 +5306,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5333,7 +5333,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5359,7 +5359,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5387,7 +5387,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5414,7 +5414,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5442,7 +5442,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5662,7 +5662,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5719,7 +5719,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5862,7 +5862,7 @@ declare namespace Office { /** * Removes the specified setting. * - * Important: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of + * **Important**: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of * the specified setting in the document, at some point after calling the Settings.remove method and before the add-in is closed, you must * call the Settings.saveAsync method. * @@ -5970,7 +5970,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6027,7 +6027,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6078,7 +6078,7 @@ declare namespace Office { /** * Sets or creates the specified setting. * - * Important: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. + * **Important**: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. * To make sure that additions or changes to settings will be available to your add-in the next time the document is opened, at some point * after calling the Settings.set method and before the add-in is closed, you must call the Settings.saveAsync method to persist settings in * the document. @@ -6128,7 +6128,7 @@ declare namespace Office { * The settingsChanged event was designed to let you to handle potential conflicts when two or more users are * attempting to save settings at the same time when your add-in is used in a shared (co-authored) document. * - * **Important:** Your add-in's code can register a handler for the settingsChanged event when the add-in + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in * is running with any Excel client, but the event will fire only when the add-in is loaded with a spreadsheet * that is opened in Excel Online, and more than one user is editing the spreadsheet (co-authoring). * Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. @@ -11741,7 +11741,7 @@ declare namespace Office { /** * The subclass of {@link Office.Item} dealing with appointments. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -11750,7 +11750,7 @@ declare namespace Office { /** * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -11880,9 +11880,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -11914,7 +11914,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -12271,7 +12271,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -12306,7 +12306,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -12566,11 +12566,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12610,11 +12610,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12643,11 +12643,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12677,11 +12677,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12818,7 +12818,7 @@ declare namespace Office { /** * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -12834,7 +12834,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * */ @@ -12874,7 +12874,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -12962,7 +12962,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -13064,9 +13064,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -13114,7 +13114,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. Before making REST API calls using this value, it * should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13209,7 +13209,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13234,7 +13234,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13252,7 +13252,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13281,7 +13281,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -13303,7 +13303,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13317,7 +13317,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13385,7 +13385,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13415,7 +13415,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13441,7 +13441,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13460,7 +13460,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13487,7 +13487,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13633,7 +13633,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13734,7 +13734,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13878,7 +13878,7 @@ declare namespace Office { /** * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -14166,7 +14166,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -14201,7 +14201,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -14396,11 +14396,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14442,11 +14442,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14475,11 +14475,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14510,11 +14510,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14653,7 +14653,7 @@ declare namespace Office { /** * The read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -14668,7 +14668,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -14718,7 +14718,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -14775,7 +14775,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14800,7 +14800,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14818,7 +14818,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14847,7 +14847,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14870,7 +14870,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14884,7 +14884,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14953,7 +14953,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14983,7 +14983,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15009,7 +15009,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15028,7 +15028,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15053,7 +15053,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15073,7 +15073,7 @@ declare namespace Office { /** * A subclass of {@link Office.Item} for messages. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -15102,7 +15102,7 @@ declare namespace Office { /** * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -15232,7 +15232,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -15592,7 +15592,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -15627,7 +15627,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -15891,11 +15891,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -15936,11 +15936,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -15968,11 +15968,11 @@ declare namespace Office { * Since appointments have no draft state, if saveAsync is called on an appointment in compose mode, the item will be saved as a normal * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16003,11 +16003,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16143,7 +16143,7 @@ declare namespace Office { /** * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -16159,7 +16159,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -16235,7 +16235,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -16244,7 +16244,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the from property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the from property is undefined. * * The from property returns an EmailAddressDetails object. * @@ -16329,7 +16329,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -16394,9 +16394,9 @@ declare namespace Office { * in a series. `null` is returned for single appointments and meeting requests of single appointments. * `undefined` is returned for messages that are not meeting requests. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment * and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -16414,7 +16414,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -16437,7 +16437,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the sender property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the sender property is undefined. * * [Api set: Mailbox 1.0] * @@ -16542,7 +16542,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16567,7 +16567,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16586,7 +16586,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -16616,7 +16616,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the * web for Office 365. * * [Api set: Mailbox Preview] @@ -16639,7 +16639,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16653,7 +16653,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16723,7 +16723,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16753,7 +16753,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16779,7 +16779,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16798,7 +16798,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -16825,7 +16825,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -17163,7 +17163,7 @@ declare namespace Office { * * The ewsUrl value can be used by a remote service to make EWS calls to the user's mailbox. For example, you can create a remote service to {@link https://docs.microsoft.com/outlook/add-ins/get-attachments-of-an-outlook-item | get attachments from the selected item}. * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ ewsUrl: string; /** @@ -17224,7 +17224,7 @@ declare namespace Office { * Item IDs retrieved via a REST API (such as the Outlook Mail API or the Microsoft Graph) use a different format than the format used by * Exchange Web Services (EWS). The convertToEwsId method converts a REST-formatted ID into the proper format for EWS. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17265,7 +17265,7 @@ declare namespace Office { /** * Converts an item ID formatted for EWS into REST format. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17316,7 +17316,7 @@ declare namespace Office { * If the specified item identifier does not identify an existing appointment, a blank pane opens on the client computer or device, and * no error message will be returned. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17342,7 +17342,7 @@ declare namespace Office { * Do not use the displayMessageForm with an itemId that represents an appointment. Use the displayAppointmentForm method to display * an existing appointment, and displayNewAppointmentForm to display a form to create a new appointment. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17371,7 +17371,7 @@ declare namespace Office { * * If any of the parameters exceed the specified size limits, or if an unknown parameter name is specified, an exception is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17453,7 +17453,7 @@ declare namespace Office { * * The add-in should use the ewsUrl property to determine the correct URL to use when making EWS calls. * - * Note: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. + * **Note**: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. * * [Api set: Mailbox 1.5] * @@ -17575,13 +17575,13 @@ declare namespace Office { * The XML result of the EWS call is provided as a string in the asyncResult.value property. * If the result exceeds 1 MB in size, an error message is returned instead. * - * Note: This method is not supported in the following scenarios: + * **Note**: This method is not supported in the following scenarios: * * - In Outlook for iOS or Outlook for Android. * * - When the add-in is loaded in a Gmail mailbox. * - * Note: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the + * **Note**: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the * makeEwsRequestAsync method to make EWS requests. * * *Version differences* @@ -18462,7 +18462,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18489,7 +18489,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18631,7 +18631,7 @@ declare namespace Office { * * The RoamingSettings object is accessible via the roamingSettings property in the Office.context namespace. * - * Important: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. + * **Important**: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. * For task panes, this means that it is only initialized when the task pane first opens. * If the task pane navigates to another page or reloads the current page, the in-memory object is reset to its initial values, even if * your add-in has persisted changes. The persisted changes will not be available until the task pane is closed and reopened. @@ -19271,7 +19271,7 @@ declare namespace Office { /** * Gets the account type of the user associated with the mailbox. * - * Note: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. + * **Note**: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. * * [Api set: Mailbox 1.6] * From c38b87afe6ff4cc7616c9a5253458e4d191c8774 Mon Sep 17 00:00:00 2001 From: Ethan Setnik <esetnik@gmail.com> Date: Thu, 7 Feb 2019 14:03:43 -0500 Subject: [PATCH 179/200] add tests --- types/redux-form/index.d.ts | 1 + types/redux-form/redux-form-tests.tsx | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 6915032138..28047e8007 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -12,6 +12,7 @@ // Maddi Joyce <https://github.com/maddijoyce> // Kamil Wojcik <https://github.com/smifun> // Mohamed Shaaban <https://github.com/mshaaban088> +// Ethan Setnik <https://github.com/esetnik> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 import { diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 25f395884c..56d782eda7 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -26,9 +26,12 @@ import { SubmissionError, FieldArrayFieldsProps } from "redux-form"; + import { Field as ImmutableField, - reduxForm as immutableReduxForm + reduxForm as immutableReduxForm, + startSubmit as immutableStartSubmit, + stopSubmit as immutableStopSubmit } from "redux-form/immutable"; import LibField, { From 9784cd1cb4a12d96c40b3d529b72a34512d83f74 Mon Sep 17 00:00:00 2001 From: Ethan Setnik <esetnik@gmail.com> Date: Thu, 7 Feb 2019 14:06:16 -0500 Subject: [PATCH 180/200] increase version number --- types/redux-form/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 28047e8007..2a3281e62b 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-form 7.4 +// Type definitions for redux-form 8.1.0 // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full <https://github.com/carsonf> // Daniel Lytkin <https://github.com/aikoven> From ac1bb23ddc777b893867db10cf8049de08d8040c Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 11:12:18 -0800 Subject: [PATCH 181/200] Update based on feedback --- types/office-js-preview/index.d.ts | 4 ++-- types/office-js/index.d.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index bbed11cdea..be6822cf36 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of `AttachmentDetails` objects is returned as the attachments property of an appointment or message item. + * An array of **AttachmentDetails** objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -13702,7 +13702,7 @@ declare namespace Office { addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult<void>) => void): void; /** - * Gets an attachment from a message or appointment and returns it as an `AttachmentContent` object. + * Gets an attachment from a message or appointment and returns it as an **AttachmentContent** object. * * The `getAttachmentContentAsync` method gets the attachment with the specified identifier from the item. As a best practice, you should use * the identifier to retrieve an attachment in the same session that the attachmentIds were retrieved with the `getAttachmentsAsync` or diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 027a90d0c2..caafa47822 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of `AttachmentDetails` objects is returned as the attachments property of an appointment or message item. + * An array of **AttachmentDetails** objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -13702,7 +13702,7 @@ declare namespace Office { addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult<void>) => void): void; /** - * Gets an attachment from a message or appointment and returns it as an `AttachmentContent` object. + * Gets an attachment from a message or appointment and returns it as an **AttachmentContent** object. * * The `getAttachmentContentAsync` method gets the attachment with the specified identifier from the item. As a best practice, you should use * the identifier to retrieve an attachment in the same session that the attachmentIds were retrieved with the `getAttachmentsAsync` or From 633d80268241b453e17f6c704708b491895a9edd Mon Sep 17 00:00:00 2001 From: Ethan Setnik <esetnik@gmail.com> Date: Thu, 7 Feb 2019 14:25:13 -0500 Subject: [PATCH 182/200] fix header version --- types/redux-form/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 2a3281e62b..8997d682a8 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-form 8.1.0 +// Type definitions for redux-form 7.5 // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full <https://github.com/carsonf> // Daniel Lytkin <https://github.com/aikoven> From 924fed466198bc97a2d9a0eb2846dbe9d40a7ff8 Mon Sep 17 00:00:00 2001 From: Derek Finlinson <derek.finlinson@journeyteam.com> Date: Thu, 7 Feb 2019 15:59:25 -0700 Subject: [PATCH 183/200] Make imageOptions optional --- types/xrm/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/xrm/index.d.ts b/types/xrm/index.d.ts index 361e33bf92..61362fa208 100644 --- a/types/xrm/index.d.ts +++ b/types/xrm/index.d.ts @@ -4633,7 +4633,7 @@ declare namespace Xrm { * Invokes the device camera to capture an image. * @returns On success, returns Base64 encoded file */ - captureImage(imageOptions: Device.CaptureImageOptions): Async.PromiseLike<Device.CaptureFileResponse>; + captureImage(imageOptions?: Device.CaptureImageOptions): Async.PromiseLike<Device.CaptureFileResponse>; /** * Invokes the device camera to capture video. From 7a2e93fd89f9f179c9ba061fd1bd3d2ee4902ff6 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 7 Feb 2019 16:10:52 -0800 Subject: [PATCH 184/200] Revert "Merge pull request #32709 from MrBullfinsh/cordova-plugin-background-download-types" This reverts commit 401af3267f6c283b7ee95d89aad7ad99a2261d41, reversing changes made to 1d78804c81accd2557b287c4e451933d2190d4f4. --- ...ordova-plugin-background-download-tests.ts | 24 ------ .../index.d.ts | 86 ------------------- .../tsconfig.json | 24 ------ .../tslint.json | 3 - 4 files changed, 137 deletions(-) delete mode 100644 types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts delete mode 100644 types/cordova-plugin-background-download/index.d.ts delete mode 100644 types/cordova-plugin-background-download/tsconfig.json delete mode 100644 types/cordova-plugin-background-download/tslint.json diff --git a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts deleted file mode 100644 index e56d14ce04..0000000000 --- a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts +++ /dev/null @@ -1,24 +0,0 @@ - let fileName = "PointerEventsCordovaPlugin.wmv"; - let uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv"; - - // open target file for download - (window as any).requestFileSystem(1, 0, (fileSystem: any) => { - fileSystem.root.getFile(fileName, { create: true }, (targetFile: File) => { - // plugin callbacks to track operation execution status and progress - const onSuccess = () => { - console.log('Done'); - }; - const onError = (err: any) => { - console.log(err); - }; - const onProgress = (progress: BackgroundTransfer.Progress) => { - console.log((100 * progress.bytesReceived / progress.totalBytesToReceive) + '%'); - }; - - const downloader = new BackgroundTransfer.BackgroundDownloader(); - // Create a new download operation. - const download = downloader.createDownload(uriString, targetFile); - // Start the download and persist the promise to be able to cancel the download. - const downloadPromise = download.startAsync().then(onSuccess, onError, onProgress); - }); - }); diff --git a/types/cordova-plugin-background-download/index.d.ts b/types/cordova-plugin-background-download/index.d.ts deleted file mode 100644 index 815d20bf66..0000000000 --- a/types/cordova-plugin-background-download/index.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -// Type definitions for cordova-plugin-background-download 0.5 -// Project: https://github.com/sgrebnov/cordova-plugin-background-download -// Definitions by: Tobias Gimpel <https://github.com/mrbullfinsh> -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.2 - -/** - * Provides an advanced file transfer functionality that persists beyond app termination and - * runs in the background. Background transfer doesn't support concurrent downloads of the same uri. - */ -declare namespace BackgroundTransfer { - class BackgroundDownloader { - /** - * Initializes a new instance of BackgroundDownloader object. - * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. - * - * @param uriMatcher The regexp to compare location of the resources with already downloading ones. - */ - constructor(uriMatcher?: RegExp); - /** - * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. - * - * @param uri The location of the resource. - * @param resultFile The file that the response will be written to. - * @param notificationTitle The title for downloading in notification. - */ - createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; - } - - interface Progress { - bytesReceived: number; - totalBytesToReceive: number; - } - - /** - * Provides a mechanism for managing interactions with asynchronous APIs based on Promises. - * See 'Asynchronous programming in JavaScript' for more details - * http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx - * http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx - * Note. Functionality is limited, support of .then and .cancel methods only, other methods are in progress. - */ - interface Promise { - _completeCallbacks: Array<() => void>; - _errorCallbacks: Array<(error: any) => void>; - _progressCallbacks: Array<(progress: Progress) => void>; - _chainedDefer: Deferral; - _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; - result: any; - then(onComplete?: () => void, onError?: (error: any) => void, onProgress?: (progress: Progress) => void): Promise; - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and - * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx - * @param flag - */ - cancel(flag?: boolean): void; - executeCallback(callback: (() => void) | ((error: any) => void) | ((progress: Progress) => void), args: any): void; - } - - interface Deferral { - resolve(data: any): void; - reject(error: any): void; - notify(value: any): void; - bind(promise: Promise): void; - } -} - -declare class DownloadOperation { - /** - * Performs an asynchronous download operation in the background. - * - * @param uri The location of the resource. - * @param resultFile The file that the response will be written to. - * @param uriMatcher The regexp to compare location of the resources with already downloading ones. - * @param notificationTitle The title for downloading in notification. - */ - constructor(uri: string, resultFile: File, uriMatcher?: RegExp, notificationTitle?: string); - /** - * Starts an asynchronous download operation. - */ - startAsync(): BackgroundTransfer.Promise; - /** - * Stops a download operation. - */ - stop(): void; -} diff --git a/types/cordova-plugin-background-download/tsconfig.json b/types/cordova-plugin-background-download/tsconfig.json deleted file mode 100644 index 830f1483ca..0000000000 --- a/types/cordova-plugin-background-download/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "cordova-plugin-background-download-tests.ts" - ] -} \ No newline at end of file diff --git a/types/cordova-plugin-background-download/tslint.json b/types/cordova-plugin-background-download/tslint.json deleted file mode 100644 index e60c15844f..0000000000 --- a/types/cordova-plugin-background-download/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "dtslint/dt.json" -} \ No newline at end of file From b737dc1ea56951ca7d06907c6a2433f0bebe6f36 Mon Sep 17 00:00:00 2001 From: Julian Gonggrijp <dev@juliangonggrijp.com> Date: Fri, 8 Feb 2019 01:16:51 +0100 Subject: [PATCH 185/200] Update backbone-relational to version 0.10.0 --- .../backbone-relational-tests.ts | 14 ++-- types/backbone-relational/index.d.ts | 71 ++++++++++--------- 2 files changed, 43 insertions(+), 42 deletions(-) diff --git a/types/backbone-relational/backbone-relational-tests.ts b/types/backbone-relational/backbone-relational-tests.ts index 6e0135fcd9..c8b94c4029 100644 --- a/types/backbone-relational/backbone-relational-tests.ts +++ b/types/backbone-relational/backbone-relational-tests.ts @@ -1,13 +1,13 @@ -import * as Backbone from 'backbone'; +import * as BackboneRel from 'backbone-relational'; -class House extends Backbone.RelationalModel { +class House extends BackboneRel.Model { // The 'relations' property, on the House's prototype. Initialized separately for each // instance of House. Each relation must define (as a minimum) the 'type', 'key' and // 'relatedModel'. Options include 'includeInJSON', 'createModels' and 'reverseRelation'. relations = [ { - type: Backbone.HasMany, // Use the type, or the string 'HasOne' or 'HasMany'. + type: BackboneRel.HasMany, // Use the type, or the string 'HasOne' or 'HasMany'. key: 'occupants', relatedModel: 'Person', includeInJSON: true, @@ -20,14 +20,14 @@ class House extends Backbone.RelationalModel { } -class Person extends Backbone.RelationalModel { +class Person extends BackboneRel.Model { relations = [ { // Create a (recursive) one-to-one relationship - type: Backbone.HasOne, + type: BackboneRel.HasOne, key: 'user', relatedModel: 'User', reverseRelation: { - type: Backbone.HasOne, + type: BackboneRel.HasOne, key: 'person' } } @@ -39,7 +39,7 @@ class Person extends Backbone.RelationalModel { } } -class User extends Backbone.RelationalModel { +class User extends BackboneRel.Model { } diff --git a/types/backbone-relational/index.d.ts b/types/backbone-relational/index.d.ts index 84406fb60a..f19cfa8daa 100644 --- a/types/backbone-relational/index.d.ts +++ b/types/backbone-relational/index.d.ts @@ -1,15 +1,16 @@ -// Type definitions for Backbone-relational 0.8.5 +// Type definitions for Backbone-relational 0.10.0 // Project: http://backbonerelational.org/ // Definitions by: Eirik Hoem <https://github.com/eirikhm> +// Julian Gonggrijp <https://github.com/jgonggrijp> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="jquery" /> -import * as Backbone from 'backbone'; +import { Events, EventsHash, Model as BModel, Collection } from 'backbone'; -declare module 'backbone' { - class RelationalModel extends Model { +declare module 'backbone-relational' { + class Model extends BModel { /** * Do not use, prefer TypeScript's extend functionality. **/ @@ -47,7 +48,7 @@ declare module 'backbone' { static findOrCreate(attributes:any, options?:any); } - export class Relation extends Model { + export class Relation extends BModel { options:any; instance:any; @@ -60,11 +61,11 @@ declare module 'backbone' { checkPreconditions():boolean; - setRelated(related:Model):void; + setRelated(related:BModel):void; - setRelated(related:Collection<Model>):void; + setRelated(related:Collection<BModel>):void; - getReverseRelations(model:RelationalModel):Relation; + getReverseRelations(model:Model):Relation; destroy():void; } @@ -72,7 +73,7 @@ declare module 'backbone' { export class HasOne extends Relation { collectionType:any; - findRelated(options:any):Model; + findRelated(options:any):BModel; setKeyContents(keyContents:string):void; @@ -82,21 +83,21 @@ declare module 'backbone' { setKeyContents(keyContents:number[]):void; - setKeyContents(keyContents:Collection<Model>):void; + setKeyContents(keyContents:Collection<BModel>):void; - onChange(model:Model, attr:any, options:any):void; + onChange(model:BModel, attr:any, options:any):void; - handleAddition(model:Model, coll:Collection<Model>, options:any):void; + handleAddition(model:BModel, coll:Collection<BModel>, options:any):void; - handleRemoval(model:Model, coll:Collection<Model>, options:any):void; + handleRemoval(model:BModel, coll:Collection<BModel>, options:any):void; - handleReset(coll:Collection<Model>, options:any):void; + handleReset(coll:Collection<BModel>, options:any):void; - tryAddRelated(model:Model, coll:any, options:any):void; + tryAddRelated(model:BModel, coll:any, options:any):void; - addRelated(model:Model, options:any):void; + addRelated(model:BModel, options:any):void; - removeRelated(model:Model, coll:any, options:any):void; + removeRelated(model:BModel, coll:any, options:any):void; } @@ -104,21 +105,21 @@ declare module 'backbone' { export class HasMany extends Relation { collectionType:any; - findRelated(options:any):Model; + findRelated(options:any):BModel; setKeyContents(keyContents:string):void; setKeyContents(keyContents:number):void; - setKeyContents(keyContents:Model):void; + setKeyContents(keyContents:BModel):void; - onChange(model:Model, attr:any, options:any):void; + onChange(model:BModel, attr:any, options:any):void; - tryAddRelated(model:Model, coll:any, options:any):void; + tryAddRelated(model:BModel, coll:any, options:any):void; - addRelated(model:Model, options:any):void; + addRelated(model:BModel, options:any):void; - removeRelated(model:Model, coll:any, options:any):void; + removeRelated(model:BModel, coll:any, options:any):void; } @@ -141,9 +142,9 @@ declare module 'backbone' { removeModelScope(scope):void; - addSubModels(subModelTypes:RelationalModel, superModelType:RelationalModel):void; + addSubModels(subModelTypes:Model, superModelType:Model):void; - setupSuperModel(modelType:RelationalModel):void; + setupSuperModel(modelType:Model):void; addReverseRelation(relation:any):void; @@ -151,30 +152,30 @@ declare module 'backbone' { processOrphanRelations():void; - retroFitRelation(relation:RelationalModel, create:boolean):Collection<Model>; + retroFitRelation(relation:Model, create:boolean):Collection<BModel>; - getCollection(type:RelationalModel, create:boolean):Collection<Model>; + getCollection(type:Model, create:boolean):Collection<BModel>; getObjectByName(name:string):any; resolveIdForItem(type:any, item:any):any; - static find(type:any, item:string):RelationalModel; + static find(type:any, item:string):Model; - static find(type:any, item:number):RelationalModel; + static find(type:any, item:number):Model; - static find(type:any, item:RelationalModel):RelationalModel; + static find(type:any, item:Model):Model; - static find(type:any, item:any):RelationalModel; + static find(type:any, item:any):Model; - register(model:RelationalModel):void; + register(model:Model):void; - checkId(model:RelationalModel, id:any):void; + checkId(model:Model, id:any):void; - update(model:RelationalModel):void; + update(model:Model):void; - unregister(model:RelationalModel, collection:Collection<Model>, options:any):void; + unregister(model:Model, collection:Collection<BModel>, options:any):void; reset():void; From 96347030c1873408d32adf9a8c80cfb53681a026 Mon Sep 17 00:00:00 2001 From: David Edmondson <threehams@gmail.com> Date: Thu, 7 Feb 2019 21:34:26 -0800 Subject: [PATCH 186/200] Add missing justifyItems definition. --- types/styled-system/index.d.ts | 4 +++- types/styled-system/styled-system-tests.tsx | 10 +++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index 19b9afcd5f..028ced7314 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for styled-system 3.2 +// Type definitions for styled-system 3.2.1 // Project: https://github.com/jxnblk/styled-system#readme // Definitions by: Marshall Bowers <https://github.com/maxdeviant> // Ben McCormick <https://github.com/phobon> @@ -421,6 +421,8 @@ export interface JustifyItemsProps { justifyItems?: ResponsiveValue<CSS.JustifyItemsProperty>; } +export function justifyItems(...args: any[]): any; + export interface JustifyContentProps { /** * The CSS justify-content property defines how the browser distributes space between and around content items diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index 397e1b0402..bfedc38182 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -43,6 +43,8 @@ import { alignContent, justifyContent, JustifyContentProps, + justifyItems, + JustifyItemsProps, FlexWrapProps, flexWrap, flexBasis, @@ -273,7 +275,8 @@ interface GridComponentProps GridAutoColumnsProps, GridAutoRowsProps, GridTemplatesRowsProps, - GridTemplatesColumnsProps {} + GridTemplatesColumnsProps, + JustifyItemsProps {} const Grid: React.ComponentType<GridComponentProps> = styled` ${gridGap}; ${gridRowGap}; @@ -285,6 +288,7 @@ const Grid: React.ComponentType<GridComponentProps> = styled` ${gridAutoColumns}; ${gridTemplateRows}; ${gridTemplateColumns}; + ${justifyItems}; `; interface ButtonProps @@ -467,6 +471,10 @@ const test = () => ( <Grid gridTemplateColumns="auto" /> <Grid gridTemplateColumns={["auto", "1fr"]} /> <Grid gridTemplateColumns={{ sm: "auto", md: "1fr" }} /> + // justifyItems + <Grid justifyItems="baseline" /> + <Grid justifyItems={["baseline", "center"]} /> + <Grid justifyItems={{ sm: "baseline", md: "center" }} /> // flex (responsive) <Box flex="1 1 auto" /> <Box flex={["1 1 auto"]} /> From 247a03b2198d698e7283095f951aebf549705668 Mon Sep 17 00:00:00 2001 From: David Edmondson <threehams@gmail.com> Date: Thu, 7 Feb 2019 22:32:38 -0800 Subject: [PATCH 187/200] Remove patch version --- types/styled-system/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index 028ced7314..788e8c305f 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for styled-system 3.2.1 +// Type definitions for styled-system 3.2 // Project: https://github.com/jxnblk/styled-system#readme // Definitions by: Marshall Bowers <https://github.com/maxdeviant> // Ben McCormick <https://github.com/phobon> From f6036e83cf9b93ae5e7c890440a2021b1f80ffe9 Mon Sep 17 00:00:00 2001 From: David Edmondson <threehams@gmail.com> Date: Thu, 7 Feb 2019 23:10:35 -0800 Subject: [PATCH 188/200] Organize justifyItems with Flex --- types/styled-system/styled-system-tests.tsx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index bfedc38182..ce7b8d24ff 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -255,7 +255,8 @@ interface FlexComponentProps JustifyContentProps, FlexWrapProps, FlexBasisProps, - FlexDirectionProps {} + FlexDirectionProps, + JustifyItemsProps {} const Flex: React.ComponentType<FlexComponentProps> = styled` ${alignItems}; ${alignContent}; @@ -263,6 +264,7 @@ const Flex: React.ComponentType<FlexComponentProps> = styled` ${flexWrap}; ${flexBasis}; ${flexDirection}; + ${justifyItems}; `; interface GridComponentProps @@ -275,8 +277,7 @@ interface GridComponentProps GridAutoColumnsProps, GridAutoRowsProps, GridTemplatesRowsProps, - GridTemplatesColumnsProps, - JustifyItemsProps {} + GridTemplatesColumnsProps{} const Grid: React.ComponentType<GridComponentProps> = styled` ${gridGap}; ${gridRowGap}; @@ -288,7 +289,6 @@ const Grid: React.ComponentType<GridComponentProps> = styled` ${gridAutoColumns}; ${gridTemplateRows}; ${gridTemplateColumns}; - ${justifyItems}; `; interface ButtonProps @@ -431,6 +431,10 @@ const test = () => ( <Flex flexDirection="column" /> <Flex flexDirection={["column"]} /> <Flex flexDirection={{ sm: "column" }} /> + // justifyItems + <Flex justifyItems="baseline" /> + <Flex justifyItems={["baseline", "center"]} /> + <Flex justifyItems={{ sm: "baseline", md: "center" }} /> // gridGap <Grid gridGap="1px" /> <Grid gridGap={["1", "2"]} /> @@ -471,10 +475,6 @@ const test = () => ( <Grid gridTemplateColumns="auto" /> <Grid gridTemplateColumns={["auto", "1fr"]} /> <Grid gridTemplateColumns={{ sm: "auto", md: "1fr" }} /> - // justifyItems - <Grid justifyItems="baseline" /> - <Grid justifyItems={["baseline", "center"]} /> - <Grid justifyItems={{ sm: "baseline", md: "center" }} /> // flex (responsive) <Box flex="1 1 auto" /> <Box flex={["1 1 auto"]} /> From 7293f118b733961c970b251ac1cdd193364d1fa6 Mon Sep 17 00:00:00 2001 From: Takuma Suzuki <pferd262@gmail.com> Date: Fri, 8 Feb 2019 17:08:34 +0900 Subject: [PATCH 189/200] Fix args type for Interval.toDuration() --- types/luxon/index.d.ts | 4 ++-- types/luxon/luxon-tests.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index b5f1134fb5..95a06b1d6a 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 1.10 +// Type definitions for luxon 1.11.1 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart <https://github.com/colbydehart> // Hyeonseok Yang <https://github.com/FourwingsY> @@ -436,7 +436,7 @@ export class Interval { splitAt(...dateTimes: DateTime[]): Interval[]; splitBy(duration: Duration | DurationObject | number): Interval[]; toDuration( - unit: DurationUnit | DurationUnit[], + unit?: DurationUnit | DurationUnit[], options?: DiffOptions ): Duration; toFormat( diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index df5481094b..59566c35c3 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -144,6 +144,7 @@ i.mapEndpoints((d) => d); // $ExpectType Interval i.toISO(); // $ExpectType string i.toString(); // $ExpectType string i.toDuration('months'); // $ExpectType Duration +i.toDuration(); // $ExpectType Duration if (Interval.isInterval(anything)) { anything; // $ExpectType Interval From 3d34d9651e1771050f2fec7ef44230286f8787e3 Mon Sep 17 00:00:00 2001 From: Jannik Keye <jannik.keye@gmail.com> Date: Fri, 8 Feb 2019 09:28:03 +0100 Subject: [PATCH 190/200] fix: set fastify-cors typings not needed --- notNeededPackages.json | 6 ++ types/fastify-cors/fastify-cors-tests.ts | 89 ------------------------ types/fastify-cors/index.d.ts | 68 ------------------ types/fastify-cors/tsconfig.json | 23 ------ types/fastify-cors/tslint.json | 1 - 5 files changed, 6 insertions(+), 181 deletions(-) delete mode 100644 types/fastify-cors/fastify-cors-tests.ts delete mode 100644 types/fastify-cors/index.d.ts delete mode 100644 types/fastify-cors/tsconfig.json delete mode 100644 types/fastify-cors/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index db3d6b10d2..e3483b3c4b 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -564,6 +564,12 @@ "sourceRepoURL": "https://www.npmjs.com/package/fast-simplex-noise", "asOfVersion": "3.0.0" }, + { + "libraryName": "fastify-cors", + "typingsPackageName": "fastify-cors", + "sourceRepoURL": "https://github.com/fastify/fastify-cors", + "asOfVersion": "2.1.0" + }, { "libraryName": "Fastify-JWT", "typingsPackageName": "fastify-jwt", diff --git a/types/fastify-cors/fastify-cors-tests.ts b/types/fastify-cors/fastify-cors-tests.ts deleted file mode 100644 index 5fcd7e20d4..0000000000 --- a/types/fastify-cors/fastify-cors-tests.ts +++ /dev/null @@ -1,89 +0,0 @@ -import fastifyCors = require("fastify-cors"); - -fastifyCors(); - -const fastifyCorsOptions: fastifyCors.FastifyCorsOptions = { - origin: true, - allowedHeaders: "authorization,content-type", - methods: "GET,POST,PUT,PATCH,DELETE,OPTIONS", - credentials: true, - exposedHeaders: "authorization", - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const fastifyCorsOptionsArray: fastifyCors.FastifyCorsOptions = { - origin: true, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originString: fastifyCors.FastifyCorsOptions = { - origin: "*", - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originRegexp: fastifyCors.FastifyCorsOptions = { - origin: /\*/, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originStringArray: fastifyCors.FastifyCorsOptions = { - origin: ["*", "something"], - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originRegexpArray: fastifyCors.FastifyCorsOptions = { - origin: [/\*/, /something/], - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originCallback: fastifyCors.FastifyCorsOptions = { - origin: (err: Error, allow: boolean) => { - throw err; - }, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; diff --git a/types/fastify-cors/index.d.ts b/types/fastify-cors/index.d.ts deleted file mode 100644 index 907689a72c..0000000000 --- a/types/fastify-cors/index.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -// Type definitions for fastify-cors 0.1 -// Project: https://github.com/fastify/fastify-cors#readme -// Definitions by: Jannik Keye <https://github.com/jannikkeye> -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -type originCallback = (err: Error, allow: boolean) => void; - -/** - * fastify-cors enables the use of CORS in a Fastify application. - */ -declare function fastifyCors(): void; - -declare namespace fastifyCors { - /** - * Options for configuring the fastify-cors plugin. - */ - interface FastifyCorsOptions { - /** - * Configures the Access-Control-Allow-Origin CORS header. - */ - origin?: string | boolean | RegExp | string[] | RegExp[] | originCallback; - /** - * Configures the Access-Control-Allow-Credentials CORS header. - * Set to true to pass the header, otherwise it is omitted. - */ - credentials?: boolean; - /** - * Configures the Access-Control-Expose-Headers CORS header. - * Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') - * or an array (ex: ['Content-Range', 'X-Content-Range']). - * If not specified, no custom headers are exposed. - */ - exposedHeaders?: string | string[]; - /** - * Configures the Access-Control-Allow-Headers CORS header. - * Expects a comma-delimited string (ex: 'Content-Type,Authorization') - * or an array (ex: ['Content-Type', 'Authorization']). If not - * specified, defaults to reflecting the headers specified in the - * request's Access-Control-Request-Headers header. - */ - allowedHeaders?: string | string[]; - /** - * Configures the Access-Control-Allow-Methods CORS header. - * Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']). - */ - methods?: string | string[]; - /** - * Configures the Access-Control-Max-Age CORS header. - * Set to an integer to pass the header, otherwise it is omitted. - */ - maxAge?: number; - /** - * Pass the CORS preflight response to the route handler (default: false). - */ - preflightContinue?: boolean; - /** - * Provides a status code to use for successful OPTIONS requests, - * since some legacy browsers (IE11, various SmartTVs) choke on 204. - */ - optionsSuccessStatus?: number; - /** - * Pass the CORS preflight response to the route handler (default: false). - */ - preflight?: boolean; - } -} - -export = fastifyCors; diff --git a/types/fastify-cors/tsconfig.json b/types/fastify-cors/tsconfig.json deleted file mode 100644 index 9e696b42e2..0000000000 --- a/types/fastify-cors/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "fastify-cors-tests.ts" - ] -} diff --git a/types/fastify-cors/tslint.json b/types/fastify-cors/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/fastify-cors/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } From 3caae783fe15d11a4ac24faba39d1ede9e4a7e92 Mon Sep 17 00:00:00 2001 From: Takuma Suzuki <pferd262@gmail.com> Date: Fri, 8 Feb 2019 18:35:16 +0900 Subject: [PATCH 191/200] fixup! Fix args type for Interval.toDuration() --- types/luxon/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 95a06b1d6a..eebf89497d 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 1.11.1 +// Type definitions for luxon 1.11 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart <https://github.com/colbydehart> // Hyeonseok Yang <https://github.com/FourwingsY> From 963e5d627569ae521f808f6670fbafa2e0169cd4 Mon Sep 17 00:00:00 2001 From: Gerardo Pacheco <gerardo@lingokids.com> Date: Fri, 8 Feb 2019 10:46:37 +0100 Subject: [PATCH 192/200] react-native-tab-view added prop --- types/react-native-tab-view/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-native-tab-view/index.d.ts b/types/react-native-tab-view/index.d.ts index 078247e97d..8118239f8a 100644 --- a/types/react-native-tab-view/index.d.ts +++ b/types/react-native-tab-view/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Kalle Ott <https://github.com/kaoDev> // Kyle Roach <https://github.com/iRoachie> // Tim Wang <https://github.com/timwangdev> +// Gerardo Pacheco <https://github.com/geriux> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { PureComponent, ReactNode, ComponentType } from 'react' @@ -214,6 +215,7 @@ export type TabBarProps<T extends RouteBase = RouteBase> = SceneRendererProps< indicatorStyle?: StyleProp<ViewStyle> labelStyle?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle> + useNativeDriver?: boolean; } export class TabBar<T extends Route = Route> extends PureComponent<TabBarProps<T>> {} From 099ad3f2cb00505ae4c2556e80b8a08ca3aec343 Mon Sep 17 00:00:00 2001 From: Malthe Borch <mborch@gmail.com> Date: Fri, 8 Feb 2019 11:45:36 +0100 Subject: [PATCH 193/200] Add missing flag 'testOnReturn' --- types/generic-pool/generic-pool-tests.ts | 1 + types/generic-pool/index.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 4b8a69aa93..3ddc8477a6 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -29,6 +29,7 @@ const opts = { min: 2, maxWaitingClients: 2, testOnBorrow: true, + testOnReturn: true, acquireTimeoutMillis: 100, fifo: true, priorityRange: 5, diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index 0fd1f58b4b..0bb0bffe2d 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -38,6 +38,7 @@ export interface Options { min?: number; maxWaitingClients?: number; testOnBorrow?: boolean; + testOnReturn?: boolean; acquireTimeoutMillis?: number; fifo?: boolean; priorityRange?: number; From 7b7942707a5eb75f30e85d628b2cca0184de2d15 Mon Sep 17 00:00:00 2001 From: Dominique Rau <domi.github@gmail.com> Date: Fri, 8 Feb 2019 12:44:19 +0100 Subject: [PATCH 194/200] feat(react-native-document-picker): add more utils types --- types/react-native-document-picker/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-native-document-picker/index.d.ts b/types/react-native-document-picker/index.d.ts index 986da6e611..77b91e81bc 100644 --- a/types/react-native-document-picker/index.d.ts +++ b/types/react-native-document-picker/index.d.ts @@ -12,6 +12,8 @@ export const DocumentPickerUtil: { pdf(): string; audio(): string; plainText(): string; + video(): string; + images(): string; }; export interface Options { From 8a6fa48e294ebae36cfd3273c69047f21907bb63 Mon Sep 17 00:00:00 2001 From: Alan Ray <rayalan@users.noreply.github.com> Date: Thu, 31 Jan 2019 19:21:12 -0500 Subject: [PATCH 195/200] stripe: Update cancel subscription options as of 2018-11-08 --- types/stripe/index.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 068755e157..366d2407b2 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -4870,6 +4870,18 @@ declare namespace Stripe { interface ISubscriptionCancellationOptions extends IDataOptions { /** + * Will generate a final invoice that invoices for any un-invoiced metered usage and new/pending proration invoice items. + */ + invoice_now?: boolean; + + /** + * Will generate a proration invoice item that credits remaining unused time until the subscription period end. + */ + prorate?: boolean; + + /** + * @deprecated Use subscription update with cancel_at_period_end option as of 2018-08-23. + * * A flag that if set to true will delay the cancellation of the subscription until the end of the current period. */ at_period_end?: boolean; From 276c76e22e721514cce2e7136f42fd19b1fd33c3 Mon Sep 17 00:00:00 2001 From: Nico Jansen <nico.jansen@infosupport.com> Date: Fri, 8 Feb 2019 10:24:17 +0100 Subject: [PATCH 196/200] Prettier: Add parser babel and babel-flow --- types/prettier/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index 6cef2ef27a..22f82096a8 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for prettier 1.15 +// Type definitions for prettier 1.16 // Project: https://github.com/prettier/prettier // Definitions by: Ika <https://github.com/ikatyang> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,9 @@ export interface FastPath<T = any> { export type BuiltInParser = (text: string, options?: any) => AST; export type BuiltInParserName = - | 'babylon' + | 'babylon' // deprecated + | 'babel' + | 'babel-flow' | 'flow' | 'typescript' | 'postcss' // deprecated From cd27a249062075086a95d2d14fcaf9eaa5cf3377 Mon Sep 17 00:00:00 2001 From: Rusty Scrivens <34690530+rscrivens@users.noreply.github.com> Date: Fri, 8 Feb 2019 10:01:26 -0800 Subject: [PATCH 197/200] Update to latest sarif version 2.0.0-csd.2.beta-2019-01-09 --- types/sarif/index.d.ts | 308 ++++++++++++++++++++++++++++++----------- 1 file changed, 229 insertions(+), 79 deletions(-) diff --git a/types/sarif/index.d.ts b/types/sarif/index.d.ts index 4bece2d3f8..2a4e57fe25 100644 --- a/types/sarif/index.d.ts +++ b/types/sarif/index.d.ts @@ -5,8 +5,8 @@ // TypeScript Version: 2.4 /** - * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2018-10-10 JSON Schema: - * a standard format for the output of static analysis tools. + * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2019-01-09 JSON Schema: a standard format for the + * output of static analysis tools. */ export interface Log { /** @@ -23,11 +23,16 @@ export interface Log { * The set of runs contained in this log file. */ runs: Run[]; + + /** + * Key/value pairs that provide additional information about the log file. + */ + properties?: PropertyBag; } export namespace Log { type version = - "2.0.0-csd.2.beta.2018-10-10"; + "2.0.0-csd.2.beta.2019-01-09"; } /** @@ -53,6 +58,11 @@ export interface Attachment { * An array of regions of interest within the attachment. */ regions?: Region[]; + + /** + * Key/value pairs that provide additional information about the attachment. + */ + properties?: PropertyBag; } /** @@ -188,57 +198,81 @@ export interface Exception { stack?: Stack; /** - * Key/value pairs that provide additional information about the exception + * Key/value pairs that provide additional information about the exception. */ properties?: PropertyBag; } /** - * References to external files that should be inlined with the content of a root log file. + * TBD */ -export interface ExternalFiles { +export interface ExternalPropertyFile { /** - * The location of a file containing a run.conversion object to be merged with the root log file. + * The location of the external property file. */ - conversion?: FileLocation; + fileLocation?: FileLocation; /** - * The location of a file containing a run.files object to be merged with the root log file. + * A stable, unique identifer for the external property file in the form of a GUID. */ - files?: FileLocation; + instanceGuid?: string; /** - * The location of a file containing a run.graphs object to be merged with the root log file. + * A non-negative integer specifying the number of items contained in the external property file. */ - graphs?: FileLocation; + itemCount?: number; /** - * An array of locations of files containing arrays of run.invocation objects to be merged with the root log - * file. - */ - invocations?: FileLocation[]; - - /** - * The location of a file containing a run.logicalLocations object to be merged with the root log file. - */ - logicalLocations?: FileLocation; - - /** - * The location of a file containing a run.resources object to be merged with the root log file. - */ - resources?: FileLocation; - - /** - * An array of locations of files containins arrays of run.result objects to be merged with the root log file. - */ - results?: FileLocation[]; - - /** - * Key/value pairs that provide additional information about the external files + * Key/value pairs that provide additional information about the external property file. */ properties?: PropertyBag; } +/** + * References to external property files that should be inlined with the content of a root log file. + */ +export interface ExternalPropertyFiles { + /** + * An external property file containing a run.conversion object to be merged with the root log file. + */ + conversion?: ExternalPropertyFile; + + /** + * An array of external property files containing run.files arrays to be merged with the root log file. + */ + files?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.graphs object to be merged with the root log file. + */ + graphs?: ExternalPropertyFile; + + /** + * An array of external property files containing run.invocations arrays to be merged with the root log file. + */ + invocations?: ExternalPropertyFile[]; + + /** + * An array of external property files containing run.logicalLocations arrays to be merged with the root log file. + */ + logicalLocations?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.resources object to be merged with the root log file. + */ + resources?: ExternalPropertyFile; + + /** + * An array of external property files containing run.results arrays to be merged with the root log file. + */ + results?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.properties object to be merged with the root log file. + */ + properties?: ExternalPropertyFile; +} + /** * A single file. In some cases, this file might be nested within another file. */ @@ -286,15 +320,20 @@ export interface File { offset?: number; /** - * Identifies the key of the immediate parent of the file, if this file is nested. + * Identifies the index of the immediate parent of the file, if this file is nested. */ - parentKey?: string; + parentIndex?: number; /** * The role or roles played by the file in the analysis. */ roles?: File.roles[]; + /** + * Specifies the source language for any file object that refers to a text file that contains source code. + */ + sourceLanguage?: string; + /** * Key/value pairs that provide additional information about the file. */ @@ -362,6 +401,11 @@ export interface FileContent { * Specifies the location of a file. */ export interface FileLocation { + /** + * The index within the run files array of the file object associated with the file location. + */ + fileIndex?: number; + /** * A string containing a valid relative or absolute URI. */ @@ -413,7 +457,7 @@ export interface Graph { /** * An array of edge objects representing the edges of the graph. */ - edges: Edge[]; + edges?: Edge[]; /** * A string that uniquely identifies the graph within a run.graphs or result.graphs array. @@ -423,7 +467,7 @@ export interface Graph { /** * An array of node objects representing the nodes of the graph. */ - nodes: Node[]; + nodes?: Node[]; /** * Key/value pairs that provide additional information about the graph. @@ -443,7 +487,7 @@ export interface GraphTraversal { /** * The sequences of edges traversed by this graph traversal. */ - edgeTraversals: EdgeTraversal[]; + edgeTraversals?: EdgeTraversal[]; /** * A string that uniquely identifies that graph being traversed. @@ -611,6 +655,11 @@ export interface Location { */ fullyQualifiedLogicalName?: string; + /** + * The index within the logical locations array of the logical location associated with the result. + */ + logicalLocationIndex?: number; + /** * A message relevant to the location. */ @@ -643,9 +692,9 @@ export interface LogicalLocation { fullyQualifiedName?: string; /** - * The type of construct this logicalLocationComponent refers to. Should be one of 'function', 'member', - * 'module', 'namespace', 'package', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of - * those accurately describe the construct. + * The type of construct this logical location component refers to. Should be one of 'function', 'member', + * 'module', 'namespace', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of those + * accurately describe the construct. */ kind?: string; @@ -656,10 +705,10 @@ export interface LogicalLocation { name?: string; /** - * Identifies the key of the immediate parent of the construct in which the result was detected. For example, + * Identifies the index of the immediate parent of the construct in which the result was detected. For example, * this property might point to a logical location that represents the namespace that holds a type. */ - parentKey?: string; + parentIndex?: number; /** * Key/value pairs that provide additional information about the logical location. @@ -763,11 +812,15 @@ export interface Notification { physicalLocation?: PhysicalLocation; /** - * The stable, unique identifier of the rule (if any) to which this notification is relevant. This member can be - * used to retrieve rule metadata from the rules dictionary, if it exists. + * The stable, unique identifier of the rule, if any, to which this notification is relevant. */ ruleId?: string; + /** + * The index within the run resources array of the rule object, if any, associated with this notification. + */ + ruleIndex?: number; + /** * The thread identifier of the code that generated the notification. */ @@ -917,6 +970,11 @@ export interface Region { */ snippet?: FileContent; + /** + * Specifies the source language, if any, of the portion of the file specified by the region object. + */ + sourceLanguage?: string; + /** * The column number of the first character in the region. */ @@ -963,10 +1021,14 @@ export interface Resources { messageStrings?: { [key: string]: string }; /** - * A dictionary, each of whose keys is a string and each of whose values is a 'rule' object, that describe all - * rules associated with an analysis tool or a specific run of an analysis tool. + * An array of rule objects relevant to the run. */ - rules?: { [key: string]: Rule }; + rules?: Rule[]; + + /** + * Key/value pairs that provide additional information about the resources. + */ + properties?: PropertyBag; } /** @@ -994,12 +1056,6 @@ export interface Result { */ codeFlows?: CodeFlow[]; - /** - * An array of physicalLocation objects which specify the portions of an analysis tool's output that a converter - * transformed into the result object. - */ - conversionProvenance?: PhysicalLocation[]; - /** * A stable, unique identifier for the equivalence class of logically identical results to which this result * belongs, in the form of a GUID. @@ -1027,6 +1083,11 @@ export interface Result { */ graphTraversals?: GraphTraversal[]; + /** + * An absolute URI at which the result can be viewed. + */ + hostedViewerUri?: string; + /** * A stable, unique identifer for the result in the form of a GUID. */ @@ -1038,7 +1099,7 @@ export interface Result { level?: Result.level; /** - * One or more locations where the result occurred. Specify only one location unless the problem indicated by + * The set of locations where the result was detected. Specify only one location unless the problem indicated by * the result can only be corrected by making a change at every specified location. */ locations?: Location[]; @@ -1047,7 +1108,7 @@ export interface Result { * A message that describes the result. The first sentence of the message only will be displayed when visible * space is limited. */ - message?: Message; + message: Message; /** * A positive integer specifying the number of times this logically unique result was observed in this run. @@ -1059,17 +1120,32 @@ export interface Result { */ partialFingerprints?: { [key: string]: string }; + /** + * Information about how and when the result was detected. + */ + provenance?: ResultProvenance; + + /** + * A number representing the priority or importance of the result. + */ + rank?: number; + /** * A set of locations relevant to this result. */ relatedLocations?: Location[]; /** - * The stable, unique identifier of the rule (if any) to which this notification is relevant. This member can be + * The stable, unique identifier of the rule, if any, to which this notification is relevant. This member can be * used to retrieve rule metadata from the rules dictionary, if it exists. */ ruleId?: string; + /** + * The index within the run resources array of the rule object associated with this result. + */ + ruleIndex?: number; + /** * An array of 'stack' objects relevant to the result. */ @@ -1081,7 +1157,7 @@ export interface Result { suppressionStates?: Result.suppressionStates[]; /** - * The URIs of the work items associated with this result + * The URIs of the work items associated with this result. */ workItemUris?: string[]; @@ -1110,6 +1186,52 @@ export namespace Result { "absent"; } +/** + * Contains information about how and when a result was detected. + */ +export interface ResultProvenance { + /** + * An array of physicalLocation objects which specify the portions of an analysis tool's output that a + * converter transformed into the result. + */ + conversionSources?: PhysicalLocation[]; + + /** + * A GUID-valued string equal to the id.instanceGuid property of the run in which the result was first + * detected. + */ + firstDetectionRunInstanceGuid?: string; + + /** + * The Coordinated Universal Time (UTC) date and time at which the result was first detected. See "Date/time + * properties" in the SARIF spec for the required format. + */ + firstDetectionTimeUtc?: string; + + /** + * The index within the run.invocations array of the invocation object which describes the tool invocation that + * detected the result. + */ + invocationIndex?: number; + + /** + * A GUID-valued string equal to the id.instanceGuid property of the run in which the result was most recently + * detected. + */ + lastDetectionRunInstanceGuid?: string; + + /** + * The Coordinated Universal Time (UTC) date and time at which the result was most recently detected. See + * "Date/time properties" in the SARIF spec for the required format. + */ + lastDetectionTimeUtc?: string; + + /** + * Key/value pairs that provide additional information about the result. + */ + properties?: PropertyBag; +} + /** * Describes an analysis rule. */ @@ -1119,6 +1241,12 @@ export interface Rule { */ configuration?: RuleConfiguration; + /** + * An array of stable, opaque identifiers by which this rule was known in some previous version of the analysis + * tool. + */ + deprecatedIds?: string[]; + /** * A description of the rule. Should, as far as possible, provide details sufficient to enable resolution of any * problem indicated by the result. @@ -1176,10 +1304,15 @@ export interface Rule { */ export interface RuleConfiguration { /** - * Specifies the default severity level of the result. + * Specifies the default severity level for results generated by this rule. */ defaultLevel?: RuleConfiguration.defaultLevel; + /** + * Specifies the default priority or importance for results generated by this rule. + */ + defaultRank?: number; + /** * Specifies whether the rule will be evaluated during the scan. */ @@ -1200,8 +1333,7 @@ export namespace RuleConfiguration { type defaultLevel = "note" | "warning" | - "error" | - "open"; + "error"; } /** @@ -1213,11 +1345,6 @@ export interface Run { */ aggregateIds?: RunAutomationDetails[]; - /** - * The hardware architecture for which the run was targeted. - */ - architecture?: string; - /** * The 'instanceGuid' property of a previous SARIF 'run' that comprises the baseline that was used to compute * result 'baselineState' properties for the run. @@ -1241,9 +1368,20 @@ export interface Run { defaultFileEncoding?: string; /** - * A dictionary, each of whose keys is a URI and each of whose values is a file object. + * Specifies the default source language for any file object that refers to a text file that contains source + * code. */ - files?: { [key: string]: File }; + defaultSourceLanguage?: string; + + /** + * References to external property files that should be inlined with the content of a root log file. + */ + externalPropertyFiles?: ExternalPropertyFiles; + + /** + * An array of file objects relevant to the run. + */ + files?: File[]; /** * A dictionary, each of whose keys is the id of a graph and each of whose values is a 'graph' object with that @@ -1262,9 +1400,15 @@ export interface Run { invocations?: Invocation[]; /** - * A dictionary, each of whose keys specifies a logical location such as a namespace, type or function. + * An array of logical locations such as namespaces, types or functions. */ - logicalLocations?: { [key: string]: LogicalLocation }; + logicalLocations?: LogicalLocation[]; + + /** + * An ordered list of character sequences that were treated as line breaks when computing region information + * for the run. + */ + newlineSequences?: string[]; /** * The file location specified by each uriBaseId symbol on the machine where the tool originally ran. @@ -1472,7 +1616,7 @@ export interface ThreadFlowLocation { module?: string; /** - * An integer representing a containment hierarchy within the thread flow + * An integer representing a containment hierarchy within the thread flow. */ nestingLevel?: number; @@ -1505,17 +1649,17 @@ export namespace ThreadFlowLocation { * The analysis tool that was run. */ export interface Tool { + /** + * The binary version of the tool's primary executable file expressed as four non-negative integers separated + * by a period (for operating systems that express file versions in this way). + */ + dottedQuadFileVersion?: string; + /** * The absolute URI from which the tool can be downloaded. */ downloadUri?: string; - /** - * The binary version of the tool's primary executable file (for operating systems such as Windows that provide - * that information). - */ - fileVersion?: string; - /** * The name of the tool along with its version and any other useful identifying information, such as its locale. */ @@ -1555,7 +1699,7 @@ export interface Tool { } /** - * TBD + * Specifies the information necessary to retrieve a desired revision from a version control system. */ export interface VersionControlDetails { /** @@ -1569,6 +1713,12 @@ export interface VersionControlDetails { */ branch?: string; + /** + * The location in the local file system to which the root of the repository was mapped at the time of the + * analysis. + */ + mappedTo?: FileLocation; + /** * The absolute URI of the repository. */ From b65f9a5bfe1aa37d7366be3c71ebca087b6a6a8b Mon Sep 17 00:00:00 2001 From: Guketlev Dmitry <yavanosta@yandex.ru> Date: Fri, 8 Feb 2019 23:57:43 +0300 Subject: [PATCH 198/200] Add typings for color support --- types/color-support/color-support-tests.ts | 48 ++++++++++++++++++++++ types/color-support/index.d.ts | 34 +++++++++++++++ types/color-support/tsconfig.json | 23 +++++++++++ types/color-support/tslint.json | 1 + 4 files changed, 106 insertions(+) create mode 100644 types/color-support/color-support-tests.ts create mode 100644 types/color-support/index.d.ts create mode 100644 types/color-support/tsconfig.json create mode 100644 types/color-support/tslint.json diff --git a/types/color-support/color-support-tests.ts b/types/color-support/color-support-tests.ts new file mode 100644 index 0000000000..5c61067dcf --- /dev/null +++ b/types/color-support/color-support-tests.ts @@ -0,0 +1,48 @@ +import * as colorSupport from 'color-support'; + +(() => { + const result = colorSupport(); + if (!result) { + console.log('color is not supported'); + } else if (result.has16m) { + console.log('\x1b[38;2;102;194;255m16m colors\x1b[0m'); + } else if (result.has256) { + console.log('\x1b[38;5;119m256 colors\x1b[0m'); + } else if (result.hasBasic) { + console.log('\x1b[31mbasic colors\x1b[0m'); + } else { + console.log('Level: ', result.level); + console.log('this is impossible, but colors are not supported'); + } +})(); + +(() => { + const result = colorSupport({ + alwaysReturn: false, + env: process.env, + ignoreCI: true, + ignoreDumb: true, + ignoreTTY: true, + level: 2, + stream: process.stdout, + term: process.env.TERM, + }, { + has16m: false, + has256: false, + hasBasic: false, + level: 0, + }); + + if (!result) { + console.log('color is not supported'); + } else if (result.has16m) { + console.log('\x1b[38;2;102;194;255m16m colors\x1b[0m'); + } else if (result.has256) { + console.log('\x1b[38;5;119m256 colors\x1b[0m'); + } else if (result.hasBasic) { + console.log('\x1b[31mbasic colors\x1b[0m'); + } else { + console.log('Level: ', result.level); + console.log('this is impossible, but colors are not supported'); + } +})(); diff --git a/types/color-support/index.d.ts b/types/color-support/index.d.ts new file mode 100644 index 0000000000..290a6e29b0 --- /dev/null +++ b/types/color-support/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for color-support 1.1 +// Project: https://github.com/isaacs/color-support#readme +// Definitions by: Guketlev Dmitry <https://github.com/Yavanosta> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// <reference types="node" /> + +type ColorSupportLevel = 0 | 1 | 2 | 3; + +interface ColorSupportOptions { + alwaysReturn?: boolean; + env?: NodeJS.ProcessEnv; + ignoreCI?: boolean; + ignoreDumb?: boolean; + ignoreTTY?: boolean; + level?: ColorSupportLevel; + stream?: NodeJS.WriteStream; + term?: string; +} + +interface ColorSupportResult { + level: ColorSupportLevel; + hasBasic: boolean; + has256: boolean; + has16m: boolean; +} + +type ColorSupport = (options?: ColorSupportOptions, + obj?: ColorSupportResult) => false | ColorSupportResult; + +declare var colorSupport: ColorSupport; + +export = colorSupport; diff --git a/types/color-support/tsconfig.json b/types/color-support/tsconfig.json new file mode 100644 index 0000000000..f1e6de8e28 --- /dev/null +++ b/types/color-support/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-support-tests.ts" + ] +} diff --git a/types/color-support/tslint.json b/types/color-support/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-support/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 721a40407c920b55a3a9981262423dd383b13dbd Mon Sep 17 00:00:00 2001 From: Guketlev Dmitry <yavanosta@yandex.ru> Date: Sat, 9 Feb 2019 01:35:05 +0300 Subject: [PATCH 199/200] Review fixes --- types/color-support/color-support-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/color-support/color-support-tests.ts b/types/color-support/color-support-tests.ts index 5c61067dcf..45bb6317cf 100644 --- a/types/color-support/color-support-tests.ts +++ b/types/color-support/color-support-tests.ts @@ -1,4 +1,4 @@ -import * as colorSupport from 'color-support'; +import colorSupport = require('color-support'); (() => { const result = colorSupport(); From 66469de2630f121c4cba2de554deea2265f39836 Mon Sep 17 00:00:00 2001 From: David Edmondson <threehams@gmail.com> Date: Fri, 8 Feb 2019 19:25:08 -0800 Subject: [PATCH 200/200] Revert whitespace change --- types/styled-system/styled-system-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index ce7b8d24ff..1a008fa045 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -277,7 +277,7 @@ interface GridComponentProps GridAutoColumnsProps, GridAutoRowsProps, GridTemplatesRowsProps, - GridTemplatesColumnsProps{} + GridTemplatesColumnsProps {} const Grid: React.ComponentType<GridComponentProps> = styled` ${gridGap}; ${gridRowGap};