From 266710318846d12d5f6af5285c17d08e3c67abd4 Mon Sep 17 00:00:00 2001 From: rzymek Date: Sat, 25 Mar 2017 09:49:19 +0100 Subject: [PATCH 01/31] lodash - _.zipObjectDeep https://lodash.com/docs/4.17.4#zipObjectDeep The same signature as _.zipObject --- types/lodash.zipobjectdeep/index.d.ts | 8 ++ types/lodash.zipobjectdeep/tsconfig.json | 21 +++++ types/lodash.zipobjectdeep/tslint.json | 1 + types/lodash/index.d.ts | 102 ++++++++++++++++++++++- types/lodash/lodash-tests.ts | 22 +++++ types/lodash/zipObjectDeep/index.d.ts | 2 + 6 files changed, 153 insertions(+), 3 deletions(-) create mode 100644 types/lodash.zipobjectdeep/index.d.ts create mode 100644 types/lodash.zipobjectdeep/tsconfig.json create mode 100644 types/lodash.zipobjectdeep/tslint.json create mode 100644 types/lodash/zipObjectDeep/index.d.ts diff --git a/types/lodash.zipobjectdeep/index.d.ts b/types/lodash.zipobjectdeep/index.d.ts new file mode 100644 index 0000000000..1944588188 --- /dev/null +++ b/types/lodash.zipobjectdeep/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for lodash.zipObjectDeep 4.1 +// Project: http://lodash.com/ +// Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { zipObjectDeep } from "lodash"; +export = zipObjectDeep; diff --git a/types/lodash.zipobjectdeep/tsconfig.json b/types/lodash.zipobjectdeep/tsconfig.json new file mode 100644 index 0000000000..92ebbc6458 --- /dev/null +++ b/types/lodash.zipobjectdeep/tsconfig.json @@ -0,0 +1,21 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/types/lodash.zipobjectdeep/tslint.json b/types/lodash.zipobjectdeep/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/types/lodash.zipobjectdeep/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index 6326773899..170ce63aaf 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -5660,9 +5660,8 @@ declare namespace _ { //_.zipObject interface LoDashStatic { /** - * The inverse of _.pairs; this method returns an object composed from arrays of property names and values. - * Provide either a single two dimensional array, e.g. [[key1, value1], [key2, value2]] or two arrays, one of - * property names and one of corresponding values. + * This method is like _.fromPairs except that it accepts two arrays, one of property + * identifiers and one of corresponding values. * * @param props The property names. * @param values The property values. @@ -5672,6 +5671,17 @@ declare namespace _ { props: List|List>, values?: List ): TResult; + /** + * This method is like _.zipObject except that it supports property paths. + * + * @param props The property names. + * @param values The property values. + * @return Returns the new object. + */ + zipObjectDeep( + props: List|List>, + values?: List + ): TResult; /** * @see _.zipObject @@ -5680,6 +5690,13 @@ declare namespace _ { props: List|List>, values?: List ): TResult; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + props: List|List>, + values?: List + ): TResult; /** * @see _.zipObject @@ -5688,6 +5705,13 @@ declare namespace _ { props: List|List>, values?: List ): _.Dictionary; + /** + * @see _.zipObjectDeep + */ + zipObjectDepp( + props: List|List>, + values?: List + ): _.Dictionary; } interface LoDashImplicitArrayWrapper { @@ -5697,6 +5721,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashImplicitObjectWrapper; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashImplicitObjectWrapper; /** * @see _.zipObject @@ -5704,6 +5734,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashImplicitObjectWrapper; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashImplicitObjectWrapper; /** * @see _.zipObject @@ -5711,6 +5747,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashImplicitObjectWrapper<_.Dictionary>; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashImplicitObjectWrapper<_.Dictionary>; } interface LoDashImplicitObjectWrapper { @@ -5720,6 +5762,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashImplicitObjectWrapper; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashImplicitObjectWrapper; /** * @see _.zipObject @@ -5727,6 +5775,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashImplicitObjectWrapper; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashImplicitObjectWrapper; /** * @see _.zipObject @@ -5734,6 +5788,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashImplicitObjectWrapper<_.Dictionary>; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashImplicitObjectWrapper<_.Dictionary>; } interface LoDashExplicitArrayWrapper { @@ -5743,6 +5803,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashExplicitObjectWrapper; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashExplicitObjectWrapper; /** * @see _.zipObject @@ -5750,6 +5816,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashExplicitObjectWrapper; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashExplicitObjectWrapper; /** * @see _.zipObject @@ -5757,6 +5829,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashExplicitObjectWrapper<_.Dictionary>; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashExplicitObjectWrapper<_.Dictionary>; } interface LoDashExplicitObjectWrapper { @@ -5766,6 +5844,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashExplicitObjectWrapper; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashExplicitObjectWrapper; /** * @see _.zipObject @@ -5773,6 +5857,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashExplicitObjectWrapper; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashExplicitObjectWrapper; /** * @see _.zipObject @@ -5780,6 +5870,12 @@ declare namespace _ { zipObject( values?: List ): _.LoDashExplicitObjectWrapper<_.Dictionary>; + /** + * @see _.zipObjectDeep + */ + zipObjectDeep( + values?: List + ): _.LoDashExplicitObjectWrapper<_.Dictionary>; } //_.zipWith diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index b260df8ee5..311e2e8242 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -2608,12 +2608,18 @@ namespace TestZipObject { let result: _.Dictionary; result = _.zipObject(arrayOfKeys); + result = _.zipObjectDeep(arrayOfKeys); result = _.zipObject(arrayOfKeys, arrayOfValues); + result = _.zipObjectDeep(arrayOfKeys, arrayOfValues); result = _.zipObject(arrayOfKeys, listOfValues); + result = _.zipObjectDeep(arrayOfKeys, listOfValues); result = _.zipObject(listOfKeys); + result = _.zipObjectDeep(listOfKeys); result = _.zipObject(listOfKeys, listOfValues); + result = _.zipObjectDeep(listOfKeys, listOfValues); result = _.zipObject(listOfKeys, arrayOfValues); + result = _.zipObjectDeep(listOfKeys, arrayOfValues); result = _.zipObject<_.Dictionary>(arrayOfKeyValuePairs); result = _.zipObject<_.Dictionary>(listOfKeyValuePairs); @@ -2647,15 +2653,23 @@ namespace TestZipObject { let result: _.LoDashImplicitObjectWrapper<_.Dictionary>; result = _(arrayOfKeys).zipObject(); + result = _(arrayOfKeys).zipObjectDeep(); result = _(arrayOfKeys).zipObject(arrayOfValues); + result = _(arrayOfKeys).zipObjectDeep(arrayOfValues); result = _(arrayOfKeys).zipObject(listOfValues); + result = _(arrayOfKeys).zipObjectDeep(listOfValues); result = _(listOfKeys).zipObject(); + result = _(listOfKeys).zipObjectDeep(); result = _(listOfKeys).zipObject(listOfValues); + result = _(listOfKeys).zipObjectDeep(listOfValues); result = _(listOfKeys).zipObject(arrayOfValues); + result = _(listOfKeys).zipObjectDeep(arrayOfValues); result = _(listOfKeys).zipObject(arrayOfKeyValuePairs); + result = _(listOfKeys).zipObjectDeep(arrayOfKeyValuePairs); result = _(listOfKeys).zipObject(listOfKeyValuePairs); + result = _(listOfKeys).zipObjectDeep(listOfKeyValuePairs); } { @@ -2686,15 +2700,23 @@ namespace TestZipObject { let result: _.LoDashExplicitObjectWrapper<_.Dictionary>; result = _(arrayOfKeys).chain().zipObject(); + result = _(arrayOfKeys).chain().zipObjectDeep(); result = _(arrayOfKeys).chain().zipObject(arrayOfValues); + result = _(arrayOfKeys).chain().zipObjectDeep(arrayOfValues); result = _(arrayOfKeys).chain().zipObject(listOfValues); + result = _(arrayOfKeys).chain().zipObjectDeep(listOfValues); result = _(listOfKeys).chain().zipObject(); + result = _(listOfKeys).chain().zipObjectDeep(); result = _(listOfKeys).chain().zipObject(listOfValues); + result = _(listOfKeys).chain().zipObjectDeep(listOfValues); result = _(listOfKeys).chain().zipObject(arrayOfValues); + result = _(listOfKeys).chain().zipObjectDeep(arrayOfValues); result = _(listOfKeys).chain().zipObject(arrayOfKeyValuePairs); + result = _(listOfKeys).chain().zipObjectDeep(arrayOfKeyValuePairs); result = _(listOfKeys).chain().zipObject(listOfKeyValuePairs); + result = _(listOfKeys).chain().zipObjectDeep(listOfKeyValuePairs); } } diff --git a/types/lodash/zipObjectDeep/index.d.ts b/types/lodash/zipObjectDeep/index.d.ts new file mode 100644 index 0000000000..a155901bb5 --- /dev/null +++ b/types/lodash/zipObjectDeep/index.d.ts @@ -0,0 +1,2 @@ +import { zipObjectDeep } from "../index"; +export = zipObjectDeep; \ No newline at end of file From 259d2a3ec8323aaa6e8d183c39b309f441fdfb0d Mon Sep 17 00:00:00 2001 From: rzymek Date: Sat, 25 Mar 2017 17:23:29 +0100 Subject: [PATCH 02/31] add zipObjectDeep to tsconfig.json fixed failed travis test: lodash/zipObjectDeep has unused file index.d.ts --- types/lodash/tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 419b6142b1..c0730d6661 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -288,6 +288,7 @@ "xorWith/index.d.ts", "zip/index.d.ts", "zipObject/index.d.ts", + "zipObjectDeep/index.d.ts", "zipWith/index.d.ts" ], "compilerOptions": { From 701ad3fcc01782b5c366f5b507a2ee4fcb6a57ec Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 24 Mar 2017 13:53:25 -0400 Subject: [PATCH 03/31] lodash: fix toPairs, toPairsIn definitions toPairs: https://github.com/lodash/lodash/blob/4.17.4/lodash.js#L13684:L13708 toPairsIn: https://github.com/lodash/lodash/blob/4.17.4/lodash.js#L13710:L13734 Fixes #14654. --- types/lodash/index.d.ts | 16 ++++++++-------- types/lodash/lodash-tests.ts | 24 ++++++++++++------------ 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index 6326773899..79326724b1 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -16993,23 +16993,23 @@ declare namespace _ { * @param object The object to query. * @return Returns the new array of key-value pairs. */ - toPairs(object?: T): any[][]; + toPairs(object?: T): [string, any][]; - toPairs(object?: T): TResult[][]; + toPairs(object?: T): [string, TResult][]; } interface LoDashImplicitObjectWrapper { /** * @see _.toPairs */ - toPairs(): LoDashImplicitArrayWrapper; + toPairs(): LoDashImplicitArrayWrapper<[string, TResult]>; } interface LoDashExplicitObjectWrapper { /** * @see _.toPairs */ - toPairs(): LoDashExplicitArrayWrapper; + toPairs(): LoDashExplicitArrayWrapper<[string, TResult]>; } //_.toPairsIn @@ -17020,23 +17020,23 @@ declare namespace _ { * @param object The object to query. * @return Returns the new array of key-value pairs. */ - toPairsIn(object?: T): any[][]; + toPairsIn(object?: T): [string, any][]; - toPairsIn(object?: T): TResult[][]; + toPairsIn(object?: T): [string, TResult][]; } interface LoDashImplicitObjectWrapper { /** * @see _.toPairsIn */ - toPairsIn(): LoDashImplicitArrayWrapper; + toPairsIn(): LoDashImplicitArrayWrapper<[string, TResult]>; } interface LoDashExplicitObjectWrapper { /** * @see _.toPairsIn */ - toPairsIn(): LoDashExplicitArrayWrapper; + toPairsIn(): LoDashExplicitArrayWrapper<[string, TResult]>; } //_.transform diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index b260df8ee5..8659859557 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -10176,37 +10176,37 @@ namespace TestToPairs { let object: _.Dictionary; { - let result: any[][]; + let result: [string, any][]; result = _.toPairs<_.Dictionary>(object); } { - let result: string[][]; + let result: [string, string][]; result = _.toPairs<_.Dictionary, string>(object); } { - let result: _.LoDashImplicitArrayWrapper; + let result: _.LoDashImplicitArrayWrapper<[string, string]>; result = _(object).toPairs(); } { - let result: _.LoDashImplicitArrayWrapper; + let result: _.LoDashImplicitArrayWrapper<[string, any]>; result = _(object).toPairs(); } { - let result: _.LoDashExplicitArrayWrapper; + let result: _.LoDashExplicitArrayWrapper<[string, string]>; result = _(object).chain().toPairs(); } { - let result: _.LoDashExplicitArrayWrapper; + let result: _.LoDashExplicitArrayWrapper<[string, any]>; result = _(object).chain().toPairs(); } @@ -10217,37 +10217,37 @@ namespace TestToPairsIn { let object: _.Dictionary; { - let result: any[][]; + let result: [string, any][]; result = _.toPairsIn<_.Dictionary>(object); } { - let result: string[][]; + let result: [string, string][]; result = _.toPairsIn<_.Dictionary, string>(object); } { - let result: _.LoDashImplicitArrayWrapper; + let result: _.LoDashImplicitArrayWrapper<[string, string]>; result = _(object).toPairsIn(); } { - let result: _.LoDashImplicitArrayWrapper; + let result: _.LoDashImplicitArrayWrapper<[string, any]>; result = _(object).toPairsIn(); } { - let result: _.LoDashExplicitArrayWrapper; + let result: _.LoDashExplicitArrayWrapper<[string, string]>; result = _(object).chain().toPairsIn(); } { - let result: _.LoDashExplicitArrayWrapper; + let result: _.LoDashExplicitArrayWrapper<[string, any]>; result = _(object).chain().toPairs(); } From 96bc18e2218cb25a20df28057880225ea12ac67f Mon Sep 17 00:00:00 2001 From: Eric Ivarsson Date: Mon, 27 Mar 2017 11:43:44 +0200 Subject: [PATCH 04/31] Added optional property navigateToLoginRequestUrl New in 1.0.14 is the ability to turn of default navigation to start page after login. --- types/adal/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/adal/index.d.ts b/types/adal/index.d.ts index 18ca3d8079..552ca468aa 100644 --- a/types/adal/index.d.ts +++ b/types/adal/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ADAL.JS 1.0.13 +// Type definitions for ADAL.JS 1.0.14 // Project: https://github.com/AzureAD/azure-activedirectory-library-for-js // Definitions by: mmaitre314 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -29,6 +29,7 @@ declare namespace adal { loginResource?: string; resource?: string; extraQueryParameter?: string; + navigateToLoginRequestUrl?: boolean; } interface User { From 8484faf7747a8731783bb8debc2a733a19de1592 Mon Sep 17 00:00:00 2001 From: Kalle Ott Date: Mon, 27 Mar 2017 21:23:45 +0200 Subject: [PATCH 05/31] update for react-virtualized 9.4 replaced single declaration file with multiple files to represent the module structure of react-virtualized. This makes the future maintanance easier, because changes in the lib can be easier mirrored in the corresponding declaration file. This typings update should be the last with large breaking changes --- types/react-virtualized/ArrowKeyStepper.d.ts | 55 ++ .../ArrowKeyStepper.test.tsx | 71 ++ types/react-virtualized/AutoSizer.d.ts | 49 ++ types/react-virtualized/AutoSizer.test.tsx | 47 ++ types/react-virtualized/CellMeasurer.d.ts | 78 ++ types/react-virtualized/CellMeasurer.test.tsx | 74 ++ types/react-virtualized/Collection.d.ts | 124 ++++ types/react-virtualized/Collection.test.tsx | 160 +++++ types/react-virtualized/ColumnSizer.d.ts | 50 ++ types/react-virtualized/ColumnSizer.test.tsx | 113 +++ types/react-virtualized/Grid.d.ts | 462 ++++++++++++ types/react-virtualized/Grid.test.tsx | 207 ++++++ types/react-virtualized/InfiniteLoader.d.ts | 80 +++ .../react-virtualized/InfiniteLoader.test.tsx | 138 ++++ types/react-virtualized/List.d.ts | 138 ++++ types/react-virtualized/List.test.tsx | 160 +++++ types/react-virtualized/Masonry.d.ts | 146 ++++ types/react-virtualized/Masonry.test.tsx | 200 ++++++ types/react-virtualized/MultiGrid.d.ts | 75 ++ types/react-virtualized/MultiGrid.test.tsx | 105 +++ types/react-virtualized/ScrollSync.d.ts | 51 ++ types/react-virtualized/ScrollSync.test.tsx | 222 ++++++ types/react-virtualized/Table.d.ts | 447 ++++++++++++ types/react-virtualized/Table.test.tsx | 196 +++++ types/react-virtualized/WindowScroller.d.ts | 60 ++ .../react-virtualized/WindowScroller.test.tsx | 88 +++ types/react-virtualized/genericTypes.d.ts | 40 ++ types/react-virtualized/index.d.ts | 671 ++++-------------- .../react-virtualized-tests.tsx | 532 -------------- types/react-virtualized/tsconfig.json | 28 +- 30 files changed, 3795 insertions(+), 1072 deletions(-) create mode 100644 types/react-virtualized/ArrowKeyStepper.d.ts create mode 100644 types/react-virtualized/ArrowKeyStepper.test.tsx create mode 100644 types/react-virtualized/AutoSizer.d.ts create mode 100644 types/react-virtualized/AutoSizer.test.tsx create mode 100644 types/react-virtualized/CellMeasurer.d.ts create mode 100644 types/react-virtualized/CellMeasurer.test.tsx create mode 100644 types/react-virtualized/Collection.d.ts create mode 100644 types/react-virtualized/Collection.test.tsx create mode 100644 types/react-virtualized/ColumnSizer.d.ts create mode 100644 types/react-virtualized/ColumnSizer.test.tsx create mode 100644 types/react-virtualized/Grid.d.ts create mode 100644 types/react-virtualized/Grid.test.tsx create mode 100644 types/react-virtualized/InfiniteLoader.d.ts create mode 100644 types/react-virtualized/InfiniteLoader.test.tsx create mode 100644 types/react-virtualized/List.d.ts create mode 100644 types/react-virtualized/List.test.tsx create mode 100644 types/react-virtualized/Masonry.d.ts create mode 100644 types/react-virtualized/Masonry.test.tsx create mode 100644 types/react-virtualized/MultiGrid.d.ts create mode 100644 types/react-virtualized/MultiGrid.test.tsx create mode 100644 types/react-virtualized/ScrollSync.d.ts create mode 100644 types/react-virtualized/ScrollSync.test.tsx create mode 100644 types/react-virtualized/Table.d.ts create mode 100644 types/react-virtualized/Table.test.tsx create mode 100644 types/react-virtualized/WindowScroller.d.ts create mode 100644 types/react-virtualized/WindowScroller.test.tsx create mode 100644 types/react-virtualized/genericTypes.d.ts delete mode 100644 types/react-virtualized/react-virtualized-tests.tsx diff --git a/types/react-virtualized/ArrowKeyStepper.d.ts b/types/react-virtualized/ArrowKeyStepper.d.ts new file mode 100644 index 0000000000..e42ff353f2 --- /dev/null +++ b/types/react-virtualized/ArrowKeyStepper.d.ts @@ -0,0 +1,55 @@ +import { PropTypes, PureComponent, Validator, Requireable } from 'react' + +export type OnSectionRenderedParams = { + columnStartIndex: number, + columnStopIndex: number, + rowStartIndex: number, + rowStopIndex: number +} + +export type ChildProps = { + onSectionRendered: (params: OnSectionRenderedParams) => void, + scrollToColumn: number, + scrollToRow: number +}; +/** + * This HOC decorates a virtualized component and responds to arrow-key events by scrolling one row or column at a time. + */ +export type ArrowKeyStepperProps = { + children?: (props: ChildProps) => React.ReactNode; + className?: string; + columnCount: number; + rowCount: number; + mode?: 'edges' | 'cells'; +} +export type ScrollIndexes = { + scrollToRow: number, + scrollToColumn: number +} +export class ArrowKeyStepper extends PureComponent { + static defaultProps: { + disabled: false, + mode: 'edges', + scrollToColumn: 0, + scrollToRow: 0 + }; + + static propTypes: { + children: Validator<(props: ChildProps) => React.ReactNode>, + className: Requireable, + columnCount: Validator, + disabled: Validator, + mode: Validator<'cells' | 'edges'>, + rowCount: Validator, + scrollToColumn: Validator, + scrollToRow: Validator + }; + + constructor(props: ArrowKeyStepperProps, context: any); + + componentWillReceiveProps(nextProps: ArrowKeyStepperProps): void; + + setScrollIndexes(params: ScrollIndexes): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/ArrowKeyStepper.test.tsx b/types/react-virtualized/ArrowKeyStepper.test.tsx new file mode 100644 index 0000000000..8204aafdd6 --- /dev/null +++ b/types/react-virtualized/ArrowKeyStepper.test.tsx @@ -0,0 +1,71 @@ +/** @flow */ +import * as React from 'react'; +import { PureComponent } from 'react' +import { ArrowKeyStepper, AutoSizer, Grid } from 'react-virtualized' + +export default class ArrowKeyStepperExample extends PureComponent { + constructor(props) { + super(props) + + this._getColumnWidth = this._getColumnWidth.bind(this) + this._getRowHeight = this._getRowHeight.bind(this) + this._cellRenderer = this._cellRenderer.bind(this) + } + + render() { + const { mode } = this.state + + return ( + + + {({ onSectionRendered, scrollToColumn, scrollToRow }) => ( +
+ + + {({ width }) => ( + this._cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style })} + rowHeight={this._getRowHeight} + rowCount={100} + scrollToColumn={scrollToColumn} + scrollToRow={scrollToRow} + width={width} + /> + )} + +
+ )} +
+ ) + } + + _getColumnWidth({ index }) { + return (1 + (index % 3)) * 60 + } + + _getRowHeight({ index }) { + return (1 + (index % 3)) * 30 + } + + _cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style }) { + + return ( +
+ {`r:${rowIndex}, c:${columnIndex}`} +
+ ) + } +} diff --git a/types/react-virtualized/AutoSizer.d.ts b/types/react-virtualized/AutoSizer.d.ts new file mode 100644 index 0000000000..6d82a44482 --- /dev/null +++ b/types/react-virtualized/AutoSizer.d.ts @@ -0,0 +1,49 @@ +import { PropTypes, PureComponent, Validator, Requireable } from 'react' + +export type Dimensions = { + height: number, + width: number +} + +export type AutoSizerProps = { + disableHeight?: boolean; + disableWidth?: boolean; + onResize?: (info: { height: number, width: number }) => any; + children?: (props: Dimensions) => React.ReactNode +}; +/** + * Decorator component that automatically adjusts the width and height of a single child. + * Child component should not be declared as a child but should rather be specified by a `ChildComponent` property. + * All other properties will be passed through to the child component. + */ +export class AutoSizer extends PureComponent { + static propTypes: { + /** + * Function responsible for rendering children. + * This function should implement the following signature: + * ({ height, width }) => PropTypes.element + */ + children: Validator<(props: Dimensions) => React.ReactNode>, + + /** Disable dynamic :height property */ + disableHeight: Requireable, + + /** Disable dynamic :width property */ + disableWidth: Requireable, + + /** Callback to be invoked on-resize: ({ height, width }) */ + onResize: Validator<(props: Dimensions) => any> + }; + + static defaultProps: { + onResize: () => { } + }; + + constructor(props: AutoSizerProps); + + componentDidMount(): void; + + componentWillUnmount(): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/AutoSizer.test.tsx b/types/react-virtualized/AutoSizer.test.tsx new file mode 100644 index 0000000000..670d77b52b --- /dev/null +++ b/types/react-virtualized/AutoSizer.test.tsx @@ -0,0 +1,47 @@ +/** @flow */ +import * as React from 'react'; +import { PureComponent } from 'react' +import { AutoSizer, List } from 'react-virtualized' + +export default class AutoSizerExample extends PureComponent { + constructor(props) { + super(props) + + this._rowRenderer = this._rowRenderer.bind(this) + } + + render() { + const { list } = this.context + const { hideDescription } = this.state + + return ( + + {({ width, height }) => ( + + )} + + ) + } + + _rowRenderer({ index, key, style }) { + const { list } = this.context + const row = list.get(index) + + return ( +
+ {row.name} +
+ ) + } +} diff --git a/types/react-virtualized/CellMeasurer.d.ts b/types/react-virtualized/CellMeasurer.d.ts new file mode 100644 index 0000000000..5e1e0db3fb --- /dev/null +++ b/types/react-virtualized/CellMeasurer.d.ts @@ -0,0 +1,78 @@ +import { PureComponent } from 'react' + +export type KeyMapper = ( + rowIndex: number, + columnIndex: number +) => any; + +export type CellMeasurerCacheParams = { + defaultHeight?: number, + defaultWidth?: number, + fixedHeight?: boolean, + fixedWidth?: boolean, + minHeight?: number, + minWidth?: number, + keyMapper?: KeyMapper +} +export class CellMeasurerCache { + constructor(params: CellMeasurerCacheParams); + clear( + rowIndex: number, + columnIndex: number + ): void; + clearAll(): void; + columnWidth: (params: { index: number }) => number | undefined; + hasFixedHeight(): boolean; + hasFixedWidth(): boolean; + getHeight( + rowIndex: number, + columnIndex: number + ): number | undefined; + getWidth( + rowIndex: number, + columnIndex: number + ): number | undefined; + has( + rowIndex: number, + columnIndex: number + ): boolean; + rowHeight: (params: { index: number }) => number | undefined; + set( + rowIndex: number, + columnIndex: number, + width: number, + height: number + ): void; +} + +export type CellMeasurerChildProps = { + getColumnWidth: () => number, + getRowHeight: () => number, + resetMeasurements: () => any, + resetMeasurementsForColumn: (index: number) => any, + resetMeasurementsForRow: (index: number) => any, +} + +export type CellMeasurerProps = { + cache?: CellMeasurerCache; + children?: (props: CellMeasurerChildProps) => React.ReactNode; + columnIndex?: number; + index?: number; + parent?: React.ReactType; + rowIndex?: number; + style?: React.CSSProperties; +} +/** + * Wraps a cell and measures its rendered content. + * Measurements are stored in a per-cell cache. + * Cached-content is not be re-measured. + */ +export class CellMeasurer extends PureComponent { + constructor(props: CellMeasurerProps, context: any); + + componentDidMount(): void; + + componentDidUpdate(prevProps: CellMeasurerProps, prevState: any): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/CellMeasurer.test.tsx b/types/react-virtualized/CellMeasurer.test.tsx new file mode 100644 index 0000000000..5b510704c0 --- /dev/null +++ b/types/react-virtualized/CellMeasurer.test.tsx @@ -0,0 +1,74 @@ +/** @flow */ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { CellMeasurer, CellMeasurerCache, List } from 'react-virtualized' + +export default class DynamicHeightList extends PureComponent { + + _cache: CellMeasurerCache + + constructor(props, context) { + super(props, context) + + this._cache = new CellMeasurerCache({ + fixedWidth: true, + minHeight: 50 + }) + + this._rowRenderer = this._rowRenderer.bind(this) + } + + render() { + const { width } = this.props + + return ( + + ) + } + + _rowRenderer({ index, isScrolling, key, parent, style }) { + const { getClassName, list } = this.props + + const datum = list.get(index % list.size) + const classNames = getClassName({ columnIndex: 0, rowIndex: index }) + + const imageWidth = 300 + const imageHeight = datum.size * 2 + + const source = `http://fillmurray.com/${imageWidth}/${imageHeight}` + + return ( + + {({ measure }) => ( +
+ +
+ )} +
+ ) + } +} diff --git a/types/react-virtualized/Collection.d.ts b/types/react-virtualized/Collection.d.ts new file mode 100644 index 0000000000..7e11946eb1 --- /dev/null +++ b/types/react-virtualized/Collection.d.ts @@ -0,0 +1,124 @@ +/** @flow */ +import { PureComponent, Validator, Requireable } from 'react' +import { + Index, + ScrollPosition, + SizeInfo, + SizeAndPositionInfo +} from './genericTypes'; + +export type CollectionCellSizeAndPosition = { height: number, width: number, x: number, y: number }; +export type CollectionCellSizeAndPositionGetter = (params: Index) => CollectionCellSizeAndPosition; + +export type CollectionCellGroupRendererParams = { + cellSizeAndPositionGetter: CollectionCellSizeAndPositionGetter, + indices: number[], + cellRenderer: CollectionCellRenderer +} +export type CollectionCellGroupRenderer = (params: CollectionCellGroupRendererParams) => React.ReactNode[]; +export type CollectionCellRendererParams = { + index: number, + key: string, + style?: React.CSSProperties +} +export type CollectionCellRenderer = (params: CollectionCellRendererParams) => React.ReactNode; +export type CollectionProps = { + 'aria-label'?: string; + cellCount: number; + cellGroupRenderer?: CollectionCellGroupRenderer, + cellRenderer: CollectionCellRenderer, + cellSizeAndPositionGetter: CollectionCellSizeAndPositionGetter, + sectionSize?: number; + className?: string; + height: number; + width:number; + horizontalOverscanSize?: number; + noContentRenderer?: () => JSX.Element; + scrollToCell?: number; + verticalOverscanSize?:number; +}; + +/** + * Renders scattered or non-linear data. + * Unlike Grid, which renders checkerboard data, Collection can render arbitrarily positioned- even overlapping- data. + */ +export class Collection extends PureComponent { + static propTypes: { + 'aria-label': Requireable, + + /** + * Number of cells in Collection. + */ + cellCount: Validator, + + /** + * Responsible for rendering a group of cells given their indices. + * Should implement the following interface: ({ + * cellSizeAndPositionGetter:Function, + * indices: Array, + * cellRenderer: Function + * }): Array + */ + cellGroupRenderer: Validator, + + /** + * Responsible for rendering a cell given an row and column index. + * Should implement the following interface: ({ index: number, key: string, style: object }): PropTypes.element + */ + cellRenderer: Validator, + + /** + * Callback responsible for returning size and offset/position information for a given cell (index). + * ({ index: number }): { height: number, width: number, x: number, y: number } + */ + cellSizeAndPositionGetter: Validator, + + /** + * Optionally override the size of the sections a Collection's cells are split into. + */ + sectionSize: Requireable + }; + + static defaultProps: { + 'aria-label': 'grid', + cellGroupRenderer: CollectionCellGroupRenderer + }; + + constructor(props: CollectionProps, context: any); + + forceUpdate(): void; + + /** See Collection#recomputeCellSizesAndPositions */ + recomputeCellSizesAndPositions(): void; + + /** React lifecycle methods */ + + render(): JSX.Element; + + /** CellLayoutManager interface */ + + calculateSizeAndPositionData(): void; + + /** + * Returns the most recently rendered set of cell indices. + */ + getLastRenderedIndices(): number[]; + + /** + * Calculates the minimum amount of change from the current scroll position to ensure the specified cell is (fully) visible. + */ + getScrollPositionForCell(params: { + align: 'auto' | 'start' | 'end' | 'center', + cellIndex: number, + height: number, + scrollLeft: number, + scrollTop: number, + width: number + }): ScrollPosition; + + getTotalSize(): SizeInfo; + + cellRenderers(params: { + isScrolling: boolean, + } & SizeInfo): React.ReactNode[]; +} diff --git a/types/react-virtualized/Collection.test.tsx b/types/react-virtualized/Collection.test.tsx new file mode 100644 index 0000000000..8a7860b3c7 --- /dev/null +++ b/types/react-virtualized/Collection.test.tsx @@ -0,0 +1,160 @@ +/** @flow */ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { AutoSizer, Collection } from 'react-virtualized' + +// Defines a pattern of sizes and positions for a range of 10 rotating cells +// These cells cover an area of 600 (wide) x 400 (tall) +const GUTTER_SIZE = 3 +const CELL_WIDTH = 75 + +export default class CollectionExample extends PureComponent { + + _columnYMap: any; + + constructor(props, context) { + super(props, context) + + this.context = context; + + this.state = { + cellCount: context.list.size, + columnCount: this._getColumnCount(context.list.size), + height: 300, + horizontalOverscanSize: 0, + scrollToCell: undefined, + showScrollingPlaceholder: false, + verticalOverscanSize: 0 + } + + this._columnYMap = [] + + this._cellRenderer = this._cellRenderer.bind(this) + this._cellSizeAndPositionGetter = this._cellSizeAndPositionGetter.bind(this) + this._noContentRenderer = this._noContentRenderer.bind(this) + this._onCellCountChange = this._onCellCountChange.bind(this) + this._onHeightChange = this._onHeightChange.bind(this) + this._onHorizontalOverscanSizeChange = this._onHorizontalOverscanSizeChange.bind(this) + this._onScrollToCellChange = this._onScrollToCellChange.bind(this) + this._onVerticalOverscanSizeChange = this._onVerticalOverscanSizeChange.bind(this) + } + + render() { + const { cellCount, height, horizontalOverscanSize, scrollToCell, showScrollingPlaceholder, verticalOverscanSize } = this.state + + return ( + + {({ width }) => ( + + )} + + ) + } + + _cellRenderer({ index, isScrolling, key, style }) { + const { list } = this.context + const { showScrollingPlaceholder } = this.state + + const datum = list.get(index % list.size) + + // Customize style + style.backgroundColor = datum.color + + return ( +
+ {showScrollingPlaceholder && isScrolling ? '...' : index} +
+ ) + } + + _cellSizeAndPositionGetter({ index }) { + const { list } = this.context + const { columnCount } = this.state + + const columnPosition = index % (columnCount || 1) + const datum = list.get(index % list.size) + + // Poor man's Masonry layout; columns won't all line up equally with the bottom. + const height = datum.size + const width = CELL_WIDTH + const x = columnPosition * (GUTTER_SIZE + width) + const y = this._columnYMap[columnPosition] || 0 + + this._columnYMap[columnPosition] = y + height + GUTTER_SIZE + + return { + height, + width, + x, + y + } + } + + _getColumnCount(cellCount) { + return Math.round(Math.sqrt(cellCount)) + } + + _onHorizontalOverscanSizeChange(event) { + const horizontalOverscanSize = parseInt(event.target.value, 10) || 0 + + this.setState({ horizontalOverscanSize }) + } + + _noContentRenderer() { + return ( +
+ No cells +
+ ) + } + + _onCellCountChange(event) { + const cellCount = parseInt(event.target.value, 10) || 0 + + this._columnYMap = [] + + this.setState({ + cellCount, + columnCount: this._getColumnCount(cellCount) + }) + } + + _onHeightChange(event) { + const height = parseInt(event.target.value, 10) || 0 + + this.setState({ height }) + } + + _onScrollToCellChange(event) { + const { cellCount } = this.state + + let scrollToCell = Math.min(cellCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToCell)) { + scrollToCell = undefined + } + + this.setState({ scrollToCell }) + } + + _onVerticalOverscanSizeChange(event) { + const verticalOverscanSize = parseInt(event.target.value, 10) || 0 + + this.setState({ verticalOverscanSize }) + } +} diff --git a/types/react-virtualized/ColumnSizer.d.ts b/types/react-virtualized/ColumnSizer.d.ts new file mode 100644 index 0000000000..6efcf8c044 --- /dev/null +++ b/types/react-virtualized/ColumnSizer.d.ts @@ -0,0 +1,50 @@ +import { PureComponent, Validator, Requireable } from 'react' + +export type SizedColumnProps = { + adjustedWidth: number, + getColumnWidth: () => number, + registerChild: any +} + +export type ColumnSizerProps = { + children?: (props: SizedColumnProps) => React.ReactNode; + columnMaxWidth?: number; + columnMinWidth?: number; + columnCount?: number; + width: number; +} +/** + * High-order component that auto-calculates column-widths for `Grid` cells. + */ +export class ColumnSizer extends PureComponent { + static propTypes: { + /** + * Function responsible for rendering a virtualized Grid. + * This function should implement the following signature: + * ({ adjustedWidth, getColumnWidth, registerChild }) => PropTypes.element + * + * The specified :getColumnWidth function should be passed to the Grid's :columnWidth property. + * The :registerChild should be passed to the Grid's :ref property. + * The :adjustedWidth property is optional; it reflects the lesser of the overall width or the width of all columns. + */ + children: Validator<(props: SizedColumnProps) => React.ReactNode>, + + /** Optional maximum allowed column width */ + columnMaxWidth: Requireable, + + /** Optional minimum allowed column width */ + columnMinWidth: Requireable, + + /** Number of columns in Grid or Table child */ + columnCount: Validator, + + /** Width of Grid or Table child */ + width: Validator + }; + + constructor(props: ColumnSizerProps, context: any); + + componentDidUpdate(prevProps: ColumnSizerProps, prevState: any): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/ColumnSizer.test.tsx b/types/react-virtualized/ColumnSizer.test.tsx new file mode 100644 index 0000000000..97de9fff45 --- /dev/null +++ b/types/react-virtualized/ColumnSizer.test.tsx @@ -0,0 +1,113 @@ +import * as React from 'react' +import { PureComponent } from 'react' +import { AutoSizer, ColumnSizer, Grid } from 'react-virtualized' + +export default class ColumnSizerExample extends PureComponent { + constructor(props) { + super(props) + + this._noColumnMaxWidthChange = this._noColumnMaxWidthChange.bind(this) + this._noColumnMinWidthChange = this._noColumnMinWidthChange.bind(this) + this._onColumnCountChange = this._onColumnCountChange.bind(this) + this._noContentRenderer = this._noContentRenderer.bind(this) + this._cellRenderer = this._cellRenderer.bind(this) + } + + render() { + const { + columnMaxWidth, + columnMinWidth, + columnCount + } = this.state + + return ( +
+ + {({ width }) => ( + + {({ adjustedWidth, getColumnWidth, registerChild }) => ( +
+ +
+ )} +
+ )} +
+
+ ) + } + + _noColumnMaxWidthChange(event) { + let columnMaxWidth = parseInt(event.target.value, 10) + + if (isNaN(columnMaxWidth)) { + columnMaxWidth = undefined + } else { + columnMaxWidth = Math.min(1000, columnMaxWidth) + } + + this.setState({ columnMaxWidth }) + } + + _noColumnMinWidthChange(event) { + let columnMinWidth = parseInt(event.target.value, 10) + + if (isNaN(columnMinWidth)) { + columnMinWidth = undefined + } else { + columnMinWidth = Math.max(1, columnMinWidth) + } + + this.setState({ columnMinWidth }) + } + + _onColumnCountChange(event) { + this.setState({ columnCount: parseInt(event.target.value, 10) || 0 }) + } + + _noContentRenderer() { + return ( +
+ No cells +
+ ) + } + + _cellRenderer({ columnIndex, key, rowIndex, style }) { + const className = columnIndex === 0 + ? 'styles.firstCell' + : 'styles.cell' + + return ( +
+ {`R:${rowIndex}, C:${columnIndex}`} +
+ ) + } +} diff --git a/types/react-virtualized/Grid.d.ts b/types/react-virtualized/Grid.d.ts new file mode 100644 index 0000000000..ea7130857c --- /dev/null +++ b/types/react-virtualized/Grid.d.ts @@ -0,0 +1,462 @@ +/** @flow */ +import { Validator, Requireable, PureComponent } from 'react' +import { List } from './List'; +import { Table } from './Table'; +import { CellMeasurerCache } from './CellMeasurer'; +import { Index, Map, Alignment } from './genericTypes'; + +export type GridCellProps = { + columnIndex: number; + isScrolling: boolean; + isVisible: boolean; + key: string; + parent: Grid | List | Table; + rowIndex: number; + style: React.CSSProperties; +}; +export type GridCellRenderer = (props: GridCellProps) => React.ReactNode; + +export type ConfigureParams = { + cellCount: number, + estimatedCellSize: number +}; +export type ContainerSizeAndOffset = { + containerSize: number, + offset: number +}; +export type SizeAndPositionData = { + offset: number, + size: number +}; +export type GetVisibleCellRangeParams = { + containerSize: number, + offset: number +}; +export type VisibleCellRange = { + start: number; + stop: number; +}; +export type ScrollParams = { + clientHeight: number, + clientWidth: number, + scrollHeight: number, + scrollLeft: number, + scrollTop: number, + scrollWidth: number +}; +export type SectionRenderedParams = { + columnStartIndex: number, + columnStopIndex: number, + rowStartIndex: number, + rowStopIndex: number +}; +export type OverscanIndicesGetterParams = { + cellCount: number, + overscanCellsCount: number, + scrollDirection: number, + startIndex: number, + stopIndex: number +}; +export type OverscanIndices = { + overscanStartIndex: number, + overscanStopIndex: number +}; + +export type CellSizeAndPositionManager = { + areOffsetsAdjusted(): boolean; + configure({ + cellCount, + estimatedCellSize + }: ConfigureParams): void; + getCellCount(): number; + getEstimatedCellSize(): number; + getLastMeasuredIndex(): number; + getOffsetAdjustment({ + containerSize, + offset // safe + }: ContainerSizeAndOffset): number; + /** + * This method returns the size and position for the cell at the specified index. + * It just-in-time calculates (or used cached values) for cells leading up to the index. + */ + getSizeAndPositionOfCell(index: number): SizeAndPositionData; + getSizeAndPositionOfLastMeasuredCell(): SizeAndPositionData; + /** + * Total size of all cells being measured. + * This value will be completedly estimated initially. + * As cells as measured the estimate will be updated. + */ + getTotalSize(): number; + /** + * Determines a new offset that ensures a certain cell is visible, given the current offset. + * If the cell is already visible then the current offset will be returned. + * If the current offset is too great or small, it will be adjusted just enough to ensure the specified index is visible. + * + * @param align Desired alignment within container; one of "auto" (default), "start", or "end" + * @param containerSize Size (width or height) of the container viewport + * @param currentOffset Container's current (x or y) offset + * @param totalSize Total size (width or height) of all cells + * @return Offset to use to ensure the specified cell is visible + */ + getUpdatedOffsetForIndex(params: { + align: string, + containerSize: number, + currentOffset: number, + targetIndex: number + }): number; + getVisibleCellRange(params: GetVisibleCellRangeParams): VisibleCellRange; + /** + * Clear all cached values for cells after the specified index. + * This method should be called for any cell that has changed its size. + * It will not immediately perform any calculations; they'll be performed the next time getSizeAndPositionOfCell() is called. + */ + resetCell(index: number): void +} + +export type GridCellRangeProps = { + cellCache: Map, + cellRenderer: GridCellRenderer, + columnSizeAndPositionManager: CellSizeAndPositionManager, + columnStartIndex: number, + columnStopIndex: number, + isScrolling: boolean, + rowSizeAndPositionManager: CellSizeAndPositionManager, + rowStartIndex: number, + rowStopIndex: number, + scrollLeft: number, + scrollTop: number +} +export type GridCellRangeRenderer = (params: GridCellRangeProps) => React.ReactNode[]; +// TODO add proper typing +export type GridProps = { + 'aria-label'?: string; + autoContainerWidth?: boolean; + autoHeight?: boolean; + cellRenderer: GridCellRenderer; + cellRangeRenderer?: GridCellRangeRenderer; + className?: string; + columnCount: number; + columnWidth: number | ((params: Index) => number); + containerStyle?: React.CSSProperties; + deferredMeasurementCache?: CellMeasurerCache; + estimatedColumnSize?: number; + estimatedRowSize?: number; + getScrollbarSize?: () => number; + height: number; + id?: string; + noContentRenderer?: () => React.ReactNode; + onScroll?: (params: ScrollParams) => any; + onSectionRendered?: (params: SectionRenderedParams) => any; + overscanColumnCount?: number; + overscanIndicesGetter?: (params: OverscanIndicesGetterParams) => OverscanIndices; + overscanRowCount?: number; + rowHeight: number | ((params: Index) => number); + rowCount: number; + scrollingResetTimeInterval?: number; + scrollLeft?: number; + scrollToAlignment?: Alignment; + scrollToColumn?: number; + scrollTop?: number; + scrollToRow?: number; + style?: React.CSSProperties; + tabIndex?: number; + width: number; +}; + +export type ScrollDirection = 'horizontal' | 'vertical'; + +export type GridState = { + isScrolling: boolean, + scrollDirectionHorizontal: ScrollDirection, + scrollDirectionVertical: ScrollDirection, + scrollLeft: number, + scrollTop: number +}; + +/** + * Specifies the number of miliseconds during which to disable pointer events while a scroll is in progress. + * This improves performance and makes scrolling smoother. + */ +export const DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150 + +/** + * Renders tabular data with virtualization along the vertical and horizontal axes. + * Row heights and column widths must be known ahead of time and specified as properties. + */ +export class Grid extends PureComponent { + static propTypes: { + 'aria-label': Requireable, + + /** + * Set the width of the inner scrollable container to 'auto'. + * This is useful for single-column Grids to ensure that the column doesn't extend below a vertical scrollbar. + */ + autoContainerWidth: Requireable, + + /** + * Removes fixed height from the scrollingContainer so that the total height + * of rows can stretch the window. Intended for use with WindowScroller + */ + autoHeight: Requireable, + + /** + * Responsible for rendering a cell given an row and column index. + * Should implement the following interface: ({ columnIndex: number, rowIndex: number }): PropTypes.node + */ + cellRenderer: Validator< (props: GridCellProps) => React.ReactNode>, + + /** + * Responsible for rendering a group of cells given their index ranges. + * Should implement the following interface: ({ + * cellCache: Map, + * cellRenderer: Function, + * columnSizeAndPositionManager: CellSizeAndPositionManager, + * columnStartIndex: number, + * columnStopIndex: number, + * isScrolling: boolean, + * rowSizeAndPositionManager: CellSizeAndPositionManager, + * rowStartIndex: number, + * rowStopIndex: number, + * scrollLeft: number, + * scrollTop: number + * }): Array + */ + cellRangeRenderer: Validator<(params: GridCellRangeProps) => React.ReactNode[]>, + + /** + * Optional custom CSS class name to attach to root Grid element. + */ + className: Requireable, + + /** + * Number of columns in grid. + */ + columnCount: Validator, + + /** + * Either a fixed column width (number) or a function that returns the width of a column given its index. + * Should implement the following interface: (index: number): number + */ + columnWidth: Validator number)>, + + /** Optional inline style applied to inner cell-container */ + containerStyle: Requireable, + + /** + * If CellMeasurer is used to measure this Grid's children, this should be a pointer to its CellMeasurerCache. + * A shared CellMeasurerCache reference enables Grid and CellMeasurer to share measurement data. + */ + deferredMeasurementCache: Requireable, + + /** + * Used to estimate the total width of a Grid before all of its columns have actually been measured. + * The estimated total width is adjusted as columns are rendered. + */ + estimatedColumnSize: Validator, + + /** + * Used to estimate the total height of a Grid before all of its rows have actually been measured. + * The estimated total height is adjusted as rows are rendered. + */ + estimatedRowSize: Validator, + + /** + * Exposed for testing purposes only. + */ + getScrollbarSize: Validator<() => number>, + + /** + * Height of Grid; this property determines the number of visible (vs virtualized) rows. + */ + height: Validator, + + /** + * Optional custom id to attach to root Grid element. + */ + id: Requireable, + + /** + * Optional renderer to be used in place of rows when either :rowCount or :columnCount is 0. + */ + noContentRenderer: Requireable<() => JSX.Element>, + + /** + * Callback invoked whenever the scroll offset changes within the inner scrollable region. + * This callback can be used to sync scrolling between lists, tables, or grids. + * ({ clientHeight, clientWidth, scrollHeight, scrollLeft, scrollTop, scrollWidth }): void + */ + onScroll: Validator<(params: ScrollParams) => void>, + + /** + * Callback invoked with information about the section of the Grid that was just rendered. + * ({ columnStartIndex, columnStopIndex, rowStartIndex, rowStopIndex }): void + */ + onSectionRendered: Validator<(params: SectionRenderedParams) => void>, + + /** + * Number of columns to render before/after the visible section of the grid. + * These columns can help for smoother scrolling on touch devices or browsers that send scroll events infrequently. + */ + overscanColumnCount: Validator, + + /** + * Calculates the number of cells to overscan before and after a specified range. + * This function ensures that overscanning doesn't exceed the available cells. + * Should implement the following interface: ({ + * cellCount: number, + * overscanCellsCount: number, + * scrollDirection: number, + * startIndex: number, + * stopIndex: number + * }): {overscanStartIndex: number, overscanStopIndex: number} + */ + overscanIndicesGetter: Validator<(params: OverscanIndicesGetterParams) => OverscanIndices>, + + /** + * Number of rows to render above/below the visible section of the grid. + * These rows can help for smoother scrolling on touch devices or browsers that send scroll events infrequently. + */ + overscanRowCount: Validator, + + /** + * ARIA role for the grid element. + */ + role: Requireable, + + /** + * Either a fixed row height (number) or a function that returns the height of a row given its index. + * Should implement the following interface: ({ index: number }): number + */ + rowHeight: Validator number)>, + + /** + * Number of rows in grid. + */ + rowCount: Validator, + + /** Wait this amount of time after the last scroll event before resetting Grid `pointer-events`. */ + scrollingResetTimeInterval: Requireable, + + /** Horizontal offset. */ + scrollLeft: Requireable, + + /** + * Controls scroll-to-cell behavior of the Grid. + * The default ("auto") scrolls the least amount possible to ensure that the specified cell is fully visible. + * Use "start" to align cells to the top/left of the Grid and "end" to align bottom/right. + */ + scrollToAlignment: Validator, + + /** + * Column index to ensure visible (by forcefully scrolling if necessary) + */ + scrollToColumn: Validator, + + /** Vertical offset. */ + scrollTop: Requireable, + + /** + * Row index to ensure visible (by forcefully scrolling if necessary) + */ + scrollToRow: Validator, + + /** Optional inline style */ + style: Requireable, + + /** Tab index for focus */ + tabIndex: Requireable, + + /** + * Width of Grid; this property determines the number of visible (vs virtualized) columns. + */ + width: Validator + }; + + static defaultProps: { + 'aria-label': 'grid', + cellRangeRenderer: GridCellRangeRenderer, + estimatedColumnSize: 100, + estimatedRowSize: 30, + getScrollbarSize: () => number, + noContentRenderer: () => null, + onScroll: () => null, + onSectionRendered: () => null, + overscanColumnCount: 0, + overscanIndicesGetter: OverscanIndicesGetterParams, + overscanRowCount: 10, + role: 'grid', + scrollingResetTimeInterval: typeof DEFAULT_SCROLLING_RESET_TIME_INTERVAL, + scrollToAlignment: 'auto', + scrollToColumn: -1, + scrollToRow: -1, + style: {}, + tabIndex: 0 + }; + + constructor(props: GridProps, context: any); + + /** + * Invalidate Grid size and recompute visible cells. + * This is a deferred wrapper for recomputeGridSize(). + * It sets a flag to be evaluated on cDM/cDU to avoid unnecessary renders. + * This method is intended for advanced use-cases like CellMeasurer. + */ + // @TODO (bvaughn) Add automated test coverage for this. + invalidateCellSizeAfterRender(params: { + columnIndex: number, + rowIndex: number + }): void + + /** + * Pre-measure all columns and rows in a Grid. + * Typically cells are only measured as needed and estimated sizes are used for cells that have not yet been measured. + * This method ensures that the next call to getTotalSize() returns an exact size (as opposed to just an estimated one). + */ + measureAllCells(): void; + + /** + * Forced recompute of row heights and column widths. + * This function should be called if dynamic column or row sizes have changed but nothing else has. + * Since Grid only receives :columnCount and :rowCount it has no way of detecting when the underlying data changes. + */ + recomputeGridSize(params?: { + columnIndex?: number, + rowIndex?: number + }): void; + + /** + * Ensure column and row are visible. + */ + scrollToCell(params: { + columnIndex: number, + rowIndex: number + }): void; + + componentDidMount(): void; + + /** + * @private + * This method updates scrollLeft/scrollTop in state for the following conditions: + * 1) New scroll-to-cell props have been set + */ + componentDidUpdate(prevProps: GridProps, prevState: GridState): void; + + componentWillMount(): void; + + componentWillUnmount(): void; + + /** + * @private + * This method updates scrollLeft/scrollTop in state for the following conditions: + * 1) Empty content (0 rows or columns) + * 2) New scroll props overriding the current state + * 3) Cells-count or cells-size has changed, making previous scroll offsets invalid + */ + componentWillReceiveProps(nextProps: GridProps): void; + + componentWillUpdate(nextProps: GridProps, nextState: GridState): void; + + render(): JSX.Element; +} + +export const defaultCellRangeRenderer: GridCellRangeRenderer; \ No newline at end of file diff --git a/types/react-virtualized/Grid.test.tsx b/types/react-virtualized/Grid.test.tsx new file mode 100644 index 0000000000..634fcdc137 --- /dev/null +++ b/types/react-virtualized/Grid.test.tsx @@ -0,0 +1,207 @@ +/** @flow */ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { AutoSizer, Grid } from 'react-virtualized' + +export default class GridExample extends PureComponent { + + + constructor(props, context) { + super(props, context) + + this.state = { + columnCount: 1000, + height: 300, + overscanColumnCount: 0, + overscanRowCount: 10, + rowHeight: 40, + rowCount: 1000, + scrollToColumn: undefined, + scrollToRow: undefined, + useDynamicRowHeight: false + } + + this._cellRenderer = this._cellRenderer.bind(this) + this._getColumnWidth = this._getColumnWidth.bind(this) + this._getRowClassName = this._getRowClassName.bind(this) + this._getRowHeight = this._getRowHeight.bind(this) + this._noContentRenderer = this._noContentRenderer.bind(this) + this._onColumnCountChange = this._onColumnCountChange.bind(this) + this._onRowCountChange = this._onRowCountChange.bind(this) + this._onScrollToColumnChange = this._onScrollToColumnChange.bind(this) + this._onScrollToRowChange = this._onScrollToRowChange.bind(this) + this._renderBodyCell = this._renderBodyCell.bind(this) + this._renderLeftSideCell = this._renderLeftSideCell.bind(this) + } + + render() { + const { + columnCount, + height, + overscanColumnCount, + overscanRowCount, + rowHeight, + rowCount, + scrollToColumn, + scrollToRow, + useDynamicRowHeight + } = this.state + + return ( + + + {({ width }) => ( + + )} + + ) + } + + _cellRenderer({ columnIndex, key, rowIndex, style }) { + if (columnIndex === 0) { + return this._renderLeftSideCell({ key, rowIndex, style }) + } else { + return this._renderBodyCell({ columnIndex, key, rowIndex, style }) + } + } + + _getColumnWidth({ index }) { + switch (index) { + case 0: + return 50 + case 1: + return 100 + case 2: + return 300 + default: + return 80 + } + } + + _getDatum(index) { + const { list } = this.context + + return list.get(index % list.size) + } + + _getRowClassName(row) { + return row % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow' + } + + _getRowHeight({ index }) { + return this._getDatum(index).size + } + + _noContentRenderer() { + return ( +
+ No cells +
+ ) + } + + _renderBodyCell({ columnIndex, key, rowIndex, style }) { + const rowClass = this._getRowClassName(rowIndex) + const datum = this._getDatum(rowIndex) + + let content + + switch (columnIndex) { + case 1: + content = datum.name + break + case 2: + content = datum.random + break + default: + content = `r:${rowIndex}, c:${columnIndex}` + break + } + + return ( +
+ {content} +
+ ) + } + + _renderLeftSideCell({ key, rowIndex, style }) { + const datum = this._getDatum(rowIndex) + + // Don't modify styles. + // These are frozen by React now (as of 16.0.0). + // Since Grid caches and re-uses them, they aren't safe to modify. + style = { + ...style, + backgroundColor: datum.color + } + + return ( +
+ {datum.name.charAt(0)} +
+ ) + } + + _updateUseDynamicRowHeights(value) { + this.setState({ + useDynamicRowHeight: value + }) + } + + _onColumnCountChange(event) { + const columnCount = parseInt(event.target.value, 10) || 0 + + this.setState({ columnCount }) + } + + _onRowCountChange(event) { + const rowCount = parseInt(event.target.value, 10) || 0 + + this.setState({ rowCount }) + } + + _onScrollToColumnChange(event) { + const { columnCount } = this.state + let scrollToColumn = Math.min(columnCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToColumn)) { + scrollToColumn = undefined + } + + this.setState({ scrollToColumn }) + } + + _onScrollToRowChange(event) { + const { rowCount } = this.state + let scrollToRow = Math.min(rowCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToRow)) { + scrollToRow = undefined + } + + this.setState({ scrollToRow }) + } +} diff --git a/types/react-virtualized/InfiniteLoader.d.ts b/types/react-virtualized/InfiniteLoader.d.ts new file mode 100644 index 0000000000..4493921e72 --- /dev/null +++ b/types/react-virtualized/InfiniteLoader.d.ts @@ -0,0 +1,80 @@ +import { PureComponent, Validator, Requireable } from 'react' +import { Index, IndexRange } from './genericTypes'; + +export type InfiniteLoaderChildProps = { + onRowsRendered: (params: { startIndex: number, stopIndex: number }) => void, + registerChild: (registeredChild: any) => void +} + +export type InfiniteLoaderProps = { + children?: (props: InfiniteLoaderChildProps) => React.ReactNode; + isRowLoaded: (params: Index) => boolean; + loadMoreRows: (params: IndexRange) => Promise; + minimumBatchSize?: number; + rowCount?: number; + threshold?: number; +}; + +/** + * Higher-order component that manages lazy-loading for "infinite" data. + * This component decorates a virtual component and just-in-time prefetches rows as a user scrolls. + * It is intended as a convenience component; fork it if you'd like finer-grained control over data-loading. + */ +export class InfiniteLoader extends PureComponent { + static propTypes: { + /** + * Function responsible for rendering a virtualized component. + * This function should implement the following signature: + * ({ onRowsRendered, registerChild }) => PropTypes.element + * + * The specified :onRowsRendered function should be passed through to the child's :onRowsRendered property. + * The :registerChild callback should be set as the virtualized component's :ref. + */ + children: Validator<(props: InfiniteLoaderChildProps) => React.ReactNode>, + + /** + * Function responsible for tracking the loaded state of each row. + * It should implement the following signature: ({ index: number }): boolean + */ + isRowLoaded: Validator<(params: Index) => boolean>, + + /** + * Callback to be invoked when more rows must be loaded. + * It should implement the following signature: ({ startIndex, stopIndex }): Promise + * The returned Promise should be resolved once row data has finished loading. + * It will be used to determine when to refresh the list with the newly-loaded data. + * This callback may be called multiple times in reaction to a single scroll event. + */ + loadMoreRows: Validator<(params: IndexRange) => Promise>, + + /** + * Minimum number of rows to be loaded at a time. + * This property can be used to batch requests to reduce HTTP requests. + */ + minimumBatchSize: Validator, + + /** + * Number of rows in list; can be arbitrary high number if actual number is unknown. + */ + rowCount: Validator, + + /** + * Threshold at which to pre-fetch data. + * A threshold X means that data will start loading when a user scrolls within X rows. + * This value defaults to 15. + */ + threshold: Validator + }; + + static defaultProps: { + minimumBatchSize: 10, + rowCount: 0, + threshold: 15 + }; + + constructor(props: InfiniteLoaderProps, context: any); + + resetLoadMoreRowsCache(): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/InfiniteLoader.test.tsx b/types/react-virtualized/InfiniteLoader.test.tsx new file mode 100644 index 0000000000..0509f46216 --- /dev/null +++ b/types/react-virtualized/InfiniteLoader.test.tsx @@ -0,0 +1,138 @@ +/** @flow */ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { AutoSizer, InfiniteLoader, List } from 'react-virtualized' + +const STATUS_LOADING = 1 +const STATUS_LOADED = 2 + +export default class InfiniteLoaderExample extends PureComponent { + _timeoutIdMap: any; + + constructor(props) { + super(props) + + this._timeoutIdMap = {} + + this._clearData = this._clearData.bind(this) + this._isRowLoaded = this._isRowLoaded.bind(this) + this._loadMoreRows = this._loadMoreRows.bind(this) + this._rowRenderer = this._rowRenderer.bind(this) + } + + componentWillUnmount() { + Object.keys(this._timeoutIdMap).forEach(timeoutId => { + clearTimeout(timeoutId as any) + }) + } + + render() { + const { list } = this.context + const { loadedRowCount, loadingRowCount } = this.state + + return ( + + {({ onRowsRendered, registerChild }) => ( + + {({ width }) => ( + + )} + + )} + + ) + } + + _clearData() { + this.setState({ + loadedRowCount: 0, + loadedRowsMap: {}, + loadingRowCount: 0 + }) + } + + _isRowLoaded({ index }) { + const { loadedRowsMap } = this.state + return !!loadedRowsMap[index] // STATUS_LOADING or STATUS_LOADED + } + + _loadMoreRows({ startIndex, stopIndex }) { + const { loadedRowsMap, loadingRowCount } = this.state + const increment = stopIndex - startIndex + 1 + + for (var i = startIndex; i <= stopIndex; i++) { + loadedRowsMap[i] = STATUS_LOADING + } + + this.setState({ + loadingRowCount: loadingRowCount + increment + }) + + const timeoutId = setTimeout(() => { + const { loadedRowCount, loadingRowCount } = this.state + + delete this._timeoutIdMap[timeoutId] + + for (var i = startIndex; i <= stopIndex; i++) { + loadedRowsMap[i] = STATUS_LOADED + } + + this.setState({ + loadingRowCount: loadingRowCount - increment, + loadedRowCount: loadedRowCount + increment + }) + + promiseResolver() + }, 1000 + Math.round(Math.random() * 2000)) + + this._timeoutIdMap[timeoutId] = true + + let promiseResolver + + return new Promise(resolve => { + promiseResolver = resolve + }) + } + + _rowRenderer({ index, key, style }) { + const { list } = this.context + const { loadedRowsMap } = this.state + + const row = list.get(index) + let content + + if (loadedRowsMap[index] === STATUS_LOADED) { + content = row.name + } else { + content = ( +
+ ) + } + + return ( +
+ {content} +
+ ) + } +} diff --git a/types/react-virtualized/List.d.ts b/types/react-virtualized/List.d.ts new file mode 100644 index 0000000000..d4d5196a34 --- /dev/null +++ b/types/react-virtualized/List.d.ts @@ -0,0 +1,138 @@ +/** @flow */ +import { PureComponent, Validator, Requireable } from 'react' +import { Grid, GridCellProps } from './Grid' +import { Index, IndexRange, Alignment } from './genericTypes' +import { CellMeasurerCache } from './CellMeasurer' + +export type ListRowProps = GridCellProps & { index: number, style: React.CSSProperties }; + +export type ListRowRenderer = (props: ListRowProps) => React.ReactNode; +export type ListProps = { + deferredMeasurementCache?: CellMeasurerCache; + className?: string; + autoHeight?: boolean; + estimatedRowSize?: number; + height: number; + noRowsRenderer?: () => JSX.Element; + onRowsRendered?: (info: { overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }) => void; + onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; + overscanRowCount?: number; + rowHeight: number | ((info: Index) => number); + rowRenderer: ListRowRenderer; + rowCount: number; + scrollToAlignment?: string; + scrollToIndex?: number; + scrollTop?: number; + style?: React.CSSProperties; + tabIndex?: number; + width: number; +} +/** + * It is inefficient to create and manage a large list of DOM elements within a scrolling container + * if only a few of those elements are visible. The primary purpose of this component is to improve + * performance by only rendering the DOM nodes that a user is able to see based on their current + * scroll position. + * + * This component renders a virtualized list of elements with either fixed or dynamic heights. + */ +export class List extends PureComponent { + static propTypes: { + 'aria-label': Requireable, + + /** + * Removes fixed height from the scrollingContainer so that the total height + * of rows can stretch the window. Intended for use with WindowScroller + */ + autoHeight: Requireable, + + /** Optional CSS class name */ + className: Requireable, + + /** + * Used to estimate the total height of a List before all of its rows have actually been measured. + * The estimated total height is adjusted as rows are rendered. + */ + estimatedRowSize: Validator, + + /** Height constraint for list (determines how many actual rows are rendered) */ + height: Validator, + + /** Optional renderer to be used in place of rows when rowCount is 0 */ + noRowsRenderer: Validator<() => JSX.Element>, + + /** + * Callback invoked with information about the slice of rows that were just rendered. + * ({ startIndex, stopIndex }): void + */ + onRowsRendered: Validator<(params: IndexRange) => void>, + + /** + * Number of rows to render above/below the visible bounds of the list. + * These rows can help for smoother scrolling on touch devices. + */ + overscanRowCount: Validator, + + /** + * Callback invoked whenever the scroll offset changes within the inner scrollable region. + * This callback can be used to sync scrolling between lists, tables, or grids. + * ({ clientHeight, scrollHeight, scrollTop }): void + */ + onScroll: Validator<(params: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void>, + + /** + * Either a fixed row height (number) or a function that returns the height of a row given its index. + * ({ index: number }): number + */ + rowHeight: Validator number)>, + + /** Responsible for rendering a row given an index; ({ index: number }): node */ + rowRenderer: Validator, + + /** Number of rows in list. */ + rowCount: Validator, + + /** See Grid#scrollToAlignment */ + scrollToAlignment: Validator, + + /** Row index to ensure visible (by forcefully scrolling if necessary) */ + scrollToIndex: Validator, + + /** Vertical offset. */ + scrollTop: Requireable, + + /** Optional inline style */ + style: Validator, + + /** Tab index for focus */ + tabIndex: Requireable, + + /** Width of list */ + width: Validator + }; + + static defaultProps: { + estimatedRowSize: 30, + noRowsRenderer: () => null, + onRowsRendered: () => null, + onScroll: () => null, + overscanRowCount: 10, + scrollToAlignment: 'auto', + scrollToIndex: -1, + style: {} + }; + + constructor(props: ListProps, context: any); + + forceUpdateGrid(): void; + + /** See Grid#measureAllCells */ + measureAllRows(): void; + + /** See Grid#recomputeGridSize */ + recomputeRowHeights(index?: number): void; + + /** See Grid#scrollToCell */ + scrollToRow(index?: number): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/List.test.tsx b/types/react-virtualized/List.test.tsx new file mode 100644 index 0000000000..86763a95f8 --- /dev/null +++ b/types/react-virtualized/List.test.tsx @@ -0,0 +1,160 @@ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { AutoSizer, List } from 'react-virtualized' + +export default class ListExample extends PureComponent { + + constructor(props, context) { + super(props, context) + + this.state = { + listHeight: 300, + listRowHeight: 50, + overscanRowCount: 10, + rowCount: context.list.size, + scrollToIndex: undefined, + showScrollingPlaceholder: false, + useDynamicRowHeight: false + } + + this._getRowHeight = this._getRowHeight.bind(this) + this._noRowsRenderer = this._noRowsRenderer.bind(this) + this._onRowCountChange = this._onRowCountChange.bind(this) + this._onScrollToRowChange = this._onScrollToRowChange.bind(this) + this._rowRenderer = this._rowRenderer.bind(this) + } + + render() { + const { + listHeight, + listRowHeight, + overscanRowCount, + rowCount, + scrollToIndex, + showScrollingPlaceholder, + useDynamicRowHeight + } = this.state + + return ( + + {({ width }) => ( + + )} + + ) + } + + _getDatum(index) { + const { list } = this.context + + return list.get(index % list.size) + } + + _getRowHeight({ index }) { + return this._getDatum(index).size + } + + _noRowsRenderer() { + return ( +
+ No rows +
+ ) + } + + _onRowCountChange(event) { + const rowCount = parseInt(event.target.value, 10) || 0 + + this.setState({ rowCount }) + } + + _onScrollToRowChange(event) { + const { rowCount } = this.state + let scrollToIndex = Math.min(rowCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToIndex)) { + scrollToIndex = undefined + } + + this.setState({ scrollToIndex }) + } + + _rowRenderer({ index, isScrolling, key, style }) { + const { + showScrollingPlaceholder, + useDynamicRowHeight + } = this.state + + if ( + showScrollingPlaceholder && + isScrolling + ) { + return ( +
+ Scrolling... +
+ ) + } + + const datum = this._getDatum(index) + + let additionalContent + + if (useDynamicRowHeight) { + switch (datum.size) { + case 75: + additionalContent =
It is medium-sized.
+ break + case 100: + additionalContent =
It is large-sized.
It has a 3rd row.
+ break + } + } + + return ( +
+
+ {datum.name.charAt(0)} +
+
+
+ {datum.name} +
+
+ This is row {index} +
+ {additionalContent} +
+ {useDynamicRowHeight && + + {datum.size}px + + } +
+ ) + } +} diff --git a/types/react-virtualized/Masonry.d.ts b/types/react-virtualized/Masonry.d.ts new file mode 100644 index 0000000000..c4187bf611 --- /dev/null +++ b/types/react-virtualized/Masonry.d.ts @@ -0,0 +1,146 @@ +import { PureComponent, Validator, Requireable } from 'react' +import { } from './genericTypes'; +import { CellMeasurerCache, KeyMapper } from './CellMeasurer'; +import { GridCellRenderer } from './Grid'; +/** + * Specifies the number of miliseconds during which to disable pointer events while a scroll is in progress. + * This improves performance and makes scrolling smoother. + */ +export const DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150 + +export type OnCellsRenderedCallback = (params: { + startIndex: number, + stopIndex: number +}) => void; + +export type OnScrollCallback = (params: { + clientHeight: number, + scrollHeight: number, + scrollTop: number +}) => void; + +export type MasonryCellProps = { + index: number, + isScrolling: boolean, + key: React.Key, + parent: React.ReactType, + style?: React.CSSProperties +} + +export type CellRenderer = (props: MasonryCellProps) => React.ReactNode + +export type MasonryProps = { + autoHeight: boolean, + cellCount: number, + cellMeasurerCache: CellMeasurerCache, + cellPositioner: Positioner, + cellRenderer: CellRenderer, + className?: string, + height: number, + id?: string, + keyMapper?: KeyMapper, + onCellsRendered?: OnCellsRenderedCallback, + onScroll?: OnScrollCallback, + overscanByPixels?: number, + role?: string, + scrollingResetTimeInterval?: number, + scrollTop?: number, + style?: React.CSSProperties, + tabIndex?: number, + width: number +} + +export type MasonryState = { + isScrolling: boolean, + scrollTop: number +} + +/** + * This component efficiently displays arbitrarily positioned cells using windowing techniques. + * Cell position is determined by an injected `cellPositioner` property. + * Windowing is vertical; this component does not support horizontal scrolling. + * + * Rendering occurs in two phases: + * 1) First pass uses estimated cell sizes (provided by the cache) to determine how many cells to measure in a batch. + * Batch size is chosen using a fast, naive layout algorithm that stacks images in order until the viewport has been filled. + * After measurement is complete (componentDidMount or componentDidUpdate) this component evaluates positioned cells + * in order to determine if another measurement pass is required (eg if actual cell sizes were less than estimated sizes). + * All measurements are permanently cached (keyed by `keyMapper`) for performance purposes. + * 2) Second pass uses the external `cellPositioner` to layout cells. + * At this time the positioner has access to cached size measurements for all cells. + * The positions it returns are cached by Masonry for fast access later. + * Phase one is repeated if the user scrolls beyond the current layout's bounds. + * If the layout is invalidated due to eg a resize, cached positions can be cleared using `recomputeCellPositions()`. + * + * Animation constraints: + * Simple animations are supported (eg translate/slide into place on initial reveal). + * More complex animations are not (eg flying from one position to another on resize). + * + * Layout constraints: + * This component supports multi-column layout. + * The height of each item may vary. + * The width of each item must not exceed the width of the column it is "in". + * The left position of all items within a column must align. + * (Items may not span multiple columns.) + */ +export class Masonry extends PureComponent { + + static defaultProps: { + autoHeight: false, + keyMapper: identity, + onCellsRendered: noop, + onScroll: noop, + overscanByPixels: 20, + role: 'grid', + scrollingResetTimeInterval: typeof DEFAULT_SCROLLING_RESET_TIME_INTERVAL, + style: emptyObject, + tabIndex: 0 + } + + constructor(props: MasonryProps, context: any); + + clearCellPositions(): void; + + // HACK This method signature was intended for Grid + invalidateCellSizeAfterRender(params: { rowIndex: number }): void + + recomputeCellPositions(): void; + + componentDidMount(): void; + + componentDidUpdate(prevProps: MasonryProps, prevState: MasonryState): void; + + componentWillUnmount(): void; + + componentWillReceiveProps(nextProps: MasonryProps): void; + + render(): JSX.Element; +} + +type emptyObject = {} + +type identity = (value: T) => T; + +type noop = () => void; + +export type Position = { + left: number, + top: number +}; + +export type createCellPositionerParams = { + cellMeasurerCache: CellMeasurerCache, + columnCount: number, + columnWidth: number, + spacer?: number +}; + +export type resetParams = { + columnCount: number, + columnWidth: number, + spacer?: number +}; + +export type Positioner = ((index: number) => Position) & {reset: (params: resetParams) => void}; + +export const createCellPositioner: (params: createCellPositionerParams) => Positioner; \ No newline at end of file diff --git a/types/react-virtualized/Masonry.test.tsx b/types/react-virtualized/Masonry.test.tsx new file mode 100644 index 0000000000..902e5498c5 --- /dev/null +++ b/types/react-virtualized/Masonry.test.tsx @@ -0,0 +1,200 @@ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { + CellMeasurer, + CellMeasurerCache, + AutoSizer, + WindowScroller, + createMasonryCellPositioner as createCellPositioner, + Positioner, + Masonry, + MasonryCellProps +} from 'react-virtualized' + +export default class GridExample extends PureComponent { + _columnCount: number; + _cache: CellMeasurerCache; + _columnHeights: any; + _width: number; + _height: number; + _scrollTop: number; + _cellPositioner?: Positioner; + _masonry: Masonry; + + constructor(props, context) { + super(props, context) + + this._columnCount = 0 + + this._cache = new CellMeasurerCache({ + defaultHeight: 250, + defaultWidth: 200, + fixedWidth: true + }) + + this._columnHeights = {} + + this.state = { + columnWidth: 200, + height: 300, + gutterSize: 10, + windowScrollerEnabled: false + } + + this._cellRenderer = this._cellRenderer.bind(this) + this._onResize = this._onResize.bind(this) + this._renderAutoSizer = this._renderAutoSizer.bind(this) + this._renderMasonry = this._renderMasonry.bind(this) + this._setMasonryRef = this._setMasonryRef.bind(this) + } + + render() { + const { + columnWidth, + height, + gutterSize, + windowScrollerEnabled + } = this.state + + let child + + if (windowScrollerEnabled) { + child = ( + + {this._renderAutoSizer} + + ) + } else { + child = this._renderAutoSizer({ height }) + } + + return ( +
+ {child} +
+ ) + } + + _calculateColumnCount() { + const { + columnWidth, + gutterSize + } = this.state + + this._columnCount = Math.floor(this._width / (columnWidth + gutterSize)) + } + + _cellRenderer({ index, key, parent, style }: MasonryCellProps) { + const { list } = this.context + const { columnWidth } = this.state + + const datum = list.get(index % list.size) + + return ( + +
+
+ {datum.random} +
+ + ) + } + + _initCellPositioner() { + if (typeof this._cellPositioner === 'undefined') { + const { + columnWidth, + gutterSize + } = this.state + + this._cellPositioner = createCellPositioner({ + cellMeasurerCache: this._cache, + columnCount: this._columnCount, + columnWidth, + spacer: gutterSize + }) + } + } + + _onResize({ height, width }) { + this._width = width + + this._columnHeights = {} + this._calculateColumnCount() + this._resetCellPositioner() + this._masonry.recomputeCellPositions() + } + + _renderAutoSizer({ height, scrollTop }: { height: number, scrollTop?: number }) { + this._height = height + this._scrollTop = scrollTop + + return ( + + {this._renderMasonry} + + ) + } + + _renderMasonry({ width }) { + this._width = width + + this._calculateColumnCount() + this._initCellPositioner() + + const { height, windowScrollerEnabled } = this.state + + return ( + + ) + } + + _resetCellPositioner() { + const { + columnWidth, + gutterSize + } = this.state + + this._cellPositioner.reset({ + columnCount: this._columnCount, + columnWidth, + spacer: gutterSize + }) + } + + _setMasonryRef(ref) { + this._masonry = ref + } +} diff --git a/types/react-virtualized/MultiGrid.d.ts b/types/react-virtualized/MultiGrid.d.ts new file mode 100644 index 0000000000..1bb8b7dfac --- /dev/null +++ b/types/react-virtualized/MultiGrid.d.ts @@ -0,0 +1,75 @@ +import { PureComponent, Validator, Requireable } from 'react' +import { GridProps } from './Grid' + +export type MultiGridProps = { + fixedColumnCount: number; + fixedRowCount: number; + style: React.CSSProperties; + styleBottomLeftGrid: React.CSSProperties; + styleBottomRightGrid: React.CSSProperties; + styleTopLeftGrid: React.CSSProperties; + styleTopRightGrid: React.CSSProperties; +} & GridProps; + +export type MultiGridState = { + scrollLeft: number, + scrollTop: number +} + +/** + * Renders 1, 2, or 4 Grids depending on configuration. + * A main (body) Grid will always be rendered. + * Optionally, 1-2 Grids for sticky header rows will also be rendered. + * If no sticky columns, only 1 sticky header Grid will be rendered. + * If sticky columns, 2 sticky header Grids will be rendered. + */ +export class MultiGrid extends PureComponent { + static propTypes: { + fixedColumnCount: Validator, + fixedRowCount: Validator, + style: Validator, + styleBottomLeftGrid: Validator, + styleBottomRightGrid: Validator, + styleTopLeftGrid: Validator, + styleTopRightGrid: Validator + }; + + static defaultProps: { + fixedColumnCount: 0, + fixedRowCount: 0, + style: {}, + styleBottomLeftGrid: {}, + styleBottomRightGrid: {}, + styleTopLeftGrid: {}, + styleTopRightGrid: {} + }; + + constructor(props: MultiGridProps, context: any); + + forceUpdateGrids(): void; + + /** See Grid#invalidateCellSizeAfterRender */ + invalidateCellSizeAfterRender(params?: { + columnIndex?: number, + rowIndex?: number + }): void; + + /** See Grid#measureAllCells */ + measureAllCells(): void; + + /** See Grid#recomputeGridSize */ + recomputeGridSize(params?: { + columnIndex?: number, + rowIndex?: number + }): void; + + componentDidMount(): void; + + componentDidUpdate(prevProps: MultiGridProps, prevState: MultiGridState): void; + + componentWillMount(): void; + + componentWillReceiveProps(nextProps: MultiGridProps, nextState: MultiGridState): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/MultiGrid.test.tsx b/types/react-virtualized/MultiGrid.test.tsx new file mode 100644 index 0000000000..f2f3af9397 --- /dev/null +++ b/types/react-virtualized/MultiGrid.test.tsx @@ -0,0 +1,105 @@ +/** @flow */ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { AutoSizer, MultiGrid } from 'react-virtualized' + +const STYLE: React.CSSProperties = { + border: '1px solid #ddd', + overflow: 'hidden' +} +const STYLE_BOTTOM_LEFT_GRID: React.CSSProperties = { + borderRight: '2px solid #aaa', + backgroundColor: '#f7f7f7' +} +const STYLE_TOP_LEFT_GRID: React.CSSProperties = { + borderBottom: '2px solid #aaa', + borderRight: '2px solid #aaa', + fontWeight: 'bold' +} +const STYLE_TOP_RIGHT_GRID: React.CSSProperties = { + borderBottom: '2px solid #aaa', + fontWeight: 'bold' +} + +export default class MultiGridExample extends PureComponent { + state + _onFixedColumnCountChange + _onFixedRowCountChange + _onScrollToColumnChange + _onScrollToRowChange + + constructor(props, context) { + super(props, context) + + this.state = { + fixedColumnCount: 2, + fixedRowCount: 1, + scrollToColumn: 0, + scrollToRow: 0 + } + + this._cellRenderer = this._cellRenderer.bind(this) + this._onFixedColumnCountChange = this._createEventHandler('fixedColumnCount') + this._onFixedRowCountChange = this._createEventHandler('fixedRowCount') + this._onScrollToColumnChange = this._createEventHandler('scrollToColumn') + this._onScrollToRowChange = this._createEventHandler('scrollToRow') + } + + render() { + return ( + + {({ width }) => ( + + )} + + ) + } + + _cellRenderer({ columnIndex, key, rowIndex, style }) { + return ( +
+ {columnIndex}, {rowIndex} +
+ ) + } + + _createEventHandler(property) { + return (event) => { + const value = parseInt(event.target.value, 10) || 0 + + this.setState({ + [property]: value + }) + } + } + + _createLabeledInput(property, eventHandler) { + const value = this.state[property] + + return ( + `` + ) + } +} diff --git a/types/react-virtualized/ScrollSync.d.ts b/types/react-virtualized/ScrollSync.d.ts new file mode 100644 index 0000000000..4f1e924a69 --- /dev/null +++ b/types/react-virtualized/ScrollSync.d.ts @@ -0,0 +1,51 @@ +import { PureComponent, Validator, Requireable } from 'react' + +export type OnScrollParams = { + clientHeight: number, + clientWidth: number, + scrollHeight: number, + scrollLeft: number, + scrollTop: number, + scrollWidth: number +} + +export type ScrollSyncChildProps = { + clientHeight: number, + clientWidth: number, + onScroll: (params: OnScrollParams) => void, + scrollHeight: number, + scrollLeft: number, + scrollTop: number, + scrollWidth: number +} + +export type ScrollSyncProps = { + children?: (props: ScrollSyncChildProps) => React.ReactNode +}; + +export type ScrollSyncState = { + clientHeight: number, + clientWidth: number, + scrollHeight: number, + scrollLeft: number, + scrollTop: number, + scrollWidth: number +}; + +/** + * HOC that simplifies the process of synchronizing scrolling between two or more virtualized components. + */ +export class ScrollSync extends PureComponent { + static propTypes: { + /** + * Function responsible for rendering 2 or more virtualized components. + * This function should implement the following signature: + * ({ onScroll, scrollLeft, scrollTop }) => PropTypes.element + */ + children: Validator<(props: ScrollSyncChildProps) => React.ReactNode> + }; + + constructor(props: ScrollSyncProps, context: any); + + render(): JSX.Element; +} \ No newline at end of file diff --git a/types/react-virtualized/ScrollSync.test.tsx b/types/react-virtualized/ScrollSync.test.tsx new file mode 100644 index 0000000000..9919b72ab3 --- /dev/null +++ b/types/react-virtualized/ScrollSync.test.tsx @@ -0,0 +1,222 @@ +import * as React from 'react' +import { PureComponent } from 'react' +import { AutoSizer, Grid, ScrollSync } from 'react-virtualized' + +const LEFT_COLOR_FROM = hexToRgb('#471061') +const LEFT_COLOR_TO = hexToRgb('#BC3959') +const TOP_COLOR_FROM = hexToRgb('#000000') +const TOP_COLOR_TO = hexToRgb('#333333') + +function scrollbarSize() { return 42; } +export default class GridExample extends PureComponent { + state + constructor(props, context) { + super(props, context) + + this.state = { + columnWidth: 75, + columnCount: 50, + height: 300, + overscanColumnCount: 0, + overscanRowCount: 5, + rowHeight: 40, + rowCount: 100 + } + + this._renderBodyCell = this._renderBodyCell.bind(this) + this._renderHeaderCell = this._renderHeaderCell.bind(this) + this._renderLeftSideCell = this._renderLeftSideCell.bind(this) + } + + render() { + const { + columnCount, + columnWidth, + height, + overscanColumnCount, + overscanRowCount, + rowHeight, + rowCount + } = this.state + + return ( + + + {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => { + const x = scrollLeft / (scrollWidth - clientWidth) + const y = scrollTop / (scrollHeight - clientHeight) + + const leftBackgroundColor = mixColors(LEFT_COLOR_FROM, LEFT_COLOR_TO, y) + const leftColor = '#ffffff' + const topBackgroundColor = mixColors(TOP_COLOR_FROM, TOP_COLOR_TO, x) + const topColor = '#ffffff' + const middleBackgroundColor = mixColors(leftBackgroundColor, topBackgroundColor, 0.5) + const middleColor = '#ffffff' + + return ( +
+
+ +
+
+ +
+
+ + {({ width }) => ( +
+
+ +
+
+ +
+
+ )} +
+
+
+ ) + }} +
+ ) + } + + _renderBodyCell({ columnIndex, key, rowIndex, style }) { + if (columnIndex < 1) { + return + } + + return this._renderLeftSideCell({ columnIndex, key, rowIndex, style }) + } + + _renderHeaderCell({ columnIndex, key, rowIndex, style }) { + if (columnIndex < 1) { + return + } + + return this._renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) + } + + _renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) { + return ( +
+ {`C${columnIndex}`} +
+ ) + } + + _renderLeftSideCell({ columnIndex, key, rowIndex, style }) { + return ( +
+ {`R${rowIndex}, C${columnIndex}`} +
+ ) + } +} + +function hexToRgb(hex) { + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : null +} + +/** + * Ported from sass implementation in C + * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 + */ +function mixColors(color1, color2, amount) { + const weight1 = amount + const weight2 = 1 - amount + + const r = Math.round(weight1 * color1.r + weight2 * color2.r) + const g = Math.round(weight1 * color1.g + weight2 * color2.g) + const b = Math.round(weight1 * color1.b + weight2 * color2.b) + + return { r, g, b } +} diff --git a/types/react-virtualized/Table.d.ts b/types/react-virtualized/Table.d.ts new file mode 100644 index 0000000000..af5cf9b0b5 --- /dev/null +++ b/types/react-virtualized/Table.d.ts @@ -0,0 +1,447 @@ +import { Validator, Requireable, PureComponent, Component } from 'react'; +import { CellMeasurerCache } from './CellMeasurer'; +import { Index, Alignment, ScrollEventData, IndexRange, OverscanIndexRange } from './genericTypes'; +import { Grid } from './Grid'; + +export type TableCellDataGetterParams = { + columnData?: any, + dataKey: string, + rowData: any +}; +export type TableCellProps = { + cellData?: any, + columnData?: any, + dataKey: string, + rowData: any, + rowIndex: number +}; +export type TableHeaderProps = { + columnData?: any, + dataKey: string, + disableSort?: boolean, + label?: string, + sortBy?: string, + sortDirection?: SortDirectionType +}; +export type TableHeaderRowProps = { + className: string, + columns: React.ReactNode[], + style: React.CSSProperties, + scrollbarWidth: number, + height: number, + width: number +}; +export type TableRowProps = { + className: string, + columns: Array, + index: number, + isScrolling: boolean, + onRowClick?: (params: RowMouseEventHandlerParams) => void, + onRowDoubleClick?: (params: RowMouseEventHandlerParams) => void, + onRowMouseOver?: (params: RowMouseEventHandlerParams) => void, + onRowMouseOut?: (params: RowMouseEventHandlerParams) => void, + rowData: any, + style: any +}; + +export type TableCellDataGetter = (params: TableCellDataGetterParams) => any; +export type TableCellRenderer = (props: TableCellProps) => React.ReactNode; +export type TableHeaderRenderer = (props: TableHeaderProps) => React.ReactNode; +export type TableHeaderRowRenderer = (props: TableHeaderRowProps) => React.ReactNode; +export type TableRowRenderer = (props: TableRowProps) => React.ReactNode; + +// https://github.com/bvaughn/react-virtualized/blob/master/docs/Column.md +export type ColumnProps = { + cellDataGetter?: TableCellDataGetter; + cellRenderer?: TableCellRenderer; + className?: string; + columnData?: any; + dataKey: any; + disableSort?: boolean; + flexGrow?: number; + flexShrink?: number; + headerClassName?: string; + headerRenderer?: TableHeaderRenderer; + label?: string; + maxWidth?: number; + minWidth?: number; + style?: React.CSSProperties; + width: number; +} +export class Column extends Component { + static propTypes: { + /** Optional aria-label value to set on the column header */ + 'aria-label': Requireable, + + /** + * Callback responsible for returning a cell's data, given its :dataKey + * ({ columnData: any, dataKey: string, rowData: any }): any + */ + cellDataGetter: Requireable, + + /** + * Callback responsible for rendering a cell's contents. + * ({ cellData: any, columnData: any, dataKey: string, rowData: any, rowIndex: number }): node + */ + cellRenderer: Requireable, + + /** Optional CSS class to apply to cell */ + className: Requireable, + + /** Optional additional data passed to this column's :cellDataGetter */ + columnData: Requireable, + + /** Uniquely identifies the row-data attribute correspnding to this cell */ + dataKey: Validator, + + /** If sort is enabled for the table at large, disable it for this column */ + disableSort: Requireable, + + /** Flex grow style; defaults to 0 */ + flexGrow: Requireable, + + /** Flex shrink style; defaults to 1 */ + flexShrink: Requireable, + + /** Optional CSS class to apply to this column's header */ + headerClassName: Requireable, + + /** + * Optional callback responsible for rendering a column header contents. + * ({ columnData: object, dataKey: string, disableSort: boolean, label: string, sortBy: string, sortDirection: string }): PropTypes.node + */ + headerRenderer: Validator, + + /** Header label for this column */ + label: Requireable, + + /** Maximum width of column; this property will only be used if :flexGrow is > 0. */ + maxWidth: Requireable, + + /** Minimum width of column. */ + minWidth: Requireable, + + /** Optional inline style to apply to cell */ + style: Requireable, + + /** Flex basis (width) for this column; This value can grow or shrink based on :flexGrow and :flexShrink properties. */ + width: Validator + }; + + static defaultProps: { + cellDataGetter: TableCellDataGetter, + cellRenderer: TableCellRenderer, + flexGrow: 0, + flexShrink: 1, + headerRenderer: TableHeaderRenderer, + style: {} + }; +} + +export type RowMouseEventHandlerParams = { + rowData: { + columnData: object, + id: string, + index: number + }, + index: number, + event: React.SyntheticEvent> +} + +export type HeaderMouseEventHandlerParams = { + dataKey: string, + columnData: any, + event: React.SyntheticEvent> +} + +// ref: https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md +export type TableProps = { + deferredMeasurementCache?: CellMeasurerCache; + autoHeight?: boolean; + children?: React.ReactChildren; + className?: string; + disableHeader?: boolean; + estimatedRowSize?: number; + gridClassName?: string; + gridStyle?: any; + headerClassName?: string; + headerHeight: number; + headerStyle?: any; + height?: number; + id?: string; + noRowsRenderer?: () => void; + onHeaderClick?: (params: HeaderMouseEventHandlerParams) => void; + onRowClick?: (info: RowMouseEventHandlerParams) => void; + onRowDoubleClick?: (info: RowMouseEventHandlerParams) => void; + onRowMouseOut?: (info: RowMouseEventHandlerParams) => void; + onRowMouseOver?: (info: RowMouseEventHandlerParams) => void; + onRowsRendered?: (info: IndexRange & OverscanIndexRange) => void; + overscanRowCount?: number; + onScroll?: (info: ScrollEventData) => void; + rowClassName?: string | ((info: Index) => string); + rowCount: number; + rowGetter?: (info: Index) => any; + rowHeight: number | ((info: Index) => number); + rowRenderer?: TableRowRenderer; + headerRowRenderer?: TableHeaderRowRenderer; + rowStyle?: React.CSSProperties | ((info: Index) => React.CSSProperties); + scrollToAlignment?: string; + scrollToIndex?: number; + scrollTop?: number; + sort?: (info: { sortBy: string, sortDirection: SortDirectionType }) => void; + sortBy?: string; + sortDirection?: SortDirectionType; + style?: React.CSSProperties; + tabIndex?: number; + width?: number; +} + +export const defaultTableCellDataGetter: TableCellDataGetter; +export const defaultTableCellRenderer: TableCellRenderer; +export const defaultTableHeaderRenderer: () => React.ReactElement[]; +export const defaultTableHeaderRowRenderer: TableHeaderRowRenderer; +export const defaultTableRowRenderer: TableRowRenderer; + +type SortDirectionStatic = { + /** + * Sort items in ascending order. + * This means arranging from the lowest value to the highest (e.g. a-z, 0-9). + */ + ASC: 'ASC', + + /** + * Sort items in descending order. + * This means arranging from the highest value to the lowest (e.g. z-a, 9-0). + */ + DESC: 'DESC' +} + +export const SortDirection: SortDirectionStatic + +export type SortDirectionType = 'ASC' | 'DESC' + +export const SortIndicator: React.StatelessComponent<{ sortDirection: SortDirectionType }> + +/** + * Table component with fixed headers and virtualized rows for improved performance with large data sets. + * This component expects explicit width, height, and padding parameters. + */ +export class Table extends PureComponent { + static propTypes: { + 'aria-label': Requireable, + + /** + * Removes fixed height from the scrollingContainer so that the total height + * of rows can stretch the window. Intended for use with WindowScroller + */ + autoHeight: Requireable, + + /** One or more Columns describing the data displayed in this row */ + children: Validator, + + /** Optional CSS class name */ + className: Requireable, + + /** Disable rendering the header at all */ + disableHeader: Requireable, + + /** + * Used to estimate the total height of a Table before all of its rows have actually been measured. + * The estimated total height is adjusted as rows are rendered. + */ + estimatedRowSize: Validator, + + /** Optional custom CSS class name to attach to inner Grid element. */ + gridClassName: Requireable, + + /** Optional inline style to attach to inner Grid element. */ + gridStyle: Requireable, + + /** Optional CSS class to apply to all column headers */ + headerClassName: Requireable, + + /** Fixed height of header row */ + headerHeight: Validator, + + /** + * Responsible for rendering a table row given an array of columns: + * Should implement the following interface: ({ + * className: string, + * columns: any[], + * style: any + * }): PropTypes.node + */ + headerRowRenderer: Requireable, + + /** Optional custom inline style to attach to table header columns. */ + headerStyle: Requireable, + + /** Fixed/available height for out DOM element */ + height: Validator, + + /** Optional id */ + id: Requireable, + + /** Optional renderer to be used in place of table body rows when rowCount is 0 */ + noRowsRenderer: Requireable<() => JSX.Element>, + + /** + * Optional callback when a column's header is clicked. + * ({ columnData: any, dataKey: string }): void + */ + onHeaderClick: Requireable<(params: HeaderMouseEventHandlerParams) => void>, + + /** + * Callback invoked when a user clicks on a table row. + * ({ index: number }): void + */ + onRowClick: Requireable<(params: RowMouseEventHandlerParams) => void>, + + /** + * Callback invoked when a user double-clicks on a table row. + * ({ index: number }): void + */ + onRowDoubleClick: Requireable<(params: RowMouseEventHandlerParams) => void>, + + /** + * Callback invoked when the mouse leaves a table row. + * ({ index: number }): void + */ + onRowMouseOut: Requireable<(params: RowMouseEventHandlerParams) => void>, + + /** + * Callback invoked when a user moves the mouse over a table row. + * ({ index: number }): void + */ + onRowMouseOver: Requireable<(params: RowMouseEventHandlerParams) => void>, + + /** + * Callback invoked with information about the slice of rows that were just rendered. + * ({ startIndex, stopIndex }): void + */ + onRowsRendered: Requireable<(params: RowMouseEventHandlerParams) => void>, + + /** + * Callback invoked whenever the scroll offset changes within the inner scrollable region. + * This callback can be used to sync scrolling between lists, tables, or grids. + * ({ clientHeight, scrollHeight, scrollTop }): void + */ + onScroll: Requireable<(params: ScrollEventData) => void>, + + /** + * Number of rows to render above/below the visible bounds of the list. + * These rows can help for smoother scrolling on touch devices. + */ + overscanRowCount: Validator, + + /** + * Optional CSS class to apply to all table rows (including the header row). + * This property can be a CSS class name (string) or a function that returns a class name. + * If a function is provided its signature should be: ({ index: number }): string + */ + rowClassName: Requireable string)>, + + /** + * Callback responsible for returning a data row given an index. + * ({ index: number }): any + */ + rowGetter: Validator<(params: Index) => any>, + + /** + * Either a fixed row height (number) or a function that returns the height of a row given its index. + * ({ index: number }): number + */ + rowHeight: Validator number)>, + + /** Number of rows in table. */ + rowCount: Validator, + + /** + * Responsible for rendering a table row given an array of columns: + * Should implement the following interface: ({ + * className: string, + * columns: Array, + * index: number, + * isScrolling: boolean, + * onRowClick: ?Function, + * onRowDoubleClick: ?Function, + * onRowMouseOver: ?Function, + * onRowMouseOut: ?Function, + * rowData: any, + * style: any + * }): PropTypes.node + */ + rowRenderer: Requireable<(props: TableRowProps) => React.ReactNode>, + + /** Optional custom inline style to attach to table rows. */ + rowStyle: Validator React.CSSProperties)>, + + /** See Grid#scrollToAlignment */ + scrollToAlignment: Validator, + + /** Row index to ensure visible (by forcefully scrolling if necessary) */ + scrollToIndex: Validator, + + /** Vertical offset. */ + scrollTop: Requireable, + + /** + * Sort function to be called if a sortable header is clicked. + * ({ sortBy: string, sortDirection: SortDirection }): void + */ + sort: Requireable<(params: { sortBy: string, sortDirection: SortDirectionType }) => void>, + + /** Table data is currently sorted by this :dataKey (if it is sorted at all) */ + sortBy: Requireable, + + /** Table data is currently sorted in this direction (if it is sorted at all) */ + sortDirection: Validator, + + /** Optional inline style */ + style: Requireable, + + /** Tab index for focus */ + tabIndex: Requireable, + + /** Width of list */ + width: Validator + }; + + static defaultProps: { + disableHeader: false, + estimatedRowSize: 30, + headerHeight: 0, + headerStyle: {}, + noRowsRenderer: () => null, + onRowsRendered: () => null, + onScroll: () => null, + overscanRowCount: 10, + rowRenderer: TableRowRenderer, + headerRowRenderer: TableHeaderRenderer, + rowStyle: {}, + scrollToAlignment: 'auto', + scrollToIndex: -1, + style: {} + }; + + Grid: Grid; + + constructor(props: TableProps); + + forceUpdateGrid(): void; + + /** See Grid#measureAllCells */ + measureAllRows(): void; + + /** See Grid#recomputeGridSize */ + recomputeRowHeights(index?: number): void; + + /** See Grid#scrollToCell */ + scrollToRow(index?: number): void + + componentDidMount(): void; + + componentDidUpdate(): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/Table.test.tsx b/types/react-virtualized/Table.test.tsx new file mode 100644 index 0000000000..8714634d1d --- /dev/null +++ b/types/react-virtualized/Table.test.tsx @@ -0,0 +1,196 @@ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { AutoSizer, Column, Table, SortDirection, SortIndicator } from 'react-virtualized' + +export default class TableExample extends PureComponent { + state; + context; + constructor(props, context) { + super(props, context) + + this.state = { + disableHeader: false, + headerHeight: 30, + height: 270, + hideIndexRow: false, + overscanRowCount: 10, + rowHeight: 40, + rowCount: 1000, + scrollToIndex: undefined, + sortBy: 'index', + sortDirection: SortDirection.ASC, + useDynamicRowHeight: false + } + + this._getRowHeight = this._getRowHeight.bind(this) + this._headerRenderer = this._headerRenderer.bind(this) + this._noRowsRenderer = this._noRowsRenderer.bind(this) + this._onRowCountChange = this._onRowCountChange.bind(this) + this._onScrollToRowChange = this._onScrollToRowChange.bind(this) + this._rowClassName = this._rowClassName.bind(this) + this._sort = this._sort.bind(this) + } + + render() { + const { + disableHeader, + headerHeight, + height, + hideIndexRow, + overscanRowCount, + rowHeight, + rowCount, + scrollToIndex, + sortBy, + sortDirection, + useDynamicRowHeight + } = this.state + + const { list } = this.context + const sortedList = this._isSortEnabled() + ? list + .sortBy(item => item[sortBy]) + .update(list => + sortDirection === SortDirection.DESC + ? list.reverse() + : list + ) + : list + + const rowGetter = ({ index }) => this._getDatum(sortedList, index) + + return ( +
+ + {({ width }) => ( + + {!hideIndexRow && + rowData.index + } + dataKey='index' + disableSort={!this._isSortEnabled()} + width={60} + /> + } + + cellData + } + flexGrow={1} + /> +
+ )} +
+
+ ) + } + + _getDatum(list, index) { + return list.get(index % list.size) + } + + _getRowHeight({ index }) { + const { list } = this.context + + return this._getDatum(list, index).size + } + + _headerRenderer({ + columnData, + dataKey, + disableSort, + label, + sortBy, + sortDirection + }) { + return ( +
+ Full Name + {sortBy === dataKey && + + } +
+ ) + } + + _isSortEnabled() { + const { list } = this.context + const { rowCount } = this.state + + return rowCount <= list.size + } + + _noRowsRenderer() { + return ( +
+ No rows +
+ ) + } + + _onRowCountChange(event) { + const rowCount = parseInt(event.target.value, 10) || 0 + + this.setState({ rowCount }) + } + + _onScrollToRowChange(event) { + const { rowCount } = this.state + let scrollToIndex = Math.min(rowCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToIndex)) { + scrollToIndex = undefined + } + + this.setState({ scrollToIndex }) + } + + _rowClassName({ index }) { + if (index < 0) { + return 'styles.headerRow' + } else { + return index % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow' + } + } + + _sort({ sortBy, sortDirection }) { + this.setState({ sortBy, sortDirection }) + } + + _updateUseDynamicRowHeight(value) { + this.setState({ + useDynamicRowHeight: value + }) + } +} diff --git a/types/react-virtualized/WindowScroller.d.ts b/types/react-virtualized/WindowScroller.d.ts new file mode 100644 index 0000000000..093debdd78 --- /dev/null +++ b/types/react-virtualized/WindowScroller.d.ts @@ -0,0 +1,60 @@ +/** @flow */ +import { Validator, Requireable, PureComponent } from 'react' + +export type WindowScrollerChildProps = { + height: number, + isScrolling: boolean, + scrollTop: number +}; + +export type WindowScrollerProps = { + children?: (props: WindowScrollerChildProps) => React.ReactNode; + onResize?: (prams: { height: number }) => void; + onScroll?: (params: { scrollTop: number }) => void; + scrollElement?: HTMLElement; +} +export type WindowScrollerState = { + height: number, + isScrolling: boolean, + scrollTop: number +} + +export class WindowScroller extends PureComponent { + static propTypes: { + /** + * Function responsible for rendering children. + * This function should implement the following signature: + * ({ height, isScrolling, scrollTop }) => PropTypes.element + */ + children: Validator<(props: WindowScrollerChildProps) => React.ReactNode>, + + /** Callback to be invoked on-resize: ({ height }) */ + onResize: Validator<(params: { height: number }) => void>, + + /** Callback to be invoked on-scroll: ({ scrollTop }) */ + onScroll: Validator<(params: { scrollTop: number }) => void>, + + /** Element to attach scroll event listeners. Defaults to window. */ + scrollElement: HTMLElement + }; + + static defaultProps: { + onResize: () => {}, + onScroll: () => {} + }; + + constructor(props: WindowScrollerProps); + + // Can’t use defaultProps for scrollElement without breaking server-side rendering + readonly scrollElement: HTMLElement | Window; + + updatePosition(scrollElement?: HTMLElement): void; + + componentDidMount(): void; + + componentWillReceiveProps(nextProps: WindowScrollerProps): void; + + componentWillUnmount(): void; + + render(): JSX.Element; +} diff --git a/types/react-virtualized/WindowScroller.test.tsx b/types/react-virtualized/WindowScroller.test.tsx new file mode 100644 index 0000000000..c72a1b197a --- /dev/null +++ b/types/react-virtualized/WindowScroller.test.tsx @@ -0,0 +1,88 @@ +import * as React from 'react' +import { PropTypes, PureComponent } from 'react' +import { WindowScroller, List, AutoSizer } from 'react-virtualized' + +export default class WindowScrollerExample extends PureComponent { + state; + context; + _windowScroller: WindowScroller; + + constructor(props) { + super(props) + + this.state = { + showHeaderText: true + } + + this._hideHeader = this._hideHeader.bind(this) + this._rowRenderer = this._rowRenderer.bind(this) + this._onCheckboxChange = this._onCheckboxChange.bind(this) + this._setRef = this._setRef.bind(this) + } + + render() { + const { list, isScrollingCustomElement, customElement } = this.context + const { showHeaderText } = this.state + + return ( + +
+ + {({ height, isScrolling, scrollTop }) => ( + + {({ width }) => ( + this._rowRenderer({ index, isScrolling, isVisible, key, style })} + scrollTop={scrollTop} + width={width} + /> + )} + + )} + +
+ ) + } + + _hideHeader() { + const { showHeaderText } = this.state + + this.setState({ + showHeaderText: !showHeaderText + }, () => { + this._windowScroller.updatePosition() + }) + } + + _rowRenderer({ index, isScrolling, isVisible, key, style }) { + const { list } = this.context + const row = list.get(index) + + return ( +
+ {row.name} +
+ ) + } + + _setRef(windowScroller) { + this._windowScroller = windowScroller + } + + _onCheckboxChange(event) { + this.context.setScrollingCustomElement(event.target.checked) + } +} diff --git a/types/react-virtualized/genericTypes.d.ts b/types/react-virtualized/genericTypes.d.ts new file mode 100644 index 0000000000..7f4b6ff4b4 --- /dev/null +++ b/types/react-virtualized/genericTypes.d.ts @@ -0,0 +1,40 @@ +export type Index = { + index: number +}; + +export type PositionInfo = { + x: number, + y: number +}; + +export type ScrollPosition = { + scrollLeft: number, + scrollTop: number +}; + +export type SizeInfo = { + height: number, + width: number +}; + +export type SizeAndPositionInfo = SizeInfo & PositionInfo; + +export type Map = { [key: string]: T }; + +export type Alignment = 'auto' | 'end' | 'start' | 'center'; + +export type IndexRange = { + startIndex: number, + stopIndex: number +} + +export type OverscanIndexRange = { + overscanStartIndex: number, + overscanStopIndex: number, +} + +export type ScrollEventData = { + clientHeight: number, + scrollHeight: number, + scrollTop: number +} \ No newline at end of file diff --git a/types/react-virtualized/index.d.ts b/types/react-virtualized/index.d.ts index f89183c90f..31a6ee29c8 100644 --- a/types/react-virtualized/index.d.ts +++ b/types/react-virtualized/index.d.ts @@ -1,545 +1,138 @@ -// Type definitions for react-virtualized 9.2.1 +// Type definitions for react-virtualized 9.4 // Project: https://github.com/bvaughn/react-virtualized // Definitions by: Kalle Ott // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -import * as React from "react"; +export { + ArrowKeyStepper, + ArrowKeyStepperProps, + ChildProps as ArrowKeyStepperChildProps +} from './ArrowKeyStepper' +export { + AutoSizer, + AutoSizerProps, + Dimensions +} from './AutoSizer' +export { + CellMeasurer, + CellMeasurerCache, + CellMeasurerCacheParams, + CellMeasurerProps, + KeyMapper +} from './CellMeasurer' +export { + Collection, + CollectionCellGroupRenderer, + CollectionCellGroupRendererParams, + CollectionCellRenderer, + CollectionCellRendererParams, + CollectionCellSizeAndPosition, + CollectionCellSizeAndPositionGetter, + CollectionProps +} from './Collection' +export { + ColumnSizer, + ColumnSizerProps, + SizedColumnProps +} from './ColumnSizer' +export { + defaultCellRangeRenderer, + Grid, + CellSizeAndPositionManager, + ConfigureParams, + ContainerSizeAndOffset, + GetVisibleCellRangeParams, + GridCellProps, + GridCellRangeProps, + GridCellRangeRenderer, + GridCellRenderer, + GridProps, + GridState, + OverscanIndices, + OverscanIndicesGetterParams, + ScrollDirection, + ScrollParams, + SectionRenderedParams, + SizeAndPositionData, + VisibleCellRange +} from './Grid' +export { + InfiniteLoader, + InfiniteLoaderChildProps, + InfiniteLoaderProps +} from './InfiniteLoader' +export { + List, + ListProps, + ListRowProps, + ListRowRenderer +} from './List' +export { + createCellPositioner as createMasonryCellPositioner, + Masonry, + CellRenderer, + MasonryCellProps, + MasonryProps, + MasonryState, + OnCellsRenderedCallback, + OnScrollCallback, + Position, + Positioner +} from './Masonry' +export { + MultiGrid, + MultiGridProps, + MultiGridState +} from './MultiGrid' +export { + ScrollSync, + OnScrollParams, + ScrollSyncChildProps, + ScrollSyncProps, + ScrollSyncState +} from './ScrollSync' +export { + defaultTableCellDataGetter, + defaultTableCellRenderer, + defaultTableHeaderRenderer, + defaultTableHeaderRowRenderer, + defaultTableRowRenderer, + Table, + Column, + SortDirection, + SortIndicator, + ColumnProps, + HeaderMouseEventHandlerParams, + RowMouseEventHandlerParams, + SortDirectionType, + TableCellDataGetter, + TableCellDataGetterParams, + TableCellProps, + TableCellRenderer, + TableHeaderProps, + TableHeaderRenderer, + TableHeaderRowProps, + TableHeaderRowRenderer, + TableProps, + TableRowProps, + TableRowRenderer +} from './Table' +export { + WindowScroller, + WindowScrollerChildProps, + WindowScrollerProps, + WindowScrollerState +} from './WindowScroller' -export interface ArrowKeyStepperProps { - children?: React.StatelessComponent<{ - onSectionRendered: Function, - scrollToColumn: number, - scrollToRow: number - }>; - className?: string; - columnCount: number; - rowCount: number; -} -export class ArrowKeyStepper extends React.PureComponent { } - -export interface AutoSizerProps { - disableHeight?: boolean; - disableWidth?: boolean; - onResize?: (info: { height: number, width: number }) => any; -} -export class AutoSizer extends React.PureComponent { } - -export interface CellMeasurerProps { - cache?: CellMeasurerCache; - children?: React.StatelessComponent<{ - getColumnWidth: () => number, - getRowHeight: () => number, - resetMeasurements: () => any, - resetMeasurementsForColumn: (index: number) => any, - resetMeasurementsForRow: (index: number) => any, - }>; - columnIndex: number; - parent?: React.ReactType; - rowIndex: number; - style?: React.CSSProperties; -} -export class CellMeasurer extends React.PureComponent { } - -export type KeyMapper = ( - rowIndex: number, - columnIndex: number -) => any; -export type Map = { [key: string]: T }; -export type Cache = Map; -export type IndexParam = { - index: number -}; - -export type CellMeasurerCacheParams = { - defaultHeight?: number, - defaultWidth?: number, - fixedHeight?: boolean, - fixedWidth?: boolean, - minHeight?: number, - minWidth?: number, - keyMapper?: KeyMapper -} -export class CellMeasurerCache { - constructor(params: CellMeasurerCacheParams); - clear( - rowIndex: number, - columnIndex: number - ): void; - clearAll(): void; - columnWidth: (params: IndexParam) => number | undefined; - hasFixedHeight(): boolean; - hasFixedWidth(): boolean; - getHeight( - rowIndex: number, - columnIndex: number - ): number | undefined; - getWidth( - rowIndex: number, - columnIndex: number - ): number | undefined; - has( - rowIndex: number, - columnIndex: number - ): boolean; - rowHeight: (params: IndexParam) => number | undefined; - set( - rowIndex: number, - columnIndex: number, - width: number, - height: number - ): void; -} - -export type CollectionCellSizeAndPosition = { height: number, width: number, x: number, y: number }; -export type CollectionCellSizeAndPositionGetter = (params: IndexParam) => CollectionCellSizeAndPosition; - -export type CollectionCellGroupRendererParams = { - cellSizeAndPositionGetter: CollectionCellSizeAndPositionGetter, - indices: number[], - cellRenderer: CollectionCellRenderer -} -export type CollectionCellGroupRenderer = (params: CollectionCellGroupRendererParams) => React.ReactNode[]; -export type CollectionCellRendererParams = { - index: number, - key: string, - style?: React.CSSProperties -} -export type CollectionCellRenderer = (params: CollectionCellRendererParams) => React.ReactNode; -export type CollectionProps = { - 'aria-label'?: string; - cellCount: number; - cellGroupRenderer?: CollectionCellGroupRenderer, - cellRenderer: CollectionCellRenderer, - cellSizeAndPositionGetter: CollectionCellSizeAndPositionGetter, - sectionSize?: number; -}; -export class Collection extends React.PureComponent { } - -export interface ColumnSizerProps { - children?: React.StatelessComponent<{ adjustedWidth: number, getColumnWidth: () => number, registerChild: any }>; - columnMaxWidth?: number; - columnMinWidth?: number; - columnCount?: number; - width: number; -} -export class ColumnSizer extends React.PureComponent { } - -export type CellDataGetterParams = { - columnData?: any, - dataKey: string, - rowData: any -}; -export type CellRendererParams = { - cellData?: any, - columnData?: any, - dataKey: string, - rowData: any, - rowIndex: number -}; -export type HeaderRendererParams = { - columnData?: any, - dataKey: string, - disableSort?: boolean, - label?: string, - sortBy?: string, - sortDirection?: SortDirectionType -}; -export type HeaderRowRendererParams = { - className: string, - columns: React.ReactNode[], - style: React.CSSProperties, - scrollbarWidth: number, - height: number, - width: number -}; -export type RowRendererParams = { - className: string, - columns: Array, - index: number, - isScrolling: boolean, - onRowClick?: Function, - onRowDoubleClick?: Function, - onRowMouseOver?: Function, - onRowMouseOut?: Function, - rowData: any, - style: any -}; - -export type TableCellDataGetter = (params: CellDataGetterParams) => any; -export type TableCellRenderer = (params: CellRendererParams) => React.ReactNode; -export type TableHeaderRenderer = (params: HeaderRendererParams) => React.ReactNode; -export type TableHeaderRowRenderer = (params: HeaderRowRendererParams) => React.ReactNode; -export type TableRowRenderer = (params: RowRendererParams) => React.ReactNode; - -// https://github.com/bvaughn/react-virtualized/blob/master/docs/Column.md -export interface ColumnProps { - cellDataGetter?: TableCellDataGetter; - cellRenderer?: TableCellRenderer; - className?: string; - columnData?: any; - dataKey: any; - disableSort?: boolean; - flexGrow?: number; - flexShrink?: number; - headerClassName?: string; - headerRenderer?: TableHeaderRenderer; - label?: string; - maxWidth?: number; - minWidth?: number; - style?: React.CSSProperties; - width: number; -} -export class Column extends React.Component { } - -export type RowClickHandlerParams = { - rowData: { - columnData: Object, - id: string, - index: number - } -} - -// ref: https://github.com/bvaughn/react-virtualized/blob/master/docs/Table.md -export interface TableProps { - deferredMeasurementCache?: CellMeasurerCache; - autoHeight?: boolean; - children?: React.ReactChildren; - className?: string; - disableHeader?: boolean; - estimatedRowSize?: number; - gridClassName?: string; - gridStyle?: any; - headerClassName?: string; - headerHeight: number; - headerStyle?: any; - height?: number; - id?: string; - noRowsRender?: () => void; - onHeaderClick?: (dataKey: string, columnData: any) => void; - onRowClick?: (info: RowClickHandlerParams) => void; - onRowDoubleClick?: (info: RowClickHandlerParams) => void; - onRowMouseOut?: (info: RowClickHandlerParams) => void; - onRowMouseOver?: (info: RowClickHandlerParams) => void; - onRowsRendered?: (info: RowClickHandlerParams) => void; - overscanRowCount?: number; - onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; - rowClassName?: string | ((info: IndexParam) => string); - rowCount: number; - rowGetter?: (info: IndexParam) => any; - rowHeight: number | ((info: IndexParam) => number); - rowRenderer?: TableRowRenderer; - headerRowRenderer?: TableHeaderRowRenderer; - rowStyle?: React.CSSProperties | ((info: IndexParam) => React.CSSProperties); - scrollToAlignment?: string; - scrollToIndex?: number; - scrollTop?: number; - sort?: (info: { sortBy: string, sortDirection: SortDirectionType }) => void; - sortBy?: string; - sortDirection?: SortDirectionType; - style?: React.CSSProperties; - tabIndex?: number; - width?: number; -} -export class Table extends React.PureComponent { - forceUpdateGrid(): void; - /** See Grid#measureAllCells */ - measureAllRows(): void; - /** See Grid#recomputeGridSize */ - recomputeRowHeights(index?: number): void; - /** See Grid#scrollToCell */ - scrollToRow(index?: number): void; - Grid: Grid; -} - -export const defaultTableCellDataGetter: TableCellDataGetter; -export const defaultTableCellRenderer: TableCellRenderer; -export const defaultTableHeaderRenderer: () => React.ReactElement[]; -export const defaultTableHeaderRowRenderer: TableHeaderRowRenderer; -export const defaultTableRowRenderer: TableRowRenderer; - -interface ISortDirection { - /** - * Sort items in ascending order. - * This means arranging from the lowest value to the highest (e.g. a-z, 0-9). - */ - ASC: 'ASC', - - /** - * Sort items in descending order. - * This means arranging from the highest value to the lowest (e.g. z-a, 9-0). - */ - DESC: 'DESC' -} - -export const SortDirection: ISortDirection - -export type SortDirectionType = 'ASC' | 'DESC' - -export const SortIndicator: React.StatelessComponent<{ sortDirection: SortDirectionType }> - - -export type DefaultCellRangeRendererParams = { - cellCache: Object, - cellRenderer: Function, - columnSizeAndPositionManager: Object, - columnStartIndex: number, - columnStopIndex: number, - horizontalOffsetAdjustment: number, - isScrolling: boolean, - rowSizeAndPositionManager: Object, - rowStartIndex: number, - rowStopIndex: number, - scrollLeft: number, - scrollTop: number, - styleCache: Object, - verticalOffsetAdjustment: number, - visibleColumnIndices: Object, - visibleRowIndices: Object -}; -export function defaultCellRangeRenderer(params: DefaultCellRangeRendererParams): React.ReactElement; - - -export type GridCellRendererParams = { - columnIndex: number; - isScrolling: boolean; - isVisible: boolean; - key: string; - parent: Grid | List | Table; - rowIndex: number; - style: React.CSSProperties; -}; -export type GridCellRenderer = (params: GridCellRendererParams) => React.ReactNode; - -export type ConfigureParams = { - cellCount: number, - estimatedCellSize: number -}; -export type ContainerSizeAndOffset = { - containerSize: number, - offset: number -}; -export type SizeAndPositionData = { - offset: number, - size: number -}; -export type GetVisibleCellRangeParams = { - containerSize: number, - offset: number -}; -export type VisibleCellRange = { - start: number; - stop: number; -} - -export type CellSizeAndPositionManager = { - areOffsetsAdjusted(): boolean; - configure({ - cellCount, - estimatedCellSize - }: ConfigureParams): void; - getCellCount(): number; - getEstimatedCellSize(): number; - getLastMeasuredIndex(): number; - getOffsetAdjustment({ - containerSize, - offset // safe - }: ContainerSizeAndOffset): number; - /** - * This method returns the size and position for the cell at the specified index. - * It just-in-time calculates (or used cached values) for cells leading up to the index. - */ - getSizeAndPositionOfCell(index: number): SizeAndPositionData; - getSizeAndPositionOfLastMeasuredCell(): SizeAndPositionData; - /** - * Total size of all cells being measured. - * This value will be completedly estimated initially. - * As cells as measured the estimate will be updated. - */ - getTotalSize(): number; - /** - * Determines a new offset that ensures a certain cell is visible, given the current offset. - * If the cell is already visible then the current offset will be returned. - * If the current offset is too great or small, it will be adjusted just enough to ensure the specified index is visible. - * - * @param align Desired alignment within container; one of "auto" (default), "start", or "end" - * @param containerSize Size (width or height) of the container viewport - * @param currentOffset Container's current (x or y) offset - * @param totalSize Total size (width or height) of all cells - * @return Offset to use to ensure the specified cell is visible - */ - getUpdatedOffsetForIndex(params: { - align: string, - containerSize: number, - currentOffset: number, - targetIndex: number - }): number; - getVisibleCellRange(params: GetVisibleCellRangeParams): VisibleCellRange; - /** - * Clear all cached values for cells after the specified index. - * This method should be called for any cell that has changed its size. - * It will not immediately perform any calculations; they'll be performed the next time getSizeAndPositionOfCell() is called. - */ - resetCell(index: number): void -} - -export type GridCellRangeRendererParams = { - cellCache: Map, - cellRenderer: GridCellRenderer, - columnSizeAndPositionManager: CellSizeAndPositionManager, - columnStartIndex: number, - columnStopIndex: number, - isScrolling: boolean, - rowSizeAndPositionManager: CellSizeAndPositionManager, - rowStartIndex: number, - rowStopIndex: number, - scrollLeft: number, - scrollTop: number -} -export type GridCellRangeRenderer = (params: GridCellRangeRendererParams) => React.ReactNode[]; -// TODO add proper typing -export type GridProps = { - 'aria-label'?: string; - autoContainerWidth?: boolean; - autoHeight?: boolean; - cellRenderer: GridCellRenderer; - cellRangeRenderer?: GridCellRangeRenderer; - className?: string; - columnCount: number; - columnWidth: number | ((params: IndexParam) => number); - containerStyle?: React.CSSProperties; - deferredMeasurementCache?: CellMeasurerCache; - estimatedColumnSize?: number; - estimatedRowSize?: number; - getScrollbarSize?: () => number; - height: number; - id?: string; - noContentRenderer?: () => React.ReactNode; - onScroll?: (params: { clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }) => any; - onSectionRendered?: (params: { columnStartIndex: number, columnStopIndex: number, rowStartIndex: number, rowStopIndex: number }) => any; - overscanColumnCount?: number; - overscanIndicesGetter?: (params: { - cellCount: number, - overscanCellsCount: number, - scrollDirection: number, - startIndex: number, - stopIndex: number - }) => { overscanStartIndex: number, overscanStopIndex: number }; - overscanRowCount?: number; - rowHeight: number | ((params: IndexParam) => number); - rowCount: number; - scrollingResetTimeInterval?: number; - scrollLeft?: number; - scrollToAlignment?: 'auto' | 'end' | 'start' | 'center'; - scrollToColumn?: number; - scrollTop?: number; - scrollToRow?: number; - style?: React.CSSProperties; - tabIndex?: number; - width: number; -}; -export class Grid extends React.PureComponent { - /** - * Invalidate Grid size and recompute visible cells. - * This is a deferred wrapper for recomputeGridSize(). - * It sets a flag to be evaluated on cDM/cDU to avoid unnecessary renders. - * This method is intended for advanced use-cases like CellMeasurer. - */ - invalidateCellSizeAfterRender(params: { - columnIndex: number, - rowIndex: number - }): void; - /** - * Pre-measure all columns and rows in a Grid. - * Typically cells are only measured as needed and estimated sizes are used for cells that have not yet been measured. - * This method ensures that the next call to getTotalSize() returns an exact size (as opposed to just an estimated one). - */ - measureAllCells(): void; - /** - * Forced recompute of row heights and column widths. - * This function should be called if dynamic column or row sizes have changed but nothing else has. - * Since Grid only receives :columnCount and :rowCount it has no way of detecting when the underlying data changes. - */ - recomputeGridSize(params?: { - columnIndex?: number, - rowIndex?: number - }): void; - /** - * Ensure column and row are visible. - */ - scrollToCell(params: { - columnIndex: number, - rowIndex: number - }): void; -} - -export type InfiniteLoaderProps = { - children?: React.StatelessComponent<{ - onRowsRendered: (params: { startIndex: number, stopIndex: number }) => void, - registerChild: (registeredChild: any) => void - }>; - isRowLoaded: (params: IndexParam) => boolean; - loadMoreRows: (params: { startIndex: number, stopIndex: number }) => Promise; - minimumBatchSize?: number; - rowCount?: number; - threshold?: number; -}; -export class InfiniteLoader extends React.PureComponent { } -export type ListRowRenderer = (params: GridCellRendererParams & { index: number, style: React.CSSProperties }) => React.ReactNode; -export interface ListProps { - className?: string; - autoHeight?: boolean; - estimatedRowSize?: number; - height: number; - noRowsRenderer?: Function; - onRowsRendered?: (info: { overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }) => void; - onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; - overscanRowCount?: number; - rowHeight: number | ((info: IndexParam) => number); - rowRenderer: ListRowRenderer; - rowCount: number; - scrollToAlignment?: string; - scrollToIndex?: number; - scrollTop?: number; - style?: React.CSSProperties; - tabIndex?: number; - width: number; -} -export class List extends React.PureComponent { } - -export interface MultiGridProps { - fixedColumnCount: number; - fixedRowCount: number; - style: React.CSSProperties; - styleBottomLeftGrid: React.CSSProperties; - styleBottomRightGrid: React.CSSProperties; - styleTopLeftGrid: React.CSSProperties; - styleTopRightGrid: React.CSSProperties; -} -export class MultiGrid extends React.PureComponent { } - -export type ScrollSyncProps = { - children?: React.StatelessComponent<{ - clientHeight: number, - clientWidth: number, - onScroll: (params: { clientHeight: number, clientWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, scrollWidth: number }) => void, - scrollHeight: number, - scrollLeft: number, - scrollTop: number, - scrollWidth: number - }>; -}; -export class ScrollSync extends React.PureComponent { } -export type WindowScrollerRenderCallBackParams = { - height: number, - isScrolling: boolean, - scrollTop: number -}; - -export type WindowScrollerProps = { - children?: React.StatelessComponent; - onResize?: (prams: { height: number }) => void; - onScroll?: (params: { scrollTop: number }) => void; - scrollElement?: HTMLElement; -} -export class WindowScroller extends React.PureComponent { } +export { + Alignment, + Index, + IndexRange, + Map, + PositionInfo, + ScrollEventData, + ScrollPosition, + SizeAndPositionInfo, + SizeInfo +} from './genericTypes' \ No newline at end of file diff --git a/types/react-virtualized/react-virtualized-tests.tsx b/types/react-virtualized/react-virtualized-tests.tsx deleted file mode 100644 index aa1dc087a9..0000000000 --- a/types/react-virtualized/react-virtualized-tests.tsx +++ /dev/null @@ -1,532 +0,0 @@ -import * as React from "react"; -import * as ReactDOM from "react-dom"; - -import { - Collection, - SortDirection, - Grid, - ArrowKeyStepper, - AutoSizer, - CellMeasurer, - ColumnSizer, - InfiniteLoader, - ScrollSync, - WindowScroller, - WindowScrollerRenderCallBackParams, - List, - Column, - Table, -} from "react-virtualized"; - -/* - * Collection - */ - -function CollectionTest() { - const list = [ - { name: "Brian Vaughn", x: 13, y: 34, width: 123, size: 234, height: 123 } - ]; - - // Render your grid - ReactDOM.render( - list[index].name} - cellSizeAndPositionGetter={({ index }) => { - const datum = list[index]; - return { - height: datum.height, - width: datum.width, - x: datum.x, - y: datum.y - }; - }} - />, - document.getElementById("example") - ); -} - -function GridTest() { - // Grid data as an array of arrays - const list = [ - ['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */] - // And so on... - ]; - - // Render your grid - ReactDOM.render( - list[rowIndex][columnIndex]} - />, - document.getElementById('example') - ); -} - -function ListTest() { - // List data - const list = [ - { name: 'Brian Vaughn', occupation: 'Software Engineer', location: 'San Jose, CA, 95125' /* ... */ } - // And so on... - ]; - - // Render your List - ReactDOM.render( - list[index]} - />, - document.getElementById('example') - ); -} - -function TableTest() { - const list = [ - { name: 'Brian Vaughn', description: 'Software engineer' } - // And so on... - ]; - ReactDOM.render( - list[index]} - > - - -
, - document.getElementById('example') - ); -} - -function ArrowKeyStepperTest() { - const columnCount = 12; - const rowCount = 3; - - ReactDOM.render( - - {({ onSectionRendered, scrollToColumn, scrollToRow }) => ( - null} - columnCount={columnCount} - onSectionRendered={onSectionRendered} - rowCount={rowCount} - scrollToColumn={scrollToColumn} - scrollToRow={scrollToRow} - /> - )} - , - document.getElementById('example') - ); -} - -function AutoSizerTest() { - // List data as an array of strings - const list = [ - 'Brian Vaughn' - // And so on... - ]; - const _rowRenderer = ({ index, key, style }) => { - - const row = list[index]; - - return ( -
- {row} -
- ) - } - - // Render your list - ReactDOM.render( - - {({ width, height }) => ( - { - const row = list[index]; - - return ( -
- {row} -
- ) - }} - width={width} - /> - )} -
, - document.getElementById('example') - ); -} - -function CellMeasurerTest() { - const columnCount = 12; - const rowCount = 3; - const cellRenderer = ({ columnIndex, rowIndex }) => `${rowIndex}, ${columnIndex}`; - const fixedRowHeight = 42; - const height = 12; - const width = 12; - - ReactDOM.render( - - {({ getColumnWidth }) => ( - - )} - , - document.getElementById('example') - ); -} - -function ColumnSizerTest() { - ReactDOM.render( - - {({ adjustedWidth, getColumnWidth, registerChild }) => ( - "test"} - rowHeight={50} - rowCount={12} - width={adjustedWidth} - /> - )} - , - document.getElementById('example') - ); -} - -function InfiniteLoaderTest() { - const list: string[] = []; - - function isRowLoaded({ index }) { - return !!list[index]; - } - - function loadMoreRows({ startIndex, stopIndex }: { startIndex: number, stopIndex: number }) { - return new Promise(resolve => resolve(list.push('test'))); - } - - function rowRenderer({ index, key, style }) { - const content = list[index]; - - return ( -
- {content} -
- ) - } - - - // Render your list - ReactDOM.render( - - {({ onRowsRendered, registerChild }) => ( - - {({ width }) => ( - - )} - - )} - , - document.getElementById('example') - ); -} - -function ScrollSyncTest() { - function hexToRgb(hex) { - const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) - return result ? { - r: parseInt(result[1], 16), - g: parseInt(result[2], 16), - b: parseInt(result[3], 16) - } : null - } - - const LEFT_COLOR_FROM = hexToRgb('#471061') - const LEFT_COLOR_TO = hexToRgb('#BC3959') - const TOP_COLOR_FROM = hexToRgb('#000000') - const TOP_COLOR_TO = hexToRgb('#333333') - const columnWidth = 20; - const rowHeight = 10; - const overscanColumnCount = 10; - const overscanRowCount = 10; - const height = 10; - const rowCount = 100; - const columnCount = 100; - - - function mixColors(color1, color2, amount) { - const weight1 = amount - const weight2 = 1 - amount - - const r = Math.round(weight1 * color1.r + weight2 * color2.r) - const g = Math.round(weight1 * color1.g + weight2 * color2.g) - const b = Math.round(weight1 * color1.b + weight2 * color2.b) - - return { r, g, b } - }; - - function renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) { - return ( -
- {`C${columnIndex}`} -
- ) - }; - function renderLeftSideCell({ columnIndex, key, rowIndex, style }) { - const rowClass = rowIndex % 2 === 0 - ? columnIndex % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow' - : columnIndex % 2 !== 0 ? 'styles.evenRow' : 'styles.oddRow' - const classNames = [rowClass, 'styles.cell'].join(' ') - - return ( -
- {`R${rowIndex}, C${columnIndex}`} -
- ) - }; - - function renderHeaderCell({ columnIndex, key, rowIndex, style }) { - if (columnIndex < 1) { - return - } - - return renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) - }; - - function renderBodyCell({ columnIndex, key, rowIndex, style }) { - if (columnIndex < 1) { - return - } - - return renderLeftSideCell({ columnIndex, key, rowIndex, style }) - } - - return ( - - {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => { - const x = scrollLeft / (scrollWidth - clientWidth) - const y = scrollTop / (scrollHeight - clientHeight) - - const leftBackgroundColor = mixColors(LEFT_COLOR_FROM, LEFT_COLOR_TO, y) - const leftColor = '#ffffff' - const topBackgroundColor = mixColors(TOP_COLOR_FROM, TOP_COLOR_TO, x) - const topColor = '#ffffff' - const middleBackgroundColor = mixColors(leftBackgroundColor, topBackgroundColor, 0.5) - const middleColor = '#ffffff' - - return ( -
-
- -
-
- -
-
- - {({ width }) => ( -
-
- -
-
- -
-
- )} -
-
-
- ) - }} -
- ); -} - -function WindowScrollerTest() { - const onScroll = function ({scrollTop}: { scrollTop: number }) { }; - const onResize = function ({height}: { height: number }) { }; - const list = [ - { name: 'Brian Vaughn', description: 'Software engineer' } - // And so on... - ]; - ReactDOM.render( - - {({ height, isScrolling, scrollTop }) => ( - - {({ width }) => ( - list[index].name} - scrollTop={scrollTop} - width={width} - /> - )} - - )} - , - document.getElementById('example') - ); - // test that onScroll & onResize are optional - ReactDOM.render( - , - document.getElementById('example') - ); -} diff --git a/types/react-virtualized/tsconfig.json b/types/react-virtualized/tsconfig.json index ac62cf83d8..21a0e43a0d 100644 --- a/types/react-virtualized/tsconfig.json +++ b/types/react-virtualized/tsconfig.json @@ -19,6 +19,32 @@ }, "files": [ "index.d.ts", - "react-virtualized-tests.tsx" + "ArrowKeyStepper.d.ts", + "ArrowKeyStepper.test.tsx", + "AutoSizer.d.ts", + "AutoSizer.test.tsx", + "CellMeasurer.d.ts", + "CellMeasurer.test.tsx", + "Collection.d.ts", + "Collection.test.tsx", + "ColumnSizer.d.ts", + "ColumnSizer.test.tsx", + "genericTypes.d.ts", + "Grid.d.ts", + "Grid.test.tsx", + "InfiniteLoader.d.ts", + "InfiniteLoader.test.tsx", + "List.d.ts", + "List.test.tsx", + "Masonry.d.ts", + "Masonry.test.tsx", + "MultiGrid.d.ts", + "MultiGrid.test.tsx", + "ScrollSync.d.ts", + "ScrollSync.test.tsx", + "Table.d.ts", + "Table.test.tsx", + "WindowScroller.d.ts", + "WindowScroller.test.tsx" ] } \ No newline at end of file From 62ad9abc10b38daae1940f0345b094882f4d5f6f Mon Sep 17 00:00:00 2001 From: Kalle Ott Date: Mon, 27 Mar 2017 21:32:02 +0200 Subject: [PATCH 06/31] fixed linting error --- types/react-virtualized/Collection.d.ts | 6 +++--- types/react-virtualized/tslint.json | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 types/react-virtualized/tslint.json diff --git a/types/react-virtualized/Collection.d.ts b/types/react-virtualized/Collection.d.ts index 7e11946eb1..52a69de286 100644 --- a/types/react-virtualized/Collection.d.ts +++ b/types/react-virtualized/Collection.d.ts @@ -31,11 +31,11 @@ export type CollectionProps = { sectionSize?: number; className?: string; height: number; - width:number; + width: number; horizontalOverscanSize?: number; noContentRenderer?: () => JSX.Element; - scrollToCell?: number; - verticalOverscanSize?:number; + scrollToCell?: number; + verticalOverscanSize?: number; }; /** diff --git a/types/react-virtualized/tslint.json b/types/react-virtualized/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/types/react-virtualized/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file From 97fd2fc247ed9996d7faf87f0ca3cd3e67eef208 Mon Sep 17 00:00:00 2001 From: Kalle Ott Date: Mon, 27 Mar 2017 21:54:40 +0200 Subject: [PATCH 07/31] replaced mulstiple testfiles with on to obey definitely typed naming --- .../ArrowKeyStepper.test.tsx | 71 - types/react-virtualized/AutoSizer.test.tsx | 47 - types/react-virtualized/CellMeasurer.test.tsx | 74 - types/react-virtualized/Collection.test.tsx | 160 -- types/react-virtualized/ColumnSizer.test.tsx | 113 -- types/react-virtualized/Grid.test.tsx | 207 -- .../react-virtualized/InfiniteLoader.test.tsx | 138 -- types/react-virtualized/List.test.tsx | 160 -- types/react-virtualized/Masonry.test.tsx | 200 -- types/react-virtualized/MultiGrid.test.tsx | 105 - types/react-virtualized/ScrollSync.test.tsx | 222 --- types/react-virtualized/Table.test.tsx | 196 -- .../react-virtualized/WindowScroller.test.tsx | 88 - .../react-virtualized-tests.tsx | 1753 +++++++++++++++++ types/react-virtualized/tsconfig.json | 14 +- 15 files changed, 1754 insertions(+), 1794 deletions(-) delete mode 100644 types/react-virtualized/ArrowKeyStepper.test.tsx delete mode 100644 types/react-virtualized/AutoSizer.test.tsx delete mode 100644 types/react-virtualized/CellMeasurer.test.tsx delete mode 100644 types/react-virtualized/Collection.test.tsx delete mode 100644 types/react-virtualized/ColumnSizer.test.tsx delete mode 100644 types/react-virtualized/Grid.test.tsx delete mode 100644 types/react-virtualized/InfiniteLoader.test.tsx delete mode 100644 types/react-virtualized/List.test.tsx delete mode 100644 types/react-virtualized/Masonry.test.tsx delete mode 100644 types/react-virtualized/MultiGrid.test.tsx delete mode 100644 types/react-virtualized/ScrollSync.test.tsx delete mode 100644 types/react-virtualized/Table.test.tsx delete mode 100644 types/react-virtualized/WindowScroller.test.tsx create mode 100644 types/react-virtualized/react-virtualized-tests.tsx diff --git a/types/react-virtualized/ArrowKeyStepper.test.tsx b/types/react-virtualized/ArrowKeyStepper.test.tsx deleted file mode 100644 index 8204aafdd6..0000000000 --- a/types/react-virtualized/ArrowKeyStepper.test.tsx +++ /dev/null @@ -1,71 +0,0 @@ -/** @flow */ -import * as React from 'react'; -import { PureComponent } from 'react' -import { ArrowKeyStepper, AutoSizer, Grid } from 'react-virtualized' - -export default class ArrowKeyStepperExample extends PureComponent { - constructor(props) { - super(props) - - this._getColumnWidth = this._getColumnWidth.bind(this) - this._getRowHeight = this._getRowHeight.bind(this) - this._cellRenderer = this._cellRenderer.bind(this) - } - - render() { - const { mode } = this.state - - return ( - - - {({ onSectionRendered, scrollToColumn, scrollToRow }) => ( -
- - - {({ width }) => ( - this._cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style })} - rowHeight={this._getRowHeight} - rowCount={100} - scrollToColumn={scrollToColumn} - scrollToRow={scrollToRow} - width={width} - /> - )} - -
- )} -
- ) - } - - _getColumnWidth({ index }) { - return (1 + (index % 3)) * 60 - } - - _getRowHeight({ index }) { - return (1 + (index % 3)) * 30 - } - - _cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style }) { - - return ( -
- {`r:${rowIndex}, c:${columnIndex}`} -
- ) - } -} diff --git a/types/react-virtualized/AutoSizer.test.tsx b/types/react-virtualized/AutoSizer.test.tsx deleted file mode 100644 index 670d77b52b..0000000000 --- a/types/react-virtualized/AutoSizer.test.tsx +++ /dev/null @@ -1,47 +0,0 @@ -/** @flow */ -import * as React from 'react'; -import { PureComponent } from 'react' -import { AutoSizer, List } from 'react-virtualized' - -export default class AutoSizerExample extends PureComponent { - constructor(props) { - super(props) - - this._rowRenderer = this._rowRenderer.bind(this) - } - - render() { - const { list } = this.context - const { hideDescription } = this.state - - return ( - - {({ width, height }) => ( - - )} - - ) - } - - _rowRenderer({ index, key, style }) { - const { list } = this.context - const row = list.get(index) - - return ( -
- {row.name} -
- ) - } -} diff --git a/types/react-virtualized/CellMeasurer.test.tsx b/types/react-virtualized/CellMeasurer.test.tsx deleted file mode 100644 index 5b510704c0..0000000000 --- a/types/react-virtualized/CellMeasurer.test.tsx +++ /dev/null @@ -1,74 +0,0 @@ -/** @flow */ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { CellMeasurer, CellMeasurerCache, List } from 'react-virtualized' - -export default class DynamicHeightList extends PureComponent { - - _cache: CellMeasurerCache - - constructor(props, context) { - super(props, context) - - this._cache = new CellMeasurerCache({ - fixedWidth: true, - minHeight: 50 - }) - - this._rowRenderer = this._rowRenderer.bind(this) - } - - render() { - const { width } = this.props - - return ( - - ) - } - - _rowRenderer({ index, isScrolling, key, parent, style }) { - const { getClassName, list } = this.props - - const datum = list.get(index % list.size) - const classNames = getClassName({ columnIndex: 0, rowIndex: index }) - - const imageWidth = 300 - const imageHeight = datum.size * 2 - - const source = `http://fillmurray.com/${imageWidth}/${imageHeight}` - - return ( - - {({ measure }) => ( -
- -
- )} -
- ) - } -} diff --git a/types/react-virtualized/Collection.test.tsx b/types/react-virtualized/Collection.test.tsx deleted file mode 100644 index 8a7860b3c7..0000000000 --- a/types/react-virtualized/Collection.test.tsx +++ /dev/null @@ -1,160 +0,0 @@ -/** @flow */ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { AutoSizer, Collection } from 'react-virtualized' - -// Defines a pattern of sizes and positions for a range of 10 rotating cells -// These cells cover an area of 600 (wide) x 400 (tall) -const GUTTER_SIZE = 3 -const CELL_WIDTH = 75 - -export default class CollectionExample extends PureComponent { - - _columnYMap: any; - - constructor(props, context) { - super(props, context) - - this.context = context; - - this.state = { - cellCount: context.list.size, - columnCount: this._getColumnCount(context.list.size), - height: 300, - horizontalOverscanSize: 0, - scrollToCell: undefined, - showScrollingPlaceholder: false, - verticalOverscanSize: 0 - } - - this._columnYMap = [] - - this._cellRenderer = this._cellRenderer.bind(this) - this._cellSizeAndPositionGetter = this._cellSizeAndPositionGetter.bind(this) - this._noContentRenderer = this._noContentRenderer.bind(this) - this._onCellCountChange = this._onCellCountChange.bind(this) - this._onHeightChange = this._onHeightChange.bind(this) - this._onHorizontalOverscanSizeChange = this._onHorizontalOverscanSizeChange.bind(this) - this._onScrollToCellChange = this._onScrollToCellChange.bind(this) - this._onVerticalOverscanSizeChange = this._onVerticalOverscanSizeChange.bind(this) - } - - render() { - const { cellCount, height, horizontalOverscanSize, scrollToCell, showScrollingPlaceholder, verticalOverscanSize } = this.state - - return ( - - {({ width }) => ( - - )} - - ) - } - - _cellRenderer({ index, isScrolling, key, style }) { - const { list } = this.context - const { showScrollingPlaceholder } = this.state - - const datum = list.get(index % list.size) - - // Customize style - style.backgroundColor = datum.color - - return ( -
- {showScrollingPlaceholder && isScrolling ? '...' : index} -
- ) - } - - _cellSizeAndPositionGetter({ index }) { - const { list } = this.context - const { columnCount } = this.state - - const columnPosition = index % (columnCount || 1) - const datum = list.get(index % list.size) - - // Poor man's Masonry layout; columns won't all line up equally with the bottom. - const height = datum.size - const width = CELL_WIDTH - const x = columnPosition * (GUTTER_SIZE + width) - const y = this._columnYMap[columnPosition] || 0 - - this._columnYMap[columnPosition] = y + height + GUTTER_SIZE - - return { - height, - width, - x, - y - } - } - - _getColumnCount(cellCount) { - return Math.round(Math.sqrt(cellCount)) - } - - _onHorizontalOverscanSizeChange(event) { - const horizontalOverscanSize = parseInt(event.target.value, 10) || 0 - - this.setState({ horizontalOverscanSize }) - } - - _noContentRenderer() { - return ( -
- No cells -
- ) - } - - _onCellCountChange(event) { - const cellCount = parseInt(event.target.value, 10) || 0 - - this._columnYMap = [] - - this.setState({ - cellCount, - columnCount: this._getColumnCount(cellCount) - }) - } - - _onHeightChange(event) { - const height = parseInt(event.target.value, 10) || 0 - - this.setState({ height }) - } - - _onScrollToCellChange(event) { - const { cellCount } = this.state - - let scrollToCell = Math.min(cellCount - 1, parseInt(event.target.value, 10)) - - if (isNaN(scrollToCell)) { - scrollToCell = undefined - } - - this.setState({ scrollToCell }) - } - - _onVerticalOverscanSizeChange(event) { - const verticalOverscanSize = parseInt(event.target.value, 10) || 0 - - this.setState({ verticalOverscanSize }) - } -} diff --git a/types/react-virtualized/ColumnSizer.test.tsx b/types/react-virtualized/ColumnSizer.test.tsx deleted file mode 100644 index 97de9fff45..0000000000 --- a/types/react-virtualized/ColumnSizer.test.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import * as React from 'react' -import { PureComponent } from 'react' -import { AutoSizer, ColumnSizer, Grid } from 'react-virtualized' - -export default class ColumnSizerExample extends PureComponent { - constructor(props) { - super(props) - - this._noColumnMaxWidthChange = this._noColumnMaxWidthChange.bind(this) - this._noColumnMinWidthChange = this._noColumnMinWidthChange.bind(this) - this._onColumnCountChange = this._onColumnCountChange.bind(this) - this._noContentRenderer = this._noContentRenderer.bind(this) - this._cellRenderer = this._cellRenderer.bind(this) - } - - render() { - const { - columnMaxWidth, - columnMinWidth, - columnCount - } = this.state - - return ( -
- - {({ width }) => ( - - {({ adjustedWidth, getColumnWidth, registerChild }) => ( -
- -
- )} -
- )} -
-
- ) - } - - _noColumnMaxWidthChange(event) { - let columnMaxWidth = parseInt(event.target.value, 10) - - if (isNaN(columnMaxWidth)) { - columnMaxWidth = undefined - } else { - columnMaxWidth = Math.min(1000, columnMaxWidth) - } - - this.setState({ columnMaxWidth }) - } - - _noColumnMinWidthChange(event) { - let columnMinWidth = parseInt(event.target.value, 10) - - if (isNaN(columnMinWidth)) { - columnMinWidth = undefined - } else { - columnMinWidth = Math.max(1, columnMinWidth) - } - - this.setState({ columnMinWidth }) - } - - _onColumnCountChange(event) { - this.setState({ columnCount: parseInt(event.target.value, 10) || 0 }) - } - - _noContentRenderer() { - return ( -
- No cells -
- ) - } - - _cellRenderer({ columnIndex, key, rowIndex, style }) { - const className = columnIndex === 0 - ? 'styles.firstCell' - : 'styles.cell' - - return ( -
- {`R:${rowIndex}, C:${columnIndex}`} -
- ) - } -} diff --git a/types/react-virtualized/Grid.test.tsx b/types/react-virtualized/Grid.test.tsx deleted file mode 100644 index 634fcdc137..0000000000 --- a/types/react-virtualized/Grid.test.tsx +++ /dev/null @@ -1,207 +0,0 @@ -/** @flow */ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { AutoSizer, Grid } from 'react-virtualized' - -export default class GridExample extends PureComponent { - - - constructor(props, context) { - super(props, context) - - this.state = { - columnCount: 1000, - height: 300, - overscanColumnCount: 0, - overscanRowCount: 10, - rowHeight: 40, - rowCount: 1000, - scrollToColumn: undefined, - scrollToRow: undefined, - useDynamicRowHeight: false - } - - this._cellRenderer = this._cellRenderer.bind(this) - this._getColumnWidth = this._getColumnWidth.bind(this) - this._getRowClassName = this._getRowClassName.bind(this) - this._getRowHeight = this._getRowHeight.bind(this) - this._noContentRenderer = this._noContentRenderer.bind(this) - this._onColumnCountChange = this._onColumnCountChange.bind(this) - this._onRowCountChange = this._onRowCountChange.bind(this) - this._onScrollToColumnChange = this._onScrollToColumnChange.bind(this) - this._onScrollToRowChange = this._onScrollToRowChange.bind(this) - this._renderBodyCell = this._renderBodyCell.bind(this) - this._renderLeftSideCell = this._renderLeftSideCell.bind(this) - } - - render() { - const { - columnCount, - height, - overscanColumnCount, - overscanRowCount, - rowHeight, - rowCount, - scrollToColumn, - scrollToRow, - useDynamicRowHeight - } = this.state - - return ( - - - {({ width }) => ( - - )} - - ) - } - - _cellRenderer({ columnIndex, key, rowIndex, style }) { - if (columnIndex === 0) { - return this._renderLeftSideCell({ key, rowIndex, style }) - } else { - return this._renderBodyCell({ columnIndex, key, rowIndex, style }) - } - } - - _getColumnWidth({ index }) { - switch (index) { - case 0: - return 50 - case 1: - return 100 - case 2: - return 300 - default: - return 80 - } - } - - _getDatum(index) { - const { list } = this.context - - return list.get(index % list.size) - } - - _getRowClassName(row) { - return row % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow' - } - - _getRowHeight({ index }) { - return this._getDatum(index).size - } - - _noContentRenderer() { - return ( -
- No cells -
- ) - } - - _renderBodyCell({ columnIndex, key, rowIndex, style }) { - const rowClass = this._getRowClassName(rowIndex) - const datum = this._getDatum(rowIndex) - - let content - - switch (columnIndex) { - case 1: - content = datum.name - break - case 2: - content = datum.random - break - default: - content = `r:${rowIndex}, c:${columnIndex}` - break - } - - return ( -
- {content} -
- ) - } - - _renderLeftSideCell({ key, rowIndex, style }) { - const datum = this._getDatum(rowIndex) - - // Don't modify styles. - // These are frozen by React now (as of 16.0.0). - // Since Grid caches and re-uses them, they aren't safe to modify. - style = { - ...style, - backgroundColor: datum.color - } - - return ( -
- {datum.name.charAt(0)} -
- ) - } - - _updateUseDynamicRowHeights(value) { - this.setState({ - useDynamicRowHeight: value - }) - } - - _onColumnCountChange(event) { - const columnCount = parseInt(event.target.value, 10) || 0 - - this.setState({ columnCount }) - } - - _onRowCountChange(event) { - const rowCount = parseInt(event.target.value, 10) || 0 - - this.setState({ rowCount }) - } - - _onScrollToColumnChange(event) { - const { columnCount } = this.state - let scrollToColumn = Math.min(columnCount - 1, parseInt(event.target.value, 10)) - - if (isNaN(scrollToColumn)) { - scrollToColumn = undefined - } - - this.setState({ scrollToColumn }) - } - - _onScrollToRowChange(event) { - const { rowCount } = this.state - let scrollToRow = Math.min(rowCount - 1, parseInt(event.target.value, 10)) - - if (isNaN(scrollToRow)) { - scrollToRow = undefined - } - - this.setState({ scrollToRow }) - } -} diff --git a/types/react-virtualized/InfiniteLoader.test.tsx b/types/react-virtualized/InfiniteLoader.test.tsx deleted file mode 100644 index 0509f46216..0000000000 --- a/types/react-virtualized/InfiniteLoader.test.tsx +++ /dev/null @@ -1,138 +0,0 @@ -/** @flow */ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { AutoSizer, InfiniteLoader, List } from 'react-virtualized' - -const STATUS_LOADING = 1 -const STATUS_LOADED = 2 - -export default class InfiniteLoaderExample extends PureComponent { - _timeoutIdMap: any; - - constructor(props) { - super(props) - - this._timeoutIdMap = {} - - this._clearData = this._clearData.bind(this) - this._isRowLoaded = this._isRowLoaded.bind(this) - this._loadMoreRows = this._loadMoreRows.bind(this) - this._rowRenderer = this._rowRenderer.bind(this) - } - - componentWillUnmount() { - Object.keys(this._timeoutIdMap).forEach(timeoutId => { - clearTimeout(timeoutId as any) - }) - } - - render() { - const { list } = this.context - const { loadedRowCount, loadingRowCount } = this.state - - return ( - - {({ onRowsRendered, registerChild }) => ( - - {({ width }) => ( - - )} - - )} - - ) - } - - _clearData() { - this.setState({ - loadedRowCount: 0, - loadedRowsMap: {}, - loadingRowCount: 0 - }) - } - - _isRowLoaded({ index }) { - const { loadedRowsMap } = this.state - return !!loadedRowsMap[index] // STATUS_LOADING or STATUS_LOADED - } - - _loadMoreRows({ startIndex, stopIndex }) { - const { loadedRowsMap, loadingRowCount } = this.state - const increment = stopIndex - startIndex + 1 - - for (var i = startIndex; i <= stopIndex; i++) { - loadedRowsMap[i] = STATUS_LOADING - } - - this.setState({ - loadingRowCount: loadingRowCount + increment - }) - - const timeoutId = setTimeout(() => { - const { loadedRowCount, loadingRowCount } = this.state - - delete this._timeoutIdMap[timeoutId] - - for (var i = startIndex; i <= stopIndex; i++) { - loadedRowsMap[i] = STATUS_LOADED - } - - this.setState({ - loadingRowCount: loadingRowCount - increment, - loadedRowCount: loadedRowCount + increment - }) - - promiseResolver() - }, 1000 + Math.round(Math.random() * 2000)) - - this._timeoutIdMap[timeoutId] = true - - let promiseResolver - - return new Promise(resolve => { - promiseResolver = resolve - }) - } - - _rowRenderer({ index, key, style }) { - const { list } = this.context - const { loadedRowsMap } = this.state - - const row = list.get(index) - let content - - if (loadedRowsMap[index] === STATUS_LOADED) { - content = row.name - } else { - content = ( -
- ) - } - - return ( -
- {content} -
- ) - } -} diff --git a/types/react-virtualized/List.test.tsx b/types/react-virtualized/List.test.tsx deleted file mode 100644 index 86763a95f8..0000000000 --- a/types/react-virtualized/List.test.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { AutoSizer, List } from 'react-virtualized' - -export default class ListExample extends PureComponent { - - constructor(props, context) { - super(props, context) - - this.state = { - listHeight: 300, - listRowHeight: 50, - overscanRowCount: 10, - rowCount: context.list.size, - scrollToIndex: undefined, - showScrollingPlaceholder: false, - useDynamicRowHeight: false - } - - this._getRowHeight = this._getRowHeight.bind(this) - this._noRowsRenderer = this._noRowsRenderer.bind(this) - this._onRowCountChange = this._onRowCountChange.bind(this) - this._onScrollToRowChange = this._onScrollToRowChange.bind(this) - this._rowRenderer = this._rowRenderer.bind(this) - } - - render() { - const { - listHeight, - listRowHeight, - overscanRowCount, - rowCount, - scrollToIndex, - showScrollingPlaceholder, - useDynamicRowHeight - } = this.state - - return ( - - {({ width }) => ( - - )} - - ) - } - - _getDatum(index) { - const { list } = this.context - - return list.get(index % list.size) - } - - _getRowHeight({ index }) { - return this._getDatum(index).size - } - - _noRowsRenderer() { - return ( -
- No rows -
- ) - } - - _onRowCountChange(event) { - const rowCount = parseInt(event.target.value, 10) || 0 - - this.setState({ rowCount }) - } - - _onScrollToRowChange(event) { - const { rowCount } = this.state - let scrollToIndex = Math.min(rowCount - 1, parseInt(event.target.value, 10)) - - if (isNaN(scrollToIndex)) { - scrollToIndex = undefined - } - - this.setState({ scrollToIndex }) - } - - _rowRenderer({ index, isScrolling, key, style }) { - const { - showScrollingPlaceholder, - useDynamicRowHeight - } = this.state - - if ( - showScrollingPlaceholder && - isScrolling - ) { - return ( -
- Scrolling... -
- ) - } - - const datum = this._getDatum(index) - - let additionalContent - - if (useDynamicRowHeight) { - switch (datum.size) { - case 75: - additionalContent =
It is medium-sized.
- break - case 100: - additionalContent =
It is large-sized.
It has a 3rd row.
- break - } - } - - return ( -
-
- {datum.name.charAt(0)} -
-
-
- {datum.name} -
-
- This is row {index} -
- {additionalContent} -
- {useDynamicRowHeight && - - {datum.size}px - - } -
- ) - } -} diff --git a/types/react-virtualized/Masonry.test.tsx b/types/react-virtualized/Masonry.test.tsx deleted file mode 100644 index 902e5498c5..0000000000 --- a/types/react-virtualized/Masonry.test.tsx +++ /dev/null @@ -1,200 +0,0 @@ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { - CellMeasurer, - CellMeasurerCache, - AutoSizer, - WindowScroller, - createMasonryCellPositioner as createCellPositioner, - Positioner, - Masonry, - MasonryCellProps -} from 'react-virtualized' - -export default class GridExample extends PureComponent { - _columnCount: number; - _cache: CellMeasurerCache; - _columnHeights: any; - _width: number; - _height: number; - _scrollTop: number; - _cellPositioner?: Positioner; - _masonry: Masonry; - - constructor(props, context) { - super(props, context) - - this._columnCount = 0 - - this._cache = new CellMeasurerCache({ - defaultHeight: 250, - defaultWidth: 200, - fixedWidth: true - }) - - this._columnHeights = {} - - this.state = { - columnWidth: 200, - height: 300, - gutterSize: 10, - windowScrollerEnabled: false - } - - this._cellRenderer = this._cellRenderer.bind(this) - this._onResize = this._onResize.bind(this) - this._renderAutoSizer = this._renderAutoSizer.bind(this) - this._renderMasonry = this._renderMasonry.bind(this) - this._setMasonryRef = this._setMasonryRef.bind(this) - } - - render() { - const { - columnWidth, - height, - gutterSize, - windowScrollerEnabled - } = this.state - - let child - - if (windowScrollerEnabled) { - child = ( - - {this._renderAutoSizer} - - ) - } else { - child = this._renderAutoSizer({ height }) - } - - return ( -
- {child} -
- ) - } - - _calculateColumnCount() { - const { - columnWidth, - gutterSize - } = this.state - - this._columnCount = Math.floor(this._width / (columnWidth + gutterSize)) - } - - _cellRenderer({ index, key, parent, style }: MasonryCellProps) { - const { list } = this.context - const { columnWidth } = this.state - - const datum = list.get(index % list.size) - - return ( - -
-
- {datum.random} -
- - ) - } - - _initCellPositioner() { - if (typeof this._cellPositioner === 'undefined') { - const { - columnWidth, - gutterSize - } = this.state - - this._cellPositioner = createCellPositioner({ - cellMeasurerCache: this._cache, - columnCount: this._columnCount, - columnWidth, - spacer: gutterSize - }) - } - } - - _onResize({ height, width }) { - this._width = width - - this._columnHeights = {} - this._calculateColumnCount() - this._resetCellPositioner() - this._masonry.recomputeCellPositions() - } - - _renderAutoSizer({ height, scrollTop }: { height: number, scrollTop?: number }) { - this._height = height - this._scrollTop = scrollTop - - return ( - - {this._renderMasonry} - - ) - } - - _renderMasonry({ width }) { - this._width = width - - this._calculateColumnCount() - this._initCellPositioner() - - const { height, windowScrollerEnabled } = this.state - - return ( - - ) - } - - _resetCellPositioner() { - const { - columnWidth, - gutterSize - } = this.state - - this._cellPositioner.reset({ - columnCount: this._columnCount, - columnWidth, - spacer: gutterSize - }) - } - - _setMasonryRef(ref) { - this._masonry = ref - } -} diff --git a/types/react-virtualized/MultiGrid.test.tsx b/types/react-virtualized/MultiGrid.test.tsx deleted file mode 100644 index f2f3af9397..0000000000 --- a/types/react-virtualized/MultiGrid.test.tsx +++ /dev/null @@ -1,105 +0,0 @@ -/** @flow */ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { AutoSizer, MultiGrid } from 'react-virtualized' - -const STYLE: React.CSSProperties = { - border: '1px solid #ddd', - overflow: 'hidden' -} -const STYLE_BOTTOM_LEFT_GRID: React.CSSProperties = { - borderRight: '2px solid #aaa', - backgroundColor: '#f7f7f7' -} -const STYLE_TOP_LEFT_GRID: React.CSSProperties = { - borderBottom: '2px solid #aaa', - borderRight: '2px solid #aaa', - fontWeight: 'bold' -} -const STYLE_TOP_RIGHT_GRID: React.CSSProperties = { - borderBottom: '2px solid #aaa', - fontWeight: 'bold' -} - -export default class MultiGridExample extends PureComponent { - state - _onFixedColumnCountChange - _onFixedRowCountChange - _onScrollToColumnChange - _onScrollToRowChange - - constructor(props, context) { - super(props, context) - - this.state = { - fixedColumnCount: 2, - fixedRowCount: 1, - scrollToColumn: 0, - scrollToRow: 0 - } - - this._cellRenderer = this._cellRenderer.bind(this) - this._onFixedColumnCountChange = this._createEventHandler('fixedColumnCount') - this._onFixedRowCountChange = this._createEventHandler('fixedRowCount') - this._onScrollToColumnChange = this._createEventHandler('scrollToColumn') - this._onScrollToRowChange = this._createEventHandler('scrollToRow') - } - - render() { - return ( - - {({ width }) => ( - - )} - - ) - } - - _cellRenderer({ columnIndex, key, rowIndex, style }) { - return ( -
- {columnIndex}, {rowIndex} -
- ) - } - - _createEventHandler(property) { - return (event) => { - const value = parseInt(event.target.value, 10) || 0 - - this.setState({ - [property]: value - }) - } - } - - _createLabeledInput(property, eventHandler) { - const value = this.state[property] - - return ( - `` - ) - } -} diff --git a/types/react-virtualized/ScrollSync.test.tsx b/types/react-virtualized/ScrollSync.test.tsx deleted file mode 100644 index 9919b72ab3..0000000000 --- a/types/react-virtualized/ScrollSync.test.tsx +++ /dev/null @@ -1,222 +0,0 @@ -import * as React from 'react' -import { PureComponent } from 'react' -import { AutoSizer, Grid, ScrollSync } from 'react-virtualized' - -const LEFT_COLOR_FROM = hexToRgb('#471061') -const LEFT_COLOR_TO = hexToRgb('#BC3959') -const TOP_COLOR_FROM = hexToRgb('#000000') -const TOP_COLOR_TO = hexToRgb('#333333') - -function scrollbarSize() { return 42; } -export default class GridExample extends PureComponent { - state - constructor(props, context) { - super(props, context) - - this.state = { - columnWidth: 75, - columnCount: 50, - height: 300, - overscanColumnCount: 0, - overscanRowCount: 5, - rowHeight: 40, - rowCount: 100 - } - - this._renderBodyCell = this._renderBodyCell.bind(this) - this._renderHeaderCell = this._renderHeaderCell.bind(this) - this._renderLeftSideCell = this._renderLeftSideCell.bind(this) - } - - render() { - const { - columnCount, - columnWidth, - height, - overscanColumnCount, - overscanRowCount, - rowHeight, - rowCount - } = this.state - - return ( - - - {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => { - const x = scrollLeft / (scrollWidth - clientWidth) - const y = scrollTop / (scrollHeight - clientHeight) - - const leftBackgroundColor = mixColors(LEFT_COLOR_FROM, LEFT_COLOR_TO, y) - const leftColor = '#ffffff' - const topBackgroundColor = mixColors(TOP_COLOR_FROM, TOP_COLOR_TO, x) - const topColor = '#ffffff' - const middleBackgroundColor = mixColors(leftBackgroundColor, topBackgroundColor, 0.5) - const middleColor = '#ffffff' - - return ( -
-
- -
-
- -
-
- - {({ width }) => ( -
-
- -
-
- -
-
- )} -
-
-
- ) - }} -
- ) - } - - _renderBodyCell({ columnIndex, key, rowIndex, style }) { - if (columnIndex < 1) { - return - } - - return this._renderLeftSideCell({ columnIndex, key, rowIndex, style }) - } - - _renderHeaderCell({ columnIndex, key, rowIndex, style }) { - if (columnIndex < 1) { - return - } - - return this._renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) - } - - _renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) { - return ( -
- {`C${columnIndex}`} -
- ) - } - - _renderLeftSideCell({ columnIndex, key, rowIndex, style }) { - return ( -
- {`R${rowIndex}, C${columnIndex}`} -
- ) - } -} - -function hexToRgb(hex) { - const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) - return result ? { - r: parseInt(result[1], 16), - g: parseInt(result[2], 16), - b: parseInt(result[3], 16) - } : null -} - -/** - * Ported from sass implementation in C - * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 - */ -function mixColors(color1, color2, amount) { - const weight1 = amount - const weight2 = 1 - amount - - const r = Math.round(weight1 * color1.r + weight2 * color2.r) - const g = Math.round(weight1 * color1.g + weight2 * color2.g) - const b = Math.round(weight1 * color1.b + weight2 * color2.b) - - return { r, g, b } -} diff --git a/types/react-virtualized/Table.test.tsx b/types/react-virtualized/Table.test.tsx deleted file mode 100644 index 8714634d1d..0000000000 --- a/types/react-virtualized/Table.test.tsx +++ /dev/null @@ -1,196 +0,0 @@ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { AutoSizer, Column, Table, SortDirection, SortIndicator } from 'react-virtualized' - -export default class TableExample extends PureComponent { - state; - context; - constructor(props, context) { - super(props, context) - - this.state = { - disableHeader: false, - headerHeight: 30, - height: 270, - hideIndexRow: false, - overscanRowCount: 10, - rowHeight: 40, - rowCount: 1000, - scrollToIndex: undefined, - sortBy: 'index', - sortDirection: SortDirection.ASC, - useDynamicRowHeight: false - } - - this._getRowHeight = this._getRowHeight.bind(this) - this._headerRenderer = this._headerRenderer.bind(this) - this._noRowsRenderer = this._noRowsRenderer.bind(this) - this._onRowCountChange = this._onRowCountChange.bind(this) - this._onScrollToRowChange = this._onScrollToRowChange.bind(this) - this._rowClassName = this._rowClassName.bind(this) - this._sort = this._sort.bind(this) - } - - render() { - const { - disableHeader, - headerHeight, - height, - hideIndexRow, - overscanRowCount, - rowHeight, - rowCount, - scrollToIndex, - sortBy, - sortDirection, - useDynamicRowHeight - } = this.state - - const { list } = this.context - const sortedList = this._isSortEnabled() - ? list - .sortBy(item => item[sortBy]) - .update(list => - sortDirection === SortDirection.DESC - ? list.reverse() - : list - ) - : list - - const rowGetter = ({ index }) => this._getDatum(sortedList, index) - - return ( -
- - {({ width }) => ( - - {!hideIndexRow && - rowData.index - } - dataKey='index' - disableSort={!this._isSortEnabled()} - width={60} - /> - } - - cellData - } - flexGrow={1} - /> -
- )} -
-
- ) - } - - _getDatum(list, index) { - return list.get(index % list.size) - } - - _getRowHeight({ index }) { - const { list } = this.context - - return this._getDatum(list, index).size - } - - _headerRenderer({ - columnData, - dataKey, - disableSort, - label, - sortBy, - sortDirection - }) { - return ( -
- Full Name - {sortBy === dataKey && - - } -
- ) - } - - _isSortEnabled() { - const { list } = this.context - const { rowCount } = this.state - - return rowCount <= list.size - } - - _noRowsRenderer() { - return ( -
- No rows -
- ) - } - - _onRowCountChange(event) { - const rowCount = parseInt(event.target.value, 10) || 0 - - this.setState({ rowCount }) - } - - _onScrollToRowChange(event) { - const { rowCount } = this.state - let scrollToIndex = Math.min(rowCount - 1, parseInt(event.target.value, 10)) - - if (isNaN(scrollToIndex)) { - scrollToIndex = undefined - } - - this.setState({ scrollToIndex }) - } - - _rowClassName({ index }) { - if (index < 0) { - return 'styles.headerRow' - } else { - return index % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow' - } - } - - _sort({ sortBy, sortDirection }) { - this.setState({ sortBy, sortDirection }) - } - - _updateUseDynamicRowHeight(value) { - this.setState({ - useDynamicRowHeight: value - }) - } -} diff --git a/types/react-virtualized/WindowScroller.test.tsx b/types/react-virtualized/WindowScroller.test.tsx deleted file mode 100644 index c72a1b197a..0000000000 --- a/types/react-virtualized/WindowScroller.test.tsx +++ /dev/null @@ -1,88 +0,0 @@ -import * as React from 'react' -import { PropTypes, PureComponent } from 'react' -import { WindowScroller, List, AutoSizer } from 'react-virtualized' - -export default class WindowScrollerExample extends PureComponent { - state; - context; - _windowScroller: WindowScroller; - - constructor(props) { - super(props) - - this.state = { - showHeaderText: true - } - - this._hideHeader = this._hideHeader.bind(this) - this._rowRenderer = this._rowRenderer.bind(this) - this._onCheckboxChange = this._onCheckboxChange.bind(this) - this._setRef = this._setRef.bind(this) - } - - render() { - const { list, isScrollingCustomElement, customElement } = this.context - const { showHeaderText } = this.state - - return ( - -
- - {({ height, isScrolling, scrollTop }) => ( - - {({ width }) => ( - this._rowRenderer({ index, isScrolling, isVisible, key, style })} - scrollTop={scrollTop} - width={width} - /> - )} - - )} - -
- ) - } - - _hideHeader() { - const { showHeaderText } = this.state - - this.setState({ - showHeaderText: !showHeaderText - }, () => { - this._windowScroller.updatePosition() - }) - } - - _rowRenderer({ index, isScrolling, isVisible, key, style }) { - const { list } = this.context - const row = list.get(index) - - return ( -
- {row.name} -
- ) - } - - _setRef(windowScroller) { - this._windowScroller = windowScroller - } - - _onCheckboxChange(event) { - this.context.setScrollingCustomElement(event.target.checked) - } -} diff --git a/types/react-virtualized/react-virtualized-tests.tsx b/types/react-virtualized/react-virtualized-tests.tsx new file mode 100644 index 0000000000..71386b2780 --- /dev/null +++ b/types/react-virtualized/react-virtualized-tests.tsx @@ -0,0 +1,1753 @@ +import * as React from 'react'; +import { PureComponent } from 'react' +import { ArrowKeyStepper, AutoSizer, Grid } from 'react-virtualized' + +export class ArrowKeyStepperExample extends PureComponent { + constructor(props) { + super(props) + + this._getColumnWidth = this._getColumnWidth.bind(this) + this._getRowHeight = this._getRowHeight.bind(this) + this._cellRenderer = this._cellRenderer.bind(this) + } + + render() { + const { mode } = this.state + + return ( + + + {({ onSectionRendered, scrollToColumn, scrollToRow }) => ( +
+ + + {({ width }) => ( + this._cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style })} + rowHeight={this._getRowHeight} + rowCount={100} + scrollToColumn={scrollToColumn} + scrollToRow={scrollToRow} + width={width} + /> + )} + +
+ )} +
+ ) + } + + _getColumnWidth({ index }) { + return (1 + (index % 3)) * 60 + } + + _getRowHeight({ index }) { + return (1 + (index % 3)) * 30 + } + + _cellRenderer({ columnIndex, key, rowIndex, scrollToColumn, scrollToRow, style }) { + + return ( +
+ {`r:${rowIndex}, c:${columnIndex}`} +
+ ) + } +} + +import { List } from 'react-virtualized' + +export class AutoSizerExample extends PureComponent { + constructor(props) { + super(props) + + this._rowRenderer = this._rowRenderer.bind(this) + } + + render() { + const { list } = this.context + const { hideDescription } = this.state + + return ( + + {({ width, height }) => ( + + )} + + ) + } + + _rowRenderer({ index, key, style }) { + const { list } = this.context + const row = list.get(index) + + return ( +
+ {row.name} +
+ ) + } +} +import { } from 'react' +import { CellMeasurer, CellMeasurerCache } from 'react-virtualized' + +export class DynamicHeightList extends PureComponent { + + _cache: CellMeasurerCache + + constructor(props, context) { + super(props, context) + + this._cache = new CellMeasurerCache({ + fixedWidth: true, + minHeight: 50 + }) + + this._rowRenderer = this._rowRenderer.bind(this) + } + + render() { + const { width } = this.props + + return ( + + ) + } + + _rowRenderer({ index, isScrolling, key, parent, style }) { + const { getClassName, list } = this.props + + const datum = list.get(index % list.size) + const classNames = getClassName({ columnIndex: 0, rowIndex: index }) + + const imageWidth = 300 + const imageHeight = datum.size * 2 + + const source = `http://fillmurray.com/${imageWidth}/${imageHeight}` + + return ( + + {({ measure }) => ( +
+ +
+ )} +
+ ) + } +} + +import { Collection } from 'react-virtualized' + +// Defines a pattern of sizes and positions for a range of 10 rotating cells +// These cells cover an area of 600 (wide) x 400 (tall) +const GUTTER_SIZE = 3 +const CELL_WIDTH = 75 + +export class CollectionExample extends PureComponent { + + _columnYMap: any; + + constructor(props, context) { + super(props, context) + + this.context = context; + + this.state = { + cellCount: context.list.size, + columnCount: this._getColumnCount(context.list.size), + height: 300, + horizontalOverscanSize: 0, + scrollToCell: undefined, + showScrollingPlaceholder: false, + verticalOverscanSize: 0 + } + + this._columnYMap = [] + + this._cellRenderer = this._cellRenderer.bind(this) + this._cellSizeAndPositionGetter = this._cellSizeAndPositionGetter.bind(this) + this._noContentRenderer = this._noContentRenderer.bind(this) + this._onCellCountChange = this._onCellCountChange.bind(this) + this._onHeightChange = this._onHeightChange.bind(this) + this._onHorizontalOverscanSizeChange = this._onHorizontalOverscanSizeChange.bind(this) + this._onScrollToCellChange = this._onScrollToCellChange.bind(this) + this._onVerticalOverscanSizeChange = this._onVerticalOverscanSizeChange.bind(this) + } + + render() { + const { cellCount, height, horizontalOverscanSize, scrollToCell, showScrollingPlaceholder, verticalOverscanSize } = this.state + + return ( + + {({ width }) => ( + + )} + + ) + } + + _cellRenderer({ index, isScrolling, key, style }) { + const { list } = this.context + const { showScrollingPlaceholder } = this.state + + const datum = list.get(index % list.size) + + // Customize style + style.backgroundColor = datum.color + + return ( +
+ {showScrollingPlaceholder && isScrolling ? '...' : index} +
+ ) + } + + _cellSizeAndPositionGetter({ index }) { + const { list } = this.context + const { columnCount } = this.state + + const columnPosition = index % (columnCount || 1) + const datum = list.get(index % list.size) + + // Poor man's Masonry layout; columns won't all line up equally with the bottom. + const height = datum.size + const width = CELL_WIDTH + const x = columnPosition * (GUTTER_SIZE + width) + const y = this._columnYMap[columnPosition] || 0 + + this._columnYMap[columnPosition] = y + height + GUTTER_SIZE + + return { + height, + width, + x, + y + } + } + + _getColumnCount(cellCount) { + return Math.round(Math.sqrt(cellCount)) + } + + _onHorizontalOverscanSizeChange(event) { + const horizontalOverscanSize = parseInt(event.target.value, 10) || 0 + + this.setState({ horizontalOverscanSize }) + } + + _noContentRenderer() { + return ( +
+ No cells +
+ ) + } + + _onCellCountChange(event) { + const cellCount = parseInt(event.target.value, 10) || 0 + + this._columnYMap = [] + + this.setState({ + cellCount, + columnCount: this._getColumnCount(cellCount) + }) + } + + _onHeightChange(event) { + const height = parseInt(event.target.value, 10) || 0 + + this.setState({ height }) + } + + _onScrollToCellChange(event) { + const { cellCount } = this.state + + let scrollToCell = Math.min(cellCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToCell)) { + scrollToCell = undefined + } + + this.setState({ scrollToCell }) + } + + _onVerticalOverscanSizeChange(event) { + const verticalOverscanSize = parseInt(event.target.value, 10) || 0 + + this.setState({ verticalOverscanSize }) + } +} + +import { ColumnSizer } from 'react-virtualized' + +export class ColumnSizerExample extends PureComponent { + constructor(props) { + super(props) + + this._noColumnMaxWidthChange = this._noColumnMaxWidthChange.bind(this) + this._noColumnMinWidthChange = this._noColumnMinWidthChange.bind(this) + this._onColumnCountChange = this._onColumnCountChange.bind(this) + this._noContentRenderer = this._noContentRenderer.bind(this) + this._cellRenderer = this._cellRenderer.bind(this) + } + + render() { + const { + columnMaxWidth, + columnMinWidth, + columnCount + } = this.state + + return ( +
+ + {({ width }) => ( + + {({ adjustedWidth, getColumnWidth, registerChild }) => ( +
+ +
+ )} +
+ )} +
+
+ ) + } + + _noColumnMaxWidthChange(event) { + let columnMaxWidth = parseInt(event.target.value, 10) + + if (isNaN(columnMaxWidth)) { + columnMaxWidth = undefined + } else { + columnMaxWidth = Math.min(1000, columnMaxWidth) + } + + this.setState({ columnMaxWidth }) + } + + _noColumnMinWidthChange(event) { + let columnMinWidth = parseInt(event.target.value, 10) + + if (isNaN(columnMinWidth)) { + columnMinWidth = undefined + } else { + columnMinWidth = Math.max(1, columnMinWidth) + } + + this.setState({ columnMinWidth }) + } + + _onColumnCountChange(event) { + this.setState({ columnCount: parseInt(event.target.value, 10) || 0 }) + } + + _noContentRenderer() { + return ( +
+ No cells +
+ ) + } + + _cellRenderer({ columnIndex, key, rowIndex, style }) { + const className = columnIndex === 0 + ? 'styles.firstCell' + : 'styles.cell' + + return ( +
+ {`R:${rowIndex}, C:${columnIndex}`} +
+ ) + } +} + +export class GridExample extends PureComponent { + + + constructor(props, context) { + super(props, context) + + this.state = { + columnCount: 1000, + height: 300, + overscanColumnCount: 0, + overscanRowCount: 10, + rowHeight: 40, + rowCount: 1000, + scrollToColumn: undefined, + scrollToRow: undefined, + useDynamicRowHeight: false + } + + this._cellRenderer = this._cellRenderer.bind(this) + this._getColumnWidth = this._getColumnWidth.bind(this) + this._getRowClassName = this._getRowClassName.bind(this) + this._getRowHeight = this._getRowHeight.bind(this) + this._noContentRenderer = this._noContentRenderer.bind(this) + this._onColumnCountChange = this._onColumnCountChange.bind(this) + this._onRowCountChange = this._onRowCountChange.bind(this) + this._onScrollToColumnChange = this._onScrollToColumnChange.bind(this) + this._onScrollToRowChange = this._onScrollToRowChange.bind(this) + this._renderBodyCell = this._renderBodyCell.bind(this) + this._renderLeftSideCell = this._renderLeftSideCell.bind(this) + } + + render() { + const { + columnCount, + height, + overscanColumnCount, + overscanRowCount, + rowHeight, + rowCount, + scrollToColumn, + scrollToRow, + useDynamicRowHeight + } = this.state + + return ( + + + {({ width }) => ( + + )} + + ) + } + + _cellRenderer({ columnIndex, key, rowIndex, style }) { + if (columnIndex === 0) { + return this._renderLeftSideCell({ key, rowIndex, style }) + } else { + return this._renderBodyCell({ columnIndex, key, rowIndex, style }) + } + } + + _getColumnWidth({ index }) { + switch (index) { + case 0: + return 50 + case 1: + return 100 + case 2: + return 300 + default: + return 80 + } + } + + _getDatum(index) { + const { list } = this.context + + return list.get(index % list.size) + } + + _getRowClassName(row) { + return row % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow' + } + + _getRowHeight({ index }) { + return this._getDatum(index).size + } + + _noContentRenderer() { + return ( +
+ No cells +
+ ) + } + + _renderBodyCell({ columnIndex, key, rowIndex, style }) { + const rowClass = this._getRowClassName(rowIndex) + const datum = this._getDatum(rowIndex) + + let content + + switch (columnIndex) { + case 1: + content = datum.name + break + case 2: + content = datum.random + break + default: + content = `r:${rowIndex}, c:${columnIndex}` + break + } + + return ( +
+ {content} +
+ ) + } + + _renderLeftSideCell({ key, rowIndex, style }) { + const datum = this._getDatum(rowIndex) + + // Don't modify styles. + // These are frozen by React now (as of 16.0.0). + // Since Grid caches and re-uses them, they aren't safe to modify. + style = { + ...style, + backgroundColor: datum.color + } + + return ( +
+ {datum.name.charAt(0)} +
+ ) + } + + _updateUseDynamicRowHeights(value) { + this.setState({ + useDynamicRowHeight: value + }) + } + + _onColumnCountChange(event) { + const columnCount = parseInt(event.target.value, 10) || 0 + + this.setState({ columnCount }) + } + + _onRowCountChange(event) { + const rowCount = parseInt(event.target.value, 10) || 0 + + this.setState({ rowCount }) + } + + _onScrollToColumnChange(event) { + const { columnCount } = this.state + let scrollToColumn = Math.min(columnCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToColumn)) { + scrollToColumn = undefined + } + + this.setState({ scrollToColumn }) + } + + _onScrollToRowChange(event) { + const { rowCount } = this.state + let scrollToRow = Math.min(rowCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToRow)) { + scrollToRow = undefined + } + + this.setState({ scrollToRow }) + } +} + +import { InfiniteLoader } from 'react-virtualized' + +const STATUS_LOADING = 1 +const STATUS_LOADED = 2 + +export class InfiniteLoaderExample extends PureComponent { + _timeoutIdMap: any; + + constructor(props) { + super(props) + + this._timeoutIdMap = {} + + this._clearData = this._clearData.bind(this) + this._isRowLoaded = this._isRowLoaded.bind(this) + this._loadMoreRows = this._loadMoreRows.bind(this) + this._rowRenderer = this._rowRenderer.bind(this) + } + + componentWillUnmount() { + Object.keys(this._timeoutIdMap).forEach(timeoutId => { + clearTimeout(timeoutId as any) + }) + } + + render() { + const { list } = this.context + const { loadedRowCount, loadingRowCount } = this.state + + return ( + + {({ onRowsRendered, registerChild }) => ( + + {({ width }) => ( + + )} + + )} + + ) + } + + _clearData() { + this.setState({ + loadedRowCount: 0, + loadedRowsMap: {}, + loadingRowCount: 0 + }) + } + + _isRowLoaded({ index }) { + const { loadedRowsMap } = this.state + return !!loadedRowsMap[index] // STATUS_LOADING or STATUS_LOADED + } + + _loadMoreRows({ startIndex, stopIndex }) { + const { loadedRowsMap, loadingRowCount } = this.state + const increment = stopIndex - startIndex + 1 + + for (var i = startIndex; i <= stopIndex; i++) { + loadedRowsMap[i] = STATUS_LOADING + } + + this.setState({ + loadingRowCount: loadingRowCount + increment + }) + + const timeoutId = setTimeout(() => { + const { loadedRowCount, loadingRowCount } = this.state + + delete this._timeoutIdMap[timeoutId] + + for (var i = startIndex; i <= stopIndex; i++) { + loadedRowsMap[i] = STATUS_LOADED + } + + this.setState({ + loadingRowCount: loadingRowCount - increment, + loadedRowCount: loadedRowCount + increment + }) + + promiseResolver() + }, 1000 + Math.round(Math.random() * 2000)) + + this._timeoutIdMap[timeoutId] = true + + let promiseResolver + + return new Promise(resolve => { + promiseResolver = resolve + }) + } + + _rowRenderer({ index, key, style }) { + const { list } = this.context + const { loadedRowsMap } = this.state + + const row = list.get(index) + let content + + if (loadedRowsMap[index] === STATUS_LOADED) { + content = row.name + } else { + content = ( +
+ ) + } + + return ( +
+ {content} +
+ ) + } +} + +export class ListExample extends PureComponent { + + constructor(props, context) { + super(props, context) + + this.state = { + listHeight: 300, + listRowHeight: 50, + overscanRowCount: 10, + rowCount: context.list.size, + scrollToIndex: undefined, + showScrollingPlaceholder: false, + useDynamicRowHeight: false + } + + this._getRowHeight = this._getRowHeight.bind(this) + this._noRowsRenderer = this._noRowsRenderer.bind(this) + this._onRowCountChange = this._onRowCountChange.bind(this) + this._onScrollToRowChange = this._onScrollToRowChange.bind(this) + this._rowRenderer = this._rowRenderer.bind(this) + } + + render() { + const { + listHeight, + listRowHeight, + overscanRowCount, + rowCount, + scrollToIndex, + showScrollingPlaceholder, + useDynamicRowHeight + } = this.state + + return ( + + {({ width }) => ( + + )} + + ) + } + + _getDatum(index) { + const { list } = this.context + + return list.get(index % list.size) + } + + _getRowHeight({ index }) { + return this._getDatum(index).size + } + + _noRowsRenderer() { + return ( +
+ No rows +
+ ) + } + + _onRowCountChange(event) { + const rowCount = parseInt(event.target.value, 10) || 0 + + this.setState({ rowCount }) + } + + _onScrollToRowChange(event) { + const { rowCount } = this.state + let scrollToIndex = Math.min(rowCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToIndex)) { + scrollToIndex = undefined + } + + this.setState({ scrollToIndex }) + } + + _rowRenderer({ index, isScrolling, key, style }) { + const { + showScrollingPlaceholder, + useDynamicRowHeight + } = this.state + + if ( + showScrollingPlaceholder && + isScrolling + ) { + return ( +
+ Scrolling... +
+ ) + } + + const datum = this._getDatum(index) + + let additionalContent + + if (useDynamicRowHeight) { + switch (datum.size) { + case 75: + additionalContent =
It is medium-sized.
+ break + case 100: + additionalContent =
It is large-sized.
It has a 3rd row.
+ break + } + } + + return ( +
+
+ {datum.name.charAt(0)} +
+
+
+ {datum.name} +
+
+ This is row {index} +
+ {additionalContent} +
+ {useDynamicRowHeight && + + {datum.size}px + + } +
+ ) + } +} + +import { + WindowScroller, + createMasonryCellPositioner as createCellPositioner, + Positioner, + Masonry, + MasonryCellProps +} from 'react-virtualized' + +export class GridExample2 extends PureComponent { + _columnCount: number; + _cache: CellMeasurerCache; + _columnHeights: any; + _width: number; + _height: number; + _scrollTop: number; + _cellPositioner?: Positioner; + _masonry: Masonry; + + constructor(props, context) { + super(props, context) + + this._columnCount = 0 + + this._cache = new CellMeasurerCache({ + defaultHeight: 250, + defaultWidth: 200, + fixedWidth: true + }) + + this._columnHeights = {} + + this.state = { + columnWidth: 200, + height: 300, + gutterSize: 10, + windowScrollerEnabled: false + } + + this._cellRenderer = this._cellRenderer.bind(this) + this._onResize = this._onResize.bind(this) + this._renderAutoSizer = this._renderAutoSizer.bind(this) + this._renderMasonry = this._renderMasonry.bind(this) + this._setMasonryRef = this._setMasonryRef.bind(this) + } + + render() { + const { + columnWidth, + height, + gutterSize, + windowScrollerEnabled + } = this.state + + let child + + if (windowScrollerEnabled) { + child = ( + + {this._renderAutoSizer} + + ) + } else { + child = this._renderAutoSizer({ height }) + } + + return ( +
+ {child} +
+ ) + } + + _calculateColumnCount() { + const { + columnWidth, + gutterSize + } = this.state + + this._columnCount = Math.floor(this._width / (columnWidth + gutterSize)) + } + + _cellRenderer({ index, key, parent, style }: MasonryCellProps) { + const { list } = this.context + const { columnWidth } = this.state + + const datum = list.get(index % list.size) + + return ( + +
+
+ {datum.random} +
+ + ) + } + + _initCellPositioner() { + if (typeof this._cellPositioner === 'undefined') { + const { + columnWidth, + gutterSize + } = this.state + + this._cellPositioner = createCellPositioner({ + cellMeasurerCache: this._cache, + columnCount: this._columnCount, + columnWidth, + spacer: gutterSize + }) + } + } + + _onResize({ height, width }) { + this._width = width + + this._columnHeights = {} + this._calculateColumnCount() + this._resetCellPositioner() + this._masonry.recomputeCellPositions() + } + + _renderAutoSizer({ height, scrollTop }: { height: number, scrollTop?: number }) { + this._height = height + this._scrollTop = scrollTop + + return ( + + {this._renderMasonry} + + ) + } + + _renderMasonry({ width }) { + this._width = width + + this._calculateColumnCount() + this._initCellPositioner() + + const { height, windowScrollerEnabled } = this.state + + return ( + + ) + } + + _resetCellPositioner() { + const { + columnWidth, + gutterSize + } = this.state + + this._cellPositioner.reset({ + columnCount: this._columnCount, + columnWidth, + spacer: gutterSize + }) + } + + _setMasonryRef(ref) { + this._masonry = ref + } +} + +import { MultiGrid } from 'react-virtualized' + +const STYLE: React.CSSProperties = { + border: '1px solid #ddd', + overflow: 'hidden' +} +const STYLE_BOTTOM_LEFT_GRID: React.CSSProperties = { + borderRight: '2px solid #aaa', + backgroundColor: '#f7f7f7' +} +const STYLE_TOP_LEFT_GRID: React.CSSProperties = { + borderBottom: '2px solid #aaa', + borderRight: '2px solid #aaa', + fontWeight: 'bold' +} +const STYLE_TOP_RIGHT_GRID: React.CSSProperties = { + borderBottom: '2px solid #aaa', + fontWeight: 'bold' +} + +export class MultiGridExample extends PureComponent { + state + _onFixedColumnCountChange + _onFixedRowCountChange + _onScrollToColumnChange + _onScrollToRowChange + + constructor(props, context) { + super(props, context) + + this.state = { + fixedColumnCount: 2, + fixedRowCount: 1, + scrollToColumn: 0, + scrollToRow: 0 + } + + this._cellRenderer = this._cellRenderer.bind(this) + this._onFixedColumnCountChange = this._createEventHandler('fixedColumnCount') + this._onFixedRowCountChange = this._createEventHandler('fixedRowCount') + this._onScrollToColumnChange = this._createEventHandler('scrollToColumn') + this._onScrollToRowChange = this._createEventHandler('scrollToRow') + } + + render() { + return ( + + {({ width }) => ( + + )} + + ) + } + + _cellRenderer({ columnIndex, key, rowIndex, style }) { + return ( +
+ {columnIndex}, {rowIndex} +
+ ) + } + + _createEventHandler(property) { + return (event) => { + const value = parseInt(event.target.value, 10) || 0 + + this.setState({ + [property]: value + }) + } + } + + _createLabeledInput(property, eventHandler) { + const value = this.state[property] + + return ( + `` + ) + } +} + +import {ScrollSync } from 'react-virtualized' + +const LEFT_COLOR_FROM = hexToRgb('#471061') +const LEFT_COLOR_TO = hexToRgb('#BC3959') +const TOP_COLOR_FROM = hexToRgb('#000000') +const TOP_COLOR_TO = hexToRgb('#333333') + +function scrollbarSize() { return 42; } +export class GridExample3 extends PureComponent { + state + constructor(props, context) { + super(props, context) + + this.state = { + columnWidth: 75, + columnCount: 50, + height: 300, + overscanColumnCount: 0, + overscanRowCount: 5, + rowHeight: 40, + rowCount: 100 + } + + this._renderBodyCell = this._renderBodyCell.bind(this) + this._renderHeaderCell = this._renderHeaderCell.bind(this) + this._renderLeftSideCell = this._renderLeftSideCell.bind(this) + } + + render() { + const { + columnCount, + columnWidth, + height, + overscanColumnCount, + overscanRowCount, + rowHeight, + rowCount + } = this.state + + return ( + + + {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => { + const x = scrollLeft / (scrollWidth - clientWidth) + const y = scrollTop / (scrollHeight - clientHeight) + + const leftBackgroundColor = mixColors(LEFT_COLOR_FROM, LEFT_COLOR_TO, y) + const leftColor = '#ffffff' + const topBackgroundColor = mixColors(TOP_COLOR_FROM, TOP_COLOR_TO, x) + const topColor = '#ffffff' + const middleBackgroundColor = mixColors(leftBackgroundColor, topBackgroundColor, 0.5) + const middleColor = '#ffffff' + + return ( +
+
+ +
+
+ +
+
+ + {({ width }) => ( +
+
+ +
+
+ +
+
+ )} +
+
+
+ ) + }} +
+ ) + } + + _renderBodyCell({ columnIndex, key, rowIndex, style }) { + if (columnIndex < 1) { + return + } + + return this._renderLeftSideCell({ columnIndex, key, rowIndex, style }) + } + + _renderHeaderCell({ columnIndex, key, rowIndex, style }) { + if (columnIndex < 1) { + return + } + + return this._renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) + } + + _renderLeftHeaderCell({ columnIndex, key, rowIndex, style }) { + return ( +
+ {`C${columnIndex}`} +
+ ) + } + + _renderLeftSideCell({ columnIndex, key, rowIndex, style }) { + return ( +
+ {`R${rowIndex}, C${columnIndex}`} +
+ ) + } +} + +function hexToRgb(hex) { + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : null +} + +/** + * Ported from sass implementation in C + * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 + */ +function mixColors(color1, color2, amount) { + const weight1 = amount + const weight2 = 1 - amount + + const r = Math.round(weight1 * color1.r + weight2 * color2.r) + const g = Math.round(weight1 * color1.g + weight2 * color2.g) + const b = Math.round(weight1 * color1.b + weight2 * color2.b) + + return { r, g, b } +} + +import { Column, Table, SortDirection, SortIndicator } from 'react-virtualized' + +export class TableExample extends PureComponent { + state; + context; + constructor(props, context) { + super(props, context) + + this.state = { + disableHeader: false, + headerHeight: 30, + height: 270, + hideIndexRow: false, + overscanRowCount: 10, + rowHeight: 40, + rowCount: 1000, + scrollToIndex: undefined, + sortBy: 'index', + sortDirection: SortDirection.ASC, + useDynamicRowHeight: false + } + + this._getRowHeight = this._getRowHeight.bind(this) + this._headerRenderer = this._headerRenderer.bind(this) + this._noRowsRenderer = this._noRowsRenderer.bind(this) + this._onRowCountChange = this._onRowCountChange.bind(this) + this._onScrollToRowChange = this._onScrollToRowChange.bind(this) + this._rowClassName = this._rowClassName.bind(this) + this._sort = this._sort.bind(this) + } + + render() { + const { + disableHeader, + headerHeight, + height, + hideIndexRow, + overscanRowCount, + rowHeight, + rowCount, + scrollToIndex, + sortBy, + sortDirection, + useDynamicRowHeight + } = this.state + + const { list } = this.context + const sortedList = this._isSortEnabled() + ? list + .sortBy(item => item[sortBy]) + .update(list => + sortDirection === SortDirection.DESC + ? list.reverse() + : list + ) + : list + + const rowGetter = ({ index }) => this._getDatum(sortedList, index) + + return ( +
+ + {({ width }) => ( + + {!hideIndexRow && + rowData.index + } + dataKey='index' + disableSort={!this._isSortEnabled()} + width={60} + /> + } + + cellData + } + flexGrow={1} + /> +
+ )} +
+
+ ) + } + + _getDatum(list, index) { + return list.get(index % list.size) + } + + _getRowHeight({ index }) { + const { list } = this.context + + return this._getDatum(list, index).size + } + + _headerRenderer({ + columnData, + dataKey, + disableSort, + label, + sortBy, + sortDirection + }) { + return ( +
+ Full Name + {sortBy === dataKey && + + } +
+ ) + } + + _isSortEnabled() { + const { list } = this.context + const { rowCount } = this.state + + return rowCount <= list.size + } + + _noRowsRenderer() { + return ( +
+ No rows +
+ ) + } + + _onRowCountChange(event) { + const rowCount = parseInt(event.target.value, 10) || 0 + + this.setState({ rowCount }) + } + + _onScrollToRowChange(event) { + const { rowCount } = this.state + let scrollToIndex = Math.min(rowCount - 1, parseInt(event.target.value, 10)) + + if (isNaN(scrollToIndex)) { + scrollToIndex = undefined + } + + this.setState({ scrollToIndex }) + } + + _rowClassName({ index }) { + if (index < 0) { + return 'styles.headerRow' + } else { + return index % 2 === 0 ? 'styles.evenRow' : 'styles.oddRow' + } + } + + _sort({ sortBy, sortDirection }) { + this.setState({ sortBy, sortDirection }) + } + + _updateUseDynamicRowHeight(value) { + this.setState({ + useDynamicRowHeight: value + }) + } +} + +export class WindowScrollerExample extends PureComponent { + state; + context; + _windowScroller: WindowScroller; + + constructor(props) { + super(props) + + this.state = { + showHeaderText: true + } + + this._hideHeader = this._hideHeader.bind(this) + this._rowRenderer = this._rowRenderer.bind(this) + this._onCheckboxChange = this._onCheckboxChange.bind(this) + this._setRef = this._setRef.bind(this) + } + + render() { + const { list, isScrollingCustomElement, customElement } = this.context + const { showHeaderText } = this.state + + return ( + +
+ + {({ height, isScrolling, scrollTop }) => ( + + {({ width }) => ( + this._rowRenderer({ index, isScrolling, isVisible, key, style })} + scrollTop={scrollTop} + width={width} + /> + )} + + )} + +
+ ) + } + + _hideHeader() { + const { showHeaderText } = this.state + + this.setState({ + showHeaderText: !showHeaderText + }, () => { + this._windowScroller.updatePosition() + }) + } + + _rowRenderer({ index, isScrolling, isVisible, key, style }) { + const { list } = this.context + const row = list.get(index) + + return ( +
+ {row.name} +
+ ) + } + + _setRef(windowScroller) { + this._windowScroller = windowScroller + } + + _onCheckboxChange(event) { + this.context.setScrollingCustomElement(event.target.checked) + } +} diff --git a/types/react-virtualized/tsconfig.json b/types/react-virtualized/tsconfig.json index 21a0e43a0d..6be15dbe8a 100644 --- a/types/react-virtualized/tsconfig.json +++ b/types/react-virtualized/tsconfig.json @@ -20,31 +20,19 @@ "files": [ "index.d.ts", "ArrowKeyStepper.d.ts", - "ArrowKeyStepper.test.tsx", "AutoSizer.d.ts", - "AutoSizer.test.tsx", "CellMeasurer.d.ts", - "CellMeasurer.test.tsx", "Collection.d.ts", - "Collection.test.tsx", "ColumnSizer.d.ts", - "ColumnSizer.test.tsx", "genericTypes.d.ts", "Grid.d.ts", - "Grid.test.tsx", "InfiniteLoader.d.ts", - "InfiniteLoader.test.tsx", "List.d.ts", - "List.test.tsx", "Masonry.d.ts", - "Masonry.test.tsx", "MultiGrid.d.ts", - "MultiGrid.test.tsx", "ScrollSync.d.ts", - "ScrollSync.test.tsx", "Table.d.ts", - "Table.test.tsx", "WindowScroller.d.ts", - "WindowScroller.test.tsx" + "react-virtualized-tests.tsx" ] } \ No newline at end of file From a500aedade3a27ccd6348c134ba0a032000a9257 Mon Sep 17 00:00:00 2001 From: Kalle Ott Date: Mon, 27 Mar 2017 21:58:19 +0200 Subject: [PATCH 08/31] update to typescript 2.2 for object type --- types/react-virtualized/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-virtualized/index.d.ts b/types/react-virtualized/index.d.ts index 31a6ee29c8..3280d8410d 100644 --- a/types/react-virtualized/index.d.ts +++ b/types/react-virtualized/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/bvaughn/react-virtualized // Definitions by: Kalle Ott // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 export { ArrowKeyStepper, From 4e37f8d9f9913922d441bf2f03ea17d7293cf5ec Mon Sep 17 00:00:00 2001 From: Kalle Ott Date: Tue, 28 Mar 2017 09:14:58 +0200 Subject: [PATCH 09/31] fixed mapping to distribution folder structure --- .../dist/commonjs/ArrowKeyStepper.d.ts | 1 + .../dist/commonjs/AutoSizer.d.ts | 1 + .../dist/commonjs/CellMeasurer.d.ts | 1 + .../dist/commonjs/Collection.d.ts | 1 + .../dist/commonjs/ColumnSizer.d.ts | 1 + .../react-virtualized/dist/commonjs/Grid.d.ts | 1 + .../dist/commonjs/InfiniteLoader.d.ts | 1 + .../react-virtualized/dist/commonjs/List.d.ts | 1 + .../dist/commonjs/Masonry.d.ts | 1 + .../dist/commonjs/MultiGrid.d.ts | 1 + .../dist/commonjs/ScrollSync.d.ts | 1 + .../dist/commonjs/Table.d.ts | 1 + .../dist/commonjs/WindowScroller.d.ts | 1 + .../{ => dist/es}/ArrowKeyStepper.d.ts | 0 .../{ => dist/es}/AutoSizer.d.ts | 0 .../{ => dist/es}/CellMeasurer.d.ts | 0 .../{ => dist/es}/Collection.d.ts | 3 +- .../{ => dist/es}/ColumnSizer.d.ts | 0 .../react-virtualized/{ => dist/es}/Grid.d.ts | 3 +- .../{ => dist/es}/InfiniteLoader.d.ts | 2 +- .../react-virtualized/{ => dist/es}/List.d.ts | 3 +- .../{ => dist/es}/Masonry.d.ts | 1 - .../{ => dist/es}/MultiGrid.d.ts | 0 .../{ => dist/es}/ScrollSync.d.ts | 0 .../{ => dist/es}/Table.d.ts | 2 +- .../{ => dist/es}/WindowScroller.d.ts | 1 - types/react-virtualized/genericTypes.d.ts | 40 ---------- types/react-virtualized/index.d.ts | 77 +++++++++++++------ 28 files changed, 71 insertions(+), 74 deletions(-) create mode 100644 types/react-virtualized/dist/commonjs/ArrowKeyStepper.d.ts create mode 100644 types/react-virtualized/dist/commonjs/AutoSizer.d.ts create mode 100644 types/react-virtualized/dist/commonjs/CellMeasurer.d.ts create mode 100644 types/react-virtualized/dist/commonjs/Collection.d.ts create mode 100644 types/react-virtualized/dist/commonjs/ColumnSizer.d.ts create mode 100644 types/react-virtualized/dist/commonjs/Grid.d.ts create mode 100644 types/react-virtualized/dist/commonjs/InfiniteLoader.d.ts create mode 100644 types/react-virtualized/dist/commonjs/List.d.ts create mode 100644 types/react-virtualized/dist/commonjs/Masonry.d.ts create mode 100644 types/react-virtualized/dist/commonjs/MultiGrid.d.ts create mode 100644 types/react-virtualized/dist/commonjs/ScrollSync.d.ts create mode 100644 types/react-virtualized/dist/commonjs/Table.d.ts create mode 100644 types/react-virtualized/dist/commonjs/WindowScroller.d.ts rename types/react-virtualized/{ => dist/es}/ArrowKeyStepper.d.ts (100%) rename types/react-virtualized/{ => dist/es}/AutoSizer.d.ts (100%) rename types/react-virtualized/{ => dist/es}/CellMeasurer.d.ts (100%) rename types/react-virtualized/{ => dist/es}/Collection.d.ts (99%) rename types/react-virtualized/{ => dist/es}/ColumnSizer.d.ts (100%) rename types/react-virtualized/{ => dist/es}/Grid.d.ts (99%) rename types/react-virtualized/{ => dist/es}/InfiniteLoader.d.ts (98%) rename types/react-virtualized/{ => dist/es}/List.d.ts (98%) rename types/react-virtualized/{ => dist/es}/Masonry.d.ts (99%) rename types/react-virtualized/{ => dist/es}/MultiGrid.d.ts (100%) rename types/react-virtualized/{ => dist/es}/ScrollSync.d.ts (100%) rename types/react-virtualized/{ => dist/es}/Table.d.ts (99%) rename types/react-virtualized/{ => dist/es}/WindowScroller.d.ts (99%) delete mode 100644 types/react-virtualized/genericTypes.d.ts diff --git a/types/react-virtualized/dist/commonjs/ArrowKeyStepper.d.ts b/types/react-virtualized/dist/commonjs/ArrowKeyStepper.d.ts new file mode 100644 index 0000000000..fd16c58feb --- /dev/null +++ b/types/react-virtualized/dist/commonjs/ArrowKeyStepper.d.ts @@ -0,0 +1 @@ +export * from '../es/ArrowKeyStepper'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/AutoSizer.d.ts b/types/react-virtualized/dist/commonjs/AutoSizer.d.ts new file mode 100644 index 0000000000..c0551a98a4 --- /dev/null +++ b/types/react-virtualized/dist/commonjs/AutoSizer.d.ts @@ -0,0 +1 @@ +export * from '../es/AutoSizer'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/CellMeasurer.d.ts b/types/react-virtualized/dist/commonjs/CellMeasurer.d.ts new file mode 100644 index 0000000000..907eafee51 --- /dev/null +++ b/types/react-virtualized/dist/commonjs/CellMeasurer.d.ts @@ -0,0 +1 @@ +export * from '../es/CellMeasurer'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/Collection.d.ts b/types/react-virtualized/dist/commonjs/Collection.d.ts new file mode 100644 index 0000000000..2764686c76 --- /dev/null +++ b/types/react-virtualized/dist/commonjs/Collection.d.ts @@ -0,0 +1 @@ +export * from '../es/Collection'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/ColumnSizer.d.ts b/types/react-virtualized/dist/commonjs/ColumnSizer.d.ts new file mode 100644 index 0000000000..80c9cf5d2e --- /dev/null +++ b/types/react-virtualized/dist/commonjs/ColumnSizer.d.ts @@ -0,0 +1 @@ +export * from '../es/ColumnSizer'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/Grid.d.ts b/types/react-virtualized/dist/commonjs/Grid.d.ts new file mode 100644 index 0000000000..168a11ac52 --- /dev/null +++ b/types/react-virtualized/dist/commonjs/Grid.d.ts @@ -0,0 +1 @@ +export * from '../es/Grid'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/InfiniteLoader.d.ts b/types/react-virtualized/dist/commonjs/InfiniteLoader.d.ts new file mode 100644 index 0000000000..29449c85ff --- /dev/null +++ b/types/react-virtualized/dist/commonjs/InfiniteLoader.d.ts @@ -0,0 +1 @@ +export * from '../es/InfiniteLoader'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/List.d.ts b/types/react-virtualized/dist/commonjs/List.d.ts new file mode 100644 index 0000000000..6fdfde2dc0 --- /dev/null +++ b/types/react-virtualized/dist/commonjs/List.d.ts @@ -0,0 +1 @@ +export * from '../es/List'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/Masonry.d.ts b/types/react-virtualized/dist/commonjs/Masonry.d.ts new file mode 100644 index 0000000000..e5189fb5f9 --- /dev/null +++ b/types/react-virtualized/dist/commonjs/Masonry.d.ts @@ -0,0 +1 @@ +export * from '../es/Masonry'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/MultiGrid.d.ts b/types/react-virtualized/dist/commonjs/MultiGrid.d.ts new file mode 100644 index 0000000000..09f385eca4 --- /dev/null +++ b/types/react-virtualized/dist/commonjs/MultiGrid.d.ts @@ -0,0 +1 @@ +export * from '../es/MultiGrid'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/ScrollSync.d.ts b/types/react-virtualized/dist/commonjs/ScrollSync.d.ts new file mode 100644 index 0000000000..ffb4423c0a --- /dev/null +++ b/types/react-virtualized/dist/commonjs/ScrollSync.d.ts @@ -0,0 +1 @@ +export * from '../es/ScrollSync'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/Table.d.ts b/types/react-virtualized/dist/commonjs/Table.d.ts new file mode 100644 index 0000000000..db2670ceda --- /dev/null +++ b/types/react-virtualized/dist/commonjs/Table.d.ts @@ -0,0 +1 @@ +export * from '../es/Table'; \ No newline at end of file diff --git a/types/react-virtualized/dist/commonjs/WindowScroller.d.ts b/types/react-virtualized/dist/commonjs/WindowScroller.d.ts new file mode 100644 index 0000000000..0380f0a4fb --- /dev/null +++ b/types/react-virtualized/dist/commonjs/WindowScroller.d.ts @@ -0,0 +1 @@ +export * from '../es/WindowScroller'; \ No newline at end of file diff --git a/types/react-virtualized/ArrowKeyStepper.d.ts b/types/react-virtualized/dist/es/ArrowKeyStepper.d.ts similarity index 100% rename from types/react-virtualized/ArrowKeyStepper.d.ts rename to types/react-virtualized/dist/es/ArrowKeyStepper.d.ts diff --git a/types/react-virtualized/AutoSizer.d.ts b/types/react-virtualized/dist/es/AutoSizer.d.ts similarity index 100% rename from types/react-virtualized/AutoSizer.d.ts rename to types/react-virtualized/dist/es/AutoSizer.d.ts diff --git a/types/react-virtualized/CellMeasurer.d.ts b/types/react-virtualized/dist/es/CellMeasurer.d.ts similarity index 100% rename from types/react-virtualized/CellMeasurer.d.ts rename to types/react-virtualized/dist/es/CellMeasurer.d.ts diff --git a/types/react-virtualized/Collection.d.ts b/types/react-virtualized/dist/es/Collection.d.ts similarity index 99% rename from types/react-virtualized/Collection.d.ts rename to types/react-virtualized/dist/es/Collection.d.ts index 52a69de286..404d329222 100644 --- a/types/react-virtualized/Collection.d.ts +++ b/types/react-virtualized/dist/es/Collection.d.ts @@ -1,11 +1,10 @@ -/** @flow */ import { PureComponent, Validator, Requireable } from 'react' import { Index, ScrollPosition, SizeInfo, SizeAndPositionInfo -} from './genericTypes'; +} from '../../index'; export type CollectionCellSizeAndPosition = { height: number, width: number, x: number, y: number }; export type CollectionCellSizeAndPositionGetter = (params: Index) => CollectionCellSizeAndPosition; diff --git a/types/react-virtualized/ColumnSizer.d.ts b/types/react-virtualized/dist/es/ColumnSizer.d.ts similarity index 100% rename from types/react-virtualized/ColumnSizer.d.ts rename to types/react-virtualized/dist/es/ColumnSizer.d.ts diff --git a/types/react-virtualized/Grid.d.ts b/types/react-virtualized/dist/es/Grid.d.ts similarity index 99% rename from types/react-virtualized/Grid.d.ts rename to types/react-virtualized/dist/es/Grid.d.ts index ea7130857c..b68cf45956 100644 --- a/types/react-virtualized/Grid.d.ts +++ b/types/react-virtualized/dist/es/Grid.d.ts @@ -1,9 +1,8 @@ -/** @flow */ import { Validator, Requireable, PureComponent } from 'react' import { List } from './List'; import { Table } from './Table'; import { CellMeasurerCache } from './CellMeasurer'; -import { Index, Map, Alignment } from './genericTypes'; +import { Index, Map, Alignment } from '../../index'; export type GridCellProps = { columnIndex: number; diff --git a/types/react-virtualized/InfiniteLoader.d.ts b/types/react-virtualized/dist/es/InfiniteLoader.d.ts similarity index 98% rename from types/react-virtualized/InfiniteLoader.d.ts rename to types/react-virtualized/dist/es/InfiniteLoader.d.ts index 4493921e72..e16359adca 100644 --- a/types/react-virtualized/InfiniteLoader.d.ts +++ b/types/react-virtualized/dist/es/InfiniteLoader.d.ts @@ -1,5 +1,5 @@ import { PureComponent, Validator, Requireable } from 'react' -import { Index, IndexRange } from './genericTypes'; +import { Index, IndexRange } from '../../index'; export type InfiniteLoaderChildProps = { onRowsRendered: (params: { startIndex: number, stopIndex: number }) => void, diff --git a/types/react-virtualized/List.d.ts b/types/react-virtualized/dist/es/List.d.ts similarity index 98% rename from types/react-virtualized/List.d.ts rename to types/react-virtualized/dist/es/List.d.ts index d4d5196a34..2a4f30dbfe 100644 --- a/types/react-virtualized/List.d.ts +++ b/types/react-virtualized/dist/es/List.d.ts @@ -1,7 +1,6 @@ -/** @flow */ import { PureComponent, Validator, Requireable } from 'react' import { Grid, GridCellProps } from './Grid' -import { Index, IndexRange, Alignment } from './genericTypes' +import { Index, IndexRange, Alignment } from '../../index' import { CellMeasurerCache } from './CellMeasurer' export type ListRowProps = GridCellProps & { index: number, style: React.CSSProperties }; diff --git a/types/react-virtualized/Masonry.d.ts b/types/react-virtualized/dist/es/Masonry.d.ts similarity index 99% rename from types/react-virtualized/Masonry.d.ts rename to types/react-virtualized/dist/es/Masonry.d.ts index c4187bf611..51c59a90fc 100644 --- a/types/react-virtualized/Masonry.d.ts +++ b/types/react-virtualized/dist/es/Masonry.d.ts @@ -1,5 +1,4 @@ import { PureComponent, Validator, Requireable } from 'react' -import { } from './genericTypes'; import { CellMeasurerCache, KeyMapper } from './CellMeasurer'; import { GridCellRenderer } from './Grid'; /** diff --git a/types/react-virtualized/MultiGrid.d.ts b/types/react-virtualized/dist/es/MultiGrid.d.ts similarity index 100% rename from types/react-virtualized/MultiGrid.d.ts rename to types/react-virtualized/dist/es/MultiGrid.d.ts diff --git a/types/react-virtualized/ScrollSync.d.ts b/types/react-virtualized/dist/es/ScrollSync.d.ts similarity index 100% rename from types/react-virtualized/ScrollSync.d.ts rename to types/react-virtualized/dist/es/ScrollSync.d.ts diff --git a/types/react-virtualized/Table.d.ts b/types/react-virtualized/dist/es/Table.d.ts similarity index 99% rename from types/react-virtualized/Table.d.ts rename to types/react-virtualized/dist/es/Table.d.ts index af5cf9b0b5..6607211dcf 100644 --- a/types/react-virtualized/Table.d.ts +++ b/types/react-virtualized/dist/es/Table.d.ts @@ -1,6 +1,6 @@ import { Validator, Requireable, PureComponent, Component } from 'react'; import { CellMeasurerCache } from './CellMeasurer'; -import { Index, Alignment, ScrollEventData, IndexRange, OverscanIndexRange } from './genericTypes'; +import { Index, Alignment, ScrollEventData, IndexRange, OverscanIndexRange } from '../../index'; import { Grid } from './Grid'; export type TableCellDataGetterParams = { diff --git a/types/react-virtualized/WindowScroller.d.ts b/types/react-virtualized/dist/es/WindowScroller.d.ts similarity index 99% rename from types/react-virtualized/WindowScroller.d.ts rename to types/react-virtualized/dist/es/WindowScroller.d.ts index 093debdd78..7e0a09379e 100644 --- a/types/react-virtualized/WindowScroller.d.ts +++ b/types/react-virtualized/dist/es/WindowScroller.d.ts @@ -1,4 +1,3 @@ -/** @flow */ import { Validator, Requireable, PureComponent } from 'react' export type WindowScrollerChildProps = { diff --git a/types/react-virtualized/genericTypes.d.ts b/types/react-virtualized/genericTypes.d.ts deleted file mode 100644 index 7f4b6ff4b4..0000000000 --- a/types/react-virtualized/genericTypes.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -export type Index = { - index: number -}; - -export type PositionInfo = { - x: number, - y: number -}; - -export type ScrollPosition = { - scrollLeft: number, - scrollTop: number -}; - -export type SizeInfo = { - height: number, - width: number -}; - -export type SizeAndPositionInfo = SizeInfo & PositionInfo; - -export type Map = { [key: string]: T }; - -export type Alignment = 'auto' | 'end' | 'start' | 'center'; - -export type IndexRange = { - startIndex: number, - stopIndex: number -} - -export type OverscanIndexRange = { - overscanStartIndex: number, - overscanStopIndex: number, -} - -export type ScrollEventData = { - clientHeight: number, - scrollHeight: number, - scrollTop: number -} \ No newline at end of file diff --git a/types/react-virtualized/index.d.ts b/types/react-virtualized/index.d.ts index 3280d8410d..d6860176ed 100644 --- a/types/react-virtualized/index.d.ts +++ b/types/react-virtualized/index.d.ts @@ -8,19 +8,19 @@ export { ArrowKeyStepper, ArrowKeyStepperProps, ChildProps as ArrowKeyStepperChildProps -} from './ArrowKeyStepper' +} from './dist/es/ArrowKeyStepper' export { AutoSizer, AutoSizerProps, Dimensions -} from './AutoSizer' +} from './dist/es/AutoSizer' export { CellMeasurer, CellMeasurerCache, CellMeasurerCacheParams, CellMeasurerProps, KeyMapper -} from './CellMeasurer' +} from './dist/es/CellMeasurer' export { Collection, CollectionCellGroupRenderer, @@ -30,12 +30,12 @@ export { CollectionCellSizeAndPosition, CollectionCellSizeAndPositionGetter, CollectionProps -} from './Collection' +} from './dist/es/Collection' export { ColumnSizer, ColumnSizerProps, SizedColumnProps -} from './ColumnSizer' +} from './dist/es/ColumnSizer' export { defaultCellRangeRenderer, Grid, @@ -56,18 +56,18 @@ export { SectionRenderedParams, SizeAndPositionData, VisibleCellRange -} from './Grid' +} from './dist/es/Grid' export { InfiniteLoader, InfiniteLoaderChildProps, InfiniteLoaderProps -} from './InfiniteLoader' +} from './dist/es/InfiniteLoader' export { List, ListProps, ListRowProps, ListRowRenderer -} from './List' +} from './dist/es/List' export { createCellPositioner as createMasonryCellPositioner, Masonry, @@ -79,19 +79,19 @@ export { OnScrollCallback, Position, Positioner -} from './Masonry' +} from './dist/es/Masonry' export { MultiGrid, MultiGridProps, MultiGridState -} from './MultiGrid' +} from './dist/es/MultiGrid' export { ScrollSync, OnScrollParams, ScrollSyncChildProps, ScrollSyncProps, ScrollSyncState -} from './ScrollSync' +} from './dist/es/ScrollSync' export { defaultTableCellDataGetter, defaultTableCellRenderer, @@ -117,22 +117,51 @@ export { TableProps, TableRowProps, TableRowRenderer -} from './Table' +} from './dist/es/Table' export { WindowScroller, WindowScrollerChildProps, WindowScrollerProps, WindowScrollerState -} from './WindowScroller' +} from './dist/es/WindowScroller' -export { - Alignment, - Index, - IndexRange, - Map, - PositionInfo, - ScrollEventData, - ScrollPosition, - SizeAndPositionInfo, - SizeInfo -} from './genericTypes' \ No newline at end of file +export type Index = { + index: number +}; + +export type PositionInfo = { + x: number, + y: number +}; + +export type ScrollPosition = { + scrollLeft: number, + scrollTop: number +}; + +export type SizeInfo = { + height: number, + width: number +}; + +export type SizeAndPositionInfo = SizeInfo & PositionInfo; + +export type Map = { [key: string]: T }; + +export type Alignment = 'auto' | 'end' | 'start' | 'center'; + +export type IndexRange = { + startIndex: number, + stopIndex: number +} + +export type OverscanIndexRange = { + overscanStartIndex: number, + overscanStopIndex: number, +} + +export type ScrollEventData = { + clientHeight: number, + scrollHeight: number, + scrollTop: number +} \ No newline at end of file From 7835e89a401fae0283530a91db2846e00e3dbf31 Mon Sep 17 00:00:00 2001 From: Kalle Ott Date: Tue, 28 Mar 2017 09:21:51 +0200 Subject: [PATCH 10/31] fixed tsconfig --- types/react-virtualized/tsconfig.json | 40 +++++++++++++++++---------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/types/react-virtualized/tsconfig.json b/types/react-virtualized/tsconfig.json index 6be15dbe8a..7e2936975f 100644 --- a/types/react-virtualized/tsconfig.json +++ b/types/react-virtualized/tsconfig.json @@ -19,20 +19,32 @@ }, "files": [ "index.d.ts", - "ArrowKeyStepper.d.ts", - "AutoSizer.d.ts", - "CellMeasurer.d.ts", - "Collection.d.ts", - "ColumnSizer.d.ts", - "genericTypes.d.ts", - "Grid.d.ts", - "InfiniteLoader.d.ts", - "List.d.ts", - "Masonry.d.ts", - "MultiGrid.d.ts", - "ScrollSync.d.ts", - "Table.d.ts", - "WindowScroller.d.ts", + "dist/es/ArrowKeyStepper.d.ts", + "dist/es/AutoSizer.d.ts", + "dist/es/CellMeasurer.d.ts", + "dist/es/Collection.d.ts", + "dist/es/ColumnSizer.d.ts", + "dist/es/Grid.d.ts", + "dist/es/InfiniteLoader.d.ts", + "dist/es/List.d.ts", + "dist/es/Masonry.d.ts", + "dist/es/MultiGrid.d.ts", + "dist/es/ScrollSync.d.ts", + "dist/es/Table.d.ts", + "dist/es/WindowScroller.d.ts", + "dist/commonjs/ArrowKeyStepper.d.ts", + "dist/commonjs/AutoSizer.d.ts", + "dist/commonjs/CellMeasurer.d.ts", + "dist/commonjs/Collection.d.ts", + "dist/commonjs/ColumnSizer.d.ts", + "dist/commonjs/Grid.d.ts", + "dist/commonjs/InfiniteLoader.d.ts", + "dist/commonjs/List.d.ts", + "dist/commonjs/Masonry.d.ts", + "dist/commonjs/MultiGrid.d.ts", + "dist/commonjs/ScrollSync.d.ts", + "dist/commonjs/Table.d.ts", + "dist/commonjs/WindowScroller.d.ts", "react-virtualized-tests.tsx" ] } \ No newline at end of file From e4aac9b800c31ce5cc3cc9fef050be50094f4439 Mon Sep 17 00:00:00 2001 From: Justin Firth Date: Tue, 28 Mar 2017 18:02:51 -0400 Subject: [PATCH 11/31] Improve inference and coercion of specific HTMLElement types in hyperscript; Fix lint errors in hyperscript tests --- types/hyperscript/hyperscript-tests.ts | 14 ++++++++++++++ types/hyperscript/index.d.ts | 8 ++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/types/hyperscript/hyperscript-tests.ts b/types/hyperscript/hyperscript-tests.ts index f4bab0550a..02ea158977 100644 --- a/types/hyperscript/hyperscript-tests.ts +++ b/types/hyperscript/hyperscript-tests.ts @@ -56,3 +56,17 @@ h2('a', {href: '#', }, "Click this") h2.cleanup() + +/* Polymorphic type tests */ + +// determine proper HTMLElement type from tagName +let test1: HTMLCanvasElement = h('canvas'); + +// allow coercion of decorated tagName to proper type +let test2: HTMLCanvasElement = h('canvas#test2'); + +// inline coercion if you were feeling pedantic +// example +h('div#page', + h('div#header', + h('h1.classy', 'h', { style: {'background-color': '#22f'} }))); \ No newline at end of file diff --git a/types/hyperscript/index.d.ts b/types/hyperscript/index.d.ts index 4274365404..b57aa455f6 100644 --- a/types/hyperscript/index.d.ts +++ b/types/hyperscript/index.d.ts @@ -6,8 +6,12 @@ declare module 'hyperscript' { interface HyperScript { - /** Creates an HTML element */ - (tagName: string, ...args: any[]): HTMLElement; + /** Creates a typed HTMLElement */ + (tagName: T, attrs?: Object, ...children: any[]): HTMLElementTagNameMap[T]; + /** Creates a typed HTMLElement via coercion */ + (tagName: string, attrs?: Object, ...children: any[]): T; + /** Creates an HTMLElement */ + (tagName: T, attrs?: Object, ...children: any[]): HTMLElement; /** Cleans up any event handlers created by this hyperscript context */ cleanup(): void; /** Creates a new hyperscript context */ From b3959a812efc71520c624d69f236683b337d2aa1 Mon Sep 17 00:00:00 2001 From: Natan Camargos Date: Fri, 24 Mar 2017 14:41:10 -0300 Subject: [PATCH 12/31] angularjs - Fix ITimeoutService interface ($timeout signature) $timeout is not correctly described by ITimeoutService, causing compile time errors like: 'TS2322:Type 'IPromise' is not assignable to type 'IPromise'...' --- types/angular/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 485ad9ebb3..4c0edf95cc 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -602,7 +602,7 @@ declare namespace angular { /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { (delay?: number, invokeApply?: boolean): IPromise; - (fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise; + (fn: (...args: any[]) => T | IPromise, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise; cancel(promise?: IPromise): boolean; } From 6200c9a89605f61e32bafbb8fbfe0f14515c4966 Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Wed, 29 Mar 2017 11:35:56 +0100 Subject: [PATCH 13/31] Updated oauth2orize typings --- types/oauth2orize/index.d.ts | 182 +++++++++++++++++++------ types/oauth2orize/oauth2orize-tests.ts | 32 ++--- 2 files changed, 156 insertions(+), 58 deletions(-) diff --git a/types/oauth2orize/index.d.ts b/types/oauth2orize/index.d.ts index 2c4b0a7601..a8fbf9c41b 100644 --- a/types/oauth2orize/index.d.ts +++ b/types/oauth2orize/index.d.ts @@ -1,46 +1,143 @@ -// Type definitions for oauth2orize v1.5.1 +// Type definitions for oauth2orize 1.8 // Project: https://github.com/jaredhanson/oauth2orize/ -// Definitions by: Wonshik Kim , Kei Son -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Wonshik Kim , Kei Son , Steve Hipwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// -import * as http from "http"; +import { ServerRequest, ServerResponse } from "http"; -interface ServerOptions { +interface OAuth2 { + client: any; + + user: any; + + transactionID: string; + + redirectURI: string; + + req: OAuth2Req; + + info: OAuth2Info; +} + +interface OAuth2Req { + clientID: string; + + redirectURI: string; + + scope: string; + + state: string; + + type: string; + + transactionID: string; +} + +interface OAuth2Info { + scope: string; +} + +export interface MiddlewareRequest extends ServerRequest { + oauth2?: OAuth2; + + user?: any; +} + +export interface ServerOptions { store: any; loadTransaction: boolean; } -export function createServer(options?: ServerOptions): OAuth2Server; + +export const createServer: (options?: ServerOptions) => OAuth2Server; export interface AuthorizeOptions { idLength?: number; sessionKey?: string; } +export interface DecisionOptions { + cancelField: string; + userProperty: string; + sessionKey: string; +} + export interface ErrorHandlerOptions { mode?: string; } -type MiddlewareFunction = (req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void; -type ValidatedFunction = (err: Error | null, client?: any, redirectURI?: string) => void; -type IssuedFunction = (err: Error | null, accessToken?: string | boolean, refreshToken?: string, params?: any) => void; +type MiddlewareFunction = (req: MiddlewareRequest, res: ServerResponse, next: MiddlewareNextFunction) => void; + +type MiddlewareErrorFunction = (err: Error, req: MiddlewareRequest, res: ServerResponse, next: MiddlewareNextFunction) => void; + +type MiddlewareNextFunction = (err?: Error) => void; + +type ValidateFunction = (clientId: string, redirectURI: string, validated: (err: Error | null, client?: any, redirectURI?: string) => void) => void; + +type ImmediateFunction = (client: any, user: any, scope: string[], type: string, areq: any, done: (err: Error | null, allow: boolean, info: any, locals: any) => void) => void; + +type DecisionParseFunction = (req: MiddlewareRequest, done: (err: Error | null, params: any) => void) => void; + +type SerializeClientFunction = (client: any, done: SerializeClientDoneFunction) => void; +type SerializeClientDoneFunction = (err: Error | null, id: string) => void; + +type DeserializeClientFunction = (id: string, done: DeserializeClientDoneFunction) => void; +type DeserializeClientDoneFunction = (err: Error | null, client?: any | boolean) => void; + +type IssueGrantCodeFunction = (client: any, redirectUri: string, user: any, res: any, issued: (err: Error | null, code?: string) => void) => void; + +type IssueGrantTokenFunction = (client: any, user: any, ares: any, issued: (err: Error | null, code?: string, params?: any) => void) => void; + + +type IssueExchangeCodeFunction = (client: any, code: string, redirectURI: string, issued: ExchangeDoneFunction) => void; + +type ExchangeDoneFunction = (err: Error | null, accessToken?: string | boolean, refreshToken?: string, params?: any) => void; + export class OAuth2Server { - exchange(fn: MiddlewareFunction): OAuth2Server; + grant(type: string, fn: MiddlewareFunction): OAuth2Server; + grant(fn: MiddlewareFunction): OAuth2Server; + exchange(type: string, fn: MiddlewareFunction): OAuth2Server; - // Parses requests to obtain authorization - authorize (options: AuthorizeOptions, validate: (clientId: string, redirectURI: string, validated: ValidatedFunction) => void): MiddlewareFunction; - authorization(options: AuthorizeOptions, validate: (clientId: string, redirectURI: string, validated: ValidatedFunction) => void): MiddlewareFunction; - authorize (validate: (clientId: string, redirectURI: string, validated: ValidatedFunction) => void): MiddlewareFunction; - authorization(validate: (clientId: string, redirectURI: string, validated: ValidatedFunction) => void): MiddlewareFunction; + exchange(fn: MiddlewareFunction): OAuth2Server; + + authorize(options: AuthorizeOptions, validate: ValidateFunction): MiddlewareFunction; + authorize(validate: ValidateFunction): MiddlewareFunction; + + authorization(options: AuthorizeOptions, validate: ValidateFunction, immediate?: ImmediateFunction): MiddlewareFunction; + authorization(validate: ValidateFunction, immediate?: ImmediateFunction): MiddlewareFunction; + + decision(options: DecisionOptions, parse: DecisionParseFunction): MiddlewareFunction; + decision(parse: DecisionParseFunction): MiddlewareFunction; token(options?: any): MiddlewareFunction; - errorHandler(options?: any): (err: Error, req: http.IncomingMessage, res: http.ServerResponse, next: any) => void; - serializeClient(fn: (client: any, done: (err: Error | null, id: string) => void) => void): void; - serializeClient(client: any, done: (err: Error | null, id: string) => void): void; - deserializeClient(fn: (id: string, done: (err: Error | null, client?: any | boolean) => void) => void): void; - deserializeClient(obj: any, done: (err: Error | null, client?: any | boolean) => void): void; + + errorHandler(options?: any): MiddlewareErrorFunction; + + serializeClient(fn: SerializeClientFunction): void; + serializeClient(client: any, done: SerializeClientDoneFunction): void; + + deserializeClient(fn: DeserializeClientFunction): void; + deserializeClient(obj: any, done: DeserializeClientDoneFunction): void; +} + +export namespace grant { + interface Options { + // For maximum flexibility, multiple scope spearators can optionally be + // allowed. This allows the server to accept clients that separate scope + // with either space or comma (' ', ','). This violates the specification, + // but achieves compatibility with existing client libraries that are already + // deployed. + scopeSeparator?: string; + } + + function code(options: Options, issue: IssueGrantCodeFunction): MiddlewareFunction; + function code(issue: IssueGrantCodeFunction): MiddlewareFunction; + + function token(options: Options, issue: IssueGrantTokenFunction): MiddlewareFunction; + function token(issue: IssueGrantTokenFunction): MiddlewareFunction; } export namespace exchange { @@ -57,41 +154,42 @@ export namespace exchange { scopeSeparator?: string; } - function authorizationCode(options: Options, issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; - function authorizationCode(issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; - function code(options: Options, issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; - function code(issue: (client: any, code: string, redirectURI: string, issued: IssuedFunction) => void): MiddlewareFunction; + function authorizationCode(options: Options, issue: IssueExchangeCodeFunction): MiddlewareFunction; + function authorizationCode(issue: IssueExchangeCodeFunction): MiddlewareFunction; + + function code(options: Options, issue: IssueExchangeCodeFunction): MiddlewareFunction; + function code(issue: IssueExchangeCodeFunction): MiddlewareFunction; // arity == 5; issue(client, scope, req.body, req.authInfo, issued); - function clientCredentials(options: Options, issue: (client: any, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction; + function clientCredentials(options: Options, issue: (client: any, scope: string[], body: any, authInfo: any, issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 4; issue(client, scope, req.body, issued); - function clientCredentials(options: Options, issue: (client: any, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction; + function clientCredentials(options: Options, issue: (client: any, scope: string[], body: any, issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 3; issue(client, scope, issued); - function clientCredentials(options: Options, issue: (client: any, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function clientCredentials(options: Options, issue: (client: any, scope: string[], issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 2; issue(client, issued); - function clientCredentials(options: Options, issue: (client: any, issued: IssuedFunction) => void): MiddlewareFunction; - function clientCredentials(issue: (client: any, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; - function clientCredentials(issue: (client: any, issued: IssuedFunction) => void): MiddlewareFunction; + function clientCredentials(options: Options, issue: (client: any, issued: ExchangeDoneFunction) => void): MiddlewareFunction; + function clientCredentials(issue: (client: any, scope: string[], issued: ExchangeDoneFunction) => void): MiddlewareFunction; + function clientCredentials(issue: (client: any, issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 7; issue(client, username, passwd, scope, req.body, req.authInfo, issued); - function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction; + function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], body: any, authInfo: any, issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 6; issue(client, username, passwd, scope, req.body, issued); - function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction; + function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], body: any, issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 5; issue(client, username, passwd, scope, issued); - function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function password(options: Options, issue: (client: any, username: string, password: string, scope: string[], issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 4; issue(client, username, passwd, issued); - function password(options: Options, issue: (client: any, username: string, password: string, issued: IssuedFunction) => void): MiddlewareFunction; - function password(issue: (client: any, username: string, password: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; - function password(issue: (client: any, username: string, password: string, issued: IssuedFunction) => void): MiddlewareFunction; + function password(options: Options, issue: (client: any, username: string, password: string, issued: ExchangeDoneFunction) => void): MiddlewareFunction; + function password(issue: (client: any, username: string, password: string, scope: string[], issued: ExchangeDoneFunction) => void): MiddlewareFunction; + function password(issue: (client: any, username: string, password: string, issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 6; issue(client, refreshToken, scope, req.body, req.authInfo, issued); - function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], body: any, authInfo: any, issued: IssuedFunction) => void): MiddlewareFunction; + function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], body: any, authInfo: any, issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 5; issue(client, refreshToken, scope, req.body, issued); - function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], body: any, issued: IssuedFunction) => void): MiddlewareFunction; + function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], body: any, issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 4; issue(client, refreshToken, scope, issued); - function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; + function refreshToken(options: Options, issue: (client: any, refreshToken: string, scope: string[], issued: ExchangeDoneFunction) => void): MiddlewareFunction; // arity == 3; issue(client, refreshToken, issued); - function refreshToken(options: Options, issue: (client: any, refreshToken: string, issued: IssuedFunction) => void): MiddlewareFunction; - function refreshToken(issue: (client: any, refreshToken: string, scope: string[], issued: IssuedFunction) => void): MiddlewareFunction; - function refreshToken(issue: (client: any, refreshToken: string, issued: IssuedFunction) => void): MiddlewareFunction; + function refreshToken(options: Options, issue: (client: any, refreshToken: string, issued: ExchangeDoneFunction) => void): MiddlewareFunction; + function refreshToken(issue: (client: any, refreshToken: string, scope: string[], issued: ExchangeDoneFunction) => void): MiddlewareFunction; + function refreshToken(issue: (client: any, refreshToken: string, issued: ExchangeDoneFunction) => void): MiddlewareFunction; } diff --git a/types/oauth2orize/oauth2orize-tests.ts b/types/oauth2orize/oauth2orize-tests.ts index 9795b3e89e..49d7c94794 100644 --- a/types/oauth2orize/oauth2orize-tests.ts +++ b/types/oauth2orize/oauth2orize-tests.ts @@ -7,15 +7,15 @@ import * as http from 'http'; const server = oauth2orize.createServer(); // Register Grants -// server.grant(oauth2orize.grant.code(function(client, redirectURI, user, ares, done) { -// var code = utils.uid(16); +server.grant(oauth2orize.grant.code((client, redirectURI, user, ares, done) => { + // var code = utils.uid(16); -// var ac = new AuthorizationCode(code, client.id, redirectURI, user.id, ares.scope); -// ac.save(function(err) { -// if (err) { return done(err); } -// return done(null, code); -// }); -// })); + // var ac = new AuthorizationCode(code, client.id, redirectURI, user.id, ares.scope); + // ac.save(function(err) { + // if (err) { return done(err); } + // return done(null, code); + // }); +})); // Register Exchanges @@ -25,8 +25,8 @@ class AuthorizationCode { }) => void): void {} } -server.exchange(oauth2orize.exchange.code(function(client, code, redirectURI, done) { - AuthorizationCode.findOne(code, function(err, code) { +server.exchange(oauth2orize.exchange.code((client, code, redirectURI, done) => { + AuthorizationCode.findOne(code, (err, code) => { if (err) { return done(err); } if (client.id !== code.clientId) { return done(null, false); } if (redirectURI !== code.redirectURI) { return done(null, false); } @@ -50,27 +50,27 @@ class Clients { // app.get('/dialog/authorize', // login.ensureLoggedIn(), - server.authorize(function(clientID, redirectURI, done) { - Clients.findOne(clientID, function(err, client) { + server.authorize((clientID, redirectURI, done) => { + Clients.findOne(clientID, (err, client) => { if (err) { return done(err); } if (!client) { return done(null, false); } if (client.redirectURI != redirectURI) { return done(null, false); } return done(null, client, client.redirectURI); }); }), - function(req: http.IncomingMessage, res: http.ServerResponse) { + (req: http.IncomingMessage, res: http.ServerResponse) => { // res.render('dialog', { transactionID: req.oauth2.transactionID, // user: req.user, client: req.oauth2.client }); } // ); // Session Serialization -server.serializeClient(function(client, done) { +server.serializeClient((client, done) => { return done(null, client.id); }); -server.deserializeClient(function(id, done) { - Clients.findOne(id, function(err, client) { +server.deserializeClient((id, done) => { + Clients.findOne(id, (err, client) => { if (err) { return done(err); } return done(null, client); }); From 172eb8218d2838c4896d46553ce4d8ac905ac562 Mon Sep 17 00:00:00 2001 From: Maxim Kulikov Date: Wed, 29 Mar 2017 15:52:59 +0300 Subject: [PATCH 14/31] Define debounce option in ng-model-options --- types/angular/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 485ad9ebb3..023f83dd1c 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -413,7 +413,7 @@ declare namespace angular { // https://docs.angularjs.org/api/ng/directive/ngModelOptions interface INgModelOptions { updateOn?: string; - debounce?: any; + debounce?: number | { [key: string]: number; }; allowInvalid?: boolean; getterSetter?: boolean; timezone?: string; From 8d717e1e250e6958fb33b1eb8144a25e891fc859 Mon Sep 17 00:00:00 2001 From: Gilad Gray Date: Wed, 29 Mar 2017 14:52:20 -0700 Subject: [PATCH 15/31] add types for kss --- types/kss/index.d.ts | 149 ++++++++++++++++++++++++++++++++++++++++ types/kss/kss-tests.ts | 10 +++ types/kss/tsconfig.json | 23 +++++++ types/kss/tslint.json | 3 + 4 files changed, 185 insertions(+) create mode 100644 types/kss/index.d.ts create mode 100644 types/kss/kss-tests.ts create mode 100644 types/kss/tsconfig.json create mode 100644 types/kss/tslint.json diff --git a/types/kss/index.d.ts b/types/kss/index.d.ts new file mode 100644 index 0000000000..0937ba408e --- /dev/null +++ b/types/kss/index.d.ts @@ -0,0 +1,149 @@ +// Type definitions for KSS 3.0.0-beta +// Project: https://github.com/kss-node/kss-node +// Definitions by: Gilad Gray +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Builds a styleguide given the proper options. */ +declare function kss(options?: kss.IKssOptions): Promise; +declare namespace kss { + interface IFile { + /** bath to source directory */ + base: string; + /** file contents */ + contents: string; + /** full path to file */ + path: string; + } + + interface ISource { + /** The name of the file. */ + filename: string; + /** The full path of the file. */ + path: string; + /** The line number where the KSS comment is found. */ + line: number; + } + + interface IOptions { + /** + * Whether to automatically format Markdown using [marked](https://github.com/chjj/marked). + * Enabled by default. + * @default true + */ + markdown?: boolean; + /** + * Use a regex or string (e.g. `*.less|*.css`) to only parse files matching this value. + * @default *.css|*.less|*.sass|*.scss|*.styl|*.stylus + */ + mask?: string | RegExp; + /** + * kss-node makes the header available separately from the description. To make kss-node + * behave like the Ruby KSS, disable this option and the title will remain a part of the + * description. Enabled by default. + * @default true. + */ + header?: boolean; + } + + interface IKssOptions extends IOptions { + builder?: any; + clone?: boolean; + custom?: any; + logErrorFunction?: (...msg: string[]) => void; + json?: boolean; + mask?: string | RegExp; + source: string[]; + verbose?: boolean; + } + + type CallbackFn = (error: Error | null, styleguide: KssStyleguide) => void; + + class KssStyleguide { + constructor(data?: object); + autoInit(autoInit: boolean): KssStyleguide; + customPropertyNames(): string[]; + customPropertyNames(names: string | string[]): KssStyleguide; + hasNumericReferences(): boolean; + init(): KssStyleguide; + referenceDelimiter(): string; + sections(): KssSection[]; + sections(query: string | RegExp): false | KssSection | KssSection[]; + sections(sections: KssSection | KssSection[]): KssStyleguide; + toJSON(): object; + } + + class KssSection { + constructor(data?: object); + custom(name: string): any; + custom(name: string, value: any): KssSection; + customPropertyNames(): string[]; + deprecated(): boolean; + deprecated(deprecated: boolean): KssSection; + depth(): number; + depth(depth: number): KssSection; + description(): string; + description(description: string): KssSection; + experimental(): boolean; + experimental(experimental: boolean): KssSection; + header(): string; + header(header: string): KssSection; + markup(): false | string; + markup(markup: string): KssSection; + modifiers(): KssModifier[]; + modifiers(query: number | string): false | KssModifier; + modifiers(modifiers: KssModifier | KssModifier[]): KssSection; + parameters(): KssParameter[]; + parameters(query: number | string): false | KssParameter; + parameters(parameters: KssParameter | KssParameter[]): KssSection; + reference(): string; + reference(reference: string): KssSection; + referenceNumber(): string; + referenceNumber(referenceNumber: string): KssSection; + referenceURI(): string; + referenceURI(referenceURI: string): KssSection; + source(): ISource; + source(source: ISource): KssSection; + sourceFileName(): string; + sourceLine(): string; + styleGuide(): KssStyleguide; + styleGuide(styleguide: KssStyleguide): KssSection; + toJSON(): object; + weight(): number; + weight(weight: number): KssSection; + } + + class KssModifier { + constructor(data?: object); + className(): string; + className(className: string): KssModifier; + description(): string; + description(description: string): KssModifier; + markup(): string; + markup(markup: string): KssModifier; + name(): string; + name(name: string): KssModifier; + section(): KssSection; + section(section: KssSection): KssModifier; + toJSON(): object; + } + + class KssParameter { + constructor(data?: object); + defaultValue(): string; + description(): string; + description(description: string): KssParameter; + name(): string; + name(name: string): KssParameter; + section(): KssSection; + section(section: KssSection): KssParameter; + toJSON(): object; + } + + /** Parse a string of documented CSS, or an array of file objects with their content. */ + function parse(input: string | IFile[], options: IOptions): KssStyleguide; + + /** Traverse a directory, parse its contents, and create a `KssStyleGuide`. */ + function traverse(directory: string | string[], options: IOptions): Promise; +} + +export = kss; diff --git a/types/kss/kss-tests.ts b/types/kss/kss-tests.ts new file mode 100644 index 0000000000..1ad03a785b --- /dev/null +++ b/types/kss/kss-tests.ts @@ -0,0 +1,10 @@ +import kss = require("kss"); + +kss.traverse("src", { markdown: false }) + .then((styleguide) => styleguide.sections()) + .then((sections) => sections.map((s) => s.toJSON())) + .then((json) => console.log(json)); + +const json = kss.parse("file contents", { header: false }).sections().map((s) => s.toJSON()); + +// both json vars should be the same type diff --git a/types/kss/tsconfig.json b/types/kss/tsconfig.json new file mode 100644 index 0000000000..4dcd9b1539 --- /dev/null +++ b/types/kss/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "kss-tests.ts" + ] +} diff --git a/types/kss/tslint.json b/types/kss/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/types/kss/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} From e2be06066be093783f698a3b900d463038339b70 Mon Sep 17 00:00:00 2001 From: Gilad Gray Date: Wed, 29 Mar 2017 14:57:03 -0700 Subject: [PATCH 16/31] fix linting --- types/kss/index.d.ts | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/types/kss/index.d.ts b/types/kss/index.d.ts index 0937ba408e..1a7359c1da 100644 --- a/types/kss/index.d.ts +++ b/types/kss/index.d.ts @@ -4,9 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** Builds a styleguide given the proper options. */ -declare function kss(options?: kss.IKssOptions): Promise; +declare function kss(options?: kss.KssOptions): Promise; declare namespace kss { - interface IFile { + interface File { /** bath to source directory */ base: string; /** file contents */ @@ -15,7 +15,7 @@ declare namespace kss { path: string; } - interface ISource { + interface Source { /** The name of the file. */ filename: string; /** The full path of the file. */ @@ -24,7 +24,7 @@ declare namespace kss { line: number; } - interface IOptions { + interface Options { /** * Whether to automatically format Markdown using [marked](https://github.com/chjj/marked). * Enabled by default. @@ -45,11 +45,11 @@ declare namespace kss { header?: boolean; } - interface IKssOptions extends IOptions { + interface KssOptions extends Options { builder?: any; clone?: boolean; custom?: any; - logErrorFunction?: (...msg: string[]) => void; + logErrorFunction?(...msg: string[]): void; json?: boolean; mask?: string | RegExp; source: string[]; @@ -59,7 +59,7 @@ declare namespace kss { type CallbackFn = (error: Error | null, styleguide: KssStyleguide) => void; class KssStyleguide { - constructor(data?: object); + constructor(data?: any); autoInit(autoInit: boolean): KssStyleguide; customPropertyNames(): string[]; customPropertyNames(names: string | string[]): KssStyleguide; @@ -69,11 +69,11 @@ declare namespace kss { sections(): KssSection[]; sections(query: string | RegExp): false | KssSection | KssSection[]; sections(sections: KssSection | KssSection[]): KssStyleguide; - toJSON(): object; + toJSON(): any; } class KssSection { - constructor(data?: object); + constructor(data?: any); custom(name: string): any; custom(name: string, value: any): KssSection; customPropertyNames(): string[]; @@ -101,19 +101,19 @@ declare namespace kss { referenceNumber(referenceNumber: string): KssSection; referenceURI(): string; referenceURI(referenceURI: string): KssSection; - source(): ISource; - source(source: ISource): KssSection; + source(): Source; + source(source: Source): KssSection; sourceFileName(): string; sourceLine(): string; styleGuide(): KssStyleguide; styleGuide(styleguide: KssStyleguide): KssSection; - toJSON(): object; + toJSON(): any; weight(): number; weight(weight: number): KssSection; } class KssModifier { - constructor(data?: object); + constructor(data?: any); className(): string; className(className: string): KssModifier; description(): string; @@ -124,11 +124,11 @@ declare namespace kss { name(name: string): KssModifier; section(): KssSection; section(section: KssSection): KssModifier; - toJSON(): object; + toJSON(): any; } class KssParameter { - constructor(data?: object); + constructor(data?: any); defaultValue(): string; description(): string; description(description: string): KssParameter; @@ -136,14 +136,14 @@ declare namespace kss { name(name: string): KssParameter; section(): KssSection; section(section: KssSection): KssParameter; - toJSON(): object; + toJSON(): any; } - /** Parse a string of documented CSS, or an array of file objects with their content. */ - function parse(input: string | IFile[], options: IOptions): KssStyleguide; + /** Parse a string of documented CSS, or an array of file anys with their content. */ + function parse(input: string | File[], options: Options): KssStyleguide; /** Traverse a directory, parse its contents, and create a `KssStyleGuide`. */ - function traverse(directory: string | string[], options: IOptions): Promise; + function traverse(directory: string | string[], options: Options): Promise; } export = kss; From 8bd131f9fe4d00090d39b72f3ff5f4a991440d17 Mon Sep 17 00:00:00 2001 From: Gilad Gray Date: Wed, 29 Mar 2017 16:31:05 -0700 Subject: [PATCH 17/31] enable strictNullChecks --- types/kss/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/kss/tsconfig.json b/types/kss/tsconfig.json index 4dcd9b1539..30cdd58f41 100644 --- a/types/kss/tsconfig.json +++ b/types/kss/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" From 66df4cafa960207cc8bd9f60f881976475649704 Mon Sep 17 00:00:00 2001 From: Jens Duttke Date: Thu, 30 Mar 2017 09:39:15 +0200 Subject: [PATCH 18/31] requirejs: RequireError.requireModules can be null In the require.js source code (line 901 in v2.3.3), requireModules is set to `null`. --- types/requirejs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/requirejs/index.d.ts b/types/requirejs/index.d.ts index ac116494f3..b2d5879e85 100644 --- a/types/requirejs/index.d.ts +++ b/types/requirejs/index.d.ts @@ -48,7 +48,7 @@ interface RequireError extends Error { /** * Required modules. **/ - requireModules: string[]; + requireModules: string[] | null; /** * The original error, if there is one (might be null). From d405d11df40c3e184143d6a3e52d2a754493461d Mon Sep 17 00:00:00 2001 From: maghis Date: Thu, 30 Mar 2017 12:21:33 -0400 Subject: [PATCH 19/31] Correct return type for getContents --- types/stream-buffers/index.d.ts | 2 +- types/stream-buffers/stream-buffers-tests.ts | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/types/stream-buffers/index.d.ts b/types/stream-buffers/index.d.ts index aa0602b835..59cf0e1df1 100644 --- a/types/stream-buffers/index.d.ts +++ b/types/stream-buffers/index.d.ts @@ -15,7 +15,7 @@ export class WritableStreamBuffer extends stream.Writable { constructor(options?: WritableStreamBufferOptions); size(): number; maxSize(): number; - getContents(length?: number): any; + getContents(length?: number): Buffer; getContentsAsString(encoding?: string, length?: number): string; } diff --git a/types/stream-buffers/stream-buffers-tests.ts b/types/stream-buffers/stream-buffers-tests.ts index c7051023b8..b50a1db286 100644 --- a/types/stream-buffers/stream-buffers-tests.ts +++ b/types/stream-buffers/stream-buffers-tests.ts @@ -20,16 +20,16 @@ myWritableStreamBuffer.size(); myWritableStreamBuffer.maxSize(); // Gets all held data as a Buffer. -myWritableStreamBuffer.getContents(); +const contents: Buffer = myWritableStreamBuffer.getContents(); // Gets all held data as a utf8 string. -myWritableStreamBuffer.getContentsAsString('utf8'); +const stringContents: string = myWritableStreamBuffer.getContentsAsString('utf8'); // Gets first 5 bytes as a Buffer. -myWritableStreamBuffer.getContents(5); +const contents2: Buffer = myWritableStreamBuffer.getContents(5); // Gets first 5 bytes as a utf8 string. -myWritableStreamBuffer.getContentsAsString('utf8', 5); +const stringContents2: string = myWritableStreamBuffer.getContentsAsString('utf8', 5); const myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({ frequency: 10, // in milliseconds. From c0083ec134066c4fcc96470deb9aebaf1ae42ef3 Mon Sep 17 00:00:00 2001 From: Justin Firth Date: Thu, 30 Mar 2017 13:03:14 -0400 Subject: [PATCH 20/31] Added version commit --- types/hyperscript/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/hyperscript/index.d.ts b/types/hyperscript/index.d.ts index b57aa455f6..b4384ba302 100644 --- a/types/hyperscript/index.d.ts +++ b/types/hyperscript/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/dominictarr/hyperscript // Definitions by: Mike Linkovich // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 declare module 'hyperscript' { From deed8459fa2d763c9f484322e793b81fbb655555 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 30 Mar 2017 11:29:31 -0700 Subject: [PATCH 21/31] Make braintree a UMD module Add tests to show that it can be imported as well as used globally. The change required lots of refactoring. The merged interface-classes are gone since their constructors were not supposed to be used anyway. And everything moved into the BraintreeWeb namespace, which was renamed to just `braintree`. --- types/braintree-web/braintree-node-tests.ts | 440 +++++++++++++++++ types/braintree-web/braintree-web-tests.ts | 54 +- types/braintree-web/index.d.ts | 520 +++++++------------- types/braintree-web/tsconfig.json | 5 +- 4 files changed, 639 insertions(+), 380 deletions(-) create mode 100644 types/braintree-web/braintree-node-tests.ts diff --git a/types/braintree-web/braintree-node-tests.ts b/types/braintree-web/braintree-node-tests.ts new file mode 100644 index 0000000000..9eed5b228d --- /dev/null +++ b/types/braintree-web/braintree-node-tests.ts @@ -0,0 +1,440 @@ +import * as braintree from 'braintree-web'; + +let version: string = braintree.VERSION; + +let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0="; + +braintree.client.create({ + authorization: clientToken +}, function (error: braintree.BraintreeError, clientInstance: any) { + + var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement; + var data: { creditCard: braintree.CreditCardInfo } = { + creditCard: { + number: form['cc-number'].value, + cvv: form['cc-cvv'].value, + expirationDate: form['cc-date'].value, + billingAddress: { + postalCode: form['cc-postal'].value + } + } + }; + + clientInstance.request({ + endpoint: 'payment_methods/credit_cards', + method: 'post', + data: data + }, function (requestErr: braintree.BraintreeError, response: { creditCards: any[]; }) { + if (requestErr) { throw new Error(requestErr.message); } + + console.log('Got nonce:', response.creditCards[0].nonce); + }); + + braintree.hostedFields.create({ + client: clientInstance, + styles: { + 'input': { + 'font-size': '16pt', + 'color': '#3A3A3A' + }, + + '.number': { + 'font-family': 'monospace' + }, + '.valid': { + 'color': 'green' + } + }, + fields: { + number: { + selector: '#card-number' + }, + cvv: { + selector: '#cvv', + type: 'password' + }, + expirationMonth: { + selector: '#expiration-month', + select: { + options: ["01 - Jan", "02 - Feb", "03 - Mar", "04 - Apr", "05 - May", "06 - Jun", "07 - Jul", "08 - Aug", "09 - Sep", "10 - Oct", "11 - Nov", "12 - Dec"] + } + }, + expirationYear: { + selector: '#expiration-year', + select: true + } + } + }, function (hostedFieldsErr?: braintree.BraintreeError, hostedFieldsInstance?: any) { + + if (hostedFieldsErr) { + // Handle error in Hosted Fields creation + console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`); + return; + } + + let form = new HTMLFormElement(); + + form.addEventListener('submit', function (event: Event) { + event.preventDefault(); + + hostedFieldsInstance.tokenize(function (tokenizeErr: braintree.BraintreeError, payload: braintree.HostedFieldsTokenizePayload) { + if (tokenizeErr) { + // Handle error in Hosted Fields tokenization + switch (tokenizeErr.code) { + case 'HOSTED_FIELDS_FIELDS_EMPTY': + console.error('All fields are empty! Please fill out the form.'); + break; + case 'HOSTED_FIELDS_FIELDS_INVALID': + console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys); + break; + case 'HOSTED_FIELDS_FAILED_TOKENIZATION': + console.error('Tokenization failed server side. Is the card valid?'); + break; + case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR': + console.error('Network error occurred when tokenizing.'); + break; + default: + console.error('Something bad happened!', tokenizeErr); + } + return; + } + + // Put `payload.nonce` into the `payment-method-nonce` input, and then + // submit the form. Alternatively, you could send the nonce to your server + // with AJAX. + (document.querySelector('input[name="payment-method-nonce"]') as HTMLInputElement).value = payload.nonce; + form.submit(); + }); + }, false); + + hostedFieldsInstance.on('focus', function (event: braintree.HostedFieldsStateObject) { + console.log(event.emittedBy, 'has been focused'); + }); + + hostedFieldsInstance.teardown(function (teardownErr: braintree.BraintreeError) { + if (teardownErr) { + console.error('Could not tear down Hosted Fields!'); + } else { + console.info('Hosted Fields has been torn down!'); + } + }); + + hostedFieldsInstance.tokenize({ + vault: true + }, function (tokenizeErr: braintree.BraintreeError, payload: braintree.HostedFieldsTokenizePayload) { + if (tokenizeErr) { + console.error(tokenizeErr); + } else { + console.log('Got nonce:', payload.nonce); + } + }); + + hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: braintree.BraintreeError) { + if (addClassErr) { + console.error(addClassErr); + } + }); + + hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: braintree.BraintreeError) { + if (addClassErr) { + console.error(addClassErr); + return; + } + + // some time later... + hostedFieldsInstance.removeClass('number', 'custom-class'); + }); + + hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: braintree.BraintreeError) { + if (placeholderErr) { + console.error(placeholderErr); + } + }); + + hostedFieldsInstance.on('cardTypeChange', function (event: braintree.HostedFieldsStateObject) { + // Update the placeholder value if there is only one possible card type + if (event.cards.length === 1) { + braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: braintree.BraintreeError) { + if (placeholderErr) { + // Handle errors, such as invalid field name + console.error(placeholderErr); + } + }); + } + }); + + hostedFieldsInstance.clear('number', function (clearErr: braintree.BraintreeError) { + if (clearErr) { + console.error(clearErr); + } + }); + + hostedFieldsInstance.clear('number'); + hostedFieldsInstance.clear('cvv'); + hostedFieldsInstance.clear('expirationDate'); + + var state = braintree.hostedFields.getState(); + + var formValid = Object.keys(state.fields).every(function (key) { + return state.fields[key].isValid; + }); + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr?: braintree.BraintreeError, applePayInstance?: any) { + if (createErr) { + // Handle error in client creation + console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`); + + return; + } + + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var paymentRequest = braintree.applePay.createPaymentRequest(request); + + console.log(paymentRequest); + // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] } + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) { + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var session = new braintree.ApplePaySession(1, request); + + session.onvalidatemerchant = function (event: { validationURL: string }) { + braintree.applePay.performValidation({ + validationURL: event.validationURL + }, function (err, validationData) { + if (err) { + console.error(err); + session.abort(); + return; + } + session.completeMerchantValidation(validationData); + }); + }; + }); + + braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) { + let request = { + countryCode: 'US', + currencyCode: 'USD', + supportedNetworks: ['visa', 'masterCard'], + merchantCapabilities: ['supports3DS'], + total: { label: 'Your Label', amount: '10.00' }, + }; + + var session = new braintree.ApplePaySession(1, request); + + session.onpaymentauthorized = function (event) { + braintree.applePay.tokenize({ + token: event.payment.token + }, function (err, tokenizedPayload) { + if (err) { + session.completePayment(braintree.ApplePayStatusCodes.STATUS_FAILURE); + return; + } + session.completePayment(braintree.ApplePayStatusCodes.STATUS_SUCCESS); + + // Send the tokenizedPayload to your server. + }); + }; + }); + + braintree.paypal.create({ + client: clientInstance + }, function (createErr, paypalInstance) { + if (createErr) { + if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') { + console.error('This browser is not supported.'); + } else { + console.error('Error!', createErr); + } + } + + let button = new HTMLButtonElement(); + + button.addEventListener('click', function () { + // Disable the button so that we don't attempt to open multiple popups. + button.setAttribute('disabled', 'disabled'); + + // Because PayPal tokenization opens a popup, this must be called + // as a result of a user action, such as a button click. + paypalInstance.tokenize({ + flow: 'vault' // Required + // Any other tokenization options + }, function (tokenizeErr: braintree.BraintreeError, payload: braintree.PayPalTokenizePayload) { + button.removeAttribute('disabled'); + + if (tokenizeErr) { + // Handle tokenization errors or premature flow closure + + switch (tokenizeErr.code) { + case 'PAYPAL_POPUP_CLOSED': + console.error('Customer closed PayPal popup.'); + break; + case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED': + console.error('PayPal tokenization failed. See details:', tokenizeErr.details); + break; + case 'PAYPAL_FLOW_FAILED': + console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details); + break; + default: + console.error('Error!', tokenizeErr); + } + } else { + // Submit payload.nonce to your server + } + }); + }); + }); + + braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) { + if (createErr) { + console.error(createErr); + return; + } + + unionpayInstance.fetchCapabilities({ + card: { + number: '4111111111111111' + } + }, function (fetchErr: braintree.BraintreeError, cardCapabilities: braintree.UnionPayFetchCapabilitiesPayload) { + if (fetchErr) { + console.error(fetchErr); + return; + } + + if (cardCapabilities.isUnionPay) { + if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) { + // Braintree cannot process this UnionPay card. + // Ask the user for a different card. + return; + } + + if (cardCapabilities.isDebit) { + // CVV and expiration date are not required + } else { + // CVV and expiration date are required + } + + // Show mobile phone number field for enrollment + } + }); + + unionpayInstance.enroll({ + card: { + number: '4111111111111111', + expirationMonth: '12', + expirationYear: '2038' + }, + mobile: { + countryCode: '62', + number: '111111111111' + } + }, function (enrollErr: braintree.BraintreeError, response: braintree.UnionPayEnrollPayload) { + if (enrollErr) { + console.error(enrollErr); + return; + } + + if (response.smsCodeRequired) { + // If smsCodeRequired, wait for SMS auth code from customer + // Then use response.enrollmentId during {@link UnionPay#tokenize} + } else { + // SMS code is not required from the user. + // {@link UnionPay#tokenize} can be called immediately + } + }); + + let enrollResponse: { + enrollmentId: string + }; + + unionpayInstance.tokenize({ + card: { + number: '4111111111111111', + expirationMonth: '12', + expirationYear: '2038', + cvv: '123' + }, + enrollmentId: enrollResponse.enrollmentId, // Returned from enroll + smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted + }, function (tokenizeErr: braintree.BraintreeError, response: braintree.UnionPayTokenizePayload) { + if (tokenizeErr) { + console.error(tokenizeErr); + return; + } + + // Send response.nonce to your server + }); + + unionpayInstance.teardown(function (teardownErr: braintree.BraintreeError) { + if (teardownErr) { + console.error('Could not tear down UnionPay.'); + } else { + console.log('UnionPay has been torn down.'); + } + }); + }); +}); + +let existingNonce = "fake-valid-nonce"; +let submitNonceToServer: (nonce: string) => void; + +braintree.threeDSecure.verifyCard({ + nonce: existingNonce, + amount: 123.45, + addFrame: function (err, iframe) { + // Set up your UI and add the iframe. + let my3DSContainer = document.createElement('div'); + my3DSContainer.appendChild(iframe); + document.body.appendChild(my3DSContainer); + }, + removeFrame: function () { + let my3DSContainer = document.createElement('div'); + + // Remove UI that you added in addFrame. + document.body.removeChild(my3DSContainer); + } +}, function (err: braintree.BraintreeError, payload: braintree.ThreeDSecureVerifyPayload) { + if (err) { + console.error(err); + return; + } + + if (payload.liabilityShifted) { + // Liablity has shifted + submitNonceToServer(payload.nonce); + } else if (payload.liabilityShiftPossible) { + // Liablity may still be shifted + // Decide if you want to submit the nonce + } else { + // Liablity has not shifted and will not shift + // Decide if you want to submit the nonce + } +}); + +braintree.threeDSecure.cancelVerifyCard(function (err: braintree.BraintreeError, verifyPayload: braintree.ThreeDSecureVerifyPayload) { + if (err) { + // Handle error + console.log(err.message); // No verification payload available + return; + } + + verifyPayload.nonce; // The nonce returned from the 3ds lookup call + verifyPayload.liabilityShifted; // boolean + verifyPayload.liabilityShiftPossible; // boolean +}); diff --git a/types/braintree-web/braintree-web-tests.ts b/types/braintree-web/braintree-web-tests.ts index c9aee724c0..22073363d4 100644 --- a/types/braintree-web/braintree-web-tests.ts +++ b/types/braintree-web/braintree-web-tests.ts @@ -4,10 +4,10 @@ let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiO braintree.client.create({ authorization: clientToken -}, function (error: BraintreeError, clientInstance: any) { +}, function (error: braintree.BraintreeError, clientInstance: any) { var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement; - var data: { creditCard: BraintreeWeb.CreditCardInfo } = { + var data: { creditCard: braintree.CreditCardInfo } = { creditCard: { number: form['cc-number'].value, cvv: form['cc-cvv'].value, @@ -22,7 +22,7 @@ braintree.client.create({ endpoint: 'payment_methods/credit_cards', method: 'post', data: data - }, function (requestErr: BraintreeError, response: { creditCards: any[]; }) { + }, function (requestErr: braintree.BraintreeError, response: { creditCards: any[]; }) { if (requestErr) { throw new Error(requestErr.message); } console.log('Got nonce:', response.creditCards[0].nonce); @@ -62,7 +62,7 @@ braintree.client.create({ select: true } } - }, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) { + }, function (hostedFieldsErr?: braintree.BraintreeError, hostedFieldsInstance?: any) { if (hostedFieldsErr) { // Handle error in Hosted Fields creation @@ -75,7 +75,7 @@ braintree.client.create({ form.addEventListener('submit', function (event: Event) { event.preventDefault(); - hostedFieldsInstance.tokenize(function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) { + hostedFieldsInstance.tokenize(function (tokenizeErr: braintree.BraintreeError, payload: braintree.HostedFieldsTokenizePayload) { if (tokenizeErr) { // Handle error in Hosted Fields tokenization switch (tokenizeErr.code) { @@ -105,11 +105,11 @@ braintree.client.create({ }); }, false); - hostedFieldsInstance.on('focus', function (event: BraintreeWeb.HostedFieldsStateObject) { + hostedFieldsInstance.on('focus', function (event: braintree.HostedFieldsStateObject) { console.log(event.emittedBy, 'has been focused'); }); - hostedFieldsInstance.teardown(function (teardownErr: BraintreeError) { + hostedFieldsInstance.teardown(function (teardownErr: braintree.BraintreeError) { if (teardownErr) { console.error('Could not tear down Hosted Fields!'); } else { @@ -119,7 +119,7 @@ braintree.client.create({ hostedFieldsInstance.tokenize({ vault: true - }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) { + }, function (tokenizeErr: braintree.BraintreeError, payload: braintree.HostedFieldsTokenizePayload) { if (tokenizeErr) { console.error(tokenizeErr); } else { @@ -127,13 +127,13 @@ braintree.client.create({ } }); - hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) { + hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: braintree.BraintreeError) { if (addClassErr) { console.error(addClassErr); } }); - hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) { + hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: braintree.BraintreeError) { if (addClassErr) { console.error(addClassErr); return; @@ -143,16 +143,16 @@ braintree.client.create({ hostedFieldsInstance.removeClass('number', 'custom-class'); }); - hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: BraintreeError) { + hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: braintree.BraintreeError) { if (placeholderErr) { console.error(placeholderErr); } }); - hostedFieldsInstance.on('cardTypeChange', function (event: BraintreeWeb.HostedFieldsStateObject) { + hostedFieldsInstance.on('cardTypeChange', function (event: braintree.HostedFieldsStateObject) { // Update the placeholder value if there is only one possible card type if (event.cards.length === 1) { - braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: BraintreeError) { + braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: braintree.BraintreeError) { if (placeholderErr) { // Handle errors, such as invalid field name console.error(placeholderErr); @@ -161,7 +161,7 @@ braintree.client.create({ } }); - hostedFieldsInstance.clear('number', function (clearErr: BraintreeError) { + hostedFieldsInstance.clear('number', function (clearErr: braintree.BraintreeError) { if (clearErr) { console.error(clearErr); } @@ -178,7 +178,7 @@ braintree.client.create({ }); }); - braintree.applePay.create({ client: clientInstance }, function (createErr?: BraintreeError, applePayInstance?: any) { + braintree.applePay.create({ client: clientInstance }, function (createErr?: braintree.BraintreeError, applePayInstance?: any) { if (createErr) { // Handle error in client creation console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`); @@ -209,7 +209,7 @@ braintree.client.create({ total: { label: 'Your Label', amount: '10.00' }, }; - var session = new ApplePaySession(1, request); + var session = new braintree.ApplePaySession(1, request); session.onvalidatemerchant = function (event: { validationURL: string }) { braintree.applePay.performValidation({ @@ -234,17 +234,17 @@ braintree.client.create({ total: { label: 'Your Label', amount: '10.00' }, }; - var session = new ApplePaySession(1, request); + var session = new braintree.ApplePaySession(1, request); session.onpaymentauthorized = function (event) { braintree.applePay.tokenize({ token: event.payment.token }, function (err, tokenizedPayload) { if (err) { - session.completePayment(ApplePayStatusCodes.STATUS_FAILURE); + session.completePayment(braintree.ApplePayStatusCodes.STATUS_FAILURE); return; } - session.completePayment(ApplePayStatusCodes.STATUS_SUCCESS); + session.completePayment(braintree.ApplePayStatusCodes.STATUS_SUCCESS); // Send the tokenizedPayload to your server. }); @@ -273,7 +273,7 @@ braintree.client.create({ paypalInstance.tokenize({ flow: 'vault' // Required // Any other tokenization options - }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.PayPalTokenizePayload) { + }, function (tokenizeErr: braintree.BraintreeError, payload: braintree.PayPalTokenizePayload) { button.removeAttribute('disabled'); if (tokenizeErr) { @@ -309,7 +309,7 @@ braintree.client.create({ card: { number: '4111111111111111' } - }, function (fetchErr: BraintreeError, cardCapabilities: BraintreeWeb.UnionPayFetchCapabilitiesPayload) { + }, function (fetchErr: braintree.BraintreeError, cardCapabilities: braintree.UnionPayFetchCapabilitiesPayload) { if (fetchErr) { console.error(fetchErr); return; @@ -342,7 +342,7 @@ braintree.client.create({ countryCode: '62', number: '111111111111' } - }, function (enrollErr: BraintreeError, response: BraintreeWeb.UnionPayEnrollPayload) { + }, function (enrollErr: braintree.BraintreeError, response: braintree.UnionPayEnrollPayload) { if (enrollErr) { console.error(enrollErr); return; @@ -370,7 +370,7 @@ braintree.client.create({ }, enrollmentId: enrollResponse.enrollmentId, // Returned from enroll smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted - }, function (tokenizeErr: BraintreeError, response: BraintreeWeb.UnionPayTokenizePayload) { + }, function (tokenizeErr: braintree.BraintreeError, response: braintree.UnionPayTokenizePayload) { if (tokenizeErr) { console.error(tokenizeErr); return; @@ -379,7 +379,7 @@ braintree.client.create({ // Send response.nonce to your server }); - unionpayInstance.teardown(function (teardownErr: BraintreeError) { + unionpayInstance.teardown(function (teardownErr: braintree.BraintreeError) { if (teardownErr) { console.error('Could not tear down UnionPay.'); } else { @@ -407,7 +407,7 @@ braintree.threeDSecure.verifyCard({ // Remove UI that you added in addFrame. document.body.removeChild(my3DSContainer); } -}, function (err: BraintreeError, payload: BraintreeWeb.ThreeDSecureVerifyPayload) { +}, function (err: braintree.BraintreeError, payload: braintree.ThreeDSecureVerifyPayload) { if (err) { console.error(err); return; @@ -425,7 +425,7 @@ braintree.threeDSecure.verifyCard({ } }); -braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPayload: BraintreeWeb.ThreeDSecureVerifyPayload) { +braintree.threeDSecure.cancelVerifyCard(function (err: braintree.BraintreeError, verifyPayload: braintree.ThreeDSecureVerifyPayload) { if (err) { // Handle error console.log(err.message); // No verification payload available @@ -435,4 +435,4 @@ braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPay verifyPayload.nonce; // The nonce returned from the 3ds lookup call verifyPayload.liabilityShifted; // boolean verifyPayload.liabilityShiftPossible; // boolean -}); \ No newline at end of file +}); diff --git a/types/braintree-web/index.d.ts b/types/braintree-web/index.d.ts index 6d896a5efe..a30a880684 100644 --- a/types/braintree-web/index.d.ts +++ b/types/braintree-web/index.d.ts @@ -7,7 +7,7 @@ * @module braintree-web/american-express * @description This module is for use with Amex Express Checkout. To accept American Express cards, use Hosted Fields. */ -declare namespace BraintreeWeb { +declare namespace braintree { export interface AmericanExpress { /** * @static @@ -24,22 +24,6 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class - * @param {object} options Options - * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead. - * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields. - */ - export class AmericanExpress { - /** - * @class - * @param {object} options Options - * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead. - * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields. - */ - constructor(options: any); /** * Gets the rewards balance associated with a Braintree nonce. @@ -63,7 +47,7 @@ declare namespace BraintreeWeb { * }); * }); */ - public getRewardsBalance(options: { nonce: string }, callback: callback): void; + getRewardsBalance(options: { nonce: string }, callback: callback): void; /** * Gets the Express Checkout nonce profile given a nonce from American Express. @@ -87,121 +71,123 @@ declare namespace BraintreeWeb { * }); * }); */ - public getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void; + getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void; } } -// more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest +declare namespace braintree { + // more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest -// billingContact -// Billing contact information for the user. -// countryCode -//Required.The merchant’s two- letter ISO 3166 country code. -// currencyCode -// Required.The three- letter ISO 4217 currency code for the payment. -// lineItems -//A set of line items that explain recurring payments and additional charges. -// merchantCapabilities -// Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit. -// requiredBillingContactFields -// The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. -// requiredShippingContactFields -// The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. -// shippingContact -// Shipping contact information for the user. -// shippingMethods -//A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation. -// shippingType -// How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping. -// supportedNetworks -// Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa. -// total -// Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation. -interface ApplePayPaymentRequest { - total: { - label: string; - amount: string; - }; - countryCode: string; - currencyCode: string; - supportedNetworks: string[]; - merchantCapabilities: string[]; + // billingContact + // Billing contact information for the user. + // countryCode + //Required.The merchant’s two- letter ISO 3166 country code. + // currencyCode + // Required.The three- letter ISO 4217 currency code for the payment. + // lineItems + //A set of line items that explain recurring payments and additional charges. + // merchantCapabilities + // Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit. + // requiredBillingContactFields + // The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. + // requiredShippingContactFields + // The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. + // shippingContact + // Shipping contact information for the user. + // shippingMethods + //A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation. + // shippingType + // How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping. + // supportedNetworks + // Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa. + // total + // Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation. + interface ApplePayPaymentRequest { + total: { + label: string; + amount: string; + }; + countryCode: string; + currencyCode: string; + supportedNetworks: string[]; + merchantCapabilities: string[]; - billingContact?: any; - shippingContact?: any; - shippingMethods?: any; - shippingType?: any; - requiredBillingContactFields?: any; - requiredShippingContactFields?: any; -} + billingContact?: any; + shippingContact?: any; + shippingMethods?: any; + shippingType?: any; + requiredBillingContactFields?: any; + requiredShippingContactFields?: any; + } -declare enum ApplePayStatusCodes { - // The requested action succeeded. - STATUS_SUCCESS = 1, - // The requested action failed. - STATUS_FAILURE, - // The billing address is not valid. - STATUS_INVALID_BILLING_POSTAL_ADDRESS, - // The shipping address is not valid. - STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, - // The shipping contact information is not valid. - STATUS_INVALID_SHIPPING_CONTACT, - // The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction. - STATUS_PIN_REQUIRED, - // The PIN information is not valid.Cards on the China Union Pay network may require a PIN. - STATUS_PIN_INCORRECT, - // The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN. - STATUS_PIN_LOCKOUT, -} + export enum ApplePayStatusCodes { + // The requested action succeeded. + STATUS_SUCCESS = 1, + // The requested action failed. + STATUS_FAILURE, + // The billing address is not valid. + STATUS_INVALID_BILLING_POSTAL_ADDRESS, + // The shipping address is not valid. + STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, + // The shipping contact information is not valid. + STATUS_INVALID_SHIPPING_CONTACT, + // The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction. + STATUS_PIN_REQUIRED, + // The PIN information is not valid.Cards on the China Union Pay network may require a PIN. + STATUS_PIN_INCORRECT, + // The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN. + STATUS_PIN_LOCKOUT, + } -interface ApplePayPayload { - merchantIdentifier: string; - domainName: string; - displayName: string; -} + interface ApplePayPayload { + merchantIdentifier: string; + domainName: string; + displayName: string; + } -declare class ApplePaySession { - constructor(version: number, request: ApplePayPaymentRequest); + export class ApplePaySession { + constructor(version: number, request: ApplePayPaymentRequest); - canMakePayments(): boolean; + canMakePayments(): boolean; - canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean; + canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean; - completeMerchantValidation(merchantSession: any): void; + completeMerchantValidation(merchantSession: any): void; - abort(): void; + abort(): void; - begin(): void; + begin(): void; - completePayment(status: ApplePayStatusCodes): void; + completePayment(status: ApplePayStatusCodes): void; - completePaymentMethodSelection(newTotal: any, newLineItems: any): void; + completePaymentMethodSelection(newTotal: any, newLineItems: any): void; - completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void; + completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void; - completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void; + completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void; - supportsVersion(version: number): boolean; + supportsVersion(version: number): boolean; - oncancel: (event: any) => void; + oncancel: (event: any) => void; - onpaymentauthorized: (event: any) => void; + onpaymentauthorized: (event: any) => void; - onpaymentmethodselected: (event: any) => void; + onpaymentmethodselected: (event: any) => void; - onshippingcontactselected: (event: any) => void; + onshippingcontactselected: (event: any) => void; - onshippingmethodselected: (event: any) => void; + onshippingmethodselected: (event: any) => void; - onvalidatemerchant: (event: any) => void; + onvalidatemerchant: (event: any) => void; + } } /** * @module braintree-web/apple-pay * @description Accept Apple Pay on the Web. *This component is currently in beta and is subject to change.* */ -declare namespace BraintreeWeb { +declare namespace braintree { export interface ApplePay { /** * @static @@ -218,22 +204,6 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class - * @param {object} options Options - * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead. - * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments. - */ - export class ApplePay { - /** - * @class - * @param {object} options Options - * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead. - * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments. - */ - constructor(options: any); /** * Merges a payment request with Braintree defaults @@ -260,7 +230,7 @@ declare namespace BraintreeWeb { * // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] } * */ - public createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest + createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest /** * Validates the merchant website, as required by ApplePaySession before payment can be authorized. @@ -302,7 +272,7 @@ declare namespace BraintreeWeb { * }; * }); */ - public performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void; + performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void; /** * Tokenizes an Apple Pay payment. @@ -332,16 +302,14 @@ declare namespace BraintreeWeb { * }; * }); */ - public tokenize(options: { token: any }, callback: callback): void; - + tokenize(options: { token: any }, callback: callback): void; } } /** @module braintree-web/client */ -declare namespace BraintreeWeb { +declare namespace braintree { /** * This object is returned by {@link Client#getConfiguration|getConfiguration}. This information is used extensively by other Braintree modules to properly configure themselves. - * @typedef {object} Client~configuration * @property {object} client The braintree-web/client parameters. * @property {string} client.authorization A tokenizationKey or clientToken. * @property {object} gatewayConfiguration Gateway-supplied configuration. @@ -398,30 +366,13 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class - * @param {Client~configuration} configuration Options - * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead. - * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}. - */ - export class Client { - /** - * @class - * @param {Client~configuration} configuration Options - * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead. - * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}. - */ - constructor(configuration: Configuration); - /** * Returns a copy of the configuration values. * @public * @returns {Client~configuration} configuration */ - public getConfiguration(): Configuration; + getConfiguration(): Configuration; /** * Used by other modules to formulate all network requests to the Braintree gateway. It is also capable of being used directly from your own form to tokenize credit card information. However, be sure to satisfy PCI compliance if you use direct card tokenization. @@ -470,13 +421,12 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void; - + request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void; } } /** @module braintree-web/data-collector */ -declare namespace BraintreeWeb { +declare namespace braintree { export interface DataCollector { /** * @static @@ -496,24 +446,6 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class - * @global - * @name DataCollector - * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead. - * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. Before using DataCollector, make sure you have enabled advanced fraud protection in the Braintree gateway. To use your own Kount ID, contact our support team ([support@braintreepayments.com](mailto:support@braintreepayments.com) or [877.434.2894](tel:877.434.2894)). - */ - export class DataCollector { - /** - * @class - * @global - * @name DataCollector - * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead. - * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. - */ - constructor(); /** * @memberof DataCollector @@ -534,12 +466,11 @@ declare namespace BraintreeWeb { * @returns {void} */ teardown(callback?: callback): void; - } } /** @module braintree-web/hosted-fields */ -declare namespace BraintreeWeb { +declare namespace braintree { /** * Fields used in {@link module:braintree-web/hosted-fields~fieldOptions fields options} * @typedef {object} field @@ -578,7 +509,6 @@ declare namespace BraintreeWeb { } /** - * @typedef {object} HostedFields~hostedFieldsCard * @description Information about the card type, sent in {@link HostedFields~stateObject|stateObjects}. * @property {string} type The code-friendly representation of the card type. It will be one of the following strings: * - `american-express` @@ -618,7 +548,6 @@ declare namespace BraintreeWeb { } /** - * @typedef {object} HostedFields~hostedFieldsFieldData * @description Data about Hosted Fields fields, sent in {@link HostedFields~stateObject|stateObjects}. * @property {HTMLElement} container Reference to the container DOM element on your page associated with the current event. * @property {boolean} isFocused Whether or not the input is currently focused. @@ -641,7 +570,6 @@ declare namespace BraintreeWeb { } /** - * @typedef {object} HostedFields~stateObject * @description The event payload sent from {@link HostedFields#on|on} or {@link HostedFields#getState|getState}. * @property {HostedFields~hostedFieldsCard[]} cards * This will return an array of potential {@link HostedFields~hostedFieldsCard|cards}. If the card type has been determined, the array will contain only one card. @@ -679,7 +607,6 @@ declare namespace BraintreeWeb { } /** - * @typedef {object} HostedFields~tokenizePayload * @property {string} nonce The payment method nonce. * @property {object} details Additional account details. * @property {string} details.cardType Type of card, ex: Visa, MasterCard. @@ -781,22 +708,6 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class HostedFields - * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options. - * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead. - * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes. - */ - export class HostedFields { - /** - * @class HostedFields - * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options. - * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead. - * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes. - */ - constructor(options: any); /** * @name HostedFields#on @@ -829,7 +740,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public teardown(callback?: callback): void; + teardown(callback?: callback): void; /** * Tokenizes fields and returns a nonce payload. @@ -872,7 +783,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public tokenize(options?: { vault: boolean }, callback?: callback): void; + tokenize(options?: { vault: boolean }, callback?: callback): void; /** * Add a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. @@ -889,7 +800,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public addClass(field: string, classname: string, callback?: callback): void; + addClass(field: string, classname: string, callback?: callback): void; /** * Removes a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. @@ -910,7 +821,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public removeClass(field: string, classname: string, callback?: callback): void; + removeClass(field: string, classname: string, callback?: callback): void; /** * Sets the placeholder of a {@link module:braintree-web/hosted-fields~field field}. @@ -940,7 +851,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public setPlaceholder(field: string, placeholder: string, callback?: callback): void; + setPlaceholder(field: string, placeholder: string, callback?: callback): void; /** * Clear the value of a {@link module:braintree-web/hosted-fields~field field}. @@ -960,7 +871,7 @@ declare namespace BraintreeWeb { * hostedFieldsInstance.clear('cvv'); * hostedFieldsInstance.clear('expirationDate'); */ - public clear(field: string, callback?: callback): void; + clear(field: string, callback?: callback): void; /** * Returns an {@link HostedFields~stateObject|object} that includes the state of all fields and possible card types. @@ -973,14 +884,13 @@ declare namespace BraintreeWeb { * return state.fields[key].isValid; * }); */ - public getState(): any; + getState(): any; } } /** @module braintree-web/paypal */ -declare namespace BraintreeWeb { +declare namespace braintree { /** - * @typedef {object} PayPal~tokenizeReturn * @property {Function} close A handle to close the PayPal checkout flow. */ interface PayPalTokenizeReturn { @@ -988,7 +898,6 @@ declare namespace BraintreeWeb { } /** - * @typedef {object} PayPal~tokenizePayload * @property {string} nonce The payment method nonce. * @property {string} type The payment method type, always `PayPalAccount`. * @property {object} details Additional PayPal account details. @@ -1082,20 +991,6 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class - * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create} - * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component. - */ - export class PayPal { - /** - * @class - * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create} - * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component. - */ - constructor(options: any); /** * Launches the PayPal login flow and returns a nonce payload. Only one PayPal login flow should be active at a time. One way to achieve this is to disable your PayPal button while the flow is open. @@ -1192,7 +1087,7 @@ declare namespace BraintreeWeb { * }); * @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame. */ - public tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn; + tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn; /** * Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}. @@ -1200,15 +1095,13 @@ declare namespace BraintreeWeb { * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. * @returns {void} */ - public teardown(callback?: () => void): void; - + teardown(callback?: () => void): void; } } /** @module braintree-web/three-d-secure */ -declare namespace BraintreeWeb { +declare namespace braintree { /** - * @typedef {object} ThreeDSecure~verifyPayload * @property {string} nonce The new payment method nonce produced by the 3D Secure lookup. The original nonce passed into {@link ThreeDSecure#verifyCard|verifyCard} was consumed. This new nonce should be used to transact on your server. * @property {object} details Additional account details. * @property {string} details.cardType Type of card, ex: Visa, MasterCard. @@ -1250,23 +1143,6 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class - * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options - * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead. - * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow. - */ - export class ThreeDSecure { - /** - * @class - * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options - * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead. - * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow. - */ - constructor(options: any); - /** * @callback ThreeDSecure~addFrameCallback @@ -1329,7 +1205,7 @@ declare namespace BraintreeWeb { * } * }); */ - public verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void; + verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void; /** * Cancel the 3DS flow and return the verification payload if available. @@ -1349,7 +1225,7 @@ declare namespace BraintreeWeb { * verifyPayload.liabilityShiftPossible; // boolean * }); */ - public cancelVerifyCard(callback: callback): void; + cancelVerifyCard(callback: callback): void; /** * Cleanly tear down anything set up by {@link module:braintree-web/three-d-secure.create|create} @@ -1357,7 +1233,7 @@ declare namespace BraintreeWeb { * @param {errback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. * @returns {void} */ - public teardown(callback?: callback): void; + teardown(callback?: callback): void; } } @@ -1365,9 +1241,8 @@ declare namespace BraintreeWeb { * @module braintree-web/unionpay * @description This module allows you to accept UnionPay payments. *It is currently in beta and is subject to change.* */ -declare namespace BraintreeWeb { +declare namespace braintree { /** - * @typedef {object} UnionPay~tokenizePayload * @property {string} nonce The payment method nonce. * @property {string} type Always CreditCard. * @property {object} details Additional account details: @@ -1388,7 +1263,6 @@ declare namespace BraintreeWeb { } /** - * @typedef {object} UnionPay~enrollPayload * @property {string} enrollmentId UnionPay enrollment ID. This value should be passed to `tokenize`. * @property {boolean} smsCodeRequired UnionPay `smsCodeRequired` flag. *

true - the user will receive an SMS code that needs to be supplied for tokenization. @@ -1400,7 +1274,6 @@ declare namespace BraintreeWeb { } /** - * @typedef {object} UnionPay~fetchCapabilitiesPayload * @property {boolean} isUnionPay Determines if this card is a UnionPay card. * @property {boolean} isDebit Determines if this card is a debit card. This property is only present if `isUnionPay` is `true`. * @property {object} unionPay UnionPay specific properties. This property is only present if `isUnionPay` is `true`. @@ -1443,22 +1316,6 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class - * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}. - * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead. - * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card. - */ - export class UnionPay { - /** - * @class - * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}. - * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead. - * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card. - */ - constructor(options: any); /** * Fetches the capabilities of a card, including whether or not the SMS enrollment process is required. @@ -1531,7 +1388,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void; + fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void; /** * Enrolls a UnionPay card. Use {@link UnionPay#fetchCapabilities|fetchCapabilities} to determine if the SMS enrollment process is required. @@ -1594,7 +1451,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void; + enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void; /** * Tokenizes a UnionPay card and returns a nonce payload. @@ -1643,7 +1500,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void; + tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void; /** * Cleanly tear down anything set up by {@link module:braintree-web/unionpay.create|create}. This only needs to be called when using UnionPay with Hosted Fields. @@ -1659,8 +1516,7 @@ declare namespace BraintreeWeb { * }); * @returns {void} */ - public teardown(callback?: callback): void; - + teardown(callback?: callback): void; } /** @@ -1683,21 +1539,6 @@ declare namespace BraintreeWeb { * @type {string} */ VERSION: string; - } - - /** - * @class - * @param {object} options See {@link module:braintree-web/us-bank-account.create|us-bank-account.create}. - * @classdesc This class represents a US Bank Account component. Instances of this class can tokenize raw bank details or present a bank login. You cannot use this constructor directly. Use {@link module:braintree-web/us-bank-account.create|braintree.us-bank-account.create} instead. - */ - export class USBankAccount { - /** - * @class - * @param {object} options See {@link module:braintree-web/us-bank-account.create|us-bank-account.create}. - * @classdesc This class represents a US Bank Account component. Instances of this class can tokenize raw bank details or present a bank login. You cannot use this constructor directly. Use {@link module:braintree-web/us-bank-account.create|braintree.us-bank-account.create} instead. - */ - constructor(options: any) - /** * Tokenizes bank information to return a payment method nonce. You can tokenize bank details by providing information like account and routing numbers. You can also tokenize with a bank login UI that prompts the customer to log into their bank account. @@ -1778,7 +1619,7 @@ declare namespace BraintreeWeb { * }); * }); */ - public tokenize(options: { mandateText: string, bankDetails: any, bankLogin: any }, callback: callback): void; + tokenize(options: { mandateText: string, bankDetails: any, bankLogin: any }, callback: callback): void; /** * Cleanly tear down anything set up by {@link module:braintree-web/us-bank-account.create|create}. @@ -1786,77 +1627,53 @@ declare namespace BraintreeWeb { * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. * @returns {void} */ - public teardown(callback?: callback): void; - - } - -} - -declare namespace BraintreeError { - /** - * Enum for {@link BraintreeError} types. - * @name BraintreeError.types - * @enum - * @readonly - * @memberof BraintreeError - * @property {string} CUSTOMER An error caused by the customer. - * @property {string} MERCHANT An error that is actionable by the merchant. - * @property {string} NETWORK An error due to a network problem. - * @property {string} INTERNAL An error caused by Braintree code. - * @property {string} UNKNOWN An error where the origin is unknown. - */ - export enum Types { - CUSTOMER, - MERCHANT, - NETWORK, - INTERNAL, - UNKNOWN + teardown(callback?: callback): void; } } -/** - * @class - * @global - * @param {object} options Construction options - * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK. - * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}. - */ -declare class BraintreeError { - /** - * @class - * @global - * @param {object} options Construction options - * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK. - * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}. - */ - constructor(options: any); +declare namespace braintree { + export namespace BraintreeError { + /** + * Enum for {@link BraintreeError} types. + * @name BraintreeError.types + * @enum + * @readonly + * @memberof BraintreeError + * @property {string} CUSTOMER An error caused by the customer. + * @property {string} MERCHANT An error that is actionable by the merchant. + * @property {string} NETWORK An error due to a network problem. + * @property {string} INTERNAL An error caused by Braintree code. + * @property {string} UNKNOWN An error where the origin is unknown. + */ + export type Types = "CUSTOMER" | "MERCHANT" | "NETWORK" | "INTERNAL" | "UNKNOWN"; + } - /** - * @type {string} - * @description A code that corresponds to specific errors. - */ - code: string; + export interface BraintreeError { + /** + * @type {string} + * @description A code that corresponds to specific errors. + */ + code: string; - /** - * @type {string} - * @description A short description of the error. - */ - message: string; + /** + * @type {string} + * @description A short description of the error. + */ + message: string; - /** - * @type {BraintreeError.types} - * @description The type of error. - */ - type: BraintreeError.Types; + /** + * @type {BraintreeError.types} + * @description The type of error. + */ + type: BraintreeError.Types; - /** - * @type {object=} - * @description Additional information about the error, such as an underlying network error response. - */ - details: any; -} + /** + * @type {object=} + * @description Additional information about the error, such as an underlying network error response. + */ + details: any; + } -declare namespace BraintreeWeb { /** * @global * @callback callback @@ -1895,39 +1712,40 @@ declare namespace BraintreeWeb { * braintreeClient.create(...); * }); */ -interface BraintreeStatic { +declare namespace braintree { /** @type {module:braintree-web/client} */ - client: BraintreeWeb.Client; + export var client: braintree.Client; /** @type {module:braintree-web/paypal} */ - paypal: BraintreeWeb.PayPal; + export var paypal: braintree.PayPal; /** @type {module:braintree-web/hosted-fields} */ - hostedFields: BraintreeWeb.HostedFields; + export var hostedFields: braintree.HostedFields; /** @type {module:braintree-web/three-d-secure} */ - threeDSecure: BraintreeWeb.ThreeDSecure; + export var threeDSecure: braintree.ThreeDSecure; /** @type {module:braintree-web/data-collector} */ - dataCollector: BraintreeWeb.DataCollector; + export var dataCollector: braintree.DataCollector; /** @type {module:braintree-web/american-express} */ - americanExpress: BraintreeWeb.AmericanExpress; + export var americanExpress: braintree.AmericanExpress; /** @type {module:braintree-web/unionpay} */ - unionpay: BraintreeWeb.UnionPay; + export var unionpay: braintree.UnionPay; /** @type {module:braintree-web/apple-pay} */ - applePay: BraintreeWeb.ApplePay; + export var applePay: braintree.ApplePay; - /** @type {module:braintree-web/us-bank-account} */ - usBankAccount: BraintreeWeb.USBankAccount; + /** @type {module:braintree-web/us-bank-account} */ + export var usBankAccount: braintree.USBankAccount; /** * @description The current version of the SDK, i.e. `3.0.2`. * @type {string} */ - VERSION: string; + export var VERSION: string; } -declare var braintree: BraintreeStatic; +export = braintree; +export as namespace braintree; diff --git a/types/braintree-web/tsconfig.json b/types/braintree-web/tsconfig.json index abc64cd9c3..b0bd853841 100644 --- a/types/braintree-web/tsconfig.json +++ b/types/braintree-web/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", - "braintree-web-tests.ts" + "braintree-web-tests.ts", + "braintree-node-tests.ts" ] -} \ No newline at end of file +} From 7fd19dab3bc358ff05972c3320bfe0540ef01293 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders Date: Thu, 30 Mar 2017 12:22:49 -0700 Subject: [PATCH 22/31] Move tests into test folder --- types/braintree-web/{braintree-node-tests.ts => test/node.ts} | 0 types/braintree-web/{braintree-web-tests.ts => test/web.ts} | 0 types/braintree-web/tsconfig.json | 4 ++-- 3 files changed, 2 insertions(+), 2 deletions(-) rename types/braintree-web/{braintree-node-tests.ts => test/node.ts} (100%) rename types/braintree-web/{braintree-web-tests.ts => test/web.ts} (100%) diff --git a/types/braintree-web/braintree-node-tests.ts b/types/braintree-web/test/node.ts similarity index 100% rename from types/braintree-web/braintree-node-tests.ts rename to types/braintree-web/test/node.ts diff --git a/types/braintree-web/braintree-web-tests.ts b/types/braintree-web/test/web.ts similarity index 100% rename from types/braintree-web/braintree-web-tests.ts rename to types/braintree-web/test/web.ts diff --git a/types/braintree-web/tsconfig.json b/types/braintree-web/tsconfig.json index b0bd853841..d326f77f12 100644 --- a/types/braintree-web/tsconfig.json +++ b/types/braintree-web/tsconfig.json @@ -18,7 +18,7 @@ }, "files": [ "index.d.ts", - "braintree-web-tests.ts", - "braintree-node-tests.ts" + "test/web.ts", + "test/node.ts" ] } From 4cac3c5b44b595aa8a5f9c08ca57c3e0ad8aec5b Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 30 Mar 2017 12:33:22 -0700 Subject: [PATCH 23/31] Apply new lint rules in more packages (#15521) --- types/ably/ably-tests.ts | 21 +-- types/ably/index.d.ts | 16 +- types/accounting/accounting-tests.ts | 9 - types/amplify/amplify-tests.ts | 22 +-- types/amqplib/amqplib-tests.ts | 15 +- types/angular/angular-tests.ts | 9 +- types/angular/index.d.ts | 3 +- types/angular/tslint.json | 4 +- types/applepayjs/applepayjs-tests.ts | 4 - types/applepayjs/index.d.ts | 16 -- types/applepayjs/tslint.json | 4 +- .../applicationinsights-js-tests.ts | 57 +++--- types/applicationinsights-js/index.d.ts | 169 +++++++++--------- .../arcgis-rest-api/arcgis-rest-api-tests.ts | 2 +- types/arcgis-rest-api/index.d.ts | 5 +- .../arcgis-to-geojson-utils-tests.ts | 4 +- types/arcgis-to-geojson-utils/index.d.ts | 2 +- types/array-uniq/array-uniq-tests.ts | 2 +- types/array-uniq/index.d.ts | 2 +- types/croppie/croppie-tests.ts | 1 - types/croppie/index.d.ts | 1 - types/dragster/dragster-tests.ts | 6 +- types/dragster/index.d.ts | 2 +- types/expect/expect-tests.ts | 6 +- types/is-root/is-root-tests.ts | 2 +- types/ityped/index.d.ts | 2 +- types/ityped/ityped-tests.ts | 2 +- types/jimp/index.d.ts | 1 - types/jimp/jimp-tests.ts | 78 ++++---- types/jui-core/index.d.ts | 15 +- types/jui-grid/jui-grid-tests.ts | 6 +- types/left-pad/index.d.ts | 2 +- types/left-pad/left-pad-tests.ts | 2 +- types/libpq/index.d.ts | 2 +- types/node-xmpp-client/index.d.ts | 2 +- types/node-xmpp-core/index.d.ts | 6 +- types/ns-api/ns-api-tests.ts | 2 +- types/opener/opener-tests.ts | 2 +- types/pad/pad-tests.ts | 2 +- types/pem/index.d.ts | 50 +++--- types/pem/pem-tests.ts | 90 +++++----- types/plugapi/index.d.ts | 50 +++--- types/python-shell/python-shell-tests.ts | 6 +- types/qlik-visualizationextensions/index.d.ts | 32 ++-- types/rrule/index.d.ts | 95 +++++----- types/sharepoint/index.d.ts | 16 +- types/sharepoint/sharepoint-tests.ts | 5 +- types/sharepoint/tslint.json | 1 + types/tweezer.js/index.d.ts | 2 +- types/tweezer.js/tweezer.js-tests.ts | 2 +- types/ui-router-extras/index.d.ts | 4 +- types/vinyl-fs/index.d.ts | 146 +++++++-------- .../wicg-mediasession-tests.ts | 1 - types/wu/wu-tests.ts | 5 +- types/xml/xml-tests.ts | 5 +- types/xml2json/xml2json-tests.ts | 10 +- types/xmpp__jid/index.d.ts | 14 +- types/xsd-schema-validator/index.d.ts | 2 +- .../xsd-schema-validator-tests.ts | 3 +- 59 files changed, 503 insertions(+), 544 deletions(-) diff --git a/types/ably/ably-tests.ts b/types/ably/ably-tests.ts index 026ef48adc..bc50d03ce6 100644 --- a/types/ably/ably-tests.ts +++ b/types/ably/ably-tests.ts @@ -1,6 +1,6 @@ import * as Ably from 'ably'; -declare var console: { log(message: any): void }; +declare const console: { log(message: any): void }; const ApiKey = 'appId.keyId:secret'; const client = new Ably.Realtime(ApiKey); @@ -19,10 +19,9 @@ client.connection.on('failed', () => { // failed connection }); - // Subscribing to a channel -var channel = client.channels.get('test'); +const channel = client.channels.get('test'); channel.subscribe(message => { message.name; // 'greeting' message.data; // 'Hello World!' @@ -68,7 +67,6 @@ channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direct console.log(messagesPage.items.length); }); - // Presence on a channel // Getting presence: @@ -118,7 +116,7 @@ channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direct // Generate a random 256-bit key for demonstration purposes (in // practice you need to create one and distribute it to clients yourselves) Ably.Realtime.Crypto.generateRandomKey((err, key) => { - var channel = client.channels.get('channelName', { cipher: { key } }); + const channel = client.channels.get('channelName', { cipher: { key } }); channel.subscribe(message => { message.name; // 'name is not encrypted' @@ -136,7 +134,7 @@ channel.setOptions({cipher: {key: ''}}, () => { // Using the REST API -var restChannel = restClient.channels.get('test'); +const restChannel = restClient.channels.get('test'); // Publishing to a channel @@ -195,7 +193,6 @@ restChannel.presence.history((err, messagesPage) => { // PaginatedResult // Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {}); - // Generate Token and Token Request // See https://www.ably.io/documentation/general/authentication for an explanation of Ably's authentication mechanism. @@ -206,7 +203,7 @@ client.auth.requestToken((err, tokenDetails) => { // see https://www.ably.io/documentation/rest/authentication/#token-details for its properties // Now we have the token, we can send it to someone who can instantiate a client with it: - var clientUsingToken = new Ably.Realtime(tokenDetails.token); + const clientUsingToken = new Ably.Realtime(tokenDetails.token); }); // requestToken can take two optional params @@ -242,15 +239,15 @@ client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as Paginat client.time({}, (err, time) => {}); // time is in ms since epoch // Getting decoded Message objects from JSON -var messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]); +const messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]); console.log(messages[0].id); -var message = Ably.Rest.Message.fromEncoded({ id: 'foo' }); +const message = Ably.Rest.Message.fromEncoded({ id: 'foo' }); console.log(message.id); // Getting decoded PresenceMessage objects from JSON -var presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]); +const presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]); console.log(presenceMessages[0].action); -var presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' }); +const presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' }); console.log(presenceMessage.action); diff --git a/types/ably/index.d.ts b/types/ably/index.d.ts index b8d1eb9bfe..7bfc2338b6 100644 --- a/types/ably/index.d.ts +++ b/types/ably/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ably // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace ablyLib { +export namespace ablyLib { namespace ChannelState { type INITIALIZED = 'initialized'; type ATTACHING = 'attaching'; @@ -130,15 +130,15 @@ declare namespace ablyLib { * A function which is called when a new token is required. * The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically * by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object. - **/ - authCallback?: (data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void) => void; + */ + authCallback?(data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void): void; authHeaders?: { [index: string]: string }; authMethod?: HTTPMethods; authParams?: { [index: string]: string }; /** * A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format). - **/ + */ authUrl?: string; key?: string; queryTime?: boolean; @@ -259,13 +259,13 @@ declare namespace ablyLib { /** * A number controlling the verbosity of the output. Valid values are: 0 (no logs), 1 (errors only), * 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output). - **/ + */ level?: number; /** * A function to handle each line of log output. If handler is not specified, console.log is used. - **/ - handler?: (...args: any[]) => void; + */ + handler?(...args: any[]): void; } interface ChannelEvent { @@ -398,7 +398,7 @@ declare namespace ablyLib { } interface Crypto { - generateRandomKey: (callback: (error: ErrorInfo, key: string) => void) => void; + generateRandomKey(callback: (error: ErrorInfo, key: string) => void): void; } class Connection extends EventEmitter { diff --git a/types/accounting/accounting-tests.ts b/types/accounting/accounting-tests.ts index 0c11683c65..a397c559eb 100644 --- a/types/accounting/accounting-tests.ts +++ b/types/accounting/accounting-tests.ts @@ -27,8 +27,6 @@ accounting.formatMoney(5318008, { // Will recursively format an array of values: accounting.formatMoney([123, 456, [78, 9]], "$", 0); // ["$123", "$456", ["$78", "$9"]] - - // formatColumn // Format list of numbers for display: @@ -40,8 +38,6 @@ accounting.formatColumn([123, 12345], "$ ", 0); // ["$ 123", "$ 12,345"] // List of numbers can be a multi-dimensional array (formatColumn is applied recursively): accounting.formatColumn([[1, 100], [900, 9]]); // [["$ 1.00", "$100.00"], ["$900.00", "$ 9.00"]] - - // formatNumber // Example usage: @@ -58,16 +54,11 @@ accounting.formatNumber(5318008, { // Will recursively format an array of values: accounting.formatNumber([123456, [7890, 123]]); // ["123,456", ["7,890", "123"]] - - // toFixed (0.615).toFixed(2); // "0.61" accounting.toFixed(0.615, 2); // "0.62" - - - // unformat // Example usage: diff --git a/types/amplify/amplify-tests.ts b/types/amplify/amplify-tests.ts index ab4a9bf1bd..62b00052dd 100644 --- a/types/amplify/amplify-tests.ts +++ b/types/amplify/amplify-tests.ts @@ -155,15 +155,11 @@ amplify.request("twitter-search", { term: "amplifyjs" } ); // Similarly, we can create a request that searches for mentions, by accepting a username: - amplify.request.define("twitter-mentions", "ajax", { - url: "http://search.twitter.com/search.json", - dataType: "jsonp", - dataMap: data => { - return { - q: "@" + data.user - }; - } - }); +amplify.request.define("twitter-mentions", "ajax", { + url: "http://search.twitter.com/search.json", + dataType: "jsonp", + dataMap: data => ({ q: "@" + data.user }), +}); amplify.request("twitter-mentions", { user: "amplifyjs" }); @@ -241,11 +237,11 @@ amplify.request({ // amplify.request comes with built in support for status.The status parameter appears in the default success or error callbacks when using an ajax definition. - amplify.request.define("statusExample1", "ajax", { - // ... - }); +amplify.request.define("statusExample1", "ajax", { + // ... +}); - amplify.request({ +amplify.request({ resourceId: "statusExample1", success: (data, status) => { }, diff --git a/types/amqplib/amqplib-tests.ts b/types/amqplib/amqplib-tests.ts index 24dade85dc..8bfcf3c9b4 100644 --- a/types/amqplib/amqplib-tests.ts +++ b/types/amqplib/amqplib-tests.ts @@ -1,7 +1,7 @@ // promise api tests import amqp = require('amqplib'); -var msg = 'Hello World'; +const msg = 'Hello World'; // test promise api amqp.connect('amqp://localhost') @@ -21,11 +21,10 @@ amqp.connect('amqp://localhost') }); // test promise api properties -var amqpMessage: amqp.Message; +let amqpMessage: amqp.Message; amqpMessage.properties.contentType = 'application/json'; -var amqpAssertExchangeOptions: amqp.Options.AssertExchange; -var anqpAssertExchangeReplies: amqp.Replies.AssertExchange; - +let amqpAssertExchangeOptions: amqp.Options.AssertExchange; +let anqpAssertExchangeReplies: amqp.Replies.AssertExchange; // callback api tests import amqpcb = require('amqplib/callback_api'); @@ -59,7 +58,7 @@ amqpcb.connect('amqp://localhost', (err, connection) => { }); // test callback api properties -var amqpcbMessage: amqpcb.Message; +let amqpcbMessage: amqpcb.Message; amqpcbMessage.properties.contentType = 'application/json'; -var amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange; -var anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange; +let amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange; +let anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange; diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index 637ebda708..53fd245f1d 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -820,8 +820,8 @@ angular.module('docsTimeDirective', []) .directive('myCurrentTime', ['$interval', 'dateFilter', ($interval: any, dateFilter: any) => { return { link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) { - let format: any, - timeoutId: any; + let format: any; + let timeoutId: any; function updateTime() { element.text(dateFilter(new Date(), format)); @@ -896,7 +896,10 @@ angular.module('docsIsoFnBindExample', []) angular.module('dragModule', []) .directive('myDraggable', ['$document', ($document: any) => { return (scope: any, element: any, attr: any) => { - let startX = 0, startY = 0, x = 0, y = 0; + let startX = 0; + let startY = 0; + let x = 0; + let y = 0; element.css({ position: 'relative', diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 6ff43a5290..d046974ab9 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -875,7 +875,8 @@ declare namespace angular { * @param identifierStart The function that will decide whether the given character is a valid identifier start character. * @param identifierContinue The function that will decide whether the given character is a valid identifier continue character. **/ - setIdentifierFns(identifierStart?: (character: string, codePoint: number) => boolean, + setIdentifierFns( + identifierStart?: (character: string, codePoint: number) => boolean, identifierContinue?: (character: string, codePoint: number) => boolean): void; } diff --git a/types/angular/tslint.json b/types/angular/tslint.json index 196218148d..057f35a770 100644 --- a/types/angular/tslint.json +++ b/types/angular/tslint.json @@ -6,11 +6,13 @@ "quotemark": [true, "single"], "variable-name": [true, "check-format"], + // Below are all TODOs "callable-types": false, "ban-types": false, "interface-name": false, - "no-empty-interface": false, + "jsdoc-format": false, "max-line-length": false, + "no-empty-interface": false, "unified-signatures": false, "void-return": false } diff --git a/types/applepayjs/applepayjs-tests.ts b/types/applepayjs/applepayjs-tests.ts index 26c61396ae..5adf61e45c 100644 --- a/types/applepayjs/applepayjs-tests.ts +++ b/types/applepayjs/applepayjs-tests.ts @@ -21,7 +21,6 @@ describe("ApplePaySession", () => { } }); it("can create a new instance", () => { - const version = 1; const paymentRequest = { countryCode: "US", @@ -42,7 +41,6 @@ describe("ApplePaySession", () => { const session = new ApplePaySession(version, paymentRequest); }); it("can call static methods", () => { - const merchantIdentifier = "MyMerchantId"; let canMakePayments: boolean = ApplePaySession.canMakePayments(); @@ -59,7 +57,6 @@ describe("ApplePaySession", () => { }); }); it("can call instance methods", () => { - const version = 1; const paymentRequest = { countryCode: "US", @@ -171,7 +168,6 @@ describe("ApplePaySession", () => { }); describe("ApplePayPaymentRequest", () => { it("can create a new instance", () => { - let paymentRequest: ApplePayJS.ApplePayPaymentRequest = { applicationData: "ApplicationData", countryCode: "GB", diff --git a/types/applepayjs/index.d.ts b/types/applepayjs/index.d.ts index 52af393ebd..744e1fd044 100644 --- a/types/applepayjs/index.d.ts +++ b/types/applepayjs/index.d.ts @@ -7,7 +7,6 @@ * A session object for managing the payment process on the web. */ declare class ApplePaySession extends EventTarget { - /** * Creates a new instance of the ApplePaySession class. * @param version - The version of the ApplePay JS API you are using. @@ -164,12 +163,10 @@ declare class ApplePaySession extends EventTarget { } declare namespace ApplePayJS { - /** * Defines a line item in a payment request - for example, total, tax, discount, or grand total. */ interface ApplePayLineItem { - /** * A short, localized description of the line item. */ @@ -190,7 +187,6 @@ declare namespace ApplePayJS { * Represents the result of authorizing a payment request and contains encrypted payment information. */ interface ApplePayPayment { - /** * The encrypted token for an authorized payment. */ @@ -211,7 +207,6 @@ declare namespace ApplePayJS { * The Apple​Pay​Payment​Authorized​Event class defines the attributes contained by the ApplePaySession.onpaymentauthorized callback function. */ abstract class ApplePayPaymentAuthorizedEvent extends Event { - /** * The payment token used to authorize a payment. */ @@ -222,7 +217,6 @@ declare namespace ApplePayJS { * Encapsulates contact information needed for billing and shipping. */ interface ApplePayPaymentContact { - /** * An email address for the contact. */ @@ -278,7 +272,6 @@ declare namespace ApplePayJS { * Contains information about an Apple Pay payment card. */ interface ApplePayPaymentMethod { - /** * A string, suitable for display, that describes the card. */ @@ -305,7 +298,6 @@ declare namespace ApplePayJS { * The Apple​Pay​Payment​Method​Selected​Event class defines the attributes contained by the ApplePaySession.onpaymentmethodselected callback function. */ abstract class ApplePayPaymentMethodSelectedEvent extends Event { - /** * The card used to complete a payment. */ @@ -316,7 +308,6 @@ declare namespace ApplePayJS { * Represents a provisioned payment card for Apple Pay payments. */ interface ApplePayPaymentPass { - /** * The unique identifier for the primary account number for the payment card. */ @@ -347,7 +338,6 @@ declare namespace ApplePayJS { * Encapsulates a request for payment, including information about payment processing capabilities, the payment amount, and shipping information. */ interface ApplePayPaymentRequest { - /** * The merchant's two-letter ISO 3166 country code. */ @@ -419,7 +409,6 @@ declare namespace ApplePayJS { * Contains the user's payment credentials. */ interface ApplePayPaymentToken { - /** * An object containing the encrypted payment data. */ @@ -440,7 +429,6 @@ declare namespace ApplePayJS { * The Apple​Pay​Shipping​Contact​Selected​Event class defines the attributes contained by the ApplePaySession.onshippingcontactselected callback function. */ abstract class ApplePayShippingContactSelectedEvent extends Event { - /** * The shipping address selected by the user. */ @@ -451,7 +439,6 @@ declare namespace ApplePayJS { * Defines a shipping method for delivering physical goods. */ interface ApplePayShippingMethod { - /** * A short description of the shipping method. */ @@ -477,7 +464,6 @@ declare namespace ApplePayJS { * The Apple​Pay​Shipping​Method​Selected​Event class defines the attribute contained by the ApplePaySession.onshippingmethodselected callback function. */ abstract class ApplePayShippingMethodSelectedEvent extends Event { - /** * The shipping method selected by the user. */ @@ -488,7 +474,6 @@ declare namespace ApplePayJS { * The Apple​Pay​Validate​Merchant​Event class defines the attributes contained by the ApplePaySession.onvalidatemerchant callback function. */ abstract class ApplePayValidateMerchantEvent extends Event { - /** * The URL used to validate the merchant server. */ @@ -496,7 +481,6 @@ declare namespace ApplePayJS { } abstract class Event { - readonly bubbles: boolean; cancelBubble: boolean; diff --git a/types/applepayjs/tslint.json b/types/applepayjs/tslint.json index 0344a1a3fa..377cc837d4 100644 --- a/types/applepayjs/tslint.json +++ b/types/applepayjs/tslint.json @@ -1,3 +1 @@ -{ - "extends": "../tslint.json" -} +{ "extends": "../tslint.json" } diff --git a/types/applicationinsights-js/applicationinsights-js-tests.ts b/types/applicationinsights-js/applicationinsights-js-tests.ts index 66bc1f268d..1a4d585795 100644 --- a/types/applicationinsights-js/applicationinsights-js-tests.ts +++ b/types/applicationinsights-js/applicationinsights-js-tests.ts @@ -1,6 +1,6 @@ // More samples on: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md -var config: Microsoft.ApplicationInsights.IConfig = { +const config: Microsoft.ApplicationInsights.IConfig = { instrumentationKey: "", endpointUrl: "endpointUrl", emitLineDelimitedJson: false, @@ -30,7 +30,7 @@ var config: Microsoft.ApplicationInsights.IConfig = { isStorageUseDisabled: true }; -var appInsights: Microsoft.ApplicationInsights.IAppInsights = { +appInsights = { config, context: null, queue: null, @@ -91,9 +91,8 @@ appInsights.setAuthenticatedUserContext("userId", "accountId"); // set config dynamically appInsights.config.instrumentationKey = ""; - // TelementryContext -var context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context; +const context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context; context.application.ver = "v0.0.0"; context.application.build = "1.1.1"; @@ -113,54 +112,54 @@ context.operation.id = "1"; context.operation.syntheticSource = "testAgent"; // track -var data = new Microsoft.Telemetry.Base(); -var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, "name"); +const data = new Microsoft.Telemetry.Base(); +const envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, "name"); context.track(envelope); -context.addTelemetryInitializer((envelope) => false); +context.addTelemetryInitializer(telemetryEnvelope => false); // track event -var eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null); -var eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Event.dataType, eventObj); -var eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType); +const eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null); +const eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Event.dataType, eventObj); +const eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType); context.track(eventEnvelope); // track exception -var exceptionObj = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error(), "handledAt", null, null, AI.SeverityLevel.Critical); -var exceptionData = new Microsoft.ApplicationInsights.Telemetry.Common.Data( +const exceptionObj = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error(), "handledAt", null, null, AI.SeverityLevel.Critical); +const exceptionData = new Microsoft.ApplicationInsights.Telemetry.Common.Data( Microsoft.ApplicationInsights.Telemetry.Exception.dataType, exceptionObj); -var exceptionEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(exceptionData, Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType); +const exceptionEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(exceptionData, Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType); context.track(exceptionEnvelope); // track metric -var metricObj = new Microsoft.ApplicationInsights.Telemetry.Metric("name", 1234, 1, 0, 100, null); -var metricData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Metric.dataType, metricObj); -var metricEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(metricData, Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType); +const metricObj = new Microsoft.ApplicationInsights.Telemetry.Metric("name", 1234, 1, 0, 100, null); +const metricData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Metric.dataType, metricObj); +const metricEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(metricData, Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType); context.track(metricEnvelope); // track page view -var pageViewObj = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", "url", 999, null, null); -var pageViewData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageViewObj); -var pageViewEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewData, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType); +const pageViewObj = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", "url", 999, null, null); +const pageViewData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageViewObj); +const pageViewEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewData, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType); context.track(pageViewEnvelope); // track page view performance -var pageViewPerfObj = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", "url", 999, null, null); -var pageViewPerfData = new Microsoft.ApplicationInsights.Telemetry.Common.Data( +const pageViewPerfObj = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", "url", 999, null, null); +const pageViewPerfData = new Microsoft.ApplicationInsights.Telemetry.Common.Data( Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.dataType, pageViewPerfObj); -var pageViewPerfEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewPerfData, Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType); +const pageViewPerfEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewPerfData, Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType); context.track(pageViewPerfEnvelope); // track remote dependency -var remoteDepObj = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("id", "url", "command", 1, true, 1234, "GET"); -var remoteDepData = new Microsoft.ApplicationInsights.Telemetry.Common.Data( +const remoteDepObj = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("id", "url", "command", 1, true, 1234, "GET"); +const remoteDepData = new Microsoft.ApplicationInsights.Telemetry.Common.Data( Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.dataType, remoteDepObj); -var remoteDepEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(remoteDepData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType); +const remoteDepEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(remoteDepData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType); context.track(pageViewPerfEnvelope); // track trace -var traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", null); -var traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj); -var traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType); -context.track(traceEnvelope); \ No newline at end of file +const traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", null); +const traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj); +const traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType); +context.track(traceEnvelope); diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index ede1584bb5..cce53f5823 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -195,8 +195,8 @@ declare module Microsoft.ApplicationInsights.Context { interface IInternal { /** - * The SDK version used to create this telemetry item. - */ + * The SDK version used to create this telemetry item. + */ sdkVersion: string; /** * The SDK agent version. @@ -206,15 +206,15 @@ declare module Microsoft.ApplicationInsights.Context { interface ISample { /** - * Sample rate - */ + * Sample rate + */ sampleRate: number; } interface ISession { /** - * The session ID. - */ + * The session ID. + */ id: string; /** * The true if this is the first session @@ -258,8 +258,8 @@ declare module Microsoft.ApplicationInsights.Context { interface IUser { /** - * The telemetry configuration. - */ + * The telemetry configuration. + */ config: any; /** * The user ID. @@ -345,12 +345,12 @@ declare module Microsoft.ApplicationInsights.Telemetry { measurements: Microsoft.ApplicationInsights.FieldType; }; /** - * Constructs a new isntance of the ExceptionTelemetry object - */ + * Constructs a new isntance of the ExceptionTelemetry object + */ constructor(exception: Error, handledAt?: string, properties?: any, measurements?: any, severityLevel?: AI.SeverityLevel); /** - * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. - */ + * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. + */ static CreateSimpleException(message: string, typeName: string, assembly: string, fileName: string, details: string, line: number, handledAt?: string): Telemetry.Exception; } @@ -414,8 +414,8 @@ declare module Microsoft.ApplicationInsights.Telemetry { getIsValid(): boolean; private durationMs; /** - * Gets the total duration (PLT) in milliseconds. Check getIsValid() before using this method. - */ + * Gets the total duration (PLT) in milliseconds. Check getIsValid() before using this method. + */ getDurationMs(): number; /** * Constructs a new instance of the PageEventTelemetry object @@ -423,8 +423,8 @@ declare module Microsoft.ApplicationInsights.Telemetry { constructor(name: string, url: string, unused: number, properties?: any, measurements?: any); static getPerformanceTiming(): PerformanceTiming; /** - * Returns true is window performance timing API is supported, false otherwise. - */ + * Returns true is window performance timing API is supported, false otherwise. + */ static isPerformanceTimingSupported(): PerformanceTiming; /** * As page loads different parts of performance timing numbers get set. When all of them are set we can report it. @@ -615,16 +615,16 @@ declare module Microsoft.ApplicationInsights { interface ITelemetryContext { /** - * The object describing a component tracked by this object. - */ + * The object describing a component tracked by this object. + */ application: Context.IApplication; /** * The object describing a device tracked by this object. */ device: Context.IDevice; /** - * The object describing internal settings. - */ + * The object describing internal settings. + */ internal: Context.IInternal; /** * The object describing a location tracked by this object. @@ -635,8 +635,8 @@ declare module Microsoft.ApplicationInsights { */ operation: Context.IOperation; /** - * The object describing sampling settings. - */ + * The object describing sampling settings. + */ sample: Context.ISample; /** * The object describing a user tracked by this object. @@ -647,13 +647,13 @@ declare module Microsoft.ApplicationInsights { */ session: Context.ISession; /** - * Adds telemetry initializer to the collection. Telemetry initializers will be called one by one - * before telemetry item is pushed for sending and in the order they were added. - */ + * Adds telemetry initializer to the collection. Telemetry initializers will be called one by one + * before telemetry item is pushed for sending and in the order they were added. + */ addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean): any; /** - * Tracks telemetry object. - */ + * Tracks telemetry object. + */ track(envelope: Microsoft.ApplicationInsights.IEnvelope): any; } @@ -662,23 +662,23 @@ declare module Microsoft.ApplicationInsights { context: ITelemetryContext; queue: Array<() => void>; /** - * Starts timing how long the user views a page or other item. Call this when the page opens. - * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. - * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. - */ + * Starts timing how long the user views a page or other item. Call this when the page opens. + * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. + * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. + */ startTrackPage(name?: string): any; /** - * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. - * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. - * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. - */ - stopTrackPage(name?: string, url?: string, properties?: { - [name: string]: string; - }, measurements?: { - [name: string]: number; - }): any; + * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. + * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. + * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + stopTrackPage( + name?: string, + url?: string, + properties?: { [name: string]: string }, + measurements?: { [name: string]: number }): any; /** * Logs that a page or other item was viewed. * @param name The string you used as the name in startTrackPage. Defaults to the document title. @@ -687,11 +687,11 @@ declare module Microsoft.ApplicationInsights { * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. * @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally. */ - trackPageView(name?: string, url?: string, properties?: { - [name: string]: string; - }, measurements?: { - [name: string]: number; - }, duration?: number): any; + trackPageView( + name?: string, + url?: string, + properties?: { [name: string]: string }, + measurements?: { [name: string]: number }, duration?: number): any; /** * Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends. * @param name A string that identifies this event uniquely within the document. @@ -703,22 +703,20 @@ declare module Microsoft.ApplicationInsights { * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ - stopTrackEvent(name: string, properties?: { - [name: string]: string; - }, measurements?: { - [name: string]: number; - }): any; + stopTrackEvent( + name: string, + properties?: { [name: string]: string }, + measurements?: { [name: string]: number }): any; /** - * Log a user action or other occurrence. - * @param name A string to identify this event in the portal. - * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. - * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. - */ - trackEvent(name: string, properties?: { - [name: string]: string; - }, measurements?: { - [name: string]: number; - }): any; + * Log a user action or other occurrence. + * @param name A string to identify this event in the portal. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + trackEvent( + name: string, + properties?: { [name: string]: string }, + measurements?: { [name: string]: number }): any; /** * Log a dependency call * @param id unique id, this is used by the backend o correlate server requests. Use Util.newId() to generate a unique Id. @@ -737,11 +735,12 @@ declare module Microsoft.ApplicationInsights { * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. * @param severityLevel AI.SeverityLevel - severity level */ - trackException(exception: Error, handledAt?: string, properties?: { - [name: string]: string; - }, measurements?: { - [name: string]: number; - }, severityLevel?: AI.SeverityLevel): any; + trackException( + exception: Error, + handledAt?: string, + properties?: { [name: string]: string }, + measurements?: { [name: string]: number }, + severityLevel?: AI.SeverityLevel): any; /** * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the @@ -752,28 +751,30 @@ declare module Microsoft.ApplicationInsights { * @param min The smallest measurement in the sample. Defaults to the average. * @param max The largest measurement in the sample. Defaults to the average. */ - trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { - [name: string]: string; - }): any; + trackMetric( + name: string, + average: number, + sampleCount?: number, + min?: number, + max?: number, + properties?: { [name: string]: string }): any; /** - * Log a diagnostic message. - * @param message A message string - * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. - */ - trackTrace(message: string, properties?: { - [name: string]: string; - }): any; + * Log a diagnostic message. + * @param message A message string + * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. + */ + trackTrace(message: string, properties?: { [name: string]: string }): any; /** * Immediately send all queued telemetry. */ flush(): any; /** - * Sets the autheticated user id and the account id in this session. - * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. - * - * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. - * @param accountId {string} - An optional string to represent the account associated with the authenticated user. - */ + * Sets the autheticated user id and the account id in this session. + * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. + * + * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. + * @param accountId {string} - An optional string to represent the account associated with the authenticated user. + */ setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any; /** * Clears the authenticated user id and the account id from the user context. @@ -796,4 +797,4 @@ declare module 'applicationinsights-js' { const AppInsights: Microsoft.ApplicationInsights.IAppInsights; } -declare var appInsights: Microsoft.ApplicationInsights.IAppInsights; \ No newline at end of file +declare var appInsights: Microsoft.ApplicationInsights.IAppInsights; diff --git a/types/arcgis-rest-api/arcgis-rest-api-tests.ts b/types/arcgis-rest-api/arcgis-rest-api-tests.ts index 0f4cf3d926..3955b02f35 100644 --- a/types/arcgis-rest-api/arcgis-rest-api-tests.ts +++ b/types/arcgis-rest-api/arcgis-rest-api-tests.ts @@ -8,4 +8,4 @@ point = { spatialReference: { wkid: 4326 } -}; \ No newline at end of file +}; diff --git a/types/arcgis-rest-api/index.d.ts b/types/arcgis-rest-api/index.d.ts index 65a02a4367..0992772fec 100644 --- a/types/arcgis-rest-api/index.d.ts +++ b/types/arcgis-rest-api/index.d.ts @@ -65,7 +65,6 @@ export interface BezierCurve { export type JsonCurve = CircularArc | Arc | OldCircularArc | BezierCurve; - export interface SpatialReferenceWkid { wkid?: number; latestWkid?: number; @@ -131,7 +130,6 @@ export interface Envelope extends Geometry { export type esriGeometryType = "esriGeometryPoint" | "esriGeometryMultipoint" | "esriGeometryPolyline" | "esriGeometryPolygon" | "esriGeometryEnvelope"; - export type Color = [number, number, number, number]; export type SimpleMarkerSymbolStyle = "esriSMSCircle" | "esriSMSCross" | "esriSMSDiamond" | "esriSMSSquare" | "esriSMSX" | "esriSMSTriangle"; export type SimpleLineSymbolStyle = "esriSLSDash" | "esriSLSDashDot" | "esriSLSDashDotDot" | "esriSLSDot" | "esriSLSNull" | "esriSLSSolid"; @@ -181,7 +179,6 @@ export interface PictureSourced { "angle"?: number; "xoffset"?: number; "yoffset"?: number; - } export interface PictureMarkerSymbol extends MarkerSymbol, PictureSourced { @@ -217,4 +214,4 @@ export interface TextSymbol extends MarkerSymbol { "kerning"?: boolean; "font"?: Font; "text"?: string; // only applicable when specified as a client-side graphic. -} \ No newline at end of file +} diff --git a/types/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts b/types/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts index 2e9337793a..5cb9d9472e 100644 --- a/types/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts +++ b/types/arcgis-to-geojson-utils/arcgis-to-geojson-utils-tests.ts @@ -14,7 +14,7 @@ const geojsonPoint: GeoJSON.Point = { }; // parse ArcGIS JSON, convert it to GeoJSON -var geojson = utils.arcgisToGeoJSON(arcgisPoint); +const geojson = utils.arcgisToGeoJSON(arcgisPoint); // take GeoJSON and convert it to ArcGIS JSON -var arcgis = utils.geojsonToArcGIS(geojsonPoint); \ No newline at end of file +const arcgis = utils.geojsonToArcGIS(geojsonPoint); diff --git a/types/arcgis-to-geojson-utils/index.d.ts b/types/arcgis-to-geojson-utils/index.d.ts index 94a86022a3..65c78a4230 100644 --- a/types/arcgis-to-geojson-utils/index.d.ts +++ b/types/arcgis-to-geojson-utils/index.d.ts @@ -15,4 +15,4 @@ export function arcgisToGeoJSON(arcgis: T): GeoJSON.G /** * Converts a GeoJSON geometry into a ArcGIS geometry. */ -export function geojsonToArcGIS(geojson: GeoJSON.GeometryObject): ArcGis.Geometry; \ No newline at end of file +export function geojsonToArcGIS(geojson: GeoJSON.GeometryObject): ArcGis.Geometry; diff --git a/types/array-uniq/array-uniq-tests.ts b/types/array-uniq/array-uniq-tests.ts index 8674d2508c..b6c90c620a 100644 --- a/types/array-uniq/array-uniq-tests.ts +++ b/types/array-uniq/array-uniq-tests.ts @@ -2,4 +2,4 @@ import arrayUniq = require("array-uniq"); arrayUniq([1, 1, 2, 3, 3]); -arrayUniq(["foo", "foo", "bar", "foo"]); \ No newline at end of file +arrayUniq(["foo", "foo", "bar", "foo"]); diff --git a/types/array-uniq/index.d.ts b/types/array-uniq/index.d.ts index 25d97c0a94..d05ad76072 100644 --- a/types/array-uniq/index.d.ts +++ b/types/array-uniq/index.d.ts @@ -5,4 +5,4 @@ declare function arrayUniq(arr: T[]): T[]; -export = arrayUniq; \ No newline at end of file +export = arrayUniq; diff --git a/types/croppie/croppie-tests.ts b/types/croppie/croppie-tests.ts index 92f6d5ca18..26b2449408 100644 --- a/types/croppie/croppie-tests.ts +++ b/types/croppie/croppie-tests.ts @@ -7,7 +7,6 @@ const c = new Croppie(document.getElementById('item'), { enableOrientation: false, }); - c.bind({ url: 'demo/demo-2.jpg', orientation: 4, diff --git a/types/croppie/index.d.ts b/types/croppie/index.d.ts index afd0c0112c..78ab07ad61 100644 --- a/types/croppie/index.d.ts +++ b/types/croppie/index.d.ts @@ -27,7 +27,6 @@ export default class Croppie { destroy(): void; } - export type CropType = 'square' | 'circle'; export type Format = 'jpeg' | 'png' | 'webp'; diff --git a/types/dragster/dragster-tests.ts b/types/dragster/dragster-tests.ts index a05d06e1dd..12b069362e 100644 --- a/types/dragster/dragster-tests.ts +++ b/types/dragster/dragster-tests.ts @@ -1,7 +1,7 @@ import Dragster = require("dragster"); -var dropzone = document.getElementById("my-dropzone") as HTMLElement; -var dragster = new Dragster(dropzone); +const dropzone = document.getElementById("my-dropzone") as HTMLElement; +const dragster = new Dragster(dropzone); dragster.removeListeners(); -dragster.reset(); \ No newline at end of file +dragster.reset(); diff --git a/types/dragster/index.d.ts b/types/dragster/index.d.ts index c02f510084..cc1e8e85b8 100644 --- a/types/dragster/index.d.ts +++ b/types/dragster/index.d.ts @@ -20,4 +20,4 @@ declare var Dragster: Dragster.DragsterStatic; export = Dragster; // Support as a global -export as namespace Dragster; \ No newline at end of file +export as namespace Dragster; diff --git a/types/expect/expect-tests.ts b/types/expect/expect-tests.ts index c4312d1ada..6238a63c60 100644 --- a/types/expect/expect-tests.ts +++ b/types/expect/expect-tests.ts @@ -32,7 +32,8 @@ describe('createSpy', () => { }); describe('A spy', () => { - let targetContext: any, targetArguments: any; + let targetContext: any; + let targetArguments: any; const target = { method() { targetContext = this; @@ -88,7 +89,8 @@ describe('A spy', () => { }); describe('that calls some other function', () => { - let otherContext: any, otherArguments: any; + let otherContext: any; + let otherArguments: any; function otherFn() { otherContext = this; otherArguments = Array.prototype.slice.call(arguments, 0); diff --git a/types/is-root/is-root-tests.ts b/types/is-root/is-root-tests.ts index b53d07a0ac..99be761d74 100644 --- a/types/is-root/is-root-tests.ts +++ b/types/is-root/is-root-tests.ts @@ -2,4 +2,4 @@ import isRoot = require('is-root'); isRoot(); -// => true \ No newline at end of file +// => true diff --git a/types/ityped/index.d.ts b/types/ityped/index.d.ts index 135ea870ca..ea5c2427a6 100644 --- a/types/ityped/index.d.ts +++ b/types/ityped/index.d.ts @@ -12,4 +12,4 @@ export interface Configuration { export function init(element: string, config: Configuration): void; -export as namespace ityped; \ No newline at end of file +export as namespace ityped; diff --git a/types/ityped/ityped-tests.ts b/types/ityped/ityped-tests.ts index b03d976ec1..cb18814532 100644 --- a/types/ityped/ityped-tests.ts +++ b/types/ityped/ityped-tests.ts @@ -15,4 +15,4 @@ init("#anotherSelector", { loop: false }); -init("#anotherOne", {}); \ No newline at end of file +init("#anotherOne", {}); diff --git a/types/jimp/index.d.ts b/types/jimp/index.d.ts index b8988e2ad4..4c39f58796 100644 --- a/types/jimp/index.d.ts +++ b/types/jimp/index.d.ts @@ -50,7 +50,6 @@ declare namespace jimp { } } | PresetFont; - class JimpImage { constructor(width: number, height: number, callback?: Callback); constructor(width: number, height: number, initialColor: number, callback?: Callback); diff --git a/types/jimp/jimp-tests.ts b/types/jimp/jimp-tests.ts index a312cd4586..10ee61073e 100644 --- a/types/jimp/jimp-tests.ts +++ b/types/jimp/jimp-tests.ts @@ -36,20 +36,20 @@ Jimp.read("http://www.example.com/path/to/lenna.jpg", (err, image) => { // do stuff with the image (if no exception) }); -var image = new Jimp(1, 2); -var w = 0; -var h = 0; -var x = 0; -var y = 0; -var f = 0; -var src = ''; -var horz = Jimp.HORIZONTAL_ALIGN_CENTER; -var vert = Jimp.VERTICAL_ALIGN_BOTTOM; -var deg = 90; -var val = 0.5; -var hex = 0xFFFFFFFF; -var r = 0; -var n = 1; +let image = new Jimp(1, 2); +const w = 0; +const h = 0; +const x = 0; +const y = 0; +const f = 0; +const src = ''; +const horz = Jimp.HORIZONTAL_ALIGN_CENTER; +const vert = Jimp.VERTICAL_ALIGN_BOTTOM; +const deg = 90; +const val = 0.5; +const hex = 0xFFFFFFFF; +const r = 0; +const n = 1; /* Resize */ image.contain(w, h); // scale the image to the given width and height, some parts of the image may be letter boxed image.cover(w, h); // scale the image to the given width and height, some parts of the image may be clipped @@ -112,15 +112,15 @@ image.resize(250, 250, Jimp.RESIZE_BEZIER); image.contain(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP); -var path = ''; -var str = ''; -var width = 0; +const path = ''; +const str = ''; +const width = 0; Jimp.loadFont(path).then(font => { // load font from .fnt file image.print(font, x, y, str); // print a message on an image image.print(font, x, y, str, width); // print a message on an image with text wrapped at width }); -var cb = (err: Error, data: any) => {}; +const cb = (err: Error, data: any) => {}; Jimp.loadFont(path, cb); // using a callback pattern Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(font => { @@ -129,17 +129,16 @@ Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(font => { image.write(path, cb); // Node-style callback will be fired when write is successful -var file = "new_name." + image.getExtension(); +const file = "new_name." + image.getExtension(); image.write(file); - -var mime = 'image/png'; +const mime = 'image/png'; image.getBuffer(mime, cb); // Node-style callback will be fired with result image.getBase64(mime, cb); // Node-style callback will be fired with result image.quality(n); // set the quality of saved JPEG, 0 - 100 -var bool = true; -var number = 0; +const bool = true; +const number = 0; image.rgba(bool); // set whether PNGs are saved as RGBA (true, default) or RGB (false) image.filterType(number); // set the filter type for the saved PNG image.deflateLevel(number); // set the deflate level for the saved PNG @@ -160,10 +159,10 @@ image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) { // idx is the position start position of this rgba tuple in the bitmap Buffer // this is the image - var red = this.bitmap.data[ idx + 0 ]; - var green = this.bitmap.data[ idx + 1 ]; - var blue = this.bitmap.data[ idx + 2 ]; - var alpha = this.bitmap.data[ idx + 3 ]; + const red = this.bitmap.data[ idx + 0 ]; + const green = this.bitmap.data[ idx + 1 ]; + const blue = this.bitmap.data[ idx + 2 ]; + const alpha = this.bitmap.data[ idx + 3 ]; // rgba values run from 0 - 255 // e.g. this.bitmap.data[idx] = 0; // removes red from this pixel @@ -171,35 +170,34 @@ image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) { image.getPixelColor(x, y); // returns the colour of that pixel e.g. 0xFFFFFFFF image.setPixelColor(hex, x, y); // sets the colour of that pixel -var g = 0; -var b = 0; -var a = 0; +const g = 0; +const b = 0; +const a = 0; Jimp.rgbaToInt(r, g, b, a); // e.g. converts 255, 255, 255, 255 to 0xFFFFFFFF Jimp.intToRGBA(hex); // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255} -var image = new Jimp(256, 256, (err, image) => { +image = new Jimp(256, 256, (err, image) => { // this image is 256 x 256, every pixel is set to 0x00000000 }); -var image = new Jimp(256, 256, 0xFF0000FF, (err, image) => { +image = new Jimp(256, 256, 0xFF0000FF, (err, image) => { // this image is 256 x 256, every pixel is set to 0xFF0000FF }); image.hash(); // aHgG4GgoFjA image.hash(2); // 1010101011010000101010000100101010010000011001001001010011100100 -var image1 = new Jimp(0, 1); -var image2 = new Jimp(0, 1); +const image1 = new Jimp(0, 1); +const image2 = new Jimp(0, 1); Jimp.distance(image1, image2); // returns a number 0-1, where 0 means the two images are perceived to be identical -var threshold = 0; -var diff = Jimp.diff(image1, image2, threshold); // threshold ranges 0-1 (default: 0.1) +const threshold = 0; +let diff = Jimp.diff(image1, image2, threshold); // threshold ranges 0-1 (default: 0.1) diff.image; // a Jimp image showing differences diff.percent; // the proportion of different pixels (0-1), where 0 means the images are pixel identical - -var distance = Jimp.distance(image, image2); // perceived distance -var diff = Jimp.diff(image, image2); // pixel difference +const distance = Jimp.distance(image, image2); // perceived distance +diff = Jimp.diff(image, image2); // pixel difference if (distance < 0.15 || diff.percent < 0.15) { // images match @@ -217,4 +215,4 @@ Jimp.read("lenna.png", (err, image) => { image.write("lena-half-bw.png"); }); }); -}); \ No newline at end of file +}); diff --git a/types/jui-core/index.d.ts b/types/jui-core/index.d.ts index 6d15361d8e..d932198d17 100644 --- a/types/jui-core/index.d.ts +++ b/types/jui-core/index.d.ts @@ -5,14 +5,15 @@ /// -declare var jui: JuiStatic; +export const jui: JuiStatic; interface UtilBase { /** * @property browser check browser agent * @property {Boolean} browser.webkit Webkit 브라우저 체크 * @property {Boolean} browser.mozilla Mozilla 브라우저 체크 - * @property {Boolean} browser.msie IE 브라우저 체크 */ + * @property {Boolean} browser.msie IE 브라우저 체크 + */ browser: { webkit: boolean, mozilla: boolean, @@ -389,11 +390,11 @@ interface JuiStatic { includeAll(): any[]; /** - * @method add - * Adds a component object created - * - * @param {Object} ui UI instance - */ + * @method add + * Adds a component object created + * + * @param {Object} ui UI instance + */ add(uiIns: any): void; /** diff --git a/types/jui-grid/jui-grid-tests.ts b/types/jui-grid/jui-grid-tests.ts index 2609e94021..3b5bfa3db8 100644 --- a/types/jui-grid/jui-grid-tests.ts +++ b/types/jui-grid/jui-grid-tests.ts @@ -40,9 +40,9 @@ jui.ready([ "grid.table" ], (table: GridTable) => { ]); const table_3_submit: Function = (index: number) => { - const name = $(table_3.root).find(".name").val(), - age = $(table_3.root).find(".age").val(), - location = $(table_3.root).find(".location").val(); + const name = $(table_3.root).find(".name").val(); + const age = $(table_3.root).find(".age").val(); + const location = $(table_3.root).find(".location").val(); //noinspection TypeScriptValidateTypes table_3.update(index, { name, age, location }); diff --git a/types/left-pad/index.d.ts b/types/left-pad/index.d.ts index 86996ccd47..ce8bc5237d 100644 --- a/types/left-pad/index.d.ts +++ b/types/left-pad/index.d.ts @@ -5,4 +5,4 @@ declare function leftPad(str: string|number, len: number, ch?: string|number): string; -export = leftPad; \ No newline at end of file +export = leftPad; diff --git a/types/left-pad/left-pad-tests.ts b/types/left-pad/left-pad-tests.ts index 53a08d1a9a..a3749feb16 100644 --- a/types/left-pad/left-pad-tests.ts +++ b/types/left-pad/left-pad-tests.ts @@ -12,4 +12,4 @@ leftPad(1, 2, "0"); // => "01" leftPad(17, 5, 0); -// => "00017" \ No newline at end of file +// => "00017" diff --git a/types/libpq/index.d.ts b/types/libpq/index.d.ts index 76bfb40935..49c00db818 100644 --- a/types/libpq/index.d.ts +++ b/types/libpq/index.d.ts @@ -102,7 +102,7 @@ declare class Libpq extends EventEmitter { * @returns {boolean} true if data was read; false if there was an error. You can access * error details with [[Libpq.errorMessage]]. */ - consumeInput(): boolean + consumeInput(): boolean; /** * Retrieves the last error message from the connection. This is intended to be used after most diff --git a/types/node-xmpp-client/index.d.ts b/types/node-xmpp-client/index.d.ts index 1747740be7..02f8a64e59 100644 --- a/types/node-xmpp-client/index.d.ts +++ b/types/node-xmpp-client/index.d.ts @@ -67,5 +67,5 @@ interface XmppOptions { interface Bosh { url?: string; - prebind?: (error: any, data: any) => void; + prebind?(error: any, data: any): void; } diff --git a/types/node-xmpp-core/index.d.ts b/types/node-xmpp-core/index.d.ts index 68d985b666..8c552c08f2 100644 --- a/types/node-xmpp-core/index.d.ts +++ b/types/node-xmpp-core/index.d.ts @@ -66,17 +66,17 @@ export class JID { /** * Convenience method to distinguish users - **/ + */ bare(): JID; /** * Comparison function - **/ + */ equals(other: JID): boolean; /** * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart - **/ + */ setLocal(local: string, escape?: any): void; getLocal(unescape?: any): string; diff --git a/types/ns-api/ns-api-tests.ts b/types/ns-api/ns-api-tests.ts index 129e54d6b9..5063a97e48 100644 --- a/types/ns-api/ns-api-tests.ts +++ b/types/ns-api/ns-api-tests.ts @@ -55,4 +55,4 @@ ns.storingen({}, (err, data) => { } else { console.log(data); } -}); \ No newline at end of file +}); diff --git a/types/opener/opener-tests.ts b/types/opener/opener-tests.ts index 477fe4b3f8..7f69d8f2dd 100644 --- a/types/opener/opener-tests.ts +++ b/types/opener/opener-tests.ts @@ -7,5 +7,5 @@ opener('./my-file.txt'); opener('firefox'); opener('npm run lint'); -var editor = opener('documentation.odt'); +const editor = opener('documentation.odt'); editor.unref(); diff --git a/types/pad/pad-tests.ts b/types/pad/pad-tests.ts index ccba560703..36befdac78 100644 --- a/types/pad/pad-tests.ts +++ b/types/pad/pad-tests.ts @@ -3,4 +3,4 @@ import pad = require('pad'); pad('pad', 5); // "pad " pad(5, 'pad'); // " pad" pad('pad', 5, '+'); // "pad++" -pad(5, 'pad', '+'); // "++pad" \ No newline at end of file +pad(5, 'pad', '+'); // "++pad" diff --git a/types/pem/index.d.ts b/types/pem/index.d.ts index c523fb8fa7..b65b60b9e1 100644 --- a/types/pem/index.d.ts +++ b/types/pem/index.d.ts @@ -144,9 +144,9 @@ type Callback = (error: any, result: T) => any; * @param {PrivateKeyCreationOptions} [options] private key encryption settings, defaults to empty object (no enryption) * @param {Callback<{ key: string }>} callback Callback function with an error object and {key} */ -declare function createPrivateKey(keyBitsize: number, options: PrivateKeyCreationOptions, callback: Callback<{ key: string }>): void; -declare function createPrivateKey(optionsOrKeyBitsize: number | PrivateKeyCreationOptions, callback: Callback<{ key: string }>): void; -declare function createPrivateKey(callback: Callback<{ key: string }>): void; +export function createPrivateKey(keyBitsize: number, options: PrivateKeyCreationOptions, callback: Callback<{ key: string }>): void; +export function createPrivateKey(optionsOrKeyBitsize: number | PrivateKeyCreationOptions, callback: Callback<{ key: string }>): void; +export function createPrivateKey(callback: Callback<{ key: string }>): void; /** * Creates a dhparam key @@ -154,8 +154,8 @@ declare function createPrivateKey(callback: Callback<{ key: string }>): void; * @param {Number} [keyBitsize=512] Size of the key, defaults to 512bit * @param {Callback<{ dhparam: any }>} callback Callback function with an error object and {dhparam} */ -declare function createDhparam(keyBitsize: number, callback: Callback<{ dhparam: any }>): void; -declare function createDhparam(callback: Callback<{ dhparam: any }>): void; +export function createDhparam(keyBitsize: number, callback: Callback<{ dhparam: any }>): void; +export function createDhparam(callback: Callback<{ dhparam: any }>): void; /** * Creates a Certificate Signing Request @@ -166,8 +166,8 @@ declare function createDhparam(callback: Callback<{ dhparam: any }>): void; * @param {CSRCreationOptions} [options] Optional options object * @param {Callback<{ csr: string, clientKey: string }>} callback Callback function with an error object and {csr, clientKey} */ -declare function createCSR(options: CSRCreationOptions, callback: Callback<{ csr: string, clientKey: string }>): void; -declare function createCSR(callback: Callback<{ csr: string, clientKey: string }>): void; +export function createCSR(options: CSRCreationOptions, callback: Callback<{ csr: string, clientKey: string }>): void; +export function createCSR(callback: Callback<{ csr: string, clientKey: string }>): void; /** * Creates a certificate based on a CSR. If CSR is not defined, a new one @@ -177,8 +177,8 @@ declare function createCSR(callback: Callback<{ csr: string, clientKey: string } * @param {Object} [CertificateCreationOptions] Optional options object * @param {Callback} callback Callback function with an error object and {certificate, csr, clientKey, serviceKey} */ -declare function createCertificate(options: CertificateCreationOptions, callback: Callback): void; -declare function createCertificate(callback: Callback): void; +export function createCertificate(options: CertificateCreationOptions, callback: Callback): void; +export function createCertificate(callback: Callback): void; /** * Reads subject data from a certificate or a CSR @@ -186,8 +186,8 @@ declare function createCertificate(callback: Callback * @param {String} certificate PEM encoded CSR or certificate * @param {Callback} callback Callback function with an error object and {country, state, locality, organization, organizationUnit, commonName, emailAddress} */ -declare function readCertificateInfo(certificate: string, callback: Callback): void; -declare function readCertificateInfo(callback: Callback): void; +export function readCertificateInfo(certificate: string, callback: Callback): void; +export function readCertificateInfo(callback: Callback): void; /** * Exports a public key from a private key, CSR or certificate @@ -195,8 +195,8 @@ declare function readCertificateInfo(callback: Callback} callback Callback function with an error object and {publicKey} */ -declare function getPublicKey(certificate: string, callback: Callback<{ publicKey: string }>): void; -declare function getPublicKey(callback: Callback<{ publicKey: string }>): void; +export function getPublicKey(certificate: string, callback: Callback<{ publicKey: string }>): void; +export function getPublicKey(callback: Callback<{ publicKey: string }>): void; /** * Gets the fingerprint for a certificate @@ -205,9 +205,9 @@ declare function getPublicKey(callback: Callback<{ publicKey: string }>): void; * @param {HashFunction} hash Hash function to use (either md5 sha1 or sha256, defaults to sha256) * @param {Callback<{ fingerprint: string }>} callback Callback function with an error object and {fingerprint} */ -declare function getFingerprint(certificate: string, hash: HashFunction, callback: Callback<{ fingerprint: string }>): void; -declare function getFingerprint(certificate: string, callback: Callback<{ fingerprint: string }>): void; -declare function getFingerprint(callback: Callback<{ fingerprint: string }>): void; +export function getFingerprint(certificate: string, hash: HashFunction, callback: Callback<{ fingerprint: string }>): void; +export function getFingerprint(certificate: string, callback: Callback<{ fingerprint: string }>): void; +export function getFingerprint(callback: Callback<{ fingerprint: string }>): void; /** * Gets the modulus from a certificate, a CSR or a private key @@ -216,8 +216,8 @@ declare function getFingerprint(callback: Callback<{ fingerprint: string }>): vo * @param {String} password password for the certificate * @param {Callback<{ modulus: any }>} callback Callback function with an error object and {modulus} */ -declare function getModulus(certificate: string, password: string, callback: Callback<{ modulus: any }>): void; -declare function getModulus(certificate: string, callback: Callback<{ modulus: any }>): void; +export function getModulus(certificate: string, password: string, callback: Callback<{ modulus: any }>): void; +export function getModulus(certificate: string, callback: Callback<{ modulus: any }>): void; /** * Gets the size and prime of DH parameters @@ -225,7 +225,7 @@ declare function getModulus(certificate: string, callback: Callback<{ modulus: a * @param {String} dh DH parameters PEM encoded * @param {Callback<{ size: any, prime: any }>} callback Callback function with an error object and {size, prime} */ -declare function getDhparamInfo(dh: string, callback: Callback<{ size: any, prime: any }>): void; +export function getDhparamInfo(dh: string, callback: Callback<{ size: any, prime: any }>): void; /** * Exports private key and certificate to a PKCS12 keystore @@ -236,8 +236,8 @@ declare function getDhparamInfo(dh: string, callback: Callback<{ size: any, prim * @param {Pkcs12CreationOptions} [options] object of cipher and optional client key password {cipher:'aes128', clientKeyPassword: 'xxx'} * @param {Callback<{ pkcs12: any }>} callback Callback function with an error object and {pkcs12} */ -declare function createPkcs12(key: string, certificate: string, password: string, options: Pkcs12CreationOptions, callback: Callback<{ pkcs12: any }>): void; -declare function createPkcs12(key: string, certificate: string, password: string, callback: Callback<{ pkcs12: any }>): void; +export function createPkcs12(key: string, certificate: string, password: string, options: Pkcs12CreationOptions, callback: Callback<{ pkcs12: any }>): void; +export function createPkcs12(key: string, certificate: string, password: string, callback: Callback<{ pkcs12: any }>): void; /** * Reads private key and certificate from a PKCS12 keystore @@ -246,8 +246,8 @@ declare function createPkcs12(key: string, certificate: string, password: string * @param {Function} callback Callback function with an error object and {pkcs12} * @returns the result of the callback */ -declare function readPkcs12(bufferOrPath: string, options: Pkcs12ReadOptions, callback: Callback<{ pkcs12: any }>): any; -declare function readPkcs12(bufferOrPath: string, callback: Callback<{ pkcs12: any }>): any; +export function readPkcs12(bufferOrPath: string, options: Pkcs12ReadOptions, callback: Callback<{ pkcs12: any }>): any; +export function readPkcs12(bufferOrPath: string, callback: Callback<{ pkcs12: any }>): any; /** * Verifies the signing chain of the passed certificate @@ -256,10 +256,10 @@ declare function readPkcs12(bufferOrPath: string, callback: Callback<{ pkcs12: a * @param {string[]} ca List of CA certificates * @param {Function} callback Callback function with an error object and a boolean valid */ -declare function verifySigningChain(certificate: string, ca: string[], callback: Callback): void; +export function verifySigningChain(certificate: string, ca: string[], callback: Callback): void; /** * config the pem module * @param {ModuleConfiguration} options */ -declare function config(options: ModuleConfiguration): void; +export function config(options: ModuleConfiguration): void; diff --git a/types/pem/pem-tests.ts b/types/pem/pem-tests.ts index 689dc42ad9..fe409b6560 100644 --- a/types/pem/pem-tests.ts +++ b/types/pem/pem-tests.ts @@ -1,10 +1,9 @@ import * as pem from 'pem'; const tests = { - 'Create default sized dhparam key': (test: any) => { pem.createDhparam((error: any, data: any) => { - var dhparam = (data && data.dhparam || '').toString(); + const dhparam = (data && data.dhparam || '').toString(); test.ifError(error); test.ok(dhparam); test.ok(dhparam.match(/^\n*\-\-\-\-\-BEGIN DH PARAMETERS\-\-\-\-\-\n/)); @@ -17,7 +16,7 @@ const tests = { 'Create 2048bit dhparam key': (test: any) => { pem.createDhparam(2048, (error: any, data: any) => { - var dhparam = (data && data.dhparam || '').toString(); + const dhparam = (data && data.dhparam || '').toString(); test.ifError(error); test.ok(dhparam); test.ok(dhparam.match(/^\n*\-\-\-\-\-BEGIN DH PARAMETERS\-\-\-\-\-\n/)); @@ -30,7 +29,7 @@ const tests = { 'Create default sized Private key': (test: any) => { pem.createPrivateKey((error: any, data: any) => { - var key = (data && data.key || '').toString(); + const key = (data && data.key || '').toString(); test.ifError(error); test.ok(key); test.ok(key.match(/^\n*\-\-\-\-\-BEGIN RSA PRIVATE KEY\-\-\-\-\-\n/)); @@ -43,7 +42,7 @@ const tests = { 'Create 2048bit Private key': (test: any) => { pem.createPrivateKey(2048, (error: any, data: any) => { - var key = (data && data.key || '').toString(); + const key = (data && data.key || '').toString(); test.ifError(error); test.ok(key); test.ok(key.match(/^\n*\-\-\-\-\-BEGIN RSA PRIVATE KEY\-\-\-\-\-\n/)); @@ -56,7 +55,7 @@ const tests = { 'Create 2048bit Private key with Password': (test: any) => { pem.createPrivateKey(2048, {cipher: 'des', password: 'TestMe'}, (error: any, data: any) => { - var key = (data && data.key || '').toString(); + const key = (data && data.key || '').toString(); test.ifError(error); test.ok(key); test.ok(key.match(/ENCRYPTED\n/)); @@ -70,7 +69,7 @@ const tests = { 'Create default CSR': (test: any) => { pem.createCSR((error: any, data: any) => { - var csr = (data && data.csr || '').toString(); + const csr = (data && data.csr || '').toString(); test.ifError(error); test.ok(csr); test.ok(csr.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE REQUEST\-\-\-\-\-\n/)); @@ -83,7 +82,7 @@ const tests = { }, 'Create CSR using config file': (test: any) => { - var certInfo = { + const certInfo = { issuer : {}, country: 'EE', state: 'Harjumaa', @@ -95,7 +94,7 @@ const tests = { }; pem.createCSR({ csrConfigFile: './test/fixtures/test.cnf' }, (error: any, data: any) => { - var csr = (data && data.csr || '').toString(); + const csr = (data && data.csr || '').toString(); test.ifError(error); test.ok(csr); test.ok(csr.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE REQUEST\-\-\-\-\-\n/)); @@ -115,12 +114,12 @@ const tests = { 'Create CSR with own key': (test: any) => { pem.createPrivateKey((error: any, data: any) => { - var key = (data && data.key || '').toString(); + const key = (data && data.key || '').toString(); pem.createCSR({ clientKey: key }, (error: any, data: any) => { - var csr = (data && data.csr || '').toString(); + const csr = (data && data.csr || '').toString(); test.ifError(error); test.ok(csr); test.ok(csr.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE REQUEST\-\-\-\-\-\n/)); @@ -136,15 +135,15 @@ const tests = { }, 'Create CSR with own encrypted key': (test: any) => { - var password = 'my:secure! "password\'s\nawesome'; + const password = 'my:secure! "password\'s\nawesome'; pem.createPrivateKey(2048, { cipher: 'des3', password }, (error: any, data: any) => { - var key = (data && data.key || '').toString(); + const key = (data && data.key || '').toString(); pem.createCSR({ clientKey: key, clientKeyPassword: password }, (error: any, data: any) => { - var csr = (data && data.csr || '').toString(); + const csr = (data && data.csr || '').toString(); test.ifError(error); test.ok(csr); test.ok(csr.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE REQUEST\-\-\-\-\-\n/)); @@ -161,7 +160,7 @@ const tests = { 'Create default certificate': (test: any) => { pem.createCertificate((error: any, data: any) => { - var certificate = (data && data.certificate || '').toString(); + const certificate = (data && data.certificate || '').toString(); test.ifError(error); test.ok(certificate); test.ok(certificate.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE\-\-\-\-\-\n/)); @@ -181,7 +180,7 @@ const tests = { pem.createCertificate({ selfSigned: true }, (error: any, data: any) => { - var certificate = (data && data.certificate || '').toString(); + const certificate = (data && data.certificate || '').toString(); test.ifError(error); test.ok(certificate); test.ok(certificate.match(/^\n*\-\-\-\-\-BEGIN CERTIFICATE\-\-\-\-\-\n/)); @@ -199,7 +198,7 @@ const tests = { 'Read default cert data from CSR': (test: any) => { pem.createCSR((error: any, data: any) => { - var csr = (data && data.csr || '').toString(); + const csr = (data && data.csr || '').toString(); test.ifError(error); // test.ok(fs.readdirSync('./tmp').length === 0); @@ -222,7 +221,7 @@ const tests = { }, 'Read edited cert data from CSR': (test: any) => { - var certInfo = { + const certInfo = { issuer : {}, country: 'EE', state: 'Harjumaa', @@ -233,7 +232,7 @@ const tests = { emailAddress: 'andris@node.ee' }; pem.createCSR(Object.create(certInfo), (error: any, data: any) => { - var csr = (data && data.csr || '').toString(); + const csr = (data && data.csr || '').toString(); test.ifError(error); // test.ok(fs.readdirSync('./tmp').length === 0); @@ -248,7 +247,7 @@ const tests = { 'Read default cert data from certificate': (test: any) => { pem.createCertificate((error: any, data: any) => { - var certificate = (data && data.certificate || '').toString(); + const certificate = (data && data.certificate || '').toString(); test.ifError(error); // test.ok(fs.readdirSync('./tmp').length === 0); @@ -286,7 +285,7 @@ const tests = { }, 'Read edited cert data from certificate': (test: any) => { - var certInfo = { + const certInfo = { issuer : { country: 'EE', state: 'Harjumaa', @@ -304,7 +303,7 @@ const tests = { emailAddress: 'andris@node.ee' }; pem.createCertificate(Object.create(certInfo), (error: any, data: any) => { - var certificate = (data && data.certificate || '').toString(); + const certificate = (data && data.certificate || '').toString(); test.ifError(error); // test.ok(fs.readdirSync('./tmp').length === 0); @@ -327,13 +326,13 @@ const tests = { 'Get public key from private key': (test: any) => { pem.createPrivateKey((error: any, data: any) => { - var key = (data && data.key || '').toString(); + const key = (data && data.key || '').toString(); test.ifError(error); test.ok(key); // test.ok(fs.readdirSync('./tmp').length === 0); pem.getPublicKey(key, (error: any, data: any) => { - var pubkey = (data && data.publicKey || '').toString(); + const pubkey = (data && data.publicKey || '').toString(); test.ifError(error); test.ok(pubkey); @@ -348,13 +347,13 @@ const tests = { 'Get public key from CSR': (test: any) => { pem.createCSR((error: any, data: any) => { - var key = (data && data.clientKey || '').toString(); + const key = (data && data.clientKey || '').toString(); test.ifError(error); test.ok(key); // test.ok(fs.readdirSync('./tmp').length === 0); pem.getPublicKey(key, (error: any, data: any) => { - var pubkey = (data && data.publicKey || '').toString(); + const pubkey = (data && data.publicKey || '').toString(); test.ifError(error); test.ok(pubkey); @@ -369,13 +368,13 @@ const tests = { 'Get public key from certificate': (test: any) => { pem.createCertificate((error: any, data: any) => { - var key = (data && data.clientKey || '').toString(); + const key = (data && data.clientKey || '').toString(); test.ifError(error); test.ok(key); // test.ok(fs.readdirSync('./tmp').length === 0); pem.getPublicKey(key, (error: any, data: any) => { - var pubkey = (data && data.publicKey || '').toString(); + const pubkey = (data && data.publicKey || '').toString(); test.ifError(error); test.ok(pubkey); @@ -390,13 +389,13 @@ const tests = { 'Get fingerprint from certificate': (test: any) => { pem.createCertificate((error: any, data: any) => { - var certificate = (data && data.certificate || '').toString(); + const certificate = (data && data.certificate || '').toString(); test.ifError(error); test.ok(certificate); // test.ok(fs.readdirSync('./tmp').length === 0); pem.getFingerprint(certificate, (error: any, data: any) => { - var fingerprint = (data && data.fingerprint || '').toString(); + const fingerprint = (data && data.fingerprint || '').toString(); test.ifError(error); test.ok(fingerprint); test.ok(fingerprint.match(/^[0-9A-F]{2}(:[0-9A-F]{2}){19}$/)); @@ -409,19 +408,19 @@ const tests = { 'Get modulus from certificate': (test: any) => { pem.createCertificate((error: any, data: any) => { - var certificate = (data && data.certificate || '').toString(); + const certificate = (data && data.certificate || '').toString(); test.ifError(error); test.ok(certificate); // test.ok(fs.readdirSync('./tmp').length === 0); pem.getModulus(certificate, (error: any, data: any) => { - var certmodulus = (data && data.modulus || '').toString(); + const certmodulus = (data && data.modulus || '').toString(); test.ifError(error); test.ok(certmodulus); test.ok(certmodulus.match(/^[0-9A-F]*$/)); // test.ok(fs.readdirSync('./tmp').length === 0); pem.getModulus(certificate, (error: any, data: any) => { - var keymodulus = (data && data.modulus || '').toString(); + const keymodulus = (data && data.modulus || '').toString(); test.ifError(error); test.ok(keymodulus); test.ok(keymodulus.match(/^[0-9A-F]*$/)); @@ -434,17 +433,17 @@ const tests = { }, 'Get modulus from a protected key': (test: any) => { - var certificate = ''; // fs.readFileSync('./test/fixtures/test.crt').toString(); - var key = ''; // fs.readFileSync('./test/fixtures/test.key').toString(); + const certificate = ''; // fs.readFileSync('./test/fixtures/test.crt').toString(); + const key = ''; // fs.readFileSync('./test/fixtures/test.key').toString(); pem.getModulus(certificate, (error: any, data: any) => { - var certmodulus = (data && data.modulus || '').toString(); + const certmodulus = (data && data.modulus || '').toString(); test.ifError(error); test.ok(certmodulus); test.ok(certmodulus.match(/^[0-9A-F]*$/)); // test.ok(fs.readdirSync('./tmp').length === 0); pem.getModulus(key, 'password', (error: any, data: any) => { - var keymodulus = (data && data.modulus || '').toString(); + const keymodulus = (data && data.modulus || '').toString(); test.ifError(error); test.ok(keymodulus); test.ok(keymodulus.match(/^[0-9A-F]*$/)); @@ -453,15 +452,14 @@ const tests = { test.done(); }); }); - }, 'Get DH param info': (test: any) => { - var dh = ''; // fs.readFileSync('./test/fixtures/test.dh').toString(); + const dh = ''; // fs.readFileSync('./test/fixtures/test.dh').toString(); pem.getDhparamInfo(dh, (error: any, data: any) => { - var size = data && data.size || 0; - var prime = (data && data.prime || '').toString(); + const size = data && data.size || 0; + const prime = (data && data.prime || '').toString(); test.ifError(error); test.equal(size, 1024); test.ok(prime); @@ -473,11 +471,11 @@ const tests = { }, 'Create and verify wildcard certificate': (test: any) => { - var certInfo = { + const certInfo = { commonName: '*.node.ee' }; pem.createCertificate(Object.create(certInfo), (error: any, data: any) => { - var certificate = (data && data.certificate || '').toString(); + const certificate = (data && data.certificate || '').toString(); test.ifError(error); // test.ok(fs.readdirSync('./tmp').length === 0); @@ -507,13 +505,12 @@ const tests = { }, 'Create PKCS12 without key password': (test: any) => { pem.createPrivateKey((error: any, data: any) => { - var key = (data && data.key || '').toString(); + const key = (data && data.key || '').toString(); pem.createCertificate({ clientKey: key, selfSigned: true }, (error: any, csr: any) => { - pem.createPkcs12(csr.clientKey, csr.certificate, 'mypassword', (err: any, pkcs12: any) => { test.ifError(err); test.ok(pkcs12); @@ -526,13 +523,12 @@ const tests = { }, 'Create PKCS12 with key password': (test: any) => { pem.createPrivateKey({cipher: 'aes128', password: 'xxx'}, (error: any, data: any) => { - var key = (data && data.key || '').toString(); + const key = (data && data.key || '').toString(); pem.createCertificate({ clientKey: key, selfSigned: true }, (error: any, csr: any) => { - pem.createPkcs12(csr.clientKey, csr.certificate, 'mypassword', {cipher: 'aes256', clientKeyPassword: 'xxx'}, (err: any, pkcs12: any) => { test.ifError(err); test.ok(pkcs12); diff --git a/types/plugapi/index.d.ts b/types/plugapi/index.d.ts index 82782a1934..e1c61ce792 100644 --- a/types/plugapi/index.d.ts +++ b/types/plugapi/index.d.ts @@ -3,20 +3,19 @@ // Definitions by: Brice Theurillat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace PlugAPI { - - export interface PlugLogin { + interface PlugLogin { email: string; password: string; } - export interface Notification { + interface Notification { action: string; id: number; timestamp: string; value: string; } - export interface RawChatMessage { + interface RawChatMessage { cid: string; message: string; sub: number; @@ -24,7 +23,7 @@ declare namespace PlugAPI { un: string; } - export interface Media { + interface Media { author: string; format: number; image: string; @@ -34,7 +33,7 @@ declare namespace PlugAPI { id: number; } - export interface Score { + interface Score { positive: number; listeners: number; grabs: number; @@ -42,23 +41,23 @@ declare namespace PlugAPI { skipped: number; } - export interface LastPlay { + interface LastPlay { dj: User.DJ; media: Media; score: Score; } - export interface FollowJoinData { + interface FollowJoinData { r: number; un: string; id: string; } - export interface LogObject { - log: () => void; + interface LogObject { + log(): void; } - export namespace User { + namespace User { interface Default { username: string; language: string; @@ -110,7 +109,7 @@ declare namespace PlugAPI { } } - export namespace Enum { + namespace Enum { interface RoomRole { NONE: number; RESIDENTDJ: number; @@ -217,7 +216,7 @@ declare namespace PlugAPI { } } - export namespace Event { + namespace Event { interface BoothCycle { moderator: string; cycle: boolean; @@ -339,21 +338,21 @@ declare namespace PlugAPI { interface Command extends Event.Chat { command: string; args: string[]; - respond: (...args: any[]) => any; - respondTimeout: (...args: any[]) => any; - havePermission: (...args: any[]) => boolean; - isFrom: (...args: any[]) => boolean; + respond(...args: any[]): any; + respondTimeout(...args: any[]): any; + havePermission(...args: any[]): boolean; + isFrom(...args: any[]): boolean; } } - export var ROOM_ROLE: Enum.RoomRole; - export var GLOBAL_ROLES: Enum.GlobalRole; - export var STATUS: Enum.Status; - export var BAN: Enum.Ban; - export var BAN_REASON: Enum.BanReason; - export var MUTE: Enum.Mute; - export var MUTE_REASON: Enum.MuteReason; - export var events: Enum.Events; + const ROOM_ROLE: Enum.RoomRole; + const GLOBAL_ROLES: Enum.GlobalRole; + const STATUS: Enum.Status; + const BAN: Enum.Ban; + const BAN_REASON: Enum.BanReason; + const MUTE: Enum.Mute; + const MUTE_REASON: Enum.MuteReason; + const events: Enum.Events; } declare class PlugAPI { @@ -412,4 +411,5 @@ declare class PlugAPI { on(event: "command", callback: (data: PlugAPI.Event.Command) => void): void; on(event: string, callback: (data: any) => void): void; } + export = PlugAPI; diff --git a/types/python-shell/python-shell-tests.ts b/types/python-shell/python-shell-tests.ts index 859ea102e2..7529edaac0 100644 --- a/types/python-shell/python-shell-tests.ts +++ b/types/python-shell/python-shell-tests.ts @@ -7,7 +7,7 @@ ps.run('my_script.py', err => { console.log('finished'); }); -var options = { +const options = { mode: 'text', pythonPath: 'path/to/python', pythonOptions: ['-u'], @@ -21,7 +21,7 @@ ps.run('my_script.py', options, (err, results) => { console.log('results: %j', results); }); -var pyshell = new PythonShell('my_script.py'); +const pyshell = new PythonShell('my_script.py'); // sends a message to the Python script via stdin pyshell.send('hello'); @@ -35,4 +35,4 @@ pyshell.on('message', message => { pyshell.end(err => { if (err) throw err; console.log('finished'); -}); \ No newline at end of file +}); diff --git a/types/qlik-visualizationextensions/index.d.ts b/types/qlik-visualizationextensions/index.d.ts index 4a4a635e4f..d4296fca5b 100644 --- a/types/qlik-visualizationextensions/index.d.ts +++ b/types/qlik-visualizationextensions/index.d.ts @@ -654,12 +654,12 @@ declare namespace BackendAPI { interface INxPatch { /** - * Operation to perform. - * One of: - * # Add - * # Remove - * # Replace - */ + * Operation to perform. + * One of: + * # Add + * # Remove + * # Replace + */ qOp: PatchType; /** @@ -1182,7 +1182,7 @@ declare namespace AppAPI { field(field?: string, state?: string): FieldAPI.IQField; /** - * Step forward in list of selections. + * Step forward in list of selections. * @return {Promise} - A promise of a Qlik engine reply. */ forward(): ng.IPromise; @@ -2178,7 +2178,7 @@ declare namespace VisualizationAPI { * # treemap * # extension * @param {array} [cols] - Optional. Column definitions, dimensions and measures. - Each entry can be of the following structures: + * Each entry can be of the following structures: * # String * # NxDimension * # NxMeasure @@ -2481,14 +2481,14 @@ interface IQVAngular { filter(object: { [name: string]: ng.Injectable }): void; /** - * Register a service constructor, which will be invoked with new to create - * the service instance. This is short for registering a service where its - * provider's $get property is a factory function that returns an instance - * instantiated by the injector from the service constructor function. - * @param name The name of the instance. - * @param serviceConstructor An injectable class (constructor function) that will be instantiated. - * @return Returns the constructed singleton of the service class/function. - */ + * Register a service constructor, which will be invoked with new to create + * the service instance. This is short for registering a service where its + * provider's $get property is a factory function that returns an instance + * instantiated by the injector from the service constructor function. + * @param name The name of the instance. + * @param serviceConstructor An injectable class (constructor function) that will be instantiated. + * @return Returns the constructed singleton of the service class/function. + */ service(name: string, serviceConstructor: ng.Injectable): T; service(object: { [name: string]: ng.Injectable }): T; diff --git a/types/rrule/index.d.ts b/types/rrule/index.d.ts index 038bde2736..3915865392 100644 --- a/types/rrule/index.d.ts +++ b/types/rrule/index.d.ts @@ -19,9 +19,9 @@ declare module "rrule" { declare namespace RRule { /** - * see - * The only required option is `freq`, one of RRule.YEARLY, RRule.MONTHLY, ... - */ + * see + * The only required option is `freq`, one of RRule.YEARLY, RRule.MONTHLY, ... + */ interface Options { freq: RRule.Frequency; dtstart?: Date; @@ -55,10 +55,10 @@ declare namespace RRule { declare class RRule { /** - * @param {Object?} options - see - * The only required option is `freq`, one of RRule.YEARLY, RRule.MONTHLY, ... - * @constructor - */ + * @param {Object?} options - see + * The only required option is `freq`, one of RRule.YEARLY, RRule.MONTHLY, ... + * @constructor + */ constructor(options: RRule.Options, noCache?: boolean); options: RRule.Options; @@ -66,55 +66,55 @@ declare class RRule { origOptions: RRule.Options; /** - * Returns the first recurrence after the given datetime instance. - * The inc keyword defines what happens if dt is an occurrence. - * With inc == True, if dt itself is an occurrence, it will be returned. - * @return Date or null - */ + * Returns the first recurrence after the given datetime instance. + * The inc keyword defines what happens if dt is an occurrence. + * With inc == True, if dt itself is an occurrence, it will be returned. + * @return Date or null + */ after(dt: Date, inc?: boolean): Date; /** - * @param {Function} iterator - optional function that will be called - * on each date that is added. It can return false - * to stop the iteration. - * @return Array containing all recurrences. - */ + * @param {Function} iterator - optional function that will be called + * on each date that is added. It can return false + * to stop the iteration. + * @return Array containing all recurrences. + */ all(iterator?: (date: Date, index?: number) => void): Date[]; /** - * Returns all the occurrences of the rrule between after and before. - * The inc keyword defines what happens if after and/or before are - * themselves occurrences. With inc == True, they will be included in the - * list, if they are found in the recurrence set. - * @return Array - */ + * Returns all the occurrences of the rrule between after and before. + * The inc keyword defines what happens if after and/or before are + * themselves occurrences. With inc == True, they will be included in the + * list, if they are found in the recurrence set. + * @return Array + */ between(a: Date, b: Date, inc?: boolean, iterator?: (date: Date, index: number) => void): Date[]; /** - * Returns the last recurrence before the given datetime instance. - * The inc keyword defines what happens if dt is an occurrence. - * With inc == True, if dt itself is an occurrence, it will be returned. - * @return Date or null - */ + * Returns the last recurrence before the given datetime instance. + * The inc keyword defines what happens if dt is an occurrence. + * With inc == True, if dt itself is an occurrence, it will be returned. + * @return Date or null + */ before(dt: Date, inc?: boolean): Date; /** - * Returns the number of recurrences in this set. It will have go trough - * the whole recurrence, if this hasn't been done before. - */ + * Returns the number of recurrences in this set. It will have go trough + * the whole recurrence, if this hasn't been done before. + */ count(): number; /** - * Converts the rrule into its string representation - * @see - * @return String - */ + * Converts the rrule into its string representation + * @see + * @return String + */ toString(): string; /** - * Will convert all rules described in nlp:ToText - * to text. - */ + * Will convert all rules described in nlp:ToText + * to text. + */ toText(gettext?: (str: string) => string, language?: any): string; isFullyConvertibleToText(): boolean; @@ -165,11 +165,10 @@ declare namespace RRule { class RRuleSet extends RRule { /** - * - * @param {Boolean?} noCache - * The same stratagy as RRule on cache, default to false - * @constructor - */ + * @param {Boolean?} noCache + * The same stratagy as RRule on cache, default to false + * @constructor + */ constructor(noCache?: boolean); rrule(rrule: RRule): void; rdate(date: Date): void; @@ -177,13 +176,13 @@ declare namespace RRule { exdate(date: Date): void; valueOf(): string[]; /** - * to generate recurrence field sush as: - * ["RRULE:FREQ=YEARLY;COUNT=2;BYDAY=TU;DTSTART=19970902T010000Z","RRULE:FREQ=YEARLY;COUNT=1;BYDAY=TH;DTSTART=19970902T010000Z"] - */ + * to generate recurrence field sush as: + * ["RRULE:FREQ=YEARLY;COUNT=2;BYDAY=TU;DTSTART=19970902T010000Z","RRULE:FREQ=YEARLY;COUNT=1;BYDAY=TH;DTSTART=19970902T010000Z"] + */ toString(): string; /** - * Create a new RRuleSet Object completely base on current instance - */ + * Create a new RRuleSet Object completely base on current instance + */ clone(): RRuleSet; } } diff --git a/types/sharepoint/index.d.ts b/types/sharepoint/index.d.ts index da19c221d4..dea4cae4fa 100644 --- a/types/sharepoint/index.d.ts +++ b/types/sharepoint/index.d.ts @@ -1549,7 +1549,7 @@ declare namespace SPAnimation { class State { SetAttribute(attributeId: Attribute, value: number): void; GetAttribute(attributeId: Attribute): number; - GetDataIndex(attributeId: Attribute): number + GetDataIndex(attributeId: Attribute): number; } class Object { @@ -5134,7 +5134,8 @@ declare namespace Microsoft.SharePoint.Client.Search { get_uiLanguage: () => number; set_uiLanguage: (value: number) => void; - getQuerySuggestionsWithResults: (iNumberOfQuerySuggestions: number, + getQuerySuggestionsWithResults: ( + iNumberOfQuerySuggestions: number, iNumberOfResultSuggestions: number, fPreQuerySuggestions: boolean, fHitHighlighting: boolean, @@ -5493,7 +5494,8 @@ declare namespace Microsoft.SharePoint.Client.Search { namespace Administration { class DocumentCrawlLog extends SP.ClientObject { constructor(context: SP.ClientContext, site: SP.Site); - getCrawledUrls: (getCountOnly: boolean, + getCrawledUrls: ( + getCountOnly: boolean, maxRows: { High: number; Low: number; }, queryString: string, isLike: boolean, @@ -9299,7 +9301,7 @@ declare class SPClientPeoplePicker { WebApplicationID: SP.Guid; // '{00000000-0000-0000-0000-000000000000}', GetAllUserInfo(): ISPClientPeoplePickerEntity[]; - SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void + SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void; AddUserKeys(userKeys: string, bSearch: boolean): void; BatchAddUserKeysOperation(allKeys: string[], numProcessed: number): void; ResolveAllUsers(fnContinuation: () => void): void; @@ -9331,7 +9333,7 @@ declare class SPClientPeoplePicker { IterateEachProcessedUser(fnCallback: (index: number, user: SPClientPeoplePickerProcessedUser) => void): void; HasResolvedUsers(): boolean; Validate(): void; - ValidateCurrentState(): void + ValidateCurrentState(): void; GetUnresolvedEntityErrorMessage(): string; ShowErrorMessage(msg: string): void; ClearServerError(): void; @@ -11652,7 +11654,7 @@ declare namespace Srch { /** Same as $addHandler with safety checks */ static addHandler(element: Element, eventName: string, handler: (instance: any, eventArgs: any) => void): void; /** Same as $removeHandler with safety checks */ - static removeHandler(element: Element, eventName: string, handler: (instance: any, eventArgs: any) => void): void + static removeHandler(element: Element, eventName: string, handler: (instance: any, eventArgs: any) => void): void; /** Returns true if the specified element is a descendant of the container element */ static isDescendant(element: Element, container: Element): boolean; @@ -11670,7 +11672,7 @@ declare namespace Srch { static findResultObjectFromDOM(e: Element, type: string): any; /** Appends specified parameter key and value string to the specified URL */ - static appendUrlParameter(url: string, keyAndValue: string): string + static appendUrlParameter(url: string, keyAndValue: string): string; /** Ensures that the given URL protocol value is allowed. Returns the specified URL value if the protocol is allowed; empty string otherwise. */ static ensureAllowedProtocol(value: string): string; diff --git a/types/sharepoint/sharepoint-tests.ts b/types/sharepoint/sharepoint-tests.ts index 34966f5a81..e6f885dcd4 100644 --- a/types/sharepoint/sharepoint-tests.ts +++ b/types/sharepoint/sharepoint-tests.ts @@ -1728,7 +1728,7 @@ namespace spdevlab { }); }); } - }; + } } } @@ -2156,7 +2156,7 @@ namespace _ { $('#report').children().remove(); $('#report').append("Failed to get session. Error: " + args.get_message()); } -}; +} // publishing.ts // Variables used in various callbacks @@ -2349,7 +2349,6 @@ namespace App { .then(l => this.lists = l) .catch((e: string) => this.$n.show(e, true)) .finally(() => this.$n.remove(loading)); - ; } } diff --git a/types/sharepoint/tslint.json b/types/sharepoint/tslint.json index e4f5db4fa0..e094a35492 100644 --- a/types/sharepoint/tslint.json +++ b/types/sharepoint/tslint.json @@ -1,6 +1,7 @@ { "extends": "../tslint.json", "rules": { + "jsdoc-format": false, "max-line-length": false } } diff --git a/types/tweezer.js/index.d.ts b/types/tweezer.js/index.d.ts index 1144eed7de..ae1f93030b 100644 --- a/types/tweezer.js/index.d.ts +++ b/types/tweezer.js/index.d.ts @@ -5,7 +5,7 @@ interface Options { duration?: number; - easing?: (currentTime: number, beginningTime: number, changeInValue: number, duration: number) => number; + easing?(currentTime: number, beginningTime: number, changeInValue: number, duration: number): number; start: number; end: number; } diff --git a/types/tweezer.js/tweezer.js-tests.ts b/types/tweezer.js/tweezer.js-tests.ts index cd3218966f..4fb7e7a05c 100644 --- a/types/tweezer.js/tweezer.js-tests.ts +++ b/types/tweezer.js/tweezer.js-tests.ts @@ -6,7 +6,7 @@ const tweezer = new Tweezer({ }); tweezer - .on('tick', (foo) => {foo.toFixed()}) + .on('tick', (foo) => { foo.toFixed(); }) .on('done', () => {}) .begin() .stop(); diff --git a/types/ui-router-extras/index.d.ts b/types/ui-router-extras/index.d.ts index 006a68b0f3..647263c912 100644 --- a/types/ui-router-extras/index.d.ts +++ b/types/ui-router-extras/index.d.ts @@ -93,8 +93,8 @@ declare module 'angular' { } /** - * Sticky state - */ + * Sticky state + */ interface IStickyState extends angular.ui.IState { /* * When marking a state sticky, the state must target its own unique named ui-view. diff --git a/types/vinyl-fs/index.d.ts b/types/vinyl-fs/index.d.ts index 84bcaf3533..46510032ee 100644 --- a/types/vinyl-fs/index.d.ts +++ b/types/vinyl-fs/index.d.ts @@ -25,17 +25,17 @@ interface SrcOptions extends globStream.Options { cwd?: string; /** - * Specifies the folder relative to the cwd - * This is used to determine the file names when saving in .dest() - * Default: where the glob begins - */ + * Specifies the folder relative to the cwd + * This is used to determine the file names when saving in .dest() + * Default: where the glob begins + */ base?: string; /** - * Setting this to false will make file.contents a paused stream - * If true it will buffer the file contents - * Default: true - */ + * Setting this to false will make file.contents a paused stream + * If true it will buffer the file contents + * Default: true + */ buffer?: boolean; /** @@ -59,10 +59,10 @@ interface SrcOptions extends globStream.Options { followSymlinks?: boolean; /** - * Setting this to false will ignore the contents of the file and disable - * writing to disk to speed up operations - * Default: true - */ + * Setting this to false will ignore the contents of the file and disable + * writing to disk to speed up operations + * Default: true + */ read?: boolean; /** @@ -95,30 +95,30 @@ interface SrcOptions extends globStream.Options { } /** -* Gets files that match the glob and converts them into the vinyl format -* @param globs Takes a glob string or an array of glob strings as the first argument -* Globs are executed in order, so negations should follow positive globs -* fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) -* @param opt Options Vinyl source options, changes the way the files are read, found, or stored in the vinyl stream -*/ + * Gets files that match the glob and converts them into the vinyl format + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + * @param opt Options Vinyl source options, changes the way the files are read, found, or stored in the vinyl stream + */ export function src(globs: string|string[], opt?: SrcOptions): NodeJS.ReadWriteStream; /** -* This is just a glob-watcher -* -* @param globs Takes a glob string or an array of glob strings as the first argument -* Globs are executed in order, so negations should follow positive globs -* fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) -*/ + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ export function watch(globs: string|string[], cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; /** -* This is just a glob-watcher -* -* @param globs Takes a glob string or an array of glob strings as the first argument -* Globs are executed in order, so negations should follow positive globs -* fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) -*/ + * This is just a glob-watcher + * + * @param globs Takes a glob string or an array of glob strings as the first argument + * Globs are executed in order, so negations should follow positive globs + * fs.src(['!b*.js', '*.js']) would not exclude any files, but this would: fs.src(['*.js', '!b*.js']) + */ export function watch( globs: string|string[], opt?: { @@ -130,24 +130,24 @@ export function watch( cb?: (outEvt: { type: any; path: any; old: any; }) => void): _events.EventEmitter; /** -* On write the stream will save the vinyl File to disk at the folder/cwd specified. -* After writing the file to disk, it will be emitted from the stream so you can keep piping these around. -* The file will be modified after being written to this stream: -* cwd, base, and path will be overwritten to match the folder -* stat.mode will be overwritten if you used a mode parameter -* contents will have it's position reset to the beginning if it is a stream -* @param folder destination folder -*/ + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param folder destination folder + */ export function dest(folder: string, opt?: { /** Specify the working directory the folder is relative to - * Default is process.cwd() - */ + * Default is process.cwd() + */ cwd?: string; /** Specify the mode the files should be created with - * Default is the mode of the input file (file.stat.mode) - * or the process mode if the input file has no mode property - */ + * Default is the mode of the input file (file.stat.mode) + * or the process mode if the input file has no mode property + */ mode?: number|string; /** Specify the mode the directory should be created with. Default is the process mode */ @@ -158,56 +158,56 @@ export function dest(folder: string, opt?: { }): NodeJS.ReadWriteStream; /** -* On write the stream will save the vinyl File to disk at the folder/cwd specified. -* After writing the file to disk, it will be emitted from the stream so you can keep piping these around. -* The file will be modified after being written to this stream: -* cwd, base, and path will be overwritten to match the folder -* stat.mode will be overwritten if you used a mode parameter -* contents will have it's position reset to the beginning if it is a stream -* @param getFolderPath function that takes in a file and returns a folder path -*/ + * On write the stream will save the vinyl File to disk at the folder/cwd specified. + * After writing the file to disk, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + * stat.mode will be overwritten if you used a mode parameter + * contents will have it's position reset to the beginning if it is a stream + * @param getFolderPath function that takes in a file and returns a folder path + */ export function dest(getFolderPath: (file: File) => string): NodeJS.ReadWriteStream; /** -* On write the stream will create a symbolic link (i.e. symlink) on disk at the folder/cwd specified. -* After creating the symbolic link, it will be emitted from the stream so you can keep piping these around. -* The file will be modified after being written to this stream: -* cwd, base, and path will be overwritten to match the folder -*/ + * On write the stream will create a symbolic link (i.e. symlink) on disk at the folder/cwd specified. + * After creating the symbolic link, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + */ export function symlink(folder: string, opts?: { /** - * Specify the working directory the folder is relative to - * Default is process.cwd() - */ + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ cwd?: string; /** Specify the mode the directory should be created with. Default is the process mode */ mode?: number|string; /** - * Specify the mode the directory should be created with - * Default is the process mode - */ + * Specify the mode the directory should be created with + * Default is the process mode + */ dirMode?: number }): NodeJS.ReadWriteStream; /** -* On write the stream will create a symbolic link (i.e. symlink) on disk at the folder/cwd generated from getFolderPath. -* After creating the symbolic link, it will be emitted from the stream so you can keep piping these around. -* The file will be modified after being written to this stream: -* cwd, base, and path will be overwritten to match the folder -*/ + * On write the stream will create a symbolic link (i.e. symlink) on disk at the folder/cwd generated from getFolderPath. + * After creating the symbolic link, it will be emitted from the stream so you can keep piping these around. + * The file will be modified after being written to this stream: + * cwd, base, and path will be overwritten to match the folder + */ export function symlink(getFolderPath: (File: File) => string, opts?: { /** - * Specify the working directory the folder is relative to - * Default is process.cwd() - */ + * Specify the working directory the folder is relative to + * Default is process.cwd() + */ cwd?: string; /** - * Specify the mode the directory should be created with - * Default is the process mode - */ + * Specify the mode the directory should be created with + * Default is the process mode + */ dirMode?: number }): NodeJS.ReadWriteStream; diff --git a/types/wicg-mediasession/wicg-mediasession-tests.ts b/types/wicg-mediasession/wicg-mediasession-tests.ts index 78731a3222..88ab80afa1 100644 --- a/types/wicg-mediasession/wicg-mediasession-tests.ts +++ b/types/wicg-mediasession/wicg-mediasession-tests.ts @@ -1,4 +1,3 @@ - const tracks: string[] = ['chapter1.mp3', 'chapter2.mp3', 'chapter3.mp3']; let trackId = 0; diff --git a/types/wu/wu-tests.ts b/types/wu/wu-tests.ts index 3c62cdb2d4..90657734e7 100644 --- a/types/wu/wu-tests.ts +++ b/types/wu/wu-tests.ts @@ -1,6 +1,9 @@ // adapted from `cat wu.js/test/* |sed '/= require/d'> wu-tests.ts` -declare var describe: any, it: any, mocha: any, assert: { +declare const describe: any; +declare const it: any; +declare const mocha: any; +declare const assert: { iterable: any; eqSet(expected: Set, actual: Iterable): any; ok: any; diff --git a/types/xml/xml-tests.ts b/types/xml/xml-tests.ts index 7bc3cd61c0..54619959af 100644 --- a/types/xml/xml-tests.ts +++ b/types/xml/xml-tests.ts @@ -7,13 +7,12 @@ interface Tester { same(a: any, b: any): void; plan(id: number): void; ok(a: any): void; -}; +} function test(c: string, f: (t: Tester) => void) { return; } - test('no elements', t => { t.is(xml(), ''); t.is(xml([]), ''); @@ -162,4 +161,4 @@ test('xml declaration options', t => { t.is(xml([{a: 'test'}], {declaration: false}), 'test'); t.is(xml([{a: 'test'}], {declaration: true, indent: '\n'}), '\ntest'); t.is(xml([{a: 'test'}], {}), 'test'); -}); \ No newline at end of file +}); diff --git a/types/xml2json/xml2json-tests.ts b/types/xml2json/xml2json-tests.ts index 409fc5f27e..fd8566ca52 100644 --- a/types/xml2json/xml2json-tests.ts +++ b/types/xml2json/xml2json-tests.ts @@ -1,15 +1,15 @@ import * as parser from 'xml2json'; -var xml = "bar"; +let xml = "bar"; // xml to json -var jsonString: string = parser.toJson(xml); +const jsonString: string = parser.toJson(xml); // json to xml -var xml: string = parser.toXml(jsonString); +xml = parser.toXml(jsonString); // xml to json in object mode and JsonOptions -var jsonObject: {} = parser.toJson(xml, { +const jsonObject: {} = parser.toJson(xml, { object: true, reversible: false, coerce: false, @@ -19,6 +19,6 @@ var jsonObject: {} = parser.toJson(xml, { }); // json to xml with XmlOptions -var xml: string = parser.toXml(jsonObject, { +xml = parser.toXml(jsonObject, { sanitize: true }); diff --git a/types/xmpp__jid/index.d.ts b/types/xmpp__jid/index.d.ts index b132680c72..a7b2e0fe7a 100644 --- a/types/xmpp__jid/index.d.ts +++ b/types/xmpp__jid/index.d.ts @@ -10,14 +10,14 @@ // Remove the `declare module` wrapper. // tslint:disable-next-line no-single-declare-module declare module "@xmpp/jid" { - export function createJID(local: string, domain: string, resource: string): JID; - export function equal(a: JID, b: JID): boolean; - export function is(a: any): boolean; + function createJID(local: string, domain: string, resource: string): JID; + function equal(a: JID, b: JID): boolean; + function is(a: any): boolean; /** * Created by marcneumann on 17.02.17. */ - export class JID { + class JID { local: string; domain: string; resource: string; @@ -30,17 +30,17 @@ declare module "@xmpp/jid" { /** * Convenience method to distinguish users - **/ + */ bare(): JID; /** * Comparison function - **/ + */ equals(other: JID): boolean; /** * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart - **/ + */ setLocal(local: string, escape?: any): void; getLocal(unescape?: any): string; diff --git a/types/xsd-schema-validator/index.d.ts b/types/xsd-schema-validator/index.d.ts index db867b4178..c4fd02e8f5 100644 --- a/types/xsd-schema-validator/index.d.ts +++ b/types/xsd-schema-validator/index.d.ts @@ -9,4 +9,4 @@ export function validateXML(xml: string|NodeJS.ReadableStream|{file: string}, pa valid: boolean; messages: string[]; result: string; -}) => void): void; \ No newline at end of file +}) => void): void; diff --git a/types/xsd-schema-validator/xsd-schema-validator-tests.ts b/types/xsd-schema-validator/xsd-schema-validator-tests.ts index d66148d219..21d8f3d2a4 100644 --- a/types/xsd-schema-validator/xsd-schema-validator-tests.ts +++ b/types/xsd-schema-validator/xsd-schema-validator-tests.ts @@ -1,7 +1,6 @@ import fs = require("fs"); import validator = require("xsd-schema-validator"); - validator.validateXML("", 'resources/foo.xsd', (err, result) => { if (err) { throw err; @@ -12,4 +11,4 @@ validator.validateXML(fs.createReadStream('some.xml'), "schema.xsd", (err) => { }); validator.validateXML({ file: "some.xml" }, "schema.xsd", (err) => { if (err) throw err; -}); \ No newline at end of file +}); From 4fd2d7547c4fb60c0577d447f0f50f7eb42a1d85 Mon Sep 17 00:00:00 2001 From: Kalle Ott Date: Thu, 30 Mar 2017 22:12:51 +0200 Subject: [PATCH 24/31] fixed the semver note in the header comment (#15522) * fixed the semver note in the header comment * changed tslint config * fixed linting --- .../dist/commonjs/ArrowKeyStepper.d.ts | 2 +- .../dist/commonjs/AutoSizer.d.ts | 2 +- .../dist/commonjs/CellMeasurer.d.ts | 2 +- .../dist/commonjs/Collection.d.ts | 2 +- .../dist/commonjs/ColumnSizer.d.ts | 2 +- .../react-virtualized/dist/commonjs/Grid.d.ts | 2 +- .../dist/commonjs/InfiniteLoader.d.ts | 2 +- .../react-virtualized/dist/commonjs/List.d.ts | 2 +- .../dist/commonjs/Masonry.d.ts | 2 +- .../dist/commonjs/MultiGrid.d.ts | 2 +- .../dist/commonjs/ScrollSync.d.ts | 2 +- .../dist/commonjs/Table.d.ts | 2 +- .../dist/commonjs/WindowScroller.d.ts | 2 +- .../react-virtualized/dist/es/AutoSizer.d.ts | 10 +- types/react-virtualized/dist/es/Grid.d.ts | 18 +-- types/react-virtualized/dist/es/Masonry.d.ts | 5 +- .../react-virtualized/dist/es/ScrollSync.d.ts | 2 +- types/react-virtualized/dist/es/Table.d.ts | 10 +- types/react-virtualized/index.d.ts | 2 +- .../react-virtualized-tests.tsx | 111 +++++++++--------- types/react-virtualized/tslint.json | 13 +- 21 files changed, 102 insertions(+), 95 deletions(-) diff --git a/types/react-virtualized/dist/commonjs/ArrowKeyStepper.d.ts b/types/react-virtualized/dist/commonjs/ArrowKeyStepper.d.ts index fd16c58feb..6cd9604575 100644 --- a/types/react-virtualized/dist/commonjs/ArrowKeyStepper.d.ts +++ b/types/react-virtualized/dist/commonjs/ArrowKeyStepper.d.ts @@ -1 +1 @@ -export * from '../es/ArrowKeyStepper'; \ No newline at end of file +export * from '../es/ArrowKeyStepper'; diff --git a/types/react-virtualized/dist/commonjs/AutoSizer.d.ts b/types/react-virtualized/dist/commonjs/AutoSizer.d.ts index c0551a98a4..6d16fa0c45 100644 --- a/types/react-virtualized/dist/commonjs/AutoSizer.d.ts +++ b/types/react-virtualized/dist/commonjs/AutoSizer.d.ts @@ -1 +1 @@ -export * from '../es/AutoSizer'; \ No newline at end of file +export * from '../es/AutoSizer'; diff --git a/types/react-virtualized/dist/commonjs/CellMeasurer.d.ts b/types/react-virtualized/dist/commonjs/CellMeasurer.d.ts index 907eafee51..77f4abea84 100644 --- a/types/react-virtualized/dist/commonjs/CellMeasurer.d.ts +++ b/types/react-virtualized/dist/commonjs/CellMeasurer.d.ts @@ -1 +1 @@ -export * from '../es/CellMeasurer'; \ No newline at end of file +export * from '../es/CellMeasurer'; diff --git a/types/react-virtualized/dist/commonjs/Collection.d.ts b/types/react-virtualized/dist/commonjs/Collection.d.ts index 2764686c76..e4905c3eee 100644 --- a/types/react-virtualized/dist/commonjs/Collection.d.ts +++ b/types/react-virtualized/dist/commonjs/Collection.d.ts @@ -1 +1 @@ -export * from '../es/Collection'; \ No newline at end of file +export * from '../es/Collection'; diff --git a/types/react-virtualized/dist/commonjs/ColumnSizer.d.ts b/types/react-virtualized/dist/commonjs/ColumnSizer.d.ts index 80c9cf5d2e..1c42d3b94b 100644 --- a/types/react-virtualized/dist/commonjs/ColumnSizer.d.ts +++ b/types/react-virtualized/dist/commonjs/ColumnSizer.d.ts @@ -1 +1 @@ -export * from '../es/ColumnSizer'; \ No newline at end of file +export * from '../es/ColumnSizer'; diff --git a/types/react-virtualized/dist/commonjs/Grid.d.ts b/types/react-virtualized/dist/commonjs/Grid.d.ts index 168a11ac52..6834f9b47d 100644 --- a/types/react-virtualized/dist/commonjs/Grid.d.ts +++ b/types/react-virtualized/dist/commonjs/Grid.d.ts @@ -1 +1 @@ -export * from '../es/Grid'; \ No newline at end of file +export * from '../es/Grid'; diff --git a/types/react-virtualized/dist/commonjs/InfiniteLoader.d.ts b/types/react-virtualized/dist/commonjs/InfiniteLoader.d.ts index 29449c85ff..d4614b32d7 100644 --- a/types/react-virtualized/dist/commonjs/InfiniteLoader.d.ts +++ b/types/react-virtualized/dist/commonjs/InfiniteLoader.d.ts @@ -1 +1 @@ -export * from '../es/InfiniteLoader'; \ No newline at end of file +export * from '../es/InfiniteLoader'; diff --git a/types/react-virtualized/dist/commonjs/List.d.ts b/types/react-virtualized/dist/commonjs/List.d.ts index 6fdfde2dc0..8a174d91e2 100644 --- a/types/react-virtualized/dist/commonjs/List.d.ts +++ b/types/react-virtualized/dist/commonjs/List.d.ts @@ -1 +1 @@ -export * from '../es/List'; \ No newline at end of file +export * from '../es/List'; diff --git a/types/react-virtualized/dist/commonjs/Masonry.d.ts b/types/react-virtualized/dist/commonjs/Masonry.d.ts index e5189fb5f9..fc2768d7b7 100644 --- a/types/react-virtualized/dist/commonjs/Masonry.d.ts +++ b/types/react-virtualized/dist/commonjs/Masonry.d.ts @@ -1 +1 @@ -export * from '../es/Masonry'; \ No newline at end of file +export * from '../es/Masonry'; diff --git a/types/react-virtualized/dist/commonjs/MultiGrid.d.ts b/types/react-virtualized/dist/commonjs/MultiGrid.d.ts index 09f385eca4..7504908682 100644 --- a/types/react-virtualized/dist/commonjs/MultiGrid.d.ts +++ b/types/react-virtualized/dist/commonjs/MultiGrid.d.ts @@ -1 +1 @@ -export * from '../es/MultiGrid'; \ No newline at end of file +export * from '../es/MultiGrid'; diff --git a/types/react-virtualized/dist/commonjs/ScrollSync.d.ts b/types/react-virtualized/dist/commonjs/ScrollSync.d.ts index ffb4423c0a..2e9ec08a4d 100644 --- a/types/react-virtualized/dist/commonjs/ScrollSync.d.ts +++ b/types/react-virtualized/dist/commonjs/ScrollSync.d.ts @@ -1 +1 @@ -export * from '../es/ScrollSync'; \ No newline at end of file +export * from '../es/ScrollSync'; diff --git a/types/react-virtualized/dist/commonjs/Table.d.ts b/types/react-virtualized/dist/commonjs/Table.d.ts index db2670ceda..c710f4050c 100644 --- a/types/react-virtualized/dist/commonjs/Table.d.ts +++ b/types/react-virtualized/dist/commonjs/Table.d.ts @@ -1 +1 @@ -export * from '../es/Table'; \ No newline at end of file +export * from '../es/Table'; diff --git a/types/react-virtualized/dist/commonjs/WindowScroller.d.ts b/types/react-virtualized/dist/commonjs/WindowScroller.d.ts index 0380f0a4fb..51cd1f6ac0 100644 --- a/types/react-virtualized/dist/commonjs/WindowScroller.d.ts +++ b/types/react-virtualized/dist/commonjs/WindowScroller.d.ts @@ -1 +1 @@ -export * from '../es/WindowScroller'; \ No newline at end of file +export * from '../es/WindowScroller'; diff --git a/types/react-virtualized/dist/es/AutoSizer.d.ts b/types/react-virtualized/dist/es/AutoSizer.d.ts index 6d82a44482..ea72c43c1e 100644 --- a/types/react-virtualized/dist/es/AutoSizer.d.ts +++ b/types/react-virtualized/dist/es/AutoSizer.d.ts @@ -19,10 +19,10 @@ export type AutoSizerProps = { export class AutoSizer extends PureComponent { static propTypes: { /** - * Function responsible for rendering children. - * This function should implement the following signature: - * ({ height, width }) => PropTypes.element - */ + * Function responsible for rendering children. + * This function should implement the following signature: + * ({ height, width }) => PropTypes.element + */ children: Validator<(props: Dimensions) => React.ReactNode>, /** Disable dynamic :height property */ @@ -36,7 +36,7 @@ export class AutoSizer extends PureComponent { }; static defaultProps: { - onResize: () => { } + onResize: () => {} }; constructor(props: AutoSizerProps); diff --git a/types/react-virtualized/dist/es/Grid.d.ts b/types/react-virtualized/dist/es/Grid.d.ts index b68cf45956..7fcd0d1314 100644 --- a/types/react-virtualized/dist/es/Grid.d.ts +++ b/types/react-virtualized/dist/es/Grid.d.ts @@ -75,16 +75,16 @@ export type CellSizeAndPositionManager = { offset // safe }: ContainerSizeAndOffset): number; /** - * This method returns the size and position for the cell at the specified index. - * It just-in-time calculates (or used cached values) for cells leading up to the index. - */ + * This method returns the size and position for the cell at the specified index. + * It just-in-time calculates (or used cached values) for cells leading up to the index. + */ getSizeAndPositionOfCell(index: number): SizeAndPositionData; getSizeAndPositionOfLastMeasuredCell(): SizeAndPositionData; /** - * Total size of all cells being measured. - * This value will be completedly estimated initially. - * As cells as measured the estimate will be updated. - */ + * Total size of all cells being measured. + * This value will be completedly estimated initially. + * As cells as measured the estimate will be updated. + */ getTotalSize(): number; /** * Determines a new offset that ensures a certain cell is visible, given the current offset. @@ -202,7 +202,7 @@ export class Grid extends PureComponent { * Responsible for rendering a cell given an row and column index. * Should implement the following interface: ({ columnIndex: number, rowIndex: number }): PropTypes.node */ - cellRenderer: Validator< (props: GridCellProps) => React.ReactNode>, + cellRenderer: Validator<(props: GridCellProps) => React.ReactNode>, /** * Responsible for rendering a group of cells given their index ranges. @@ -458,4 +458,4 @@ export class Grid extends PureComponent { render(): JSX.Element; } -export const defaultCellRangeRenderer: GridCellRangeRenderer; \ No newline at end of file +export const defaultCellRangeRenderer: GridCellRangeRenderer; diff --git a/types/react-virtualized/dist/es/Masonry.d.ts b/types/react-virtualized/dist/es/Masonry.d.ts index 51c59a90fc..eb44635978 100644 --- a/types/react-virtualized/dist/es/Masonry.d.ts +++ b/types/react-virtualized/dist/es/Masonry.d.ts @@ -83,7 +83,6 @@ export type MasonryState = { * (Items may not span multiple columns.) */ export class Masonry extends PureComponent { - static defaultProps: { autoHeight: false, keyMapper: identity, @@ -140,6 +139,6 @@ export type resetParams = { spacer?: number }; -export type Positioner = ((index: number) => Position) & {reset: (params: resetParams) => void}; +export type Positioner = ((index: number) => Position) & { reset: (params: resetParams) => void }; -export const createCellPositioner: (params: createCellPositionerParams) => Positioner; \ No newline at end of file +export const createCellPositioner: (params: createCellPositionerParams) => Positioner; diff --git a/types/react-virtualized/dist/es/ScrollSync.d.ts b/types/react-virtualized/dist/es/ScrollSync.d.ts index 4f1e924a69..d244262d25 100644 --- a/types/react-virtualized/dist/es/ScrollSync.d.ts +++ b/types/react-virtualized/dist/es/ScrollSync.d.ts @@ -48,4 +48,4 @@ export class ScrollSync extends PureComponent constructor(props: ScrollSyncProps, context: any); render(): JSX.Element; -} \ No newline at end of file +} diff --git a/types/react-virtualized/dist/es/Table.d.ts b/types/react-virtualized/dist/es/Table.d.ts index 6607211dcf..118215f4fa 100644 --- a/types/react-virtualized/dist/es/Table.d.ts +++ b/types/react-virtualized/dist/es/Table.d.ts @@ -33,7 +33,7 @@ export type TableHeaderRowProps = { }; export type TableRowProps = { className: string, - columns: Array, + columns: any[], index: number, isScrolling: boolean, onRowClick?: (params: RowMouseEventHandlerParams) => void, @@ -198,7 +198,7 @@ export type TableProps = { export const defaultTableCellDataGetter: TableCellDataGetter; export const defaultTableCellRenderer: TableCellRenderer; -export const defaultTableHeaderRenderer: () => React.ReactElement[]; +export const defaultTableHeaderRenderer: () => Array>; export const defaultTableHeaderRowRenderer: TableHeaderRowRenderer; export const defaultTableRowRenderer: TableRowRenderer; @@ -286,9 +286,9 @@ export class Table extends PureComponent { noRowsRenderer: Requireable<() => JSX.Element>, /** - * Optional callback when a column's header is clicked. - * ({ columnData: any, dataKey: string }): void - */ + * Optional callback when a column's header is clicked. + * ({ columnData: any, dataKey: string }): void + */ onHeaderClick: Requireable<(params: HeaderMouseEventHandlerParams) => void>, /** diff --git a/types/react-virtualized/index.d.ts b/types/react-virtualized/index.d.ts index d6860176ed..2440e1dcf3 100644 --- a/types/react-virtualized/index.d.ts +++ b/types/react-virtualized/index.d.ts @@ -164,4 +164,4 @@ export type ScrollEventData = { clientHeight: number, scrollHeight: number, scrollTop: number -} \ No newline at end of file +} diff --git a/types/react-virtualized/react-virtualized-tests.tsx b/types/react-virtualized/react-virtualized-tests.tsx index 71386b2780..18de45e25a 100644 --- a/types/react-virtualized/react-virtualized-tests.tsx +++ b/types/react-virtualized/react-virtualized-tests.tsx @@ -113,7 +113,7 @@ export class AutoSizerExample extends PureComponent { ) } } -import { } from 'react' +import { } from 'react' import { CellMeasurer, CellMeasurerCache } from 'react-virtualized' export class DynamicHeightList extends PureComponent { @@ -194,7 +194,6 @@ const GUTTER_SIZE = 3 const CELL_WIDTH = 75 export class CollectionExample extends PureComponent { - _columnYMap: any; constructor(props, context) { @@ -457,8 +456,6 @@ export class ColumnSizerExample extends PureComponent { } export class GridExample extends PureComponent { - - constructor(props, context) { super(props, context) @@ -731,7 +728,7 @@ export class InfiniteLoaderExample extends PureComponent { const { loadedRowsMap, loadingRowCount } = this.state const increment = stopIndex - startIndex + 1 - for (var i = startIndex; i <= stopIndex; i++) { + for (let i = startIndex; i <= stopIndex; i++) { loadedRowsMap[i] = STATUS_LOADING } @@ -744,7 +741,7 @@ export class InfiniteLoaderExample extends PureComponent { delete this._timeoutIdMap[timeoutId] - for (var i = startIndex; i <= stopIndex; i++) { + for (let i = startIndex; i <= stopIndex; i++) { loadedRowsMap[i] = STATUS_LOADED } @@ -1251,7 +1248,7 @@ export class MultiGridExample extends PureComponent { } } -import {ScrollSync } from 'react-virtualized' +import { ScrollSync } from 'react-virtualized' const LEFT_COLOR_FROM = hexToRgb('#471061') const LEFT_COLOR_TO = hexToRgb('#BC3959') @@ -1532,59 +1529,59 @@ export class TableExample extends PureComponent { const rowGetter = ({ index }) => this._getDatum(sortedList, index) return ( -
- - {({ width }) => ( - - {!hideIndexRow && - rowData.index - } - dataKey='index' - disableSort={!this._isSortEnabled()} - width={60} - /> - } +
+ + {({ width }) => ( +
+ {!hideIndexRow && - cellData + label='Index' + cellDataGetter={ + ({ columnData, dataKey, rowData }) => rowData.index } - flexGrow={1} + dataKey='index' + disableSort={!this._isSortEnabled()} + width={60} /> -
- )} -
-
+ } + + cellData + } + flexGrow={1} + /> + + )} + +
) } diff --git a/types/react-virtualized/tslint.json b/types/react-virtualized/tslint.json index 2221e40e4a..65f4cad455 100644 --- a/types/react-virtualized/tslint.json +++ b/types/react-virtualized/tslint.json @@ -1 +1,12 @@ -{ "extends": "../tslint.json" } \ No newline at end of file +{ + "extends": "../tslint.json", + "rules": { + "interface-over-type-literal": false, + "semicolon": [ + false + ], + "prefer-method-signature": false, + "prefer-declare-function": false, + "no-padding": false + } +} \ No newline at end of file From 3d13ec53995bcccc68bdd4317e5bccb2235ee25e Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 30 Mar 2017 14:11:46 -0700 Subject: [PATCH 25/31] Lint react-* packages (#15526) --- types/react-autosuggest/index.d.ts | 28 +- types/react-body-classname/index.d.ts | 2 +- .../react-body-classname-tests.tsx | 2 +- types/react-bootstrap-date-picker/index.d.ts | 8 +- types/react-copy-to-clipboard/index.d.ts | 2 +- .../react-day-picker-tests.tsx | 2 +- .../react-dnd-html5-backend-tests.ts | 48 +-- types/react-event-listener/index.d.ts | 372 +++++++++--------- types/react-facebook-login/index.d.ts | 4 +- types/react-gravatar/index.d.ts | 6 +- types/react-gravatar/react-gravatar-tests.tsx | 2 +- types/react-highlight-words/index.d.ts | 2 +- .../react-highlighter-tests.tsx | 2 +- types/react-icon-base/index.d.ts | 4 +- .../react-icon-base/react-icon-base-tests.tsx | 2 +- types/react-icons/react-icons-tests.tsx | 2 - types/react-icons/tslint.json | 9 +- types/react-input-mask/index.d.ts | 4 +- types/react-joyride/index.d.ts | 2 +- types/react-json-pretty/index.d.ts | 4 +- types/react-leaflet/index.d.ts | 106 ++--- types/react-leaflet/react-leaflet-tests.tsx | 7 +- types/react-modal/index.d.ts | 6 +- types/react-modal/react-modal-tests.tsx | 2 +- types/react-onsenui/index.d.ts | 260 ++++++------ types/react-onsenui/react-onsenui-tests.tsx | 11 +- types/react-overlays/index.d.ts | 26 +- .../react-overlays/lib/RootCloseWrapper.d.ts | 2 +- types/react-overlays/react-overlays-tests.tsx | 1 - types/react-paginate/index.d.ts | 4 +- types/react-paginate/react-paginate-tests.tsx | 1 - types/react-portal/index.d.ts | 10 +- types/react-portal/react-portal-tests.tsx | 6 +- types/react-recaptcha/index.d.ts | 6 +- .../react-recaptcha/react-recaptcha-tests.tsx | 2 +- types/react-sidebar/index.d.ts | 2 +- types/react-smooth-scrollbar/index.d.ts | 3 +- types/react-sticky/index.d.ts | 2 +- types/react-test-renderer/index.d.ts | 2 +- types/reactstrap/index.d.ts | 140 +++---- types/reactstrap/reactstrap-tests.tsx | 83 ++-- 41 files changed, 575 insertions(+), 614 deletions(-) diff --git a/types/react-autosuggest/index.d.ts b/types/react-autosuggest/index.d.ts index 7199fefcdb..165262eb39 100644 --- a/types/react-autosuggest/index.d.ts +++ b/types/react-autosuggest/index.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 - import * as React from 'react'; declare class Autosuggest extends React.Component {} @@ -32,11 +31,11 @@ declare namespace Autosuggest { interface InputProps extends React.HTMLAttributes { value: string; - onChange: (event: React.FormEvent, params?: ChangeEvent) => void; - onBlur?: (event: React.FormEvent, params?: BlurEvent) => void; + onChange(event: React.FormEvent, params?: ChangeEvent): void; + onBlur?(event: React.FormEvent, params?: BlurEvent): void; } - export interface SuggestionSelectedEventData { + interface SuggestionSelectedEventData { method: 'click' | 'enter'; sectionIndex: number | null; suggestion: TSuggestion; @@ -57,23 +56,22 @@ declare namespace Autosuggest { interface AutosuggestProps extends React.Props { suggestions: any[]; - onSuggestionsFetchRequested: (request: SuggestionsFetchRequest) => void; - onSuggestionsClearRequested?: () => void; - getSuggestionValue: (suggestion: any) => any; - renderSuggestion: (suggestion: any, inputValues: InputValues) => JSX.Element; + onSuggestionsFetchRequested(request: SuggestionsFetchRequest): void; + onSuggestionsClearRequested?(): void; + getSuggestionValue(suggestion: any): any; + renderSuggestion(suggestion: any, inputValues: InputValues): JSX.Element; inputProps: InputProps; - onSuggestionSelected?: (event: React.FormEvent, data: SuggestionSelectedEventData) => void; - shouldRenderSuggestions?: (value: string) => boolean; + onSuggestionSelected?(event: React.FormEvent, data: SuggestionSelectedEventData): void; + shouldRenderSuggestions?(value: string): boolean; alwaysRenderSuggestions?: boolean; focusFirstSuggestion?: boolean; focusInputOnSuggestionClick?: boolean; multiSection?: boolean; - renderSectionTitle?: (section: any, inputValues: InputValues) => JSX.Element; - getSectionSuggestions?: (section: any) => any[]; - renderInputComponent?: () => JSX.Element; - renderSuggestionsContainer?: (children: any) => JSX.Element; + renderSectionTitle?(section: any, inputValues: InputValues): JSX.Element; + getSectionSuggestions?(section: any): any[]; + renderInputComponent?(): JSX.Element; + renderSuggestionsContainer?(children: any): JSX.Element; theme?: Theme; id?: string; } - } diff --git a/types/react-body-classname/index.d.ts b/types/react-body-classname/index.d.ts index e20bffdc73..b7f0856df9 100644 --- a/types/react-body-classname/index.d.ts +++ b/types/react-body-classname/index.d.ts @@ -13,4 +13,4 @@ declare class BodyClassName extends React.Component<{ className: string }, any> static displayName: string; static peek(): any; static rewind(): any; -} \ No newline at end of file +} diff --git a/types/react-body-classname/react-body-classname-tests.tsx b/types/react-body-classname/react-body-classname-tests.tsx index 7fb971fe44..019105bee6 100644 --- a/types/react-body-classname/react-body-classname-tests.tsx +++ b/types/react-body-classname/react-body-classname-tests.tsx @@ -23,4 +23,4 @@ class App { // Becuase we nested the component, our body will now have 'app home' // as the class name } -} \ No newline at end of file +} diff --git a/types/react-bootstrap-date-picker/index.d.ts b/types/react-bootstrap-date-picker/index.d.ts index f905dc77a7..28a5b0c72b 100644 --- a/types/react-bootstrap-date-picker/index.d.ts +++ b/types/react-bootstrap-date-picker/index.d.ts @@ -14,10 +14,9 @@ declare const DatePicker: DatePicker; type DatePicker = ComponentClass; declare namespace DatePicker { + type ChangeCallback = (value: string, formattedValue: string) => void; - export type ChangeCallback = (value: string, formattedValue: string) => void; - - export interface DatePickerProps { + interface DatePickerProps { value?: string; defaultValue?: string; style?: any; @@ -30,7 +29,7 @@ declare namespace DatePicker { dateFormat?: string; clearButtonElement?: ReactNode; showClearButton?: boolean; - onClear?: () => void; + onClear?(): void; previousButtonElement?: ReactNode; nextButtonElement?: ReactNode; cellPadding?: string; @@ -43,5 +42,4 @@ declare namespace DatePicker { todayButtonLabel?: string; customControl?: StatelessComponent | ComponentClass; } - } diff --git a/types/react-copy-to-clipboard/index.d.ts b/types/react-copy-to-clipboard/index.d.ts index e4a0948962..67b70b0ad1 100644 --- a/types/react-copy-to-clipboard/index.d.ts +++ b/types/react-copy-to-clipboard/index.d.ts @@ -18,7 +18,7 @@ declare namespace CopyToClipboard { interface Props { text: string; - onCopy?: (a: string) => void; + onCopy?(a: string): void; options?: Options; } } diff --git a/types/react-day-picker/react-day-picker-tests.tsx b/types/react-day-picker/react-day-picker-tests.tsx index 52da9e9735..1733b713dd 100644 --- a/types/react-day-picker/react-day-picker-tests.tsx +++ b/types/react-day-picker/react-day-picker-tests.tsx @@ -47,6 +47,6 @@ class CaptionElement extends React.Component { { localeUtils.formatMonthTitle(date, locale) }
); - }; + } } }/>; diff --git a/types/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts b/types/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts index 68703d062d..198909b7e9 100644 --- a/types/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts +++ b/types/react-dnd-html5-backend/react-dnd-html5-backend-tests.ts @@ -4,7 +4,7 @@ import React = require("react"); import ReactDnd = require("react-dnd"); -var r = React.DOM; +const r = React.DOM; import DragSource = ReactDnd.DragSource; import DropTarget = ReactDnd.DropTarget; @@ -15,8 +15,8 @@ import HTML5Backend, { getEmptyImage } from 'react-dnd-html5-backend'; // ---------------------------------------------------------------------- namespace Game { - var knightPosition = [0, 0]; - var observer: any = null; + let knightPosition = [0, 0]; + let observer: any = null; function emitChange() { observer(knightPosition); @@ -47,7 +47,7 @@ namespace Game { } } -var ItemTypes = { +const ItemTypes = { KNIGHT: "knight" }; @@ -61,7 +61,7 @@ namespace Knight { isDragging: boolean; } - var knightSource: ReactDnd.DragSourceSpec = { + const knightSource: ReactDnd.DragSourceSpec = { beginDrag: (props) => { return {}; } @@ -81,7 +81,7 @@ namespace Knight { static create = React.createFactory(Knight); componentDidMount() { - var img = getEmptyImage(); + const img = getEmptyImage(); img.onload = () => this.props.connectDragPreview(img); } @@ -99,8 +99,8 @@ namespace Knight { } } - export var DndKnight = DragSource(ItemTypes.KNIGHT, knightSource, knightCollect)(Knight); - export var create = React.createFactory(DndKnight); + export const DndKnight = DragSource(ItemTypes.KNIGHT, knightSource, knightCollect)(Knight); + export const create = React.createFactory(DndKnight); } // Square Component @@ -113,7 +113,7 @@ namespace Square { export class Square extends React.Component { render() { - var fill = this.props.black ? 'black' : 'white'; + const fill = this.props.black ? 'black' : 'white'; return r.div({ style: { backgroundColor: fill @@ -122,7 +122,7 @@ namespace Square { } } - export var create = React.createFactory(Square); + export const create = React.createFactory(Square); } // BoardSquare Component @@ -137,7 +137,7 @@ namespace BoardSquare { canDrop?: boolean; } - var boardSquareTarget: ReactDnd.DropTargetSpec = { + const boardSquareTarget: ReactDnd.DropTargetSpec = { canDrop: (props) => Game.canMoveKnight(props.x, props.y), drop: (props) => Game.moveKnight(props.x, props.y) }; @@ -169,9 +169,9 @@ namespace BoardSquare { } render() { - var black = (this.props.x + this.props.y) % 2 === 1; - var isOver = this.props.isOver; - var canDrop = this.props.canDrop; + const black = (this.props.x + this.props.y) % 2 === 1; + const isOver = this.props.isOver; + const canDrop = this.props.canDrop; return this.props.connectDropTarget( r.div({ @@ -191,8 +191,8 @@ namespace BoardSquare { } } - export var DndBoardSquare = DropTarget(ItemTypes.KNIGHT, boardSquareTarget, boardSquareCollect)(BoardSquare); - export var create = React.createFactory(DndBoardSquare); + export const DndBoardSquare = DropTarget(ItemTypes.KNIGHT, boardSquareTarget, boardSquareCollect)(BoardSquare); + export const create = React.createFactory(DndBoardSquare); } // Custom Drag Layer Component @@ -216,9 +216,9 @@ namespace CustomDragLayer { } } - export var dragLayer = DragLayer(dragLayerCollect)(CustomDragLayer); + export const dragLayer = DragLayer(dragLayerCollect)(CustomDragLayer); - export var create = React.createFactory(dragLayer); + export const create = React.createFactory(dragLayer); } // Board Component @@ -231,16 +231,16 @@ namespace Board { export class Board extends React.Component { private _renderPiece = (x: number, y: number) => { - var knightX = this.props.knightPosition[0]; - var knightY = this.props.knightPosition[1]; + const knightX = this.props.knightPosition[0]; + const knightY = this.props.knightPosition[1]; return x === knightX && y === knightY ? Knight.create() : null; } private _renderSquare = (i: number) => { - var x = i % 8; - var y = Math.floor(i / 8); + const x = i % 8; + const y = Math.floor(i / 8); return r.div({ key: i, @@ -252,7 +252,7 @@ namespace Board { } render() { - var squares: Array> = []; + const squares: Array> = []; for (let i = 0; i < 64; i++) { squares.push(this._renderSquare(i)); } @@ -274,7 +274,7 @@ namespace Board { } } - export var createWithHTMLBackend = React.createFactory(DragDropContext(HTML5Backend)(Board)); + export const createWithHTMLBackend = React.createFactory(DragDropContext(HTML5Backend)(Board)); } // Render the Board Component diff --git a/types/react-event-listener/index.d.ts b/types/react-event-listener/index.d.ts index c6d05b313b..906e3711e0 100644 --- a/types/react-event-listener/index.d.ts +++ b/types/react-event-listener/index.d.ts @@ -21,188 +21,188 @@ export function withOptions(handler: (ev: T) => any, options: EventOptions): export interface EventListenerProps { // Global events - onPointerCancel?: (ev: PointerEvent) => any; - onPointerCancelCapture?: (ev: PointerEvent) => any; - onPointerDown?: (ev: PointerEvent) => any; - onPointerDownCapture?: (ev: PointerEvent) => any; - onPointerEnter?: (ev: PointerEvent) => any; - onPointerEnterCapture?: (ev: PointerEvent) => any; - onPointerLeave?: (ev: PointerEvent) => any; - onPointerLeaveCapture?: (ev: PointerEvent) => any; - onPointerMove?: (ev: PointerEvent) => any; - onPointerMoveCapture?: (ev: PointerEvent) => any; - onPointerOut?: (ev: PointerEvent) => any; - onPointerOutCapture?: (ev: PointerEvent) => any; - onPointerOver?: (ev: PointerEvent) => any; - onPointerOverCapture?: (ev: PointerEvent) => any; - onPointerUp?: (ev: PointerEvent) => any; - onPointerUpCapture?: (ev: PointerEvent) => any; - onWheel?: (ev: WheelEvent) => any; - onWheelCapture?: (ev: WheelEvent) => any; - onAbort?: (ev: Event) => any; - onAbortCapture?: (ev: Event) => any; - onAfterPrint?: (ev: Event) => any; - onAfterPrintCapture?: (ev: Event) => any; - onBeforePrint?: (ev: Event) => any; - onBeforePrintCapture?: (ev: Event) => any; - onBeforeUnload?: (ev: BeforeUnloadEvent) => any; - onBeforeUnloadCapture?: (ev: BeforeUnloadEvent) => any; - onBlur?: (ev: FocusEvent) => any; - onBlurCapture?: (ev: FocusEvent) => any; - onCanPlay?: (ev: Event) => any; - onCanPlayCapture?: (ev: Event) => any; - onCanPlayThrough?: (ev: Event) => any; - onCanPlayThroughCapture?: (ev: Event) => any; - onChange?: (ev: Event) => any; - onChangeCapture?: (ev: Event) => any; - onClick?: (ev: MouseEvent) => any; - onClickCapture?: (ev: MouseEvent) => any; - onCompassNeedsCalibration?: (ev: Event) => any; - onCompassNeedsCalibrationCapture?: (ev: Event) => any; - onContextMenu?: (ev: PointerEvent) => any; - onContextMenuCapture?: (ev: PointerEvent) => any; - onDblClick?: (ev: MouseEvent) => any; - onDblClickCapture?: (ev: MouseEvent) => any; - onDeviceMotion?: (ev: DeviceMotionEvent) => any; - onDeviceMotionCapture?: (ev: DeviceMotionEvent) => any; - onDeviceOrientation?: (ev: DeviceOrientationEvent) => any; - onDeviceOrientationCapture?: (ev: DeviceOrientationEvent) => any; - onDrag?: (ev: DragEvent) => any; - onDragCapture?: (ev: DragEvent) => any; - onDragEnd?: (ev: DragEvent) => any; - onDragEndCapture?: (ev: DragEvent) => any; - onDragEnter?: (ev: DragEvent) => any; - onDragEnterCapture?: (ev: DragEvent) => any; - onDragLeave?: (ev: DragEvent) => any; - onDragLeaveCapture?: (ev: DragEvent) => any; - onDragOver?: (ev: DragEvent) => any; - onDragOverCapture?: (ev: DragEvent) => any; - onDragStart?: (ev: DragEvent) => any; - onDragStartCapture?: (ev: DragEvent) => any; - onDrop?: (ev: DragEvent) => any; - onDropCapture?: (ev: DragEvent) => any; - onDurationChange?: (ev: Event) => any; - onDurationChangeCapture?: (ev: Event) => any; - onEmptied?: (ev: Event) => any; - onEmptiedCapture?: (ev: Event) => any; - onEnded?: (ev: Event) => any; - onEndedCapture?: (ev: Event) => any; + onPointerCancel?(ev: PointerEvent): any; + onPointerCancelCapture?(ev: PointerEvent): any; + onPointerDown?(ev: PointerEvent): any; + onPointerDownCapture?(ev: PointerEvent): any; + onPointerEnter?(ev: PointerEvent): any; + onPointerEnterCapture?(ev: PointerEvent): any; + onPointerLeave?(ev: PointerEvent): any; + onPointerLeaveCapture?(ev: PointerEvent): any; + onPointerMove?(ev: PointerEvent): any; + onPointerMoveCapture?(ev: PointerEvent): any; + onPointerOut?(ev: PointerEvent): any; + onPointerOutCapture?(ev: PointerEvent): any; + onPointerOver?(ev: PointerEvent): any; + onPointerOverCapture?(ev: PointerEvent): any; + onPointerUp?(ev: PointerEvent): any; + onPointerUpCapture?(ev: PointerEvent): any; + onWheel?(ev: WheelEvent): any; + onWheelCapture?(ev: WheelEvent): any; + onAbort?(ev: Event): any; + onAbortCapture?(ev: Event): any; + onAfterPrint?(ev: Event): any; + onAfterPrintCapture?(ev: Event): any; + onBeforePrint?(ev: Event): any; + onBeforePrintCapture?(ev: Event): any; + onBeforeUnload?(ev: BeforeUnloadEvent): any; + onBeforeUnloadCapture?(ev: BeforeUnloadEvent): any; + onBlur?(ev: FocusEvent): any; + onBlurCapture?(ev: FocusEvent): any; + onCanPlay?(ev: Event): any; + onCanPlayCapture?(ev: Event): any; + onCanPlayThrough?(ev: Event): any; + onCanPlayThroughCapture?(ev: Event): any; + onChange?(ev: Event): any; + onChangeCapture?(ev: Event): any; + onClick?(ev: MouseEvent): any; + onClickCapture?(ev: MouseEvent): any; + onCompassNeedsCalibration?(ev: Event): any; + onCompassNeedsCalibrationCapture?(ev: Event): any; + onContextMenu?(ev: PointerEvent): any; + onContextMenuCapture?(ev: PointerEvent): any; + onDblClick?(ev: MouseEvent): any; + onDblClickCapture?(ev: MouseEvent): any; + onDeviceMotion?(ev: DeviceMotionEvent): any; + onDeviceMotionCapture?(ev: DeviceMotionEvent): any; + onDeviceOrientation?(ev: DeviceOrientationEvent): any; + onDeviceOrientationCapture?(ev: DeviceOrientationEvent): any; + onDrag?(ev: DragEvent): any; + onDragCapture?(ev: DragEvent): any; + onDragEnd?(ev: DragEvent): any; + onDragEndCapture?(ev: DragEvent): any; + onDragEnter?(ev: DragEvent): any; + onDragEnterCapture?(ev: DragEvent): any; + onDragLeave?(ev: DragEvent): any; + onDragLeaveCapture?(ev: DragEvent): any; + onDragOver?(ev: DragEvent): any; + onDragOverCapture?(ev: DragEvent): any; + onDragStart?(ev: DragEvent): any; + onDragStartCapture?(ev: DragEvent): any; + onDrop?(ev: DragEvent): any; + onDropCapture?(ev: DragEvent): any; + onDurationChange?(ev: Event): any; + onDurationChangeCapture?(ev: Event): any; + onEmptied?(ev: Event): any; + onEmptiedCapture?(ev: Event): any; + onEnded?(ev: Event): any; + onEndedCapture?(ev: Event): any; onError?: ErrorEventHandler; onErrorCapture?: ErrorEventHandler; - onFocus?: (ev: FocusEvent) => any; - onFocusCapture?: (ev: FocusEvent) => any; - onHashChange?: (ev: HashChangeEvent) => any; - onHashChangeCapture?: (ev: HashChangeEvent) => any; - onInput?: (ev: Event) => any; - onInputCapture?: (ev: Event) => any; - onKeyDown?: (ev: KeyboardEvent) => any; - onKeyDownCapture?: (ev: KeyboardEvent) => any; - onKeyPress?: (ev: KeyboardEvent) => any; - onKeyPressCapture?: (ev: KeyboardEvent) => any; - onKeyUp?: (ev: KeyboardEvent) => any; - onKeyUpCapture?: (ev: KeyboardEvent) => any; - onLoad?: (ev: Event) => any; - onLoadCapture?: (ev: Event) => any; - onLoadedData?: (ev: Event) => any; - onLoadedDataCapture?: (ev: Event) => any; - onLoadedMetadata?: (ev: Event) => any; - onLoadedMetadataCapture?: (ev: Event) => any; - onLoadStart?: (ev: Event) => any; - onLoadStartCapture?: (ev: Event) => any; - onMessage?: (ev: MessageEvent) => any; - onMessageCapture?: (ev: MessageEvent) => any; - onMouseDown?: (ev: MouseEvent) => any; - onMouseDownCapture?: (ev: MouseEvent) => any; - onMouseEnter?: (ev: MouseEvent) => any; - onMouseEnterCapture?: (ev: MouseEvent) => any; - onMouseLeave?: (ev: MouseEvent) => any; - onMouseLeaveCapture?: (ev: MouseEvent) => any; - onMouseMove?: (ev: MouseEvent) => any; - onMouseMoveCapture?: (ev: MouseEvent) => any; - onMouseOut?: (ev: MouseEvent) => any; - onMouseOutCapture?: (ev: MouseEvent) => any; - onMouseOver?: (ev: MouseEvent) => any; - onMouseOverCapture?: (ev: MouseEvent) => any; - onMouseUp?: (ev: MouseEvent) => any; - onMouseUpCapture?: (ev: MouseEvent) => any; - onMouseWheel?: (ev: MouseWheelEvent) => any; - onMouseWheelCapture?: (ev: MouseWheelEvent) => any; - onMsGestureChange?: (ev: MSGestureEvent) => any; - onMsGestureChangeCapture?: (ev: MSGestureEvent) => any; - onMsGestureDoubleTap?: (ev: MSGestureEvent) => any; - onMsGestureDoubleTapCapture?: (ev: MSGestureEvent) => any; - onMsGestureEnd?: (ev: MSGestureEvent) => any; - onMsGestureEndCapture?: (ev: MSGestureEvent) => any; - onMsGestureHold?: (ev: MSGestureEvent) => any; - onMsGestureHoldCapture?: (ev: MSGestureEvent) => any; - onMsGestureStart?: (ev: MSGestureEvent) => any; - onMsGestureStartCapture?: (ev: MSGestureEvent) => any; - onMsGestureTap?: (ev: MSGestureEvent) => any; - onMsGestureTapCapture?: (ev: MSGestureEvent) => any; - onMsInertiaStart?: (ev: MSGestureEvent) => any; - onMsInertiaStartCapture?: (ev: MSGestureEvent) => any; - onMsPointerCancel?: (ev: MSPointerEvent) => any; - onMsPointerCancelCapture?: (ev: MSPointerEvent) => any; - onMsPointerDown?: (ev: MSPointerEvent) => any; - onMsPointerDownCapture?: (ev: MSPointerEvent) => any; - onMsPointerEnter?: (ev: MSPointerEvent) => any; - onMsPointerEnterCapture?: (ev: MSPointerEvent) => any; - onMsPointerLeave?: (ev: MSPointerEvent) => any; - onMsPointerLeaveCapture?: (ev: MSPointerEvent) => any; - onMsPointerMove?: (ev: MSPointerEvent) => any; - onMsPointerMoveCapture?: (ev: MSPointerEvent) => any; - onMsPointerOut?: (ev: MSPointerEvent) => any; - onMsPointerOutCapture?: (ev: MSPointerEvent) => any; - onMsPointerOver?: (ev: MSPointerEvent) => any; - onMsPointerOverCapture?: (ev: MSPointerEvent) => any; - oNmsPointerUp?: (ev: MSPointerEvent) => any; - oNmsPointerUpCapture?: (ev: MSPointerEvent) => any; - onOffline?: (ev: Event) => any; - onOfflineCapture?: (ev: Event) => any; - onOnline?: (ev: Event) => any; - onOnlineCapture?: (ev: Event) => any; - onOrientationChange?: (ev: Event) => any; - onOrientationChangeCapture?: (ev: Event) => any; - onPageHide?: (ev: PageTransitionEvent) => any; - onPageHideCapture?: (ev: PageTransitionEvent) => any; - onPageShow?: (ev: PageTransitionEvent) => any; - onPageShowCapture?: (ev: PageTransitionEvent) => any; - onPause?: (ev: Event) => any; - onPauseCapture?: (ev: Event) => any; - onPlay?: (ev: Event) => any; - onPlayCapture?: (ev: Event) => any; - onPlaying?: (ev: Event) => any; - onPlayingCapture?: (ev: Event) => any; - onPopState?: (ev: PopStateEvent) => any; - onPopStateCapture?: (ev: PopStateEvent) => any; - onProgress?: (ev: ProgressEvent) => any; - onProgressCapture?: (ev: ProgressEvent) => any; - onRateChange?: (ev: Event) => any; - onRateChangeCapture?: (ev: Event) => any; - onReadyStateChange?: (ev: ProgressEvent) => any; - onReadyStateChangeCapture?: (ev: ProgressEvent) => any; - onReset?: (ev: Event) => any; - onResetCapture?: (ev: Event) => any; - onResize?: (ev: UIEvent) => any; - onResizeCapture?: (ev: UIEvent) => any; - onScroll?: (ev: UIEvent) => any; - onScrollCapture?: (ev: UIEvent) => any; - onSeeked?: (ev: Event) => any; - onSeekedCapture?: (ev: Event) => any; - onSeeking?: (ev: Event) => any; - onSeekingCapture?: (ev: Event) => any; - onSelect?: (ev: UIEvent) => any; - onSelectCapture?: (ev: UIEvent) => any; - onStalled?: (ev: Event) => any; - onStalledCapture?: (ev: Event) => any; - onStorage?: (ev: StorageEvent) => any; - onStorageCapture?: (ev: StorageEvent) => any; - onSubmit?: (ev: Event) => any; - onSubmitCapture?: (ev: Event) => any; - onSuspend?: (ev: Event) => any; - onSuspendCapture?: (ev: Event) => any; - onTimeUpdate?: (ev: Event) => any; - onTimeUpdateCapture?: (ev: Event) => any; + onFocus?(ev: FocusEvent): any; + onFocusCapture?(ev: FocusEvent): any; + onHashChange?(ev: HashChangeEvent): any; + onHashChangeCapture?(ev: HashChangeEvent): any; + onInput?(ev: Event): any; + onInputCapture?(ev: Event): any; + onKeyDown?(ev: KeyboardEvent): any; + onKeyDownCapture?(ev: KeyboardEvent): any; + onKeyPress?(ev: KeyboardEvent): any; + onKeyPressCapture?(ev: KeyboardEvent): any; + onKeyUp?(ev: KeyboardEvent): any; + onKeyUpCapture?(ev: KeyboardEvent): any; + onLoad?(ev: Event): any; + onLoadCapture?(ev: Event): any; + onLoadedData?(ev: Event): any; + onLoadedDataCapture?(ev: Event): any; + onLoadedMetadata?(ev: Event): any; + onLoadedMetadataCapture?(ev: Event): any; + onLoadStart?(ev: Event): any; + onLoadStartCapture?(ev: Event): any; + onMessage?(ev: MessageEvent): any; + onMessageCapture?(ev: MessageEvent): any; + onMouseDown?(ev: MouseEvent): any; + onMouseDownCapture?(ev: MouseEvent): any; + onMouseEnter?(ev: MouseEvent): any; + onMouseEnterCapture?(ev: MouseEvent): any; + onMouseLeave?(ev: MouseEvent): any; + onMouseLeaveCapture?(ev: MouseEvent): any; + onMouseMove?(ev: MouseEvent): any; + onMouseMoveCapture?(ev: MouseEvent): any; + onMouseOut?(ev: MouseEvent): any; + onMouseOutCapture?(ev: MouseEvent): any; + onMouseOver?(ev: MouseEvent): any; + onMouseOverCapture?(ev: MouseEvent): any; + onMouseUp?(ev: MouseEvent): any; + onMouseUpCapture?(ev: MouseEvent): any; + onMouseWheel?(ev: MouseWheelEvent): any; + onMouseWheelCapture?(ev: MouseWheelEvent): any; + onMsGestureChange?(ev: MSGestureEvent): any; + onMsGestureChangeCapture?(ev: MSGestureEvent): any; + onMsGestureDoubleTap?(ev: MSGestureEvent): any; + onMsGestureDoubleTapCapture?(ev: MSGestureEvent): any; + onMsGestureEnd?(ev: MSGestureEvent): any; + onMsGestureEndCapture?(ev: MSGestureEvent): any; + onMsGestureHold?(ev: MSGestureEvent): any; + onMsGestureHoldCapture?(ev: MSGestureEvent): any; + onMsGestureStart?(ev: MSGestureEvent): any; + onMsGestureStartCapture?(ev: MSGestureEvent): any; + onMsGestureTap?(ev: MSGestureEvent): any; + onMsGestureTapCapture?(ev: MSGestureEvent): any; + onMsInertiaStart?(ev: MSGestureEvent): any; + onMsInertiaStartCapture?(ev: MSGestureEvent): any; + onMsPointerCancel?(ev: MSPointerEvent): any; + onMsPointerCancelCapture?(ev: MSPointerEvent): any; + onMsPointerDown?(ev: MSPointerEvent): any; + onMsPointerDownCapture?(ev: MSPointerEvent): any; + onMsPointerEnter?(ev: MSPointerEvent): any; + onMsPointerEnterCapture?(ev: MSPointerEvent): any; + onMsPointerLeave?(ev: MSPointerEvent): any; + onMsPointerLeaveCapture?(ev: MSPointerEvent): any; + onMsPointerMove?(ev: MSPointerEvent): any; + onMsPointerMoveCapture?(ev: MSPointerEvent): any; + onMsPointerOut?(ev: MSPointerEvent): any; + onMsPointerOutCapture?(ev: MSPointerEvent): any; + onMsPointerOver?(ev: MSPointerEvent): any; + onMsPointerOverCapture?(ev: MSPointerEvent): any; + oNmsPointerUp?(ev: MSPointerEvent): any; + oNmsPointerUpCapture?(ev: MSPointerEvent): any; + onOffline?(ev: Event): any; + onOfflineCapture?(ev: Event): any; + onOnline?(ev: Event): any; + onOnlineCapture?(ev: Event): any; + onOrientationChange?(ev: Event): any; + onOrientationChangeCapture?(ev: Event): any; + onPageHide?(ev: PageTransitionEvent): any; + onPageHideCapture?(ev: PageTransitionEvent): any; + onPageShow?(ev: PageTransitionEvent): any; + onPageShowCapture?(ev: PageTransitionEvent): any; + onPause?(ev: Event): any; + onPauseCapture?(ev: Event): any; + onPlay?(ev: Event): any; + onPlayCapture?(ev: Event): any; + onPlaying?(ev: Event): any; + onPlayingCapture?(ev: Event): any; + onPopState?(ev: PopStateEvent): any; + onPopStateCapture?(ev: PopStateEvent): any; + onProgress?(ev: ProgressEvent): any; + onProgressCapture?(ev: ProgressEvent): any; + onRateChange?(ev: Event): any; + onRateChangeCapture?(ev: Event): any; + onReadyStateChange?(ev: ProgressEvent): any; + onReadyStateChangeCapture?(ev: ProgressEvent): any; + onReset?(ev: Event): any; + onResetCapture?(ev: Event): any; + onResize?(ev: UIEvent): any; + onResizeCapture?(ev: UIEvent): any; + onScroll?(ev: UIEvent): any; + onScrollCapture?(ev: UIEvent): any; + onSeeked?(ev: Event): any; + onSeekedCapture?(ev: Event): any; + onSeeking?(ev: Event): any; + onSeekingCapture?(ev: Event): any; + onSelect?(ev: UIEvent): any; + onSelectCapture?(ev: UIEvent): any; + onStalled?(ev: Event): any; + onStalledCapture?(ev: Event): any; + onStorage?(ev: StorageEvent): any; + onStorageCapture?(ev: StorageEvent): any; + onSubmit?(ev: Event): any; + onSubmitCapture?(ev: Event): any; + onSuspend?(ev: Event): any; + onSuspendCapture?(ev: Event): any; + onTimeUpdate?(ev: Event): any; + onTimeUpdateCapture?(ev: Event): any; onTouchCancel?: any; onTouchCancelCapture?: any; onTouchEnd?: any; @@ -211,12 +211,12 @@ export interface EventListenerProps { onTouchMoveCapture?: any; onTouchStart?: any; onTouchStartCapture?: any; - onUnload?: (ev: Event) => any; - onUnloadCapture?: (ev: Event) => any; - onVolumeChange?: (ev: Event) => any; - onVolumeChangeCapture?: (ev: Event) => any; - onWaiting?: (ev: Event) => any; - onWaitingCapture?: (ev: Event) => any; + onUnload?(ev: Event): any; + onUnloadCapture?(ev: Event): any; + onVolumeChange?(ev: Event): any; + onVolumeChangeCapture?(ev: Event): any; + onWaiting?(ev: Event): any; + onWaitingCapture?(ev: Event): any; /** * Target (window or document) diff --git a/types/react-facebook-login/index.d.ts b/types/react-facebook-login/index.d.ts index 577846e4a5..9f83d7ae8b 100644 --- a/types/react-facebook-login/index.d.ts +++ b/types/react-facebook-login/index.d.ts @@ -9,7 +9,7 @@ import * as React from "react"; declare namespace ReactFacebookLogin { interface ReactFacebookLoginProps { appId: string; - callback: (userInfo: ReactFacebookLoginInfo) => void; + callback(userInfo: ReactFacebookLoginInfo): void; autoLoad?: boolean; buttonStyle?: React.CSSProperties; @@ -21,7 +21,7 @@ declare namespace ReactFacebookLogin { icon?: string | React.ReactNode; isDisabled?: boolean; language?: string; - onClick?: () => void; + onClick?(): void; reAuthenticate?: boolean; redirectUri?: string; scope?: string; diff --git a/types/react-gravatar/index.d.ts b/types/react-gravatar/index.d.ts index 3e33584a4b..9307c6fb93 100644 --- a/types/react-gravatar/index.d.ts +++ b/types/react-gravatar/index.d.ts @@ -22,10 +22,10 @@ declare class Gravatar extends React.Component { } declare namespace Gravatar { - export type DefaultImage = "404" | "mm" | "identicon" | "monsterid" | "wavatar" | "retro" | "blank"; - export type Rating = "g" | "pg" | "r" | "x"; + type DefaultImage = "404" | "mm" | "identicon" | "monsterid" | "wavatar" | "retro" | "blank"; + type Rating = "g" | "pg" | "r" | "x"; - export interface Props { + interface Props { /** * The email address used to look up the Gravatar image. * If you wish to avoid sending an email address to the client, you can compute the md5 hash on the server and diff --git a/types/react-gravatar/react-gravatar-tests.tsx b/types/react-gravatar/react-gravatar-tests.tsx index e3b36b7259..1dee72f2c9 100644 --- a/types/react-gravatar/react-gravatar-tests.tsx +++ b/types/react-gravatar/react-gravatar-tests.tsx @@ -37,4 +37,4 @@ class GravatarMinimalTest extends React.Component { render() { return ; } -} \ No newline at end of file +} diff --git a/types/react-highlight-words/index.d.ts b/types/react-highlight-words/index.d.ts index aae2eff04e..220c245638 100644 --- a/types/react-highlight-words/index.d.ts +++ b/types/react-highlight-words/index.d.ts @@ -22,7 +22,7 @@ interface HighlighterProps { /** Type of tag to wrap around highlighted matches; defaults to mark */ highlightTag?: string; /** Process each search word and text to highlight before comparing (eg remove accents); signature (text: string): string */ - sanitize?: (text: string) => string; + sanitize?(text: string): string; /** Array of search words */ searchWords: string[]; /** Text to highlight matches in */ diff --git a/types/react-highlighter/react-highlighter-tests.tsx b/types/react-highlighter/react-highlighter-tests.tsx index 9065bd1fab..79760228dd 100644 --- a/types/react-highlighter/react-highlighter-tests.tsx +++ b/types/react-highlighter/react-highlighter-tests.tsx @@ -10,4 +10,4 @@ export class ReactHolderTest extends React.Component {
); } -} \ No newline at end of file +} diff --git a/types/react-icon-base/index.d.ts b/types/react-icon-base/index.d.ts index c0246569f6..600d33dff7 100644 --- a/types/react-icon-base/index.d.ts +++ b/types/react-icon-base/index.d.ts @@ -12,6 +12,4 @@ export interface IconBaseProps { style?: React.CSSProperties; } -export default class IconBase extends React.Component { - -} \ No newline at end of file +export default class IconBase extends React.Component {} diff --git a/types/react-icon-base/react-icon-base-tests.tsx b/types/react-icon-base/react-icon-base-tests.tsx index 68388f69d6..16ebafd133 100644 --- a/types/react-icon-base/react-icon-base-tests.tsx +++ b/types/react-icon-base/react-icon-base-tests.tsx @@ -1,4 +1,4 @@ import * as React from 'react'; import IconBase from 'react-icon-base'; -export default ; \ No newline at end of file +export default ; diff --git a/types/react-icons/react-icons-tests.tsx b/types/react-icons/react-icons-tests.tsx index 0c37cc9da2..1cb773fb4d 100644 --- a/types/react-icons/react-icons-tests.tsx +++ b/types/react-icons/react-icons-tests.tsx @@ -7,5 +7,3 @@ class Question extends React.Component { return

Lets go for a ?

; } } - - diff --git a/types/react-icons/tslint.json b/types/react-icons/tslint.json index 377cc837d4..05b3b474eb 100644 --- a/types/react-icons/tslint.json +++ b/types/react-icons/tslint.json @@ -1 +1,8 @@ -{ "extends": "../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "eofline": false, + "no-useless-files": false, + "no-var": false + } +} diff --git a/types/react-input-mask/index.d.ts b/types/react-input-mask/index.d.ts index fe6cc718e4..560dc8cc2b 100644 --- a/types/react-input-mask/index.d.ts +++ b/types/react-input-mask/index.d.ts @@ -7,7 +7,7 @@ import * as React from "react"; declare namespace reactInputMask { - export interface ReactInputMaskProps extends React.HTMLAttributes { + interface ReactInputMaskProps extends React.HTMLAttributes { /** * Mask string. Format characters are: * * `9`: `0-9` @@ -37,7 +37,7 @@ declare namespace reactInputMask { */ alwaysShowMask?: boolean; } - export class ReactInputMask extends React.Component { + class ReactInputMask extends React.Component { } } declare var ReactInputMask: typeof reactInputMask.ReactInputMask; diff --git a/types/react-joyride/index.d.ts b/types/react-joyride/index.d.ts index 1a6d674ed4..ebc086770b 100644 --- a/types/react-joyride/index.d.ts +++ b/types/react-joyride/index.d.ts @@ -130,7 +130,7 @@ interface Props { /** * It will be called when the tour's state changes. */ - callback?: (options: any) => void; + callback?(options: any): void; } export interface Step { diff --git a/types/react-json-pretty/index.d.ts b/types/react-json-pretty/index.d.ts index bf165faaf5..00f3f8b4ff 100644 --- a/types/react-json-pretty/index.d.ts +++ b/types/react-json-pretty/index.d.ts @@ -14,9 +14,7 @@ declare const JSONPretty: JSONPretty; type JSONPretty = ComponentClass; declare namespace JSONPretty { - - export interface JSONPrettyProps extends HTMLProps { + interface JSONPrettyProps extends HTMLProps { json: {} | string; } - } diff --git a/types/react-leaflet/index.d.ts b/types/react-leaflet/index.d.ts index 8caed9e4e1..9414e11f77 100644 --- a/types/react-leaflet/index.d.ts +++ b/types/react-leaflet/index.d.ts @@ -11,59 +11,59 @@ import * as React from 'react'; // which already declares things with some of the same names interface LeafletLayerEvents { - onbaselayerchange?: (event: Leaflet.LayersControlEvent) => void; - onoverlayadd?: (event: Leaflet.LayersControlEvent) => void; - onoverlayremove?: (event: Leaflet.LayersControlEvent) => void; - onlayeradd?: (event: Leaflet.LayerEvent) => void; - onlayerremove?: (event: Leaflet.LayerEvent) => void; + onbaselayerchange?(event: Leaflet.LayersControlEvent): void; + onoverlayadd?(event: Leaflet.LayersControlEvent): void; + onoverlayremove?(event: Leaflet.LayersControlEvent): void; + onlayeradd?(event: Leaflet.LayerEvent): void; + onlayerremove?(event: Leaflet.LayerEvent): void; } interface LeafletMapStateChangeEvents { - onzoomlevelschange?: (event: Leaflet.Event) => void; - onresize?: (event: Leaflet.ResizeEvent) => void; - onunload?: (event: Leaflet.Event) => void; - onviewreset?: (event: Leaflet.Event) => void; - onload?: (event: Leaflet.Event) => void; - onzoomstart?: (event: Leaflet.Event) => void; - onmovestart?: (event: Leaflet.Event) => void; - onzoom?: (event: Leaflet.Event) => void; - onmove?: (event: Leaflet.Event) => void; - onzoomend?: (event: Leaflet.Event) => void; - onmoveend?: (event: Leaflet.Event) => void; + onzoomlevelschange?(event: Leaflet.Event): void; + onresize?(event: Leaflet.ResizeEvent): void; + onunload?(event: Leaflet.Event): void; + onviewreset?(event: Leaflet.Event): void; + onload?(event: Leaflet.Event): void; + onzoomstart?(event: Leaflet.Event): void; + onmovestart?(event: Leaflet.Event): void; + onzoom?(event: Leaflet.Event): void; + onmove?(event: Leaflet.Event): void; + onzoomend?(event: Leaflet.Event): void; + onmoveend?(event: Leaflet.Event): void; } interface LeafletPopupEvents { - onpopupopen?: (event: Leaflet.PopupEvent) => void; - onpopupclose?: (event: Leaflet.PopupEvent) => void; - onautopanstart?: (event: Leaflet.Event) => void; + onpopupopen?(event: Leaflet.PopupEvent): void; + onpopupclose?(event: Leaflet.PopupEvent): void; + onautopanstart?(event: Leaflet.Event): void; } interface LeafletTooltipEvents { - ontooltipopen?: (event: Leaflet.TooltipEvent) => void; - ontooltipclose?: (event: Leaflet.TooltipEvent) => void; + ontooltipopen?(event: Leaflet.TooltipEvent): void; + ontooltipclose?(event: Leaflet.TooltipEvent): void; } interface LeafletLocationEvents { - onlocationerror?: (event: Leaflet.ErrorEvent) => void; - onlocationfound?: (event: Leaflet.LocationEvent) => void; + onlocationerror?(event: Leaflet.ErrorEvent): void; + onlocationfound?(event: Leaflet.LocationEvent): void; } interface LeafletInteractionEvents { - onclick?: (event: Leaflet.MouseEvent) => void; - ondblclick?: (event: Leaflet.MouseEvent) => void; - onmousedown?: (event: Leaflet.MouseEvent) => void; - onmouseup?: (event: Leaflet.MouseEvent) => void; - onmouseover?: (event: Leaflet.MouseEvent) => void; - onmouseout?: (event: Leaflet.MouseEvent) => void; - onmousemove?: (event: Leaflet.MouseEvent) => void; - oncontextmenu?: (event: Leaflet.MouseEvent) => void; - onkeypress?: (event: Leaflet.KeyboardEvent) => void; - onpreclick?: (event: Leaflet.MouseEvent) => void; + onclick?(event: Leaflet.MouseEvent): void; + ondblclick?(event: Leaflet.MouseEvent): void; + onmousedown?(event: Leaflet.MouseEvent): void; + onmouseup?(event: Leaflet.MouseEvent): void; + onmouseover?(event: Leaflet.MouseEvent): void; + onmouseout?(event: Leaflet.MouseEvent): void; + onmousemove?(event: Leaflet.MouseEvent): void; + oncontextmenu?(event: Leaflet.MouseEvent): void; + onkeypress?(event: Leaflet.KeyboardEvent): void; + onpreclick?(event: Leaflet.MouseEvent): void; } interface LeafletOtherEvents { - onzoomanim?: (event: Leaflet.ZoomAnimEvent) => void; + onzoomanim?(event: Leaflet.ZoomAnimEvent): void; } interface LeafletDraggingEvents { - ondragstart?: (event: Leaflet.Event) => void; - onmovestart?: (event: Leaflet.Event) => void; - ondrag?: (event: Leaflet.Event) => void; - ondragend?: (event: Leaflet.DragEndEvent) => void; - onmoveend?: (event: Leaflet.Event) => void; + ondragstart?(event: Leaflet.Event): void; + onmovestart?(event: Leaflet.Event): void; + ondrag?(event: Leaflet.Event): void; + ondragend?(event: Leaflet.DragEndEvent): void; + onmoveend?(event: Leaflet.Event): void; } interface MapProps extends React.HTMLProps, @@ -92,16 +92,16 @@ export const Pane: React.ComponentClass; // There is no Layer class, these are the base props for all layers on the map interface LayerProps extends LeafletInteractionEvents { - onadd?: (event: Leaflet.Event) => void; - onremove?: (event: Leaflet.Event) => void; + onadd?(event: Leaflet.Event): void; + onremove?(event: Leaflet.Event): void; // Popup events - onpopupopen?: (event: Leaflet.PopupEvent) => void; - onpopupclose?: (event: Leaflet.PopupEvent) => void; + onpopupopen?(event: Leaflet.PopupEvent): void; + onpopupclose?(event: Leaflet.PopupEvent): void; // Tooltip events - ontooltipopen?: (event: Leaflet.TooltipEvent) => void; - ontooltipclose?: (event: Leaflet.TooltipEvent) => void; + ontooltipopen?(event: Leaflet.TooltipEvent): void; + ontooltipclose?(event: Leaflet.TooltipEvent): void; } interface MarkerProps extends LayerProps, LeafletDraggingEvents { @@ -129,12 +129,12 @@ interface GridLayerProps extends LayerProps { opacity?: number; zIndex?: number; - onloading?: (event: Leaflet.Event) => void; - ontileunload?: (event: Leaflet.TileEvent) => void; - ontileloadstart?: (event: Leaflet.TileEvent) => void; - ontileerror?: (event: Leaflet.TileErrorEvent) => void; - ontileload?: (event: Leaflet.TileEvent) => void; - onload?: (event: Leaflet.Event) => void; + onloading?(event: Leaflet.Event): void; + ontileunload?(event: Leaflet.TileEvent): void; + ontileloadstart?(event: Leaflet.TileEvent): void; + ontileerror?(event: Leaflet.TileErrorEvent): void; + ontileload?(event: Leaflet.TileEvent): void; + onload?(event: Leaflet.Event): void; } export const GridLayer: React.ComponentClass; @@ -221,8 +221,8 @@ export namespace LayersControl { interface MapControlProps { position?: Leaflet.ControlPosition; } -declare class MapControl extends React.Component { - leafletElement?: L.Control +export class MapControl extends React.Component { + leafletElement?: L.Control; } interface ScaleControlProps { diff --git a/types/react-leaflet/react-leaflet-tests.tsx b/types/react-leaflet/react-leaflet-tests.tsx index 3c928dc322..7646109d69 100644 --- a/types/react-leaflet/react-leaflet-tests.tsx +++ b/types/react-leaflet/react-leaflet-tests.tsx @@ -603,8 +603,7 @@ const ZoomControlExample = () => ( ); - -//MapControl https://github.com/PaulLeCam/react-leaflet/issues/130 +// MapControl https://github.com/PaulLeCam/react-leaflet/issues/130 const mapControlCenter: [number, number] = [51.505, -0.09]; class CenterControl extends MapControl { // note we're extending MapControl from react-leaflet, not Component from react componentWillMount() { @@ -612,7 +611,7 @@ class CenterControl extends MapControl { // note we're extendi const jsx = ( // PUT YOUR JSX FOR THE COMPONENT HERE:
- // add your JSX + // add your JSX
); @@ -665,4 +664,4 @@ const LegendControlExample = () => ( -); \ No newline at end of file +); diff --git a/types/react-modal/index.d.ts b/types/react-modal/index.d.ts index d4a772366c..bb158bc6be 100644 --- a/types/react-modal/index.d.ts +++ b/types/react-modal/index.d.ts @@ -28,9 +28,9 @@ declare namespace ReactModal { /* Set this to properly hide your application from assistive screenreaders and other assistive technologies while the modal is open. */ appElement?: HTMLElement | {}; /* Function that will be run after the modal has opened. */ - onAfterOpen?: () => void; + onAfterOpen?(): void; /* Function that will be run when the modal is requested to be closed, prior to actually closing. */ - onRequestClose?: (event: (MouseEvent | KeyboardEvent)) => void; + onRequestClose?(event: (MouseEvent | KeyboardEvent)): void; /* Number indicating the milliseconds to wait before closing the modal. Defaults to zero (no timeout). */ closeTimeoutMS?: number; /* Boolean indicating if the appElement should be hidden. Defaults to true. */ @@ -48,7 +48,7 @@ declare namespace ReactModal { /* String indicating the role of the modal, allowing the 'dialog' role to be applied if desired. */ role?: string; /* Function that will be called to get the parent element that the modal will be attached to. */ - parentSelector?: () => HTMLElement; + parentSelector?(): HTMLElement; } } diff --git a/types/react-modal/react-modal-tests.tsx b/types/react-modal/react-modal-tests.tsx index d85796c065..51cdffba0a 100644 --- a/types/react-modal/react-modal-tests.tsx +++ b/types/react-modal/react-modal-tests.tsx @@ -42,4 +42,4 @@ class ExampleOfUsingReactModal extends React.Component<{}, {}> { ); } -}; +} diff --git a/types/react-onsenui/index.d.ts b/types/react-onsenui/index.d.ts index 3ce4a26686..5c25131be1 100644 --- a/types/react-onsenui/index.d.ts +++ b/types/react-onsenui/index.d.ts @@ -5,32 +5,32 @@ // TypeScript Version: 2.1 import { Component } from 'react'; -declare interface Modifiers_string { - default?: string, - material?: string +export interface Modifiers_string { + default?: string; + material?: string; } -declare interface Modifiers_number { - default?: number, - material?: number +export interface Modifiers_number { + default?: number; + material?: number; } -declare interface AnimationOptions { - duration?: number, - delay?: number, - timing?: string +export interface AnimationOptions { + duration?: number; + delay?: number; + timing?: string; } /*** splitter ***/ -declare class SplitterSide extends Component<{ +export class SplitterSide extends Component<{ side?: "left" | "right", collapse?: "portrait" | "landscape" | boolean, isOpen?: boolean, - onOpen?: (e?: Event) => void, - onPreOpen?: (e?: Event) => void, - onPreClose?: (e?: Event) => void, - onModeChange?: (e?: Event) => void, - onClose?: (e?: Event) => void, + onOpen?(e?: Event): void, + onPreOpen?(e?: Event): void, + onPreClose?(e?: Event): void, + onModeChange?(e?: Event): void, + onClose?(e?: Event): void, isSwipeable?: boolean, swipeTargetWidth?: number, width?: number, @@ -38,80 +38,77 @@ declare class SplitterSide extends Component<{ animationOptions?: AnimationOptions, openThreshold?: number, mode?: "collapse" | "split" -}, any>{ } +}, any> { } +export class SplitterContent extends Component<{}, any> { } -declare class SplitterContent extends Component<{}, any> { } - -declare class Splitter extends Component<{}, any> { } +export class Splitter extends Component<{}, any> { } /*** toolbar ***/ -declare class Toolbar extends Component<{}, any>{} +export class Toolbar extends Component<{}, any> {} - -declare class BottomToolbar extends Component<{ +export class BottomToolbar extends Component<{ modifier?: string -}, any>{} +}, any> {} - -declare class ToolbarButton extends Component<{ +export class ToolbarButton extends Component<{ modifier?: string, disabled?: boolean, - onClick?: (e?: Event) => void -}, any>{} + onClick?(e?: Event): void +}, any> {} /*** icon ***/ -declare class Icon extends Component<{ +export class Icon extends Component<{ modifier?: string, icon?: string | Modifiers_string, size?: number | Modifiers_number, rotate?: 90 | 180 | 270, fixedWidth?: boolean, spin?: boolean -}, any>{} +}, any> {} /*** page ***/ -declare class Page extends Component<{ +export class Page extends Component<{ contentStyle?: any, modifier?: string, - renderModal?: () => void, - renderToolbar?: () => void, - renderBottomToolbar?: () => void, - renderFixed?: () => void, - onInit?: () => void, - onShow?: () => void, - onHide?: () => void -}, any>{} + renderModal?(): void, + renderToolbar?(): void, + renderBottomToolbar?(): void, + renderFixed?(): void, + onInit?(): void, + onShow?(): void, + onHide?(): void +}, any> {} /*** Grid ***/ -declare class Col extends Component<{ +export class Col extends Component<{ verticalAlign?: "top" | "bottom" | "center", width?: string -}, any>{} +}, any> {} -declare class Row extends Component<{ +export class Row extends Component<{ verticalAlign?: "top" | "bottom" | "center", -}, any>{} +}, any> {} /*** Navigation ***/ -declare class BackButton extends Component<{ +export class BackButton extends Component<{ modifier?: string, - onClick?: (navigator: Navigator) => void -}, any>{} + onClick?(navigator: Navigator): void +}, any> {} -declare class Navigator extends Component<{ - renderPage: () => any, +export class Navigator extends Component<{ + renderPage(): any, initialRouteStack?: string[], initialRoute?: any, - onPrePush?: () => void, - onPostPush?: () => void, - onPrePop?: () => void, - onPostPop?: () => void, + onPrePush?(): void, + onPostPush?(): void, + onPrePop?(): void, + onPostPop?(): void, animation?: "slide" | "lift" | "fade" | "none" | string, animationOptions?: AnimationOptions -}, any>{ +}, any> { resetPage(route: any, options: any): void; resetPageStack(route: any, options: any): void; pushPage(route: any, options: any): void; @@ -119,7 +116,7 @@ declare class Navigator extends Component<{ } /*** Carousel ***/ -declare class Carousel extends Component<{ +export class Carousel extends Component<{ direction?: "horizontal" | "vertical", fullscreen?: boolean, overscrollable?: boolean, @@ -132,19 +129,19 @@ declare class Carousel extends Component<{ disabled?: boolean, index?: number, autoRefresh?: boolean, - onPostChange?: () => void, - onRefresh?: () => void, - onOverscroll?: () => void + onPostChange?(): void, + onRefresh?(): void, + onOverscroll?(): void animationOptions?: AnimationOptions -}, any>{} +}, any> {} -declare class CarouselItem extends Component<{ +export class CarouselItem extends Component<{ modifier: string -}, any>{} +}, any> {} /*** AlertDialog ***/ -declare class AlertDialog extends Component<{ - onCancel?: () => void, +export class AlertDialog extends Component<{ + onCancel?(): void, isOpen?: boolean, isCancelable?: boolean, isDisabled?: boolean, @@ -152,14 +149,14 @@ declare class AlertDialog extends Component<{ modifier?: string, maskColor?: string, animationOptions?: AnimationOptions, - onPreShow?: () => void, - onPostShow?: () => void, - onPreHide?: () => void, - onPostHide?: () => void, -}, any>{} + onPreShow?(): void, + onPostShow?(): void, + onPreHide?(): void, + onPostHide?(): void, +}, any> {} -declare class Dialog extends Component<{ - onCancel?: () => void, +export class Dialog extends Component<{ + onCancel?(): void, isOpen?: boolean, isCancelable?: boolean, isDisabled?: boolean, @@ -167,23 +164,23 @@ declare class Dialog extends Component<{ modifier?: string, maskColor?: string, animationOptions?: AnimationOptions, - onPreShow?: () => void, - onPostShow?: () => void, - onPreHide?: () => void, - onPostHide?: () => void, -}, any>{} + onPreShow?(): void, + onPostShow?(): void, + onPreHide?(): void, + onPostHide?(): void, +}, any> {} -declare class Modal extends Component<{ +export class Modal extends Component<{ animation?: "fade" | "none", animationOptions?: AnimationOptions - onShow?: () => void, - onHide?: () => void, + onShow?(): void, + onHide?(): void, isOpen?: boolean -}, any>{} +}, any> {} -declare class Popover extends Component<{ - getTarget?: () => Component | HTMLElement, - onCancel?: () => void, +export class Popover extends Component<{ + getTarget?(): Component | HTMLElement, + onCancel?(): void, isOpen?: boolean, isCancelable?: boolean, isDisabled?: boolean, @@ -191,52 +188,52 @@ declare class Popover extends Component<{ modifier?: string, maskColor?: string, animationOptions?: AnimationOptions, - onPreShow?: () => void, - onPostShow?: () => void, - onPreHide?: () => void, - onPostHide?: () => void, -}, any>{} + onPreShow?(): void, + onPostShow?(): void, + onPreHide?(): void, + onPostHide?(): void, +}, any> {} -declare class ProgressBar extends Component<{ +export class ProgressBar extends Component<{ modifier?: string, value?: number, secondaryValue?: boolean, intermediate?: boolean, }, any> {} -declare class ProgressCircular extends Component<{ +export class ProgressCircular extends Component<{ modifier?: string, value?: number, secondaryValue?: boolean, intermediate?: boolean, -}, any>{} +}, any> {} -declare class Ripple extends Component<{ +export class Ripple extends Component<{ color?: string, background?: string, disabled?: boolean, -}, any>{} +}, any> {} /*** Forms ***/ -declare class Fab extends Component<{ +export class Fab extends Component<{ modifier?: string, ripple?: boolean, position?: string, disabled?: boolean, - onClick?: () => void, -}, any>{} + onClick?(): void, +}, any> {} -declare class Button extends Component<{ +export class Button extends Component<{ modifier?: string, disabled?: boolean, ripple?: boolean, - onClick?: (e?: Event) => void -}, any>{} + onClick?(e?: Event): void +}, any> {} -declare class Input extends Component<{ +export class Input extends Component<{ modifier?: string, disabled?: boolean, - onChange?: (e: Event) => void, + onChange?(e: Event): void, value?: string, checked?: boolean, placeholder?: string, @@ -245,70 +242,67 @@ declare class Input extends Component<{ float?: boolean, }, any> {} -declare class Range extends Component<{ +export class Range extends Component<{ modifier?: string, - onChange?: (e: Event) => void, + onChange?(e: Event): void, value?: number, disabled?: boolean, -}, any>{} +}, any> {} -declare class Switch extends Component<{ - onChange?: (e: Event) => void, +export class Switch extends Component<{ + onChange?(e: Event): void, checked?: boolean, disabled?: boolean, inputId?: string -}, any>{} +}, any> {} /** -* Tabs -*/ + * Tabs + */ -declare class Tab extends Component<{}, any>{ } +export class Tab extends Component<{}, any> { } -declare class TabActive extends Component<{}, any>{ } +export class TabActive extends Component<{}, any> { } -declare class TabInactive extends Component<{}, any>{ } +export class TabInactive extends Component<{}, any> { } -declare class Tabbar extends Component<{ +export class Tabbar extends Component<{ index?: number, - renderTabs?: () => any, + renderTabs?(): any, position?: "bottom" | "top" | "auto", animation: "none" | "slide" | "fade", animationOptions?: AnimationOptions, - onPreChange?: () => void, - onPostChange?: () => void, - onReactive?: () => void, + onPreChange?(): void, + onPostChange?(): void, + onReactive?(): void, }, any> { } - /** -* Lists -*/ + * Lists + */ -declare class LazyList extends Component<{ +export class LazyList extends Component<{ modifier?: string, length?: number, - renderRow: (rowIndex: number) => any, - calculateItemHeight: (rowIndex: number) => any, -}, any>{ } + renderRow(rowIndex: number): any, + calculateItemHeight(rowIndex: number): any, +}, any> { } -declare class List extends Component<{ +export class List extends Component<{ modifier?: string, dataSource?: string[], - renderRow?: () => void, - renderHeader?: () => void, - renderFooter?: () => void, -}, any>{} + renderRow?(): void, + renderHeader?(): void, + renderFooter?(): void, +}, any> {} -declare class ListHeader extends Component<{ +export class ListHeader extends Component<{ modifier?: string, -}, any>{} +}, any> {} -declare class ListItem extends Component<{ +export class ListItem extends Component<{ modifier?: string, tappable?: boolean, tapBackgroundColor?: string, lockOnDrag?: boolean, -}, any>{} - - +}, any> {} diff --git a/types/react-onsenui/react-onsenui-tests.tsx b/types/react-onsenui/react-onsenui-tests.tsx index b72e8c3a37..fdc498fa17 100644 --- a/types/react-onsenui/react-onsenui-tests.tsx +++ b/types/react-onsenui/react-onsenui-tests.tsx @@ -6,11 +6,9 @@ class AppState { isOpen: boolean = false; } -interface AppProps { -} - -export class App extends React.Component{ +interface AppProps {} // tslint:disable-line no-empty-interface +export class App extends React.Component { constructor(props?: AppProps) { super(props); this.state = new AppState(); @@ -21,7 +19,6 @@ export class App extends React.Component{ } render() { - return ( { ); } - } - -ReactDOM.render(, document.getElementById('react-body')); \ No newline at end of file +ReactDOM.render(, document.getElementById('react-body')); diff --git a/types/react-overlays/index.d.ts b/types/react-overlays/index.d.ts index 10b67d9d51..db292d7f52 100644 --- a/types/react-overlays/index.d.ts +++ b/types/react-overlays/index.d.ts @@ -58,37 +58,36 @@ interface AffixProps { /** * Callback fired when the right before the `affixStyle` and `affixStyle` props are rendered */ - onAffix?: () => void; + onAffix?(): void; /** * Callback fired after the component `affixStyle` and `affixClassName` props have been rendered. */ - onAffixed?: () => void; + onAffixed?(): void; /** * Callback fired when the right before the `topStyle` and `topClassName` props are rendered */ - onAffixTop?: () => void; + onAffixTop?(): void; /** * Callback fired after the component `topStyle` and `topClassName` props have been rendered. */ - onAffixedTop?: () => void; + onAffixedTop?(): void; /** * Callback fired when the right before the `bottomStyle` and `bottomClassName` props are rendered */ - onAffixBottom?: () => void; + onAffixBottom?(): void; /** * Callback fired after the component `bottomStyle` and `bottomClassName` props have been rendered. */ - onAffixedBottom?: () => void; + onAffixedBottom?(): void; } export class Affix extends React.Component { } // interface AutoAffixProps extends AffixProps { - /** * The logical container node or component for determining offset from bottom * of viewport, or a function that returns it @@ -155,32 +154,31 @@ interface TransitionProps { /** * Callback fired before the "entering" classes are applied */ - onEnter?: (element: Element) => void; + onEnter?(element: Element): void; /** * Callback fired after the "entering" classes are applied */ - onEntering?: (element: Element) => void; + onEntering?(element: Element): void; /** * Callback fired after the "enter" classes are applied */ - onEntered?: (element: Element) => void; + onEntered?(element: Element): void; /** * Callback fired before the "exiting" classes are applied */ - onExit?: (element: Element) => void; + onExit?(element: Element): void; /** * Callback fired after the "exiting" classes are applied */ - onExiting?: (element: Element) => void; + onExiting?(element: Element): void; /** * Callback fired after the "exited" classes are applied */ - onExited?: (element: Element) => void; + onExited?(element: Element): void; } export class Transition extends React.Component { } - diff --git a/types/react-overlays/lib/RootCloseWrapper.d.ts b/types/react-overlays/lib/RootCloseWrapper.d.ts index 0642bdcc52..384df80f4a 100644 --- a/types/react-overlays/lib/RootCloseWrapper.d.ts +++ b/types/react-overlays/lib/RootCloseWrapper.d.ts @@ -2,7 +2,7 @@ import * as React from "react"; // interface RootCloseWrapperProps { - onRootClose?: () => void; + onRootClose?(): void; children?: React.ReactNode; /** diff --git a/types/react-overlays/react-overlays-tests.tsx b/types/react-overlays/react-overlays-tests.tsx index dd151e10e9..bbe526853f 100644 --- a/types/react-overlays/react-overlays-tests.tsx +++ b/types/react-overlays/react-overlays-tests.tsx @@ -17,7 +17,6 @@ function testTransition() { ); } - class TestAffix extends React.Component<{}, {}> { render(): JSX.Element { return ( diff --git a/types/react-paginate/index.d.ts b/types/react-paginate/index.d.ts index 18636a8f6f..b6b50170c2 100644 --- a/types/react-paginate/index.d.ts +++ b/types/react-paginate/index.d.ts @@ -45,7 +45,7 @@ interface ReactPaginateProps { /** * The method to call when a page is clicked. Exposes the current page object as an argument. */ - onPageChange?: (selectedItem: {selected: number}) => void; + onPageChange?(selectedItem: {selected: number}): void; /** * The initial page selected. @@ -110,7 +110,7 @@ interface ReactPaginateProps { /** * The method is called to generate the href attribute value on tag a of each page element. */ - hrefBuilder?: (pageIndex: number) => void; + hrefBuilder?(pageIndex: number): void; } declare const ReactPaginate: React.ComponentClass; diff --git a/types/react-paginate/react-paginate-tests.tsx b/types/react-paginate/react-paginate-tests.tsx index 5f8f8f1994..31efb805ce 100644 --- a/types/react-paginate/react-paginate-tests.tsx +++ b/types/react-paginate/react-paginate-tests.tsx @@ -2,7 +2,6 @@ import * as React from "react"; import ReactPaginate = require("react-paginate"); class Test extends React.Component<{}, {}> { - render() { return ( { - closePortal: () => {}; + closePortal(): {}; } interface ReactPortalProps { @@ -15,10 +15,10 @@ interface ReactPortalProps { openByClickOn?: React.ReactElement; closeOnEsc?: boolean; closeOnOutsideClick?: boolean; - onOpen?: (node: HTMLDivElement) => {}; - beforeClose?: (node: HTMLDivElement, resetPortalState: () => void) => {}; - onClose?: () => {}; - onUpdate?: () => {}; + onOpen?(node: HTMLDivElement): {}; + beforeClose?(node: HTMLDivElement, resetPortalState: () => void): {}; + onClose?(): {}; + onUpdate?(): {}; } declare const ReactPortal: React.ComponentClass; diff --git a/types/react-portal/react-portal-tests.tsx b/types/react-portal/react-portal-tests.tsx index b192e297c7..f3bd6d4b83 100644 --- a/types/react-portal/react-portal-tests.tsx +++ b/types/react-portal/react-portal-tests.tsx @@ -4,7 +4,6 @@ import * as ReactDOM from "react-dom"; import * as Portal from "react-portal"; export default class App extends React.Component<{}, {}> { - render() { const button1 = ; @@ -17,10 +16,9 @@ export default class App extends React.Component<{}, {}> { ); } - } -export class PseudoModal extends React.Component<{ closePortal?: () => {} }, {}> { +export class PseudoModal extends React.Component<{ closePortal?(): {} }, {}> { render() { return (
@@ -31,4 +29,4 @@ export class PseudoModal extends React.Component<{ closePortal?: () => {} }, {}> } } -ReactDOM.render(, document.getElementById('react-body')); \ No newline at end of file +ReactDOM.render(, document.getElementById('react-body')); diff --git a/types/react-recaptcha/index.d.ts b/types/react-recaptcha/index.d.ts index 39cca4037c..af6853efb3 100644 --- a/types/react-recaptcha/index.d.ts +++ b/types/react-recaptcha/index.d.ts @@ -10,16 +10,16 @@ export = Recaptcha; interface RecaptchaProps { className?: string; elementID?: string; - expiredCallback?: () => any; + expiredCallback?(): any; expiredCallbackName?: string; - onloadCallback?: () => any; + onloadCallback?(): any; onloadCallbackName?: string; render?: string; size?: string; tabindex?: string; theme?: "dark" | "light"; type?: string; - verifyCallback?: () => any; + verifyCallback?(): any; verifyCallbackName?: string; sitekey?: string; } diff --git a/types/react-recaptcha/react-recaptcha-tests.tsx b/types/react-recaptcha/react-recaptcha-tests.tsx index 624020cc62..d931e45ae3 100644 --- a/types/react-recaptcha/react-recaptcha-tests.tsx +++ b/types/react-recaptcha/react-recaptcha-tests.tsx @@ -7,4 +7,4 @@ ReactDOM.render( sitekey="xxxxxxxxxxxxxxxxxxxx" />, document.getElementById('example') -); \ No newline at end of file +); diff --git a/types/react-sidebar/index.d.ts b/types/react-sidebar/index.d.ts index a68749488c..1f3484762a 100644 --- a/types/react-sidebar/index.d.ts +++ b/types/react-sidebar/index.d.ts @@ -9,7 +9,7 @@ export interface SidebarProps { contentClassName?: string; docked?: boolean; dragToggleDistance?: number; - onSetOpen?: () => {}; + onSetOpen?(): {}; open?: boolean; overlayClassName?: string; pullRight?: boolean; diff --git a/types/react-smooth-scrollbar/index.d.ts b/types/react-smooth-scrollbar/index.d.ts index 6aea289136..54cc7d91b5 100644 --- a/types/react-smooth-scrollbar/index.d.ts +++ b/types/react-smooth-scrollbar/index.d.ts @@ -12,7 +12,7 @@ declare namespace Scrollbar { /** * Pipe to scrollbar.addListener() */ - onScroll?: (status: ScrollStatusObject, scrollbarInstance: SmoothScrollbar) => void; + onScroll?(status: ScrollStatusObject, scrollbarInstance: SmoothScrollbar): void; /** * Keep scrollbar tracks visible whether it's scrolling or not * @default false @@ -34,7 +34,6 @@ declare class Scrollbar extends React.Component { * Scrollbar instance */ readonly scrollbar: SmoothScrollbar; - } export as namespace Scrollbar; diff --git a/types/react-sticky/index.d.ts b/types/react-sticky/index.d.ts index 8c965da4ab..b83fa37ac4 100644 --- a/types/react-sticky/index.d.ts +++ b/types/react-sticky/index.d.ts @@ -16,7 +16,7 @@ export interface StickyProps { stickyStyle?: any; topOffset?: number; bottomOffset?: number; - onStickyStateChange?: (isSticky: boolean) => void; + onStickyStateChange?(isSticky: boolean): void; } export const Sticky: React.ComponentClass; diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index 9908394888..927e041378 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -16,7 +16,7 @@ interface ReactTestRendererJSON { $$typeof?: any; } interface TestRendererOptions { - createNodeMock: (element: ReactElement) => any; + createNodeMock(element: ReactElement): any; } // https://github.com/facebook/react/blob/master/src/renderers/testing/ReactTestMount.js#L155 export function create(nextElement: ReactElement, options?: TestRendererOptions): Renderer; diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index 198b410ed4..6dadd6d284 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -4,79 +4,79 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export { default as Alert } from './lib/Alert' -export { default as Badge } from './lib/Badge' -export { default as Breadcrumb } from './lib/Breadcrumb' -export { default as BreadcrumbItem } from './lib/BreadcrumbItem' -export { default as Button } from './lib/Button' -export { default as ButtonDropdown } from './lib/ButtonDropdown' -export { default as ButtonGroup } from './lib/ButtonGroup' -export { default as ButtonToolbar } from './lib/ButtonToolbar' -export { default as Card } from './lib/Card' -export { default as CardBlock } from './lib/CardBlock' -export { default as CardColumns } from './lib/CardColumns' -export { default as CardDeck } from './lib/CardDeck' -export { default as CardFooter } from './lib/CardFooter' -export { default as CardGroup } from './lib/CardGroup' -export { default as CardHeader } from './lib/CardHeader' -export { default as CardImg } from './lib/CardImg' -export { default as CardImgOverlay } from './lib/CardImgOverlay' -export { default as CardLink } from './lib/CardLink' -export { default as CardSubtitle } from './lib/CardSubtitle' -export { default as CardText } from './lib/CardText' -export { default as CardTitle } from './lib/CardTitle' -export { default as Col } from './lib/Col' -export { default as Collapse } from './lib/Collapse' -export { default as Container } from './lib/Container' -export { default as Dropdown } from './lib/Dropdown' -export { default as DropdownItem } from './lib/DropdownItem' -export { default as DropdownMenu } from './lib/DropdownMenu' -export { default as DropdownToggle } from './lib/DropdownToggle' -export { default as Fade } from './lib/Fade' -export { default as Form } from './lib/Form' -export { default as FormFeedback } from './lib/FormFeedback' -export { default as FormGroup } from './lib/FormGroup' -export { default as FormText } from './lib/FormText' -export { default as Input } from './lib/Input' -export { default as InputGroup } from './lib/InputGroup' -export { default as InputGroupAddon } from './lib/InputGroupAddon' -export { default as InputGroupButton } from './lib/InputGroupButton' -export { default as Jumbotron } from './lib/Jumbotron' -export { default as Label } from './lib/Label' -export { default as ListGroup } from './lib/ListGroup' -export { default as ListGroupItem } from './lib/ListGroupItem' -export { default as ListGroupItemHeading } from './lib/ListGroupItemHeading' -export { default as ListGroupItemText } from './lib/ListGroupItemText' -export { default as Media } from './lib/Media' -export { default as Modal } from './lib/Modal' -export { default as ModalBody } from './lib/ModalBody' -export { default as ModalFooter } from './lib/ModalFooter' -export { default as ModalHeader } from './lib/ModalHeader' -export { default as Nav } from './lib/Nav' -export { default as Navbar } from './lib/Navbar' -export { default as NavbarBrand } from './lib/NavbarBrand' -export { default as NavbarToggler } from './lib/NavbarToggler' -export { default as NavDropdown } from './lib/NavDropdown' -export { default as NavItem } from './lib/NavItem' -export { default as NavLink } from './lib/NavLink' -export { default as Pagination } from './lib/Pagination' -export { default as PaginationItem } from './lib/PaginationItem' -export { default as PaginationLink } from './lib/PaginationLink' -export { default as Popover } from './lib/Popover' -export { default as PopoverContent } from './lib/PopoverContent' -export { default as PopoverTitle } from './lib/PopoverTitle' -export { default as Progress } from './lib/Progress' -export { default as Row } from './lib/Row' -export { default as TabContent } from './lib/TabContent' -export { default as Table } from './lib/Table' -export { default as TabPane } from './lib/TabPane' -export { default as Tag } from './lib/Tag' -export { default as TetherContent } from './lib/TetherContent' -export { default as Tooltip } from './lib/Tooltip' +export { default as Alert } from './lib/Alert'; +export { default as Badge } from './lib/Badge'; +export { default as Breadcrumb } from './lib/Breadcrumb'; +export { default as BreadcrumbItem } from './lib/BreadcrumbItem'; +export { default as Button } from './lib/Button'; +export { default as ButtonDropdown } from './lib/ButtonDropdown'; +export { default as ButtonGroup } from './lib/ButtonGroup'; +export { default as ButtonToolbar } from './lib/ButtonToolbar'; +export { default as Card } from './lib/Card'; +export { default as CardBlock } from './lib/CardBlock'; +export { default as CardColumns } from './lib/CardColumns'; +export { default as CardDeck } from './lib/CardDeck'; +export { default as CardFooter } from './lib/CardFooter'; +export { default as CardGroup } from './lib/CardGroup'; +export { default as CardHeader } from './lib/CardHeader'; +export { default as CardImg } from './lib/CardImg'; +export { default as CardImgOverlay } from './lib/CardImgOverlay'; +export { default as CardLink } from './lib/CardLink'; +export { default as CardSubtitle } from './lib/CardSubtitle'; +export { default as CardText } from './lib/CardText'; +export { default as CardTitle } from './lib/CardTitle'; +export { default as Col } from './lib/Col'; +export { default as Collapse } from './lib/Collapse'; +export { default as Container } from './lib/Container'; +export { default as Dropdown } from './lib/Dropdown'; +export { default as DropdownItem } from './lib/DropdownItem'; +export { default as DropdownMenu } from './lib/DropdownMenu'; +export { default as DropdownToggle } from './lib/DropdownToggle'; +export { default as Fade } from './lib/Fade'; +export { default as Form } from './lib/Form'; +export { default as FormFeedback } from './lib/FormFeedback'; +export { default as FormGroup } from './lib/FormGroup'; +export { default as FormText } from './lib/FormText'; +export { default as Input } from './lib/Input'; +export { default as InputGroup } from './lib/InputGroup'; +export { default as InputGroupAddon } from './lib/InputGroupAddon'; +export { default as InputGroupButton } from './lib/InputGroupButton'; +export { default as Jumbotron } from './lib/Jumbotron'; +export { default as Label } from './lib/Label'; +export { default as ListGroup } from './lib/ListGroup'; +export { default as ListGroupItem } from './lib/ListGroupItem'; +export { default as ListGroupItemHeading } from './lib/ListGroupItemHeading'; +export { default as ListGroupItemText } from './lib/ListGroupItemText'; +export { default as Media } from './lib/Media'; +export { default as Modal } from './lib/Modal'; +export { default as ModalBody } from './lib/ModalBody'; +export { default as ModalFooter } from './lib/ModalFooter'; +export { default as ModalHeader } from './lib/ModalHeader'; +export { default as Nav } from './lib/Nav'; +export { default as Navbar } from './lib/Navbar'; +export { default as NavbarBrand } from './lib/NavbarBrand'; +export { default as NavbarToggler } from './lib/NavbarToggler'; +export { default as NavDropdown } from './lib/NavDropdown'; +export { default as NavItem } from './lib/NavItem'; +export { default as NavLink } from './lib/NavLink'; +export { default as Pagination } from './lib/Pagination'; +export { default as PaginationItem } from './lib/PaginationItem'; +export { default as PaginationLink } from './lib/PaginationLink'; +export { default as Popover } from './lib/Popover'; +export { default as PopoverContent } from './lib/PopoverContent'; +export { default as PopoverTitle } from './lib/PopoverTitle'; +export { default as Progress } from './lib/Progress'; +export { default as Row } from './lib/Row'; +export { default as TabContent } from './lib/TabContent'; +export { default as Table } from './lib/Table'; +export { default as TabPane } from './lib/TabPane'; +export { default as Tag } from './lib/Tag'; +export { default as TetherContent } from './lib/TetherContent'; +export { default as Tooltip } from './lib/Tooltip'; export { UncontrolledAlert, UncontrolledButtonDropdown, UncontrolledDropdown, UncontrolledNavDropdown, UncontrolledTooltip -} from './lib/Uncontrolled' \ No newline at end of file +} from './lib/Uncontrolled'; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index 71ab35ff9b..d4320246b7 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -76,8 +76,7 @@ import { Tooltip } from 'reactstrap'; - -//--------------- Alert +// --------------- Alert const Examplea = (props: any) => { return (
@@ -103,7 +102,7 @@ class AlertExample extends React.Component { this.state = { visible: true - } + }; } onDismiss = () => { @@ -127,7 +126,7 @@ function AlertExample1() { ); } -//--------------- Badge +// --------------- Badge class Example2 extends React.Component { render() { return ( @@ -173,7 +172,7 @@ class Example4 extends React.Component { } } -//------------- Breadcrumbs +// ------------- Breadcrumbs const Example5 = (props: any) => { return (
@@ -206,7 +205,7 @@ const Example6 = (props: any) => { ); }; -//------------- Buttons +// ------------- Buttons class Example7 extends React.Component { render() { return ( @@ -243,35 +242,35 @@ const Example9 = ( {' '}
-) +); const Example10 = (
{' '}
-) +); const Example11 = (
-) +); const Example12 = (
{' '}
-) +); const Example13 = (
{' '}
-) +); class Example14 extends React.Component { constructor(props: any) { @@ -320,7 +319,7 @@ class Example14 extends React.Component { } } -//------------- Button Dropdown +// ------------- Button Dropdown class Example15 extends React.Component { constructor(props: any) { super(props); @@ -368,7 +367,7 @@ const Example16 = ( Another Action -) +); const Example17 = (props: any) => ( true}> @@ -382,7 +381,7 @@ const Example17 = (props: any) => ( Another Action -) +); const Example18 = (
@@ -406,7 +405,7 @@ const Example18 = (
-) +); const Example19 = ( true} dropup> @@ -418,11 +417,9 @@ const Example19 = ( Another Action -) +); - - -//--------------- ButtonGroup +// --------------- ButtonGroup class Example20 extends React.Component { render() { return ( @@ -478,7 +475,7 @@ const Example22 = (props: any) => (
-) +); const Example23 = (props: any) => ( @@ -494,8 +491,7 @@ const Example23 = (props: any) => ( - -) +); const Example24 = (props: any) => ( @@ -511,10 +507,9 @@ const Example24 = (props: any) => ( -) +); - -//------------------ Cards +// ------------------ Cards const Example25 = (props: any) => { return (
@@ -862,8 +857,7 @@ const Example36 = (props: any) => { ); }; - -//------------------ Collapse +// ------------------ Collapse class Example37 extends React.Component { constructor(props: any) { @@ -937,8 +931,7 @@ class Example38 extends React.Component { } } - -//------- Dropdown +// ------- Dropdown class Example39 extends React.Component { constructor(props: any) { @@ -987,11 +980,11 @@ const Example40 = (props: any) => ( Another Action -) +); const Example41 = (props: any) => ( Header -) +); const Example42 = (props: any) => (
@@ -1014,7 +1007,7 @@ const Example42 = (props: any) => (
-) +); class Example43 extends React.Component { constructor(props: any) { @@ -1071,8 +1064,7 @@ function Example44() { ); } - -//------------------ Form +// ------------------ Form class Example45 extends React.Component { render() { return ( @@ -1476,7 +1468,7 @@ const Example53 = (props: any) => {
); -} +}; const Example54 = (props: any) => { return ( @@ -1602,7 +1594,6 @@ const Example59 = (props: any) => { ); }; - const Example60 = (props: any) => { return (
@@ -1933,8 +1924,7 @@ const Example71 = () => { ); }; - -//--------------- Modal +// --------------- Modal class ModalExample72 extends React.Component { constructor(props: any) { super(props); @@ -2322,7 +2312,7 @@ class Example80 extends React.Component { } } -//----------- Pagination +// ----------- Pagination class Example81 extends React.Component { render() { return ( @@ -2363,7 +2353,6 @@ class Example81 extends React.Component { } } - class Example82 extends React.Component { render() { return ( @@ -2404,7 +2393,6 @@ class Example82 extends React.Component { } } - class Example83 extends React.Component { render() { return ( @@ -2465,8 +2453,7 @@ class Example84 extends React.Component { } } - -//------------------------- Popover +// ------------------------- Popover class Example85 extends React.Component { constructor(props: any) { super(props); @@ -2529,7 +2516,7 @@ class PopoverItem extends React.Component { } } -class PopoverExampleMulti extends React.Component { +class PopoverExampleMulti extends React.Component}> { constructor(props: any) { super(props); @@ -2566,8 +2553,7 @@ class PopoverExampleMulti extends React.Component { return ( @@ -2711,8 +2697,7 @@ const Example92 = (props: any) => { ); }; - -//--------------- Table +// --------------- Table class Example93 extends React.Component { render() { return ( @@ -3103,7 +3088,6 @@ class Example101 extends React.Component { } } - class Example102 extends React.Component { constructor(props: any) { super(props); @@ -3132,7 +3116,6 @@ class Example102 extends React.Component { } } - class Example103 extends React.Component { constructor(props: any) { super(props); From 6a285d2dcf6d2bece6fc2a5032644df187f38fd9 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 30 Mar 2017 14:12:02 -0700 Subject: [PATCH 26/31] Lint d3-* packages (#15523) --- types/d3-array/index.d.ts | 4 +- types/d3-axis/index.d.ts | 16 +++--- types/d3-drag/d3-drag-tests.ts | 5 -- types/d3-drag/index.d.ts | 3 -- types/d3-dsv/v0/index.d.ts | 92 ++++++++++++++++---------------- types/d3-ease/d3-ease-tests.ts | 1 - types/d3-ease/index.d.ts | 37 ++++++------- types/d3-force/d3-force-tests.ts | 17 ------ types/d3-force/index.d.ts | 3 -- types/d3-geo/d3-geo-tests.ts | 4 +- types/d3-geo/index.d.ts | 66 +++++++++++------------ types/d3-scale/d3-scale-tests.ts | 41 -------------- types/d3-scale/index.d.ts | 75 +++++++++++--------------- types/d3-selection/index.d.ts | 22 ++++---- types/d3-shape/index.d.ts | 6 +-- 15 files changed, 153 insertions(+), 239 deletions(-) diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index ccd2d568bb..8f5d4eab2e 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -153,8 +153,8 @@ export function bisectRight(array: Date[], x: Date, lo?: number, hi?: number): n export const bisect: typeof bisectRight; export interface Bisector { - left: (array: T[], x: U, lo?: number, hi?: number) => number; - right: (array: T[], x: U, lo?: number, hi?: number) => number; + left(array: T[], x: U, lo?: number, hi?: number): number; + right(array: T[], x: U, lo?: number, hi?: number): number; } export function bisector(comparator: (a: T, b: U) => number): Bisector; diff --git a/types/d3-axis/index.d.ts b/types/d3-axis/index.d.ts index 4a65952070..9cee537067 100644 --- a/types/d3-axis/index.d.ts +++ b/types/d3-axis/index.d.ts @@ -61,10 +61,10 @@ export interface Axis { (context: Selection): void; /** - * Render the axis to the given context. - * - * @param context A transition defined on SVG containers (either SVG or G elements). - */ + * Render the axis to the given context. + * + * @param context A transition defined on SVG containers (either SVG or G elements). + */ (context: TransitionLike): void; /** @@ -142,10 +142,10 @@ export interface Axis { tickArguments(args: [AxisTimeInterval, string]): this; /** - * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. - * - * @param args An array with arguments suitable for the scale to be used for tick generation - */ + * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * + * @param args An array with arguments suitable for the scale to be used for tick generation + */ tickArguments(args: any[]): this; /** diff --git a/types/d3-drag/d3-drag-tests.ts b/types/d3-drag/d3-drag-tests.ts index deb5a6dc55..4283cb259f 100644 --- a/types/d3-drag/d3-drag-tests.ts +++ b/types/d3-drag/d3-drag-tests.ts @@ -55,7 +55,6 @@ let circleDrag: d3Drag.DragBehavior; - // create new drag behavior ------------------------------------------ circleDrag = d3Drag.drag(); // Use short form method @@ -99,7 +98,6 @@ filterFn = function(d) { // chainable circleDrag = circleDrag.filter(function(d, i, group) { - return (d.color !== 'green' && this.r.baseVal.value < 10) ? !event.button : true; // 'this' is SVGCircleElement and d is CircleDatum }); @@ -192,10 +190,8 @@ const wrongSelection: Selection = select = event; - circleDrag = e.target; // target return drag behavior const type: string = e.type; @@ -224,7 +220,6 @@ handler = e.on('dragged'); // fails, handler with wrong datum type // let wrongHandler4: ((this:SVGCircleElement, d:{test: number}, i: number, group: SVGCircleElement[] | NodeListOf)=> void) | undefined = e.on('dragged'); - // ----------------------------------------------------------------------------- // Test dragDisable() and dragEnable() // ----------------------------------------------------------------------------- diff --git a/types/d3-drag/index.d.ts b/types/d3-drag/index.d.ts index d49e0bbc02..d3a65fb377 100644 --- a/types/d3-drag/index.d.ts +++ b/types/d3-drag/index.d.ts @@ -7,12 +7,10 @@ import { ArrayLike, Selection, ValueFn } from 'd3-selection'; - // -------------------------------------------------------------------------- // Shared Type Definitions and Interfaces // -------------------------------------------------------------------------- - /** * DraggedElementBaseType serves as an alias for the 'minimal' data type which can be selected * without 'd3-drag' (and related code in 'd3-selection') trying to use properties internally which would otherwise not @@ -20,7 +18,6 @@ import { ArrayLike, Selection, ValueFn } from 'd3-selection'; */ export type DraggedElementBaseType = Element; - /** * Container element type usable for mouse/touch functions */ diff --git a/types/d3-dsv/v0/index.d.ts b/types/d3-dsv/v0/index.d.ts index 82ccd0f87f..18701f64ea 100644 --- a/types/d3-dsv/v0/index.d.ts +++ b/types/d3-dsv/v0/index.d.ts @@ -4,11 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** A parser and formatter for DSV (CSV and TSV) files. Extracted from D3. */ -declare var loader: ( - /** the symbol used to seperate cells in the row.*/ +declare function loader( + /** the symbol used to seperate cells in the row. */ delimiter: string, /** example: "text/plain" */ - encoding?: string) => D3Dsv; + encoding?: string): D3Dsv; export = loader; export as namespace d3_dsv; @@ -16,21 +16,21 @@ export as namespace d3_dsv; /** A parser and formatter for DSV (CSV and TSV) files. Extracted from D3. */ interface D3Dsv { /** - Parses the specified string, which is the contents of a CSV file, returning an array of objects representing the parsed rows. - The string is assumed to be RFC4180-compliant. - Unlike the parseRows method, this method requires that the first line of the CSV file contains a comma-separated list of column names; - these column names become the attributes on the returned objects. - For example, consider the following CSV file: - - Year,Make,Model,Length - 1997,Ford,E350,2.34 - 2000,Mercury,Cougar,2.38 - - The resulting JavaScript array is: - - [ {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"}, - {"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"} ] - */ + * Parses the specified string, which is the contents of a CSV file, returning an array of objects representing the parsed rows. + * The string is assumed to be RFC4180-compliant. + * Unlike the parseRows method, this method requires that the first line of the CSV file contains a comma-separated list of column names; + * these column names become the attributes on the returned objects. + * For example, consider the following CSV file: + * + * Year,Make,Model,Length + * 1997,Ford,E350,2.34 + * 2000,Mercury,Cougar,2.38 + * + * The resulting JavaScript array is: + * + * [ {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"}, + * {"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"} ] + */ parse( table: string, /** coerce cells (strings) into different types or modify them. return null to strip this row from the output results. */ @@ -38,42 +38,42 @@ interface D3Dsv { ): TRow[]; /** - Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. - The string is assumed to be RFC4180-compliant. - Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. - Each row is represented as an array rather than an object. - Rows may have variable length. - For example, consider the following CSV file: - - 1997,Ford,E350,2.34 - 2000,Mercury,Cougar,2.38 - The resulting JavaScript array is: - - [ ["1997", "Ford", "E350", "2.34"], - ["2000", "Mercury", "Cougar", "2.38"] ] - Note that the values themselves are always strings; they will not be automatically converted to numbers. See parse for details. - */ + * Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. + * The string is assumed to be RFC4180-compliant. + * Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. + * Each row is represented as an array rather than an object. + * Rows may have variable length. + * For example, consider the following CSV file: + * + * 1997,Ford,E350,2.34 + * 2000,Mercury,Cougar,2.38 + * The resulting JavaScript array is: + * + * [ ["1997", "Ford", "E350", "2.34"], + * ["2000", "Mercury", "Cougar", "2.38"] ] + * Note that the values themselves are always strings; they will not be automatically converted to numbers. See parse for details. + */ parseRows( table: string, - /** coerce cells (strings) into different types or modify them. return null to strip this row from the output results.*/ + /** coerce cells (strings) into different types or modify them. return null to strip this row from the output results. */ accessor?: (row: string[]) => TRow ): TRow[]; /** - Converts the specified array of rows into comma-separated values format, returning a string. - This operation is the reverse of parse. - Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). - Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. - - Each row should be an object, and all object properties will be converted into fields. - For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. - */ + * Converts the specified array of rows into comma-separated values format, returning a string. + * This operation is the reverse of parse. + * Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). + * Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. + * + * Each row should be an object, and all object properties will be converted into fields. + * For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. + */ format(rows: any[]): string; /** - Converts the specified array of rows into comma-separated values format, returning a string. - This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). - Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. - */ + * Converts the specified array of rows into comma-separated values format, returning a string. + * This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). + * Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. + */ formatRows(rows: any[]): string; } diff --git a/types/d3-ease/d3-ease-tests.ts b/types/d3-ease/d3-ease-tests.ts index b50ceba9a4..67a0f32b1b 100644 --- a/types/d3-ease/d3-ease-tests.ts +++ b/types/d3-ease/d3-ease-tests.ts @@ -23,7 +23,6 @@ t_out = d3Ease.easeCubicIn(t_in); t_out = d3Ease.easeCubicOut(t_in); t_out = d3Ease.easeCubicInOut(t_in); - let easePolyFactory: d3Ease.PolynomialEasingFactory; easePolyFactory = d3Ease.easePoly; diff --git a/types/d3-ease/index.d.ts b/types/d3-ease/index.d.ts index 704b55e5e0..3de6fd2e87 100644 --- a/types/d3-ease/index.d.ts +++ b/types/d3-ease/index.d.ts @@ -94,25 +94,24 @@ export interface PolynomialEasingFactory { * Symmetric polynomial easing/easing factory; scales polyIn for t in [0, 0.5] and polyOut for t in [0.5, 1]. * If the exponent is not specified, it defaults to 3, equivalent to cubic. */ -export var easePoly: PolynomialEasingFactory; +export const easePoly: PolynomialEasingFactory; /** * Polynomial easing/easing factory; raises t to the specified exponent. * If the exponent is not specified, it defaults to 3, equivalent to cubicIn. */ -export var easePolyIn: PolynomialEasingFactory; +export const easePolyIn: PolynomialEasingFactory; /** * Reverse polynomial easing/easing factory; equivalent to 1 - polyIn(1 - t). * If the exponent is not specified, it defaults to 3, equivalent to cubicOut. */ -export var easePolyOut: PolynomialEasingFactory; +export const easePolyOut: PolynomialEasingFactory; /** * Symmetric polynomial easing/easing factory; scales polyIn for t in [0, 0.5] and polyOut for t in [0.5, 1]. * If the exponent is not specified, it defaults to 3, equivalent to cubic. */ -export var easePolyInOut: PolynomialEasingFactory; - +export const easePolyInOut: PolynomialEasingFactory; /** * Symmetric sinusoidal easing; scales sinIn for t in [0, 0.5] and sinOut for t in [0.5, 1]. @@ -226,7 +225,6 @@ export function easeBounceOut(normalizedTime: number): number; */ export function easeBounceInOut(normalizedTime: number): number; - /** * Anticipatory easing function factory */ @@ -249,26 +247,25 @@ export interface BackEasingFactory { * Symmetric anticipatory easing; scales backIn for t in [0, 0.5] and backOut for t in [0.5, 1]. * The degree of overshoot is configurable; it not specified, it defaults to 1.70158. */ -export var easeBack: BackEasingFactory; +export const easeBack: BackEasingFactory; /** * Anticipatory easing, like a dancer bending his knees before jumping off the floor. * The degree of overshoot is configurable; it not specified, it defaults to 1.70158. */ -export var easeBackIn: BackEasingFactory; +export const easeBackIn: BackEasingFactory; /** * Reverse anticipatory easing; equivalent to 1 - backIn(1 - t). * The degree of overshoot is configurable; it not specified, it defaults to 1.70158. */ -export var easeBackOut: BackEasingFactory; +export const easeBackOut: BackEasingFactory; /** * Symmetric anticipatory easing; scales backIn for t in [0, 0.5] and backOut for t in [0.5, 1]. * The degree of overshoot is configurable; it not specified, it defaults to 1.70158. */ -export var easeBackInOut: BackEasingFactory; - +export const easeBackInOut: BackEasingFactory; /** * Elastic easing function factory @@ -287,11 +284,11 @@ export interface ElasticEasingFactory { */ amplitude(a: number): ElasticEasingFactory; /** - * Returns a new elastic easing with the specified amplitude a. - * Defaults to 0.3,if not specified. - * - * @param p Period for elastic easing. - */ + * Returns a new elastic easing with the specified amplitude a. + * Defaults to 0.3,if not specified. + * + * @param p Period for elastic easing. + */ period(p: number): ElasticEasingFactory; } @@ -300,25 +297,25 @@ export interface ElasticEasingFactory { * The amplitude and period of the oscillation are configurable; * if not specified, they default to 1 and 0.3, respectively. */ -export var easeElastic: ElasticEasingFactory; +export const easeElastic: ElasticEasingFactory; /** * Elastic easing, like a rubber band. * The amplitude and period of the oscillation are configurable; * if not specified, they default to 1 and 0.3, respectively. */ -export var easeElasticIn: ElasticEasingFactory; +export const easeElasticIn: ElasticEasingFactory; /** * Reverse elastic easing; equivalent to 1 - elasticIn(1 - t). * The amplitude and period of the oscillation are configurable; * if not specified, they default to 1 and 0.3, respectively. */ -export var easeElasticOut: ElasticEasingFactory; +export const easeElasticOut: ElasticEasingFactory; /** * Symmetric elastic easing; scales elasticIn for t in [0, 0.5] and elasticOut for t in [0.5, 1]. * The amplitude and period of the oscillation are configurable; * if not specified, they default to 1 and 0.3, respectively. */ -export var easeElasticInOut: ElasticEasingFactory; +export const easeElasticInOut: ElasticEasingFactory; diff --git a/types/d3-force/d3-force-tests.ts b/types/d3-force/d3-force-tests.ts index 0ecd7555d3..c08e1b5cee 100644 --- a/types/d3-force/d3-force-tests.ts +++ b/types/d3-force/d3-force-tests.ts @@ -6,7 +6,6 @@ * are not intended as functional tests. */ - import * as d3Force from 'd3-force'; // ------------------------------------------------------------------------------------- @@ -30,7 +29,6 @@ interface Graph { links: SimLink[]; } - const graph: Graph = { nodes: [ { id: 'Myriel', group: 1, r: 5 }, @@ -112,7 +110,6 @@ forceCollide = d3Force.forceCollide((node, index, nodes) => { return n.r; }); - // Configure Collision force ----------------------------------------------------------- let radiusAccessor: (node: SimNode, i: number, nodes: SimNode[]) => number; @@ -139,7 +136,6 @@ num = forceCollide.strength(); forceCollide = forceCollide.iterations(10); num = forceCollide.iterations(); - // Use Collision force ----------------------------------------------------------------- forceCollide.initialize(graph.nodes); @@ -157,7 +153,6 @@ forceLink = d3Force.forceLink(); // with link data forceLink = d3Force.forceLink(graph.links); - // Configure Link force ----------------------------------------------------------- let linkNumberAccessor: (link: SimLink, i: number, links: SimLink[]) => number; @@ -181,7 +176,6 @@ num = simLink.value; num = simLink.d; num = simLink.s; - // id (node id accessor) forceLink = forceLink.id((node, index, nodes) => { @@ -220,13 +214,11 @@ linkNumberAccessor = forceLink.strength(); forceLink = forceLink.iterations(10); num = forceLink.iterations(); - // Use Link force ----------------------------------------------------------------- forceLink.initialize(graph.nodes); forceLink(0.1); // alpha - // ManyBody ============================================================================ // create ManyBody force -------------------------------------------------------------- @@ -255,7 +247,6 @@ simNodeNumberAccessor = forceCharge.strength(); forceCharge = forceCharge.theta(0.8); num = forceCharge.theta(); - // distanceMin forceCharge = forceCharge.distanceMin(1); @@ -266,13 +257,11 @@ num = forceCharge.distanceMin(); forceCharge = forceCharge.distanceMax(1000); num = forceCharge.distanceMax(); - // Use ManyBody force ----------------------------------------------------------------- forceCharge.initialize(graph.nodes); forceCharge(0.1); // alpha - // ForceX ============================================================================== // create ForceX force -------------------------------------------------------------- @@ -327,7 +316,6 @@ simNodeNumberAccessor = forcePosX.x(); forcePosX.initialize(graph.nodes); forcePosX(0.1); // alpha - // ForceY ============================================================================== // create ForceY force -------------------------------------------------------------- @@ -388,7 +376,6 @@ forcePosY(0.1); // alpha // Create Force Simulation ============================================================= - let nodeSimulation: d3Force.Simulation; let nodeLinkSimulation: d3Force.Simulation; @@ -435,7 +422,6 @@ num = nodeLinkSimulation.alphaTarget(); nodeLinkSimulation = nodeLinkSimulation.velocityDecay(0.4); num = nodeLinkSimulation.velocityDecay(); - // force() ----------------------------------------------------------------------------- nodeSimulation = nodeSimulation.force('posx', forcePosX); @@ -444,7 +430,6 @@ nodeSimulation.force('posy', forcePosY); // Remove force nodeSimulation = nodeSimulation.force('posx', null); - nodeLinkSimulation = nodeLinkSimulation.force('link', forceLink); nodeLinkSimulation @@ -480,7 +465,6 @@ simLinks = nodeLinkSimulation.force>('link') // fLink = nodeLinkSimulation.force('link')!; // fails, as ForceLink specific properties are missing from 'generic' force - // on() -------------------------------------------------------------------------------- function drawLink(d: SimLink) { @@ -502,7 +486,6 @@ function drawNode(d: SimNode) { } nodeLinkSimulation = nodeLinkSimulation.on('tick', function ticked() { - const that: d3Force.Simulation = this; if (context) { diff --git a/types/d3-force/index.d.ts b/types/d3-force/index.d.ts index 6faa27449a..23f83c7ea3 100644 --- a/types/d3-force/index.d.ts +++ b/types/d3-force/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - // Last module patch version validated against: 1.0.4 // ----------------------------------------------------------------------- @@ -356,7 +355,6 @@ export interface Force {} } = d3Geo.geoTransform({}); +const transformFunction: { stream(s: d3Geo.GeoStream): {} } = d3Geo.geoTransform({}); interface CustomTranformProto extends d3Geo.GeoTransformPrototype { a: number; @@ -612,7 +612,7 @@ customTransformProto = { a: 10 }; -const t: { stream: (s: d3Geo.GeoStream) => (CustomTranformProto & d3Geo.GeoStream) } = d3Geo.geoTransform(customTransformProto); +const t: { stream(s: d3Geo.GeoStream): CustomTranformProto & d3Geo.GeoStream } = d3Geo.geoTransform(customTransformProto); // geoIdentity() ======================================================== diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index 1e9fed9b92..f6e4fa150d 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -699,14 +699,14 @@ export interface GeoProjection extends GeoStreamWrapper { */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature): this; /** - * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. - * Returns the projection. - * - * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. - * - * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. - * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). - */ + * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection>): this; /** * Sets the projection’s scale and translate to fit the specified geographic geometry object in the center of the given extent. @@ -719,14 +719,14 @@ export interface GeoProjection extends GeoStreamWrapper { */ fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this; /** - * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. - * Returns the projection. - * - * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. - * - * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. - * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). - */ + * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection): this; /** @@ -1340,7 +1340,7 @@ export interface GeoTransformPrototype { * * @param methods An object with custom method implementations, which are used to create a transform projection. */ -export function geoTransform(methods: T): { stream: (s: GeoStream) => (T & GeoStream) }; +export function geoTransform(methods: T): { stream(s: GeoStream): T & GeoStream }; // geoIdentity() ================================================================= @@ -1382,14 +1382,14 @@ export interface GeoIdentityTranform extends GeoStreamWrapper { */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeature): this; /** - * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. - * Returns the projection. - * - * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. - * - * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. - * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). - */ + * Sets the projection’s scale and translate to fit the specified geographic feature collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic feature collection supported by d3-geo (An extension of GeoJSON feature collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedFeatureCollection>): this; /** * Sets the projection’s scale and translate to fit the specified geographic geometry object in the center of the given extent. @@ -1402,14 +1402,14 @@ export interface GeoIdentityTranform extends GeoStreamWrapper { */ fitExtent(extent: [[number, number], [number, number]], object: GeoGeometryObjects): this; /** - * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. - * Returns the projection. - * - * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. - * - * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. - * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). - */ + * Sets the projection’s scale and translate to fit the specified geographic geometry collection in the center of the given extent. + * Returns the projection. + * + * Any clip extent is ignored when determining the new scale and translate. The precision used to compute the bounding box of the given object is computed at an effective scale of 150. + * + * @param extent The extent, specified as an array [[x₀, y₀], [x₁, y₁]], where x₀ is the left side of the bounding box, y₀ is the top, x₁ is the right and y₁ is the bottom. + * @param object A geographic geometry collection supported by d3-geo (An extension of GeoJSON geometry collection). + */ fitExtent(extent: [[number, number], [number, number]], object: ExtendedGeometryCollection): this; /** diff --git a/types/d3-scale/d3-scale-tests.ts b/types/d3-scale/d3-scale-tests.ts index c1feb4766a..f317e342ec 100644 --- a/types/d3-scale/d3-scale-tests.ts +++ b/types/d3-scale/d3-scale-tests.ts @@ -92,7 +92,6 @@ linearScaleNumString = linearScaleNumString.domain(domainNumeric); linearScaleNumString = linearScaleNumString.domain(domainNumbers); domainNumbers = linearScaleNumString.domain(); - // range(...) ----------------------------------------------------------------- linearScaleNumber = linearScaleNumber.range(rangeNumbers); @@ -138,7 +137,6 @@ linearScaleNumString = linearScaleNumber.interpolate((a, b) => { // nice(...) ----------------------------------------------------------------------- - // chainable linearScaleNumber = linearScaleNumber.nice(); linearScaleNumber = linearScaleNumber.nice(5); @@ -180,7 +178,6 @@ powerScaleNumber = d3Scale.scalePow(); powerScaleString = d3Scale.scalePow(); powerScaleNumString = d3Scale.scalePow(); - let squarerootScaleNumber: d3Scale.ScalePower; let squarerootScaleString: d3Scale.ScalePower; let squarerootScaleNumString: d3Scale.ScalePower; @@ -211,7 +208,6 @@ powerScaleNumString = powerScaleNumString.domain(domainNumeric); powerScaleNumString = powerScaleNumString.domain(domainNumbers); domainNumbers = powerScaleNumString.domain(); - // range(...) ----------------------------------------------------------------- powerScaleNumber = powerScaleNumber.range(rangeNumbers); @@ -282,7 +278,6 @@ const copiedPowerScale: d3Scale.ScalePower = powerScaleNumString // Logarithmic Scale Factory // ------------------------------------------------------------------------------- - // scaleLog() --------------------------------------------------------------------- let logScaleNumber: d3Scale.ScaleLogarithmic; @@ -293,7 +288,6 @@ logScaleNumber = d3Scale.scaleLog(); logScaleString = d3Scale.scaleLog(); logScaleNumString = d3Scale.scaleLog(); - // ScaleLogarithmic Interface ======================================================== // base -------------------------------------------------------------------- @@ -316,7 +310,6 @@ logScaleNumString = logScaleNumString.domain(domainNumeric); logScaleNumString = logScaleNumString.domain(domainNumbers); domainNumbers = logScaleNumString.domain(); - // range(...) ----------------------------------------------------------------- logScaleNumber = logScaleNumber.range(rangeNumbers); @@ -393,10 +386,8 @@ let identityScale: d3Scale.ScaleIdentity; identityScale = d3Scale.scaleIdentity(); - // ScaleIdentity Interface ======================================================== - // domain(...) ----------------------------------------------------------------- identityScale = identityScale.domain(domainNumeric); @@ -434,12 +425,10 @@ tickFormatNumberFn = identityScale.tickFormat(5, '+%'); outputNumber = identityScale(10); - // copy(...) ----------------------------------------------------------------- const copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy(); - // ------------------------------------------------------------------------------- // Time Scale Factories // ------------------------------------------------------------------------------- @@ -454,7 +443,6 @@ localTimeScaleNumber = d3Scale.scaleTime(); localTimeScaleString = d3Scale.scaleTime(); localTimeScaleNumString = d3Scale.scaleTime(); - let utcScaleNumber: d3Scale.ScaleTime; let utcScaleString: d3Scale.ScaleTime; let utcScaleNumString: d3Scale.ScaleTime; @@ -475,7 +463,6 @@ domainDates = localTimeScaleString.domain(); localTimeScaleNumString = localTimeScaleNumString.domain(domainDates); domainDates = localTimeScaleNumString.domain(); - // range(...) ----------------------------------------------------------------- localTimeScaleNumber = localTimeScaleNumber.range(rangeNumbers); @@ -534,7 +521,6 @@ if (timeInterval !== null) { ticksDates = localTimeScaleNumString.ticks(timeInterval); } - // tickFormat(...) ----------------------------------------------------------------- tickFormatDateFn = localTimeScaleNumber.tickFormat(); @@ -543,7 +529,6 @@ if (timeInterval !== null) { tickFormatDateFn = localTimeScaleNumber.tickFormat(timeInterval, '%I %p'); } - // (...) value mapping from domain to output ----------------------------------- outputNumber = localTimeScaleNumber(new Date(2016, 6, 4)); @@ -595,8 +580,6 @@ outputString = sequentialScaleColorString(10); const copiedSequentialScale: d3Scale.ScaleSequential = sequentialScaleColorString.copy(); - - // ------------------------------------------------------------------------------- // Color Interpolators for Sequential Scale Factory // ------------------------------------------------------------------------------- @@ -619,7 +602,6 @@ colorInterpolator = d3Scale.interpolateCool; colorInterpolator = d3Scale.interpolateCubehelixDefault; - // ------------------------------------------------------------------------------- // Quantize Scale Factory // ------------------------------------------------------------------------------- @@ -632,7 +614,6 @@ let quantizeScaleString: d3Scale.ScaleQuantize; quantizeScaleNumber = d3Scale.scaleQuantize(); quantizeScaleString = d3Scale.scaleQuantize(); - // ScaleQuantize Interface ======================================================== // domain(...) ----------------------------------------------------------------- @@ -649,7 +630,6 @@ rangeNumbers = quantizeScaleNumber.range(); quantizeScaleString = quantizeScaleString.range(['steelblue', 'brown']); rangeStrings = quantizeScaleString.range(); - // invertExtent(...) ----------------------------------------------------------------- numExtent = quantizeScaleNumber.invertExtent(500); @@ -681,12 +661,10 @@ outputNumber = quantizeScaleNumber(0.51); const copiedQuantizeScale: d3Scale.ScaleQuantize = quantizeScaleNumber.copy(); - // ------------------------------------------------------------------------------- // Quantile Scale Factory // ------------------------------------------------------------------------------- - // scaleQuantile() ----------------------------------------------------------------- let quantileScaleNumber: d3Scale.ScaleQuantile; @@ -695,7 +673,6 @@ let quantileScaleString: d3Scale.ScaleQuantile; quantileScaleNumber = d3Scale.scaleQuantile(); quantileScaleString = d3Scale.scaleQuantile(); - // ScaleQuantile Interface ======================================================== // domain(...) ----------------------------------------------------------------- @@ -714,7 +691,6 @@ rangeNumbers = quantileScaleNumber.range(); quantileScaleString = quantileScaleString.range(['q25', 'q50', 'q75']); rangeStrings = quantileScaleString.range(); - // invertExtent(...) ----------------------------------------------------------------- numExtent = quantileScaleNumber.invertExtent(2); @@ -733,7 +709,6 @@ outputNumber = quantileScaleNumber(0.51); const copiedQuantileScale: d3Scale.ScaleQuantile = quantileScaleNumber.copy(); - // ------------------------------------------------------------------------------- // Threshold Scale Factory // ------------------------------------------------------------------------------- @@ -746,7 +721,6 @@ let thresholdScaleNumberString: d3Scale.ScaleThreshold; thresholdScaleNumberNumber = d3Scale.scaleThreshold(); thresholdScaleNumberString = d3Scale.scaleThreshold(); - // ScaleThreshold Interface ======================================================== // domain(...) ----------------------------------------------------------------- @@ -764,7 +738,6 @@ rangeNumbers = thresholdScaleNumberNumber.range(); thresholdScaleNumberString = thresholdScaleNumberString.range(['steelblue', 'seagreen', 'brown']); rangeStrings = thresholdScaleNumberString.range(); - // invertExtent(...) ----------------------------------------------------------------- numOrUndefinedExtent = thresholdScaleNumberNumber.invertExtent(100); @@ -781,7 +754,6 @@ outputString = thresholdScaleNumberString(0.9); const copiedThresholdScale: d3Scale.ScaleThreshold = thresholdScaleNumberString.copy(); - // ------------------------------------------------------------------------------- // Ordinal Scale Factory // ------------------------------------------------------------------------------- @@ -794,7 +766,6 @@ let ordinalScaleStringNumber: d3Scale.ScaleOrdinal; ordinalScaleStringString = d3Scale.scaleOrdinal(); ordinalScaleStringNumber = d3Scale.scaleOrdinal(); - // ScaleOrdinal Interface ======================================================== // domain(...) ----------------------------------------------------------------- @@ -812,7 +783,6 @@ rangeStrings = ordinalScaleStringString.range(); ordinalScaleStringNumber = ordinalScaleStringNumber.range([-1, 0, 1]); rangeNumbers = ordinalScaleStringNumber.range(); - // unknown(...) and d3Scale.scaleImplicit -------------------------------------- const implicit: { name: 'implicit' } = d3Scale.scaleImplicit; @@ -839,7 +809,6 @@ outputNumber = ordinalScaleStringNumber('negative'); const copiedOrdinalScale: d3Scale.ScaleOrdinal = ordinalScaleStringNumber.copy(); - // ------------------------------------------------------------------------------- // Band Scale Factory // ------------------------------------------------------------------------------- @@ -852,7 +821,6 @@ let bandScaleCoercible: d3Scale.ScaleBand; bandScaleString = d3Scale.scaleBand(); bandScaleCoercible = d3Scale.scaleBand(); - // ScaleBand Interface ======================================================== // domain(...) ----------------------------------------------------------------- @@ -870,12 +838,10 @@ let rangeExtent: [number, number] = bandScaleString.range(); bandScaleCoercible = bandScaleCoercible.range([0, 300]); rangeExtent = bandScaleCoercible.range(); - // rangeRound(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.rangeRound([0, 300]); - // round(...) ----------------------------------------------------------------- bandScaleCoercible = bandScaleCoercible.round(true); @@ -891,7 +857,6 @@ num = bandScaleString.paddingInner(); bandScaleString = bandScaleString.paddingOuter(0.1); num = bandScaleString.paddingOuter(); - // padding(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.padding(0.1); @@ -910,7 +875,6 @@ num = bandScaleString.bandwidth(); num = bandScaleString.step(); - // (...) value mapping from domain to output ----------------------------------- outputNumberMaybe = bandScaleString('neutral'); @@ -921,7 +885,6 @@ outputNumberMaybe = bandScaleCoercible(new StringCoercible('negative')); const copiedBandScale: d3Scale.ScaleBand = bandScaleCoercible.copy(); - // ------------------------------------------------------------------------------- // Point Scale Factory // ------------------------------------------------------------------------------- @@ -934,7 +897,6 @@ let pointScaleCoercible: d3Scale.ScalePoint; pointScaleString = d3Scale.scalePoint(); pointScaleCoercible = d3Scale.scalePoint(); - // ScalePoint Interface ======================================================== // domain(...) ----------------------------------------------------------------- @@ -952,18 +914,15 @@ rangeExtent = pointScaleString.range(); pointScaleCoercible = pointScaleCoercible.range([0, 300]); rangeExtent = pointScaleCoercible.range(); - // rangeRound(...) ----------------------------------------------------------------- pointScaleString = pointScaleString.rangeRound([0, 300]); - // round(...) ----------------------------------------------------------------- pointScaleCoercible = pointScaleCoercible.round(true); roundingFlag = pointScaleCoercible.round(); - // padding(...) ----------------------------------------------------------------- pointScaleString = pointScaleString.padding(0.1); diff --git a/types/d3-scale/index.d.ts b/types/d3-scale/index.d.ts index 2ba9eeec8a..8a114d90e1 100644 --- a/types/d3-scale/index.d.ts +++ b/types/d3-scale/index.d.ts @@ -33,16 +33,15 @@ export interface InterpolatorFactory { * A helper interface for a continuous scale defined over a numeric domain. */ export interface ScaleContinuousNumeric { - /** - * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. - * - * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. - * - * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. - * - * @param value A numeric value from the domain. - */ + * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. + * + * @param value A numeric value from the domain. + */ (value: number | { valueOf(): number }): Output; /** @@ -163,7 +162,6 @@ export interface ScaleContinuousNumeric { * Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa. */ copy(): this; - } // ------------------------------------------------------------------------------- @@ -188,7 +186,6 @@ export interface ScaleContinuousNumeric { * convert the interpolated range element to a corresponding output element. */ export interface ScaleLinear extends ScaleContinuousNumeric { - /** * Returns the scale’s current interpolator factory, which defaults to interpolate. */ @@ -222,7 +219,6 @@ export interface ScaleLinear extends ScaleContinuousNumeric(interpolate: InterpolatorFactory): ScaleLinear; - } /** @@ -281,7 +277,6 @@ export function scaleLinear(): ScaleLinear; * convert the interpolated range element to a corresponding output element. */ export interface ScalePower extends ScaleContinuousNumeric { - /** * Returns the scale’s current interpolator factory, which defaults to interpolate. */ @@ -428,7 +423,6 @@ export function scaleSqrt(): ScalePower; * convert the interpolated range element to a corresponding output element. */ export interface ScaleLogarithmic extends ScaleContinuousNumeric { - /** * Returns a copy of the scale’s current domain. */ @@ -578,16 +572,15 @@ export function scaleLog(): ScaleLogarithmic; * These scales are occasionally useful when working with pixel coordinates, say in conjunction with an axis or brush. */ export interface ScaleIdentity { - /** - * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. - * - * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. - * - * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. - * - * @param value A numeric value from the domain. - */ + * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. + * + * @param value A numeric value from the domain. + */ (value: number | { valueOf(): number }): number; /** @@ -688,7 +681,6 @@ export interface ScaleIdentity { */ export function scaleIdentity(): ScaleIdentity; - // ------------------------------------------------------------------------------- // Time Scale Factories // ------------------------------------------------------------------------------- @@ -710,16 +702,15 @@ export function scaleIdentity(): ScaleIdentity; * convert the interpolated range element to a corresponding output element. */ export interface ScaleTime { - /** - * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. - * - * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. - * - * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. - * - * @param value A temporal value from the domain. If the value is not a Date, it will be coerced to Date. - */ + * Given a value from the domain, returns the corresponding value from the range, subject to interpolation, if any. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * Note: The interpolation function applied by the scale may change the output type from the range type as part of the interpolation. + * + * @param value A temporal value from the domain. If the value is not a Date, it will be coerced to Date. + */ (value: Date | number | { valueOf(): number }): Output; /** @@ -1022,14 +1013,13 @@ export function scaleUtc(): ScaleTime; * The generic corresponds to the data type of the output of the interpolator underlying the scale. */ export interface ScaleSequential { - /** - * Given a value from the domain, returns the corresponding value from the output range, subject to interpolation. - * - * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. - * - * @param value A numeric value from the domain. - */ + * Given a value from the domain, returns the corresponding value from the output range, subject to interpolation. + * + * If the given value is outside the domain, and clamping is not enabled, the mapping may be extrapolated such that the returned value is outside the range. + * + * @param value A numeric value from the domain. + */ (value: number | { valueOf(): number }): Output; /** @@ -1209,7 +1199,7 @@ export interface ScaleQuantize { */ range(range: Range[]): this; - /** + /** * Returns approximately count representative values from the scale’s domain. * * If count is not specified, it defaults to 10. @@ -1282,7 +1272,6 @@ export function scaleQuantize(): ScaleQuantize; * The generic correponds to the data type of range elements. */ export interface ScaleQuantile { - /** * Given a value in the input domain, returns the corresponding value in the output range. * @@ -1542,7 +1531,6 @@ export function scaleOrdinal(range */ export const scaleImplicit: { name: 'implicit' }; - // ------------------------------------------------------------------------------- // Band Scale Factory // ------------------------------------------------------------------------------- @@ -1828,7 +1816,6 @@ export function scalePoint(): ScalePoint; */ export function scalePoint(): ScalePoint; - // ------------------------------------------------------------------------------- // Categorical Color Schemas for Ordinal Scales // ------------------------------------------------------------------------------- diff --git a/types/d3-selection/index.d.ts b/types/d3-selection/index.d.ts index b007573b1f..34196f755e 100644 --- a/types/d3-selection/index.d.ts +++ b/types/d3-selection/index.d.ts @@ -552,17 +552,17 @@ interface Selection; /** - * Filters the selection, returning a new selection that contains only the elements for - * which the specified filter is true. - * - * The returned filtered selection preserves the parents of this selection, but like array.filter, - * it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed. - * - * The generic refers to the type of element which will be selected after applying the filter, i.e. if the element types - * contained in a pre-filter selection are narrowed to a subset as part of the filtering. - * - * @param selector A CSS selector string to match when filtering. - */ + * Filters the selection, returning a new selection that contains only the elements for + * which the specified filter is true. + * + * The returned filtered selection preserves the parents of this selection, but like array.filter, + * it does not preserve indexes as some elements may be removed; use selection.select to preserve the index, if needed. + * + * The generic refers to the type of element which will be selected after applying the filter, i.e. if the element types + * contained in a pre-filter selection are narrowed to a subset as part of the filtering. + * + * @param selector A CSS selector string to match when filtering. + */ filter(selector: string): Selection; /** * Filter the selection, returning a new selection that contains only the elements for diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index e1d80b6786..517f84e501 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -1990,14 +1990,14 @@ export interface Symbol { /** * Constructs a new symbol generator with the default settings. */ -export function symbol(): Symbol; +export function symbol(): Symbol; // tslint:disable-line ban-types /** * Constructs a new symbol generator with the default settings. * * The generic corrsponds to the data type of the datum underlying the symbol. */ -export function symbol(): Symbol; +export function symbol(): Symbol; // tslint:disable-line ban-types /** * Constructs a new symbol generator with the default settings. @@ -2005,7 +2005,7 @@ export function symbol(): Symbol; * The first generic corresponds to the "this" context within which the symbol generator is invoked. * The second generic corrsponds to the data type of the datum underlying the symbol. */ -export function symbol(): Symbol; +export function symbol(): Symbol; // tslint:disable-line ban-types /** * An array containing the set of all built-in symbol types: circle, cross, diamond, square, star, triangle, and wye. From 389adfc542fee64c48cf040510bd2dcce8546c74 Mon Sep 17 00:00:00 2001 From: cailenmusselman Date: Thu, 30 Mar 2017 15:15:34 -0600 Subject: [PATCH 27/31] findNodeHandle also accepts base react-native components (#15444) * findNodeHandle also accepts base react-native components We're also able to pass in base react-native components like View, TextView, etc. to findNodeHandle * Added static tests for findNodeHandle definition * Removed trailing whitespace * Okay NOW all trailing white-space is removed --- types/react-native/index.d.ts | 2 +- types/react-native/test/index.tsx | 37 ++++++++++++++++++++++++++----- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 3742bf5003..083c646be7 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -8418,7 +8418,7 @@ export function requireNativeComponent

( extraConfig?: {nativeOnly?: any} ): React.ComponentClass

; -export function findNodeHandle(componentOrHandle: null | number | React.Component): null | number; +export function findNodeHandle(componentOrHandle: null | number | React.Component | React.ComponentClass): null | number; export function processColor(color: any): number; diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 575693211e..45a5b510e9 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -25,6 +25,7 @@ import { View, ViewStyle, ViewPagerAndroid, + findNodeHandle } from 'react-native'; function testDimensions() { @@ -88,20 +89,43 @@ const stylesAlt = StyleSheet.create( } ) +class CustomView extends React.Component<{}, {}> { + + render() { + return ( + Custom View + ); + } + +} class Welcome extends React.Component { refs: { - [key: string]: any - rootView: View + [key: string]: any + rootView: View + customView: CustomView } testNativeMethods() { - // this.setNativeProps({}); + // this.setNativeProps({}); - const { rootView } = this.refs; + const { rootView } = this.refs; + + rootView.measure((x: number, y: number, width: number, height: number) => { + }); + + } + + testFindNodeHandle() { + + const { rootView, customView } = this.refs; + + let nativeComponentHandle = findNodeHandle(rootView); + + let customComponentHandle = findNodeHandle(customView); + + let fromHandle = findNodeHandle(customComponentHandle); - rootView.measure((x: number, y: number, width: number, height: number) => { - }); } render() { @@ -117,6 +141,7 @@ class Welcome extends React.Component { Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu + ) } From 68e0aea47ae978cf9abbed03c5a70776d9082c35 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 30 Mar 2017 14:25:38 -0700 Subject: [PATCH 28/31] Lint additional react packages (#15527) --- .../google-map-react-tests.tsx | 2 +- types/google-map-react/index.d.ts | 24 +++--- .../test/CustomColumnComponent.tsx | 2 +- types/navigation-react/index.d.ts | 2 +- types/qrcode.react/index.d.ts | 4 +- types/react-native-datepicker/index.d.ts | 4 +- .../react-native-datepicker-tests.tsx | 1 - .../index.d.ts | 77 +++++++++--------- ...ct-native-google-analytics-bridge-tests.ts | 29 ++++--- types/react-native/tslint.json | 2 + types/react-router-config/index.d.ts | 4 +- .../react-router-config-tests.tsx | 11 ++- types/react-router-dom/index.d.ts | 13 +--- types/react-router/test/ModalGallery.tsx | 1 - types/react-router/test/Recursive.tsx | 2 +- types/react-router/tslint.json | 8 +- types/react-router/v3/lib/IndexRoute.d.ts | 4 +- types/react-router/v3/lib/Route.d.ts | 4 +- .../v3/lib/applyRouterMiddleware.d.ts | 4 +- types/react-router/v3/react-router-tests.tsx | 12 +-- types/realm/index.d.ts | 78 +++++++++---------- 21 files changed, 139 insertions(+), 149 deletions(-) diff --git a/types/google-map-react/google-map-react-tests.tsx b/types/google-map-react/google-map-react-tests.tsx index 9cec9138e2..959bb8e68a 100644 --- a/types/google-map-react/google-map-react-tests.tsx +++ b/types/google-map-react/google-map-react-tests.tsx @@ -3,4 +3,4 @@ import * as React from 'react'; const center = { lat: 0, lng: 0 }; - +; diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index 45ce0341a6..98fb290e5d 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -15,7 +15,7 @@ export interface Options { styles?: any[]; scrollwheel?: boolean; panControl?: boolean; - mapTypeControl?: boolean, + mapTypeControl?: boolean; minZoomOverride?: boolean; minZoom?: number; gestureHandling?: string; @@ -59,18 +59,18 @@ export interface Props { margin?: any[]; debounced?: boolean; layerTypes?: string[]; - onClick?: ({x, y, lat, lng, event}: { x: number, y: number, lat: number, lng: number, event: any }) => any; - onChange?: ({ center, zoom, bounds, marginBounds }: { center: [number, number], zoom: number, bounds: [number, number, number, number], marginBounds: [number, number, number, number] }) => any; + onClick?({x, y, lat, lng, event}: { x: number, y: number, lat: number, lng: number, event: any }): any; + onChange?({ center, zoom, bounds, marginBounds }: { center: [number, number], zoom: number, bounds: [number, number, number, number], marginBounds: [number, number, number, number] }): any; resetBoundsOnResize?: boolean; - onChildClick?: (hoverKey: any, childProps: any) => void; - onChildMouseEnter?: (hoverKey: any, childProps: any) => void; - onChildMouseLeave?: (hoverKey: any, childProps: any) => void; - onZoomAnimationStart?: (args: any) => void; - onZoomAnimationEnd?: (args: any) => void; - onMapTypeIdChange?: (args: any) => void; - distanceToMouse?: (pt: {x: number, y: number}, mousePos: {x: number, y: number}) => void; - googleMapLoader?: (bootstrapURLKeys: any) => void; - onGoogleApiLoaded?: ({map, maps}: { map: any, maps: any }) => void; + onChildClick?(hoverKey: any, childProps: any): void; + onChildMouseEnter?(hoverKey: any, childProps: any): void; + onChildMouseLeave?(hoverKey: any, childProps: any): void; + onZoomAnimationStart?(args: any): void; + onZoomAnimationEnd?(args: any): void; + onMapTypeIdChange?(args: any): void; + distanceToMouse?(pt: {x: number, y: number}, mousePos: {x: number, y: number}): void; + googleMapLoader?(bootstrapURLKeys: any): void; + onGoogleApiLoaded?({map, maps}: { map: any, maps: any }): void; yesIWantToUseGoogleMapApiInternals?: boolean; } diff --git a/types/griddle-react/test/CustomColumnComponent.tsx b/types/griddle-react/test/CustomColumnComponent.tsx index e47b2c36bb..fff018dcfb 100644 --- a/types/griddle-react/test/CustomColumnComponent.tsx +++ b/types/griddle-react/test/CustomColumnComponent.tsx @@ -64,7 +64,7 @@ class CustomColumnComponentGrid extends React.Component { sortDescendingComponent={} customRowComponent={LinkComponent} /> ); - }; + } } export default CustomColumnComponentGrid; diff --git a/types/navigation-react/index.d.ts b/types/navigation-react/index.d.ts index 32ee6570f3..106b14bf43 100644 --- a/types/navigation-react/index.d.ts +++ b/types/navigation-react/index.d.ts @@ -22,7 +22,7 @@ interface LinkProps extends HTMLProps { /** * Handles Link click events */ - navigating?: (e: MouseEvent, domId: string, link: string) => boolean; + navigating?(e: MouseEvent, domId: string, link: string): boolean; /** * The State Navigator */ diff --git a/types/qrcode.react/index.d.ts b/types/qrcode.react/index.d.ts index c7a6b85d72..4de6ba60db 100644 --- a/types/qrcode.react/index.d.ts +++ b/types/qrcode.react/index.d.ts @@ -7,7 +7,7 @@ /// declare namespace qrcode { - export interface QRCodeProps { + interface QRCodeProps { value: string; size?: number; bgColor?: string; @@ -15,7 +15,7 @@ declare namespace qrcode { level?: "L"|"M"|"Q"|"H"; } - export type QRCode = React.ComponentClass; + type QRCode = React.ComponentClass; } declare const qrcode: qrcode.QRCode; diff --git a/types/react-native-datepicker/index.d.ts b/types/react-native-datepicker/index.d.ts index 232f2f56d1..ab3831dde8 100644 --- a/types/react-native-datepicker/index.d.ts +++ b/types/react-native-datepicker/index.d.ts @@ -18,9 +18,9 @@ interface DatePickerProps { cancelBtnText?: string; showIcon?: boolean; disabled?: boolean; - onDateChange?: (dateStr: string, date: Date) => void; + onDateChange?(dateStr: string, date: Date): void; placeholder?: string; - modalOnResponderTerminationRequest?: (e: any) => boolean; + modalOnResponderTerminationRequest?(e: any): boolean; is24Hour?: boolean; style?: any; customStyles?: any; diff --git a/types/react-native-datepicker/react-native-datepicker-tests.tsx b/types/react-native-datepicker/react-native-datepicker-tests.tsx index 22af7674d8..cce86882f8 100644 --- a/types/react-native-datepicker/react-native-datepicker-tests.tsx +++ b/types/react-native-datepicker/react-native-datepicker-tests.tsx @@ -39,4 +39,3 @@ export default class MyDatePicker extends React.Component<{}, MyDatePickerState> ); } } - diff --git a/types/react-native-google-analytics-bridge/index.d.ts b/types/react-native-google-analytics-bridge/index.d.ts index 38afee3512..1edf5514e2 100644 --- a/types/react-native-google-analytics-bridge/index.d.ts +++ b/types/react-native-google-analytics-bridge/index.d.ts @@ -3,8 +3,7 @@ // Definitions by: Huhuanming // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - export class GoogleAnalyticsTracker { +export class GoogleAnalyticsTracker { /** * Save all tracker related data that is needed to call native methods with proper data. * @param trackerId {String} @@ -22,13 +21,13 @@ * @param customDimensions {Object} * @returns {Object} */ - transformCustomDimensionsFieldsToIndexes(customDimensions: {}): void + transformCustomDimensionsFieldsToIndexes(customDimensions: {}): void; /** * Track the current screen/view * @param {String} screenName The name of the current screen */ - trackScreenView(screenName: string): void + trackScreenView(screenName: string): void; /** * Track an event that has occured @@ -36,14 +35,14 @@ * @param {String} action The event action * @param {Object} optionalValues An object containing optional label and value */ - trackEvent(category: string, action: string, optionalValues?: {}): void + trackEvent(category: string, action: string, optionalValues?: {}): void; /** * Track the current screen/view with custom dimension values * @param {String} screenName The name of the current screen * @param {Object} customDimensionValues An object containing custom dimension key/value pairs */ - trackScreenViewWithCustomDimensionValues(screenName: string, customDimensionValues: {}): void + trackScreenViewWithCustomDimensionValues(screenName: string, customDimensionValues: {}): void; /** * Track an event that has occured with custom dimension values @@ -57,7 +56,7 @@ action: string, optionalValues: {}, customDimensionValues: {}, - ): void + ): void; /** * Track an event that has occured @@ -65,7 +64,7 @@ * @param {Number} value The timing measurement in milliseconds * @param {Object} optionalValues An object containing optional name and label */ - trackTiming(category: string, value: number, optionalValues: {}): void + trackTiming(category: string, value: number, optionalValues: {}): void; /** * Track a purchase event. This uses the Enhanced Ecommerce GA feature. @@ -79,7 +78,7 @@ transaction: {}, eventCategory?: string, eventAction?: string, - ): void + ): void; /** * Track a purchase event. This uses the Enhanced Ecommerce GA feature. @@ -89,11 +88,11 @@ * @param {String} eventAction The event action, defaults to Purchase */ trackMultiProductsPurchaseEvent( - products: {}[], + products: Array<{}>, ransaction: {}, eventCategory?: string, eventAction?: string - ): void + ): void; /** * Track a purchase event with custom dimensions. This uses the Enhanced Ecommerce GA feature. @@ -104,31 +103,31 @@ * @param {Object} customDimensionValues An object containing custom dimension key/value pairs */ trackMultiProductsPurchaseEventWithCustomDimensionValues( - products: {}[], + products: Array<{}>, transaction: {}, eventCategory?: string, eventAction?: string, customDimensions?: {}, - ): void + ): void; /** * Track an exception * @param {String} error The description of the error * @param {Boolean} fatal A value indiciating if the error was fatal, defaults to false */ - trackException(error: string, fatal?: boolean): void + trackException(error: string, fatal?: boolean): void; /** * Sets the current userId for tracking. * @param {String} userId The current userId */ - setUser(userId: string): void + setUser(userId: string): void; /** * Sets if IDFA (identifier for advertisers) collection should be enabled * @param {Boolean} enabled Defaults to true */ - allowIDFA(enabled?: boolean): void + allowIDFA(enabled?: boolean): void; /** * Track a social interaction, Facebook, Twitter, etc. @@ -136,70 +135,70 @@ * @param {String} action * @param {String} targetUrl */ - trackSocialInteraction(network: string, action: string, targetUrl: string): void + trackSocialInteraction(network: string, action: string, targetUrl: string): void; /** * Sets if uncaught exceptions should be tracked * @param {Boolean} enabled */ - setTrackUncaughtExceptions(enabled: boolean): void + setTrackUncaughtExceptions(enabled: boolean): void; /** * Sets the trackers appName * The Bundle name is used by default * @param {String} appName */ - setAppName(appName: string): void + setAppName(appName: string): void; /** * Sets the trackers appVersion * @param {String} appVersion */ - setAppVersion(appVersion: string): void + setAppVersion(appVersion: string): void; /** * Sets if AnonymizeIp is enabled * If enabled the last octet of the IP address will be removed * @param {Boolean} enabled */ - setAnonymizeIp(enabled: string): void + setAnonymizeIp(enabled: string): void; /** * Sets tracker sampling rate. * @param {Float} sampleRatio Percentage 0 - 100 */ - setSamplingRate(sampleRatio: number): void - } + setSamplingRate(sampleRatio: number): void; +} - interface GAEvent { - event: string - payload: T - } +interface GAEvent { + event: string; + payload: T; +} - export class GoogleTagManager { +export class GoogleTagManager { /** * Call once to open the container for all subsequent static calls. * @param {String} containerId */ - static openContainerWithId(containerId: string): void + static openContainerWithId(containerId: string): void; /** * Retrieves a boolean value with the given key from the opened container. * @param {String} key */ - static boolForKey(key: string): boolean + static boolForKey(key: string): boolean; /** * Retrieves a string with the given key from the opened container. * @param {String} key */ - static stringForKey(key: string): string + static stringForKey(key: string): string; /** * Retrieves a number with the given key from the opened container. * @param {String} key */ - static doubleForKey(key: string): number + static doubleForKey(key: string): number; /** * push a datalayer event for Google Analytics through Google Tag Manager. @@ -207,16 +206,16 @@ * it must have at least one key "event" with event name * example: {event: "eventName", pageId: "/home"} */ - static pushDataLayerEvent(dictionary: GAEvent): void - } + static pushDataLayerEvent(dictionary: GAEvent): void; +} - export class GoogleAnalyticsSettings { +export class GoogleAnalyticsSettings { /** * Sets if OptOut is active and disables Google Analytics * This has to be set each time the App starts * @param {Boolean} enabled */ - static setOptOut(enabled: boolean): void + static setOptOut(enabled: boolean): void; /** * Sets the trackers dispatch interval @@ -224,12 +223,12 @@ * are sent to your tracker. * @param {Number} intervalInSeconds */ - static setDispatchInterval(intervalInSeconds: number): void + static setDispatchInterval(intervalInSeconds: number): void; /** * Sets if the tracker should have dry run enabled. * If dry run is enabled, no analytics data will be sent to your tracker. * @param {Boolean} enabled */ - static setDryRun(enabled: boolean): void - } + static setDryRun(enabled: boolean): void; +} diff --git a/types/react-native-google-analytics-bridge/react-native-google-analytics-bridge-tests.ts b/types/react-native-google-analytics-bridge/react-native-google-analytics-bridge-tests.ts index 3f9835fb83..8e365cb01d 100644 --- a/types/react-native-google-analytics-bridge/react-native-google-analytics-bridge-tests.ts +++ b/types/react-native-google-analytics-bridge/react-native-google-analytics-bridge-tests.ts @@ -2,27 +2,26 @@ import { GoogleAnalyticsTracker, GoogleTagManager, GoogleAnalyticsSettings, -} from './index' +} from 'react-native-google-analytics-bridge'; -const tracker = new GoogleAnalyticsTracker('GA_UA') +const tracker = new GoogleAnalyticsTracker('GA_UA'); -tracker.allowIDFA() -tracker.allowIDFA(true) +tracker.allowIDFA(); +tracker.allowIDFA(true); -tracker.setAnonymizeIp('1.1.1.1') +tracker.setAnonymizeIp('1.1.1.1'); -tracker.setAppName('name') +tracker.setAppName('name'); -GoogleTagManager.openContainerWithId('123') -GoogleTagManager.boolForKey('key') -GoogleTagManager.stringForKey('key') -GoogleTagManager.doubleForKey('key') +GoogleTagManager.openContainerWithId('123'); +GoogleTagManager.boolForKey('key'); +GoogleTagManager.stringForKey('key'); +GoogleTagManager.doubleForKey('key'); GoogleTagManager.pushDataLayerEvent({ event: 'event', payload: 'payload', -}) - -GoogleAnalyticsSettings.setOptOut(true) -GoogleAnalyticsSettings.setDispatchInterval(1000) -GoogleAnalyticsSettings.setDryRun(true) +}); +GoogleAnalyticsSettings.setOptOut(true); +GoogleAnalyticsSettings.setDispatchInterval(1000); +GoogleAnalyticsSettings.setDryRun(true); diff --git a/types/react-native/tslint.json b/types/react-native/tslint.json index b58d132131..7bd0b4c549 100644 --- a/types/react-native/tslint.json +++ b/types/react-native/tslint.json @@ -4,9 +4,11 @@ // Lowercase `object` is available in TypeScript 2.2 only. "ban-types": false, // Below are all TODO + "align": false, "array-type": false, "comment-format": false, "interface-over-type-literal": false, + "jsdoc-format": false, "no-misused-new": false, "no-consecutive-blank-lines": false, "no-empty-interface": false, diff --git a/types/react-router-config/index.d.ts b/types/react-router-config/index.d.ts index 7c7c218557..4979cbfd6b 100644 --- a/types/react-router-config/index.d.ts +++ b/types/react-router-config/index.d.ts @@ -23,9 +23,9 @@ export interface RouteConfig { export interface MatchedRoute { route: RouteConfig; - match: match + match: match; } -export function matchRoutes(routes: RouteConfig[], pathname: string): MatchedRoute[]; +export function matchRoutes(routes: RouteConfig[], pathname: string): Array>; export function renderRoutes(routes: RouteConfig[] | undefined): JSX.Element; diff --git a/types/react-router-config/react-router-config-tests.tsx b/types/react-router-config/react-router-config-tests.tsx index 47b54927b8..d1d28f93c0 100644 --- a/types/react-router-config/react-router-config-tests.tsx +++ b/types/react-router-config/react-router-config-tests.tsx @@ -8,13 +8,13 @@ const Root = ({ route }: RouteConfigComponentProps) => ( {/* child routes won't render without this */} {renderRoutes(route && route.routes)}

-) +); const Home = ({ route }: RouteConfigComponentProps) => (

Home

-) +); const Child = ({ route }: RouteConfigComponentProps) => (
@@ -22,13 +22,13 @@ const Child = ({ route }: RouteConfigComponentProps) => ( {/* child routes won't render without this */} {renderRoutes(route && route.routes)}
-) +); const GrandChild = () => (

Grand Child

-) +); // route config const routes: RouteConfig[] = [ @@ -44,7 +44,6 @@ const routes: RouteConfig[] = [ path: "/child/:id", component: Child, routes: [{ - path: "/child/:id/grand-child", component: GrandChild }] @@ -53,7 +52,7 @@ const routes: RouteConfig[] = [ } ]; -const branch: MatchedRoute<{}>[] = matchRoutes<{}>(routes, "/child/23"); +const branch: Array> = matchRoutes<{}>(routes, "/child/23"); // using the routes shown earlier, this returns // [ // routes[0], diff --git a/types/react-router-dom/index.d.ts b/types/react-router-dom/index.d.ts index 6ee8255cc7..6c480d46c0 100644 --- a/types/react-router-dom/index.d.ts +++ b/types/react-router-dom/index.d.ts @@ -24,41 +24,36 @@ declare module 'react-router-dom' { import * as React from 'react'; import * as H from 'history'; - interface BrowserRouterProps { basename?: string; - getUserConfirmation?: () => void; + getUserConfirmation?(): void; forceRefresh?: boolean; keyLength?: number; } class BrowserRouter extends React.Component {} - interface HashRouterProps { basename?: string; - getUserConfirmation?: () => void; + getUserConfirmation?(): void; hashType?: 'slash' | 'noslash' | 'hashbang'; } class HashRouter extends React.Component {} - interface LinkProps extends React.HTMLAttributes { to: H.LocationDescriptor; replace?: boolean; } class Link extends React.Component {} - interface NavLinkProps extends LinkProps { activeClassName?: string; activeStyle?: React.CSSProperties; exact?: boolean; strict?: boolean; - isActive?: (location: H.Location, props: any) => boolean; + isActive?(location: H.Location, props: any): boolean; } class NavLink extends React.Component {} - export { BrowserRouter, HashRouter, @@ -78,5 +73,5 @@ declare module 'react-router-dom' { matchPath, withRouter, RouterChildContext - } + }; } diff --git a/types/react-router/test/ModalGallery.tsx b/types/react-router/test/ModalGallery.tsx index ccaefe3adc..ae817e0cc9 100644 --- a/types/react-router/test/ModalGallery.tsx +++ b/types/react-router/test/ModalGallery.tsx @@ -17,7 +17,6 @@ import { // on top of the old screen. class ModalSwitch extends React.Component, void> { - // We can pass a location to that will tell it to // ignore the router's current location and use the location // prop instead. diff --git a/types/react-router/test/Recursive.tsx b/types/react-router/test/Recursive.tsx index 748e00a968..31b7c5fe29 100644 --- a/types/react-router/test/Recursive.tsx +++ b/types/react-router/test/Recursive.tsx @@ -15,7 +15,7 @@ const PEEPS = [ { id: 3, name: 'David', friends: [ 1, 2 ] } ] -const find = (id: number) => PEEPS.find(p => p.id == id) +const find = (id: number) => PEEPS.find(p => p.id === id) const RecursiveExample = () => ( diff --git a/types/react-router/tslint.json b/types/react-router/tslint.json index 0209984d72..a773d31b69 100644 --- a/types/react-router/tslint.json +++ b/types/react-router/tslint.json @@ -1,8 +1,14 @@ { "extends": "../tslint.json", "rules": { + "align": false, + "array-type": false, + "eofline": false, + "no-consecutive-blank-lines": false, "no-empty-interface": false, + "prefer-method-signature": false, "void-return": false, - "no-single-declare-module": false + "no-single-declare-module": false, + "semicolon": false } } diff --git a/types/react-router/v3/lib/IndexRoute.d.ts b/types/react-router/v3/lib/IndexRoute.d.ts index 44b8c82919..9c82775c12 100644 --- a/types/react-router/v3/lib/IndexRoute.d.ts +++ b/types/react-router/v3/lib/IndexRoute.d.ts @@ -15,8 +15,8 @@ type ComponentsCallback = (err: any, components: RouteComponents) => any; export interface IndexRouteProps { component?: RouteComponent; components?: RouteComponents; - getComponent?: (nextState: RouterState, callback: ComponentCallback) => void; - getComponents?: (nextState: RouterState, callback: ComponentsCallback) => void; + getComponent?(nextState: RouterState, callback: ComponentCallback): void; + getComponents?(nextState: RouterState, callback: ComponentsCallback): void; onEnter?: EnterHook; onChange?: ChangeHook; onLeave?: LeaveHook; diff --git a/types/react-router/v3/lib/Route.d.ts b/types/react-router/v3/lib/Route.d.ts index 9063ac8b45..15aafebc75 100644 --- a/types/react-router/v3/lib/Route.d.ts +++ b/types/react-router/v3/lib/Route.d.ts @@ -25,7 +25,7 @@ type RoutesCallback = (err: any, routesArray: PlainRoute[]) => void; export interface PlainRoute extends RouteProps { childRoutes?: PlainRoute[]; - getChildRoutes?: (partialNextState: LocationState, callback: RoutesCallback) => void; + getChildRoutes?(partialNextState: LocationState, callback: RoutesCallback): void; indexRoute?: PlainRoute; - getIndexRoute?: (partialNextState: LocationState, callback: RouteCallback) => void; + getIndexRoute?(partialNextState: LocationState, callback: RouteCallback): void; } diff --git a/types/react-router/v3/lib/applyRouterMiddleware.d.ts b/types/react-router/v3/lib/applyRouterMiddleware.d.ts index e4d023a792..40872cd77a 100644 --- a/types/react-router/v3/lib/applyRouterMiddleware.d.ts +++ b/types/react-router/v3/lib/applyRouterMiddleware.d.ts @@ -2,8 +2,8 @@ import { RouteComponent } from "react-router"; import RouterContext from "react-router/lib/RouterContext"; export interface Middleware { - renderRouterContext?: (previous: RouterContext, props: any) => RouterContext; - renderRouteComponent?: (previous: RouteComponent, props: any) => RouteComponent; + renderRouterContext?(previous: RouterContext, props: any): RouterContext; + renderRouteComponent?(previous: RouteComponent, props: any): RouteComponent; } export default function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: any) => RouterContext; diff --git a/types/react-router/v3/react-router-tests.tsx b/types/react-router/v3/react-router-tests.tsx index 314c78c6ce..084b21ac22 100644 --- a/types/react-router/v3/react-router-tests.tsx +++ b/types/react-router/v3/react-router-tests.tsx @@ -49,7 +49,6 @@ interface MasterContext { } class Master extends Component { - static contextTypes: ValidationMap = { router: routerShape }; @@ -57,7 +56,7 @@ class Master extends Component { context: MasterContext; navigate() { - var router = this.context.router; + const router = this.context.router; router.push("/users"); router.push({ pathname: "/users/12", @@ -73,7 +72,6 @@ class Master extends Component {

{this.props.children}

; } - } interface DashboardProps { @@ -84,7 +82,7 @@ class Dashboard extends React.Component { static staticMethodToBeHoisted(): void {} navigate() { - var router = this.props.router; + const router = this.props.router; router.push("/users"); router.push({ pathname: "/users/12", @@ -98,7 +96,6 @@ class Dashboard extends React.Component { This is a dashboard
; } - } const DashboardWithRouter = withRouter(Dashboard); @@ -106,29 +103,24 @@ const DashboardWithRouter = withRouter(Dashboard); DashboardWithRouter.staticMethodToBeHoisted(); class NotFound extends React.Component<{}, {}> { - render() { return
This path does not exists
; } - } type UsersProps = RouteComponentProps<{}, {}>; class Users extends React.Component { - render() { const { location, params, route, routes, router, routeParams } = this.props; return
This is a user list
; } - } - ReactDOM.render(( diff --git a/types/realm/index.d.ts b/types/realm/index.d.ts index 5f48d75ff7..993f0bcc0f 100644 --- a/types/realm/index.d.ts +++ b/types/realm/index.d.ts @@ -6,15 +6,15 @@ declare namespace Realm { /** - * PropertyType - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~PropertyType } - */ + * PropertyType + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~PropertyType } + */ type PropertyType = string | 'bool' | 'int' | 'float' | 'double' | 'string' | 'data' | 'date' | 'list'; /** - * ObjectSchemaProperty - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectSchemaProperty } - */ + * ObjectSchemaProperty + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectSchemaProperty } + */ interface ObjectSchemaProperty { type: PropertyType; objectType?: string; @@ -29,9 +29,9 @@ declare namespace Realm { } /** - * ObjectSchema - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectSchema } - */ + * ObjectSchema + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectSchema } + */ interface ObjectSchema { name: string; primaryKey?: string; @@ -39,17 +39,17 @@ declare namespace Realm { } /** - * ObjectClass - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectClass } - */ + * ObjectClass + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectClass } + */ interface ObjectClass { schema: ObjectSchema; } /** - * ObjectType - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectType } - */ + * ObjectType + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~ObjectType } + */ interface ObjectType { type: ObjectClass; } @@ -60,9 +60,9 @@ declare namespace Realm { } /** - * realm configuration - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~Configuration } - */ + * realm configuration + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.html#~Configuration } + */ interface Configuration { encryptionKey?: any; migration?: any; @@ -79,9 +79,9 @@ declare namespace Realm { } /** - * SortDescriptor - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Collection.html#~SortDescriptor } - */ + * SortDescriptor + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Collection.html#~SortDescriptor } + */ type SortDescriptor = string | [string, boolean] | any[]; /** @@ -99,9 +99,9 @@ declare namespace Realm { } /** - * Collection - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Collection.html } - */ + * Collection + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Collection.html } + */ interface Collection { readonly length: number; @@ -237,9 +237,9 @@ declare namespace Realm { } /** - * Object - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Object.html } - */ + * Object + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Object.html } + */ interface Object { /** * @returns boolean @@ -248,9 +248,9 @@ declare namespace Realm { } /** - * List - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.List.html } - */ + * List + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.List.html } + */ interface List extends Collection { /** * @returns T @@ -284,9 +284,9 @@ declare namespace Realm { } /** - * Results - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Results.html } - */ + * Results + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Results.html } + */ type Results = Collection; /** @@ -341,15 +341,15 @@ declare namespace Realm { } /** - * LogLevel - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.html#~LogLevel } - */ + * LogLevel + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.html#~LogLevel } + */ type LogLevelType = string | 'error' | 'info' | 'defug'; /** - * Sync - * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.html } - */ + * Sync + * @see { @link https://realm.io/docs/javascript/latest/api/Realm.Sync.html } + */ interface Sync { User: User; Session: Session; From d7218e2fe3345e43c1bb90649abec084c71a8592 Mon Sep 17 00:00:00 2001 From: Justin Firth Date: Thu, 30 Mar 2017 18:13:46 -0400 Subject: [PATCH 29/31] Support SVG elements; Remove extraneous definition --- types/hyperscript/hyperscript-tests.ts | 19 +++++++++++++++---- types/hyperscript/index.d.ts | 11 ++++------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/types/hyperscript/hyperscript-tests.ts b/types/hyperscript/hyperscript-tests.ts index 02ea158977..687a2591c1 100644 --- a/types/hyperscript/hyperscript-tests.ts +++ b/types/hyperscript/hyperscript-tests.ts @@ -59,14 +59,25 @@ h2.cleanup() /* Polymorphic type tests */ -// determine proper HTMLElement type from tagName -let test1: HTMLCanvasElement = h('canvas'); +// fall back to Element when in doubt +let fallbackTest = h('canvas#test3'); + +// determine proper Element type from tagName +let htmlTest1: HTMLCanvasElement = h('canvas'); // allow coercion of decorated tagName to proper type -let test2: HTMLCanvasElement = h('canvas#test2'); +let htmlTest2: HTMLCanvasElement = h('canvas#test2'); + +// if you need it to be an HTMLElement, you must coerce +let htmlTest3 = h('canvas#test3'); + +// support SVG elements +let svgTest1 = h('svg'); + +// allow coercions on SVG elements +let svgTest2 = h('svg#test5'); // inline coercion if you were feeling pedantic -// example h('div#page', h('div#header', h('h1.classy', 'h', { style: {'background-color': '#22f'} }))); \ No newline at end of file diff --git a/types/hyperscript/index.d.ts b/types/hyperscript/index.d.ts index b4384ba302..cec67e56ab 100644 --- a/types/hyperscript/index.d.ts +++ b/types/hyperscript/index.d.ts @@ -1,18 +1,15 @@ // Type definitions for hyperscript // Project: https://github.com/dominictarr/hyperscript -// Definitions by: Mike Linkovich +// Definitions by: Mike Linkovich , Justin Firth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 declare module 'hyperscript' { interface HyperScript { - /** Creates a typed HTMLElement */ - (tagName: T, attrs?: Object, ...children: any[]): HTMLElementTagNameMap[T]; - /** Creates a typed HTMLElement via coercion */ - (tagName: string, attrs?: Object, ...children: any[]): T; - /** Creates an HTMLElement */ - (tagName: T, attrs?: Object, ...children: any[]): HTMLElement; + /** Creates an Element */ + (tagName: T, attrs?: Object, ...children: any[]): ElementTagNameMap[T]; + (tagName: string, attrs?: Object, ...children: any[]): T; /** Cleans up any event handlers created by this hyperscript context */ cleanup(): void; /** Creates a new hyperscript context */ From ff0d451b567d3ed245e6598c0eb2f3bc9b93d310 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 30 Mar 2017 15:33:16 -0700 Subject: [PATCH 30/31] Fix various lint errors (#15529) --- types/artyom.js/artyom.js-tests.ts | 2 +- types/artyom.js/index.d.ts | 40 +-- types/bigi/bigi-tests.ts | 8 +- types/bitcoinjs-lib/bitcoinjs-lib-tests.ts | 34 +- types/blacklist/blacklist-tests.ts | 4 +- types/clndr/clndr-tests.ts | 2 +- types/cookies/cookies-tests.ts | 6 +- types/cpy/cpy-tests.ts | 3 +- types/cpy/index.d.ts | 5 +- types/csvtojson/index.d.ts | 6 +- types/csvtojson/tslint.json | 7 +- types/del/del-tests.ts | 3 +- types/dockerode/dockerode-tests.ts | 2 +- types/dockerode/index.d.ts | 1 - types/ecurve/ecurve-tests.ts | 22 +- types/f1/f1-tests.ts | 4 +- types/f1/index.d.ts | 4 +- types/falcor/index.d.ts | 66 ++-- types/fetch.io/index.d.ts | 24 +- types/globule/index.d.ts | 2 +- types/google-protobuf/tslint.json | 15 +- types/inert/index.d.ts | 2 +- .../is-absolute-url/is-absolute-url-tests.ts | 2 +- types/isbn-utils/index.d.ts | 1 - types/isbn-utils/isbn-utils-tests.ts | 1 - types/jsnlog/index.d.ts | 26 +- types/koa-json-error/index.d.ts | 6 +- types/koa-jwt/index.d.ts | 2 +- types/later/index.d.ts | 86 +++--- types/later/later-tests.ts | 68 ++-- types/memcached/memcached-tests.ts | 34 +- types/mock-raf/index.d.ts | 6 +- types/mock-raf/mock-raf-tests.ts | 2 +- types/nedb/index.d.ts | 6 +- types/optics-agent/index.d.ts | 2 +- types/parsimmon/index.d.ts | 8 +- types/progressbar/progressbar-tests.ts | 6 +- types/pump/index.d.ts | 4 +- types/raven/index.d.ts | 59 ++-- types/raven/raven-tests.ts | 7 +- types/rheostat/index.d.ts | 15 +- types/sha1/sha1-tests.ts | 25 +- types/sharp/sharp-tests.ts | 2 +- types/slimerjs/index.d.ts | 69 ++--- types/slimerjs/slimerjs-tests.ts | 25 +- types/sshpk/index.d.ts | 128 ++++---- types/sshpk/sshpk-tests.ts | 1 - types/strip-bom/strip-bom-tests.ts | 2 +- types/swiper/index.d.ts | 73 +++-- types/swiper/swiper-tests.ts | 141 +++++---- types/swiper/v2/index.d.ts | 25 +- types/swiper/v2/swiper-tests.ts | 58 ++-- types/tcomb/tcomb-tests.ts | 2 +- types/uikit/index.d.ts | 105 +++---- types/uikit/uikit-tests.ts | 136 ++++---- types/uuid-js/uuid-js-tests.ts | 22 +- types/vis/index.d.ts | 64 ++-- types/vis/vis-tests.ts | 44 +-- types/webpack-chain/index.d.ts | 290 +++++++++--------- types/webpack-chain/webpack-chain-tests.ts | 2 +- 60 files changed, 838 insertions(+), 979 deletions(-) diff --git a/types/artyom.js/artyom.js-tests.ts b/types/artyom.js/artyom.js-tests.ts index 67e5908883..d301c9a6f4 100644 --- a/types/artyom.js/artyom.js-tests.ts +++ b/types/artyom.js/artyom.js-tests.ts @@ -29,4 +29,4 @@ artyom.getVoices(); artyom.getLanguage(); // Get the artyom.js version -artyom.getVersion(); \ No newline at end of file +artyom.getVersion(); diff --git a/types/artyom.js/index.d.ts b/types/artyom.js/index.d.ts index ae120015ca..b4f85781c6 100644 --- a/types/artyom.js/index.d.ts +++ b/types/artyom.js/index.d.ts @@ -22,16 +22,16 @@ interface SpeechRecognition extends EventTarget { start(): void; stop(): void; abort(): void; - onaudiostart: (ev: Event) => any; - onsoundstart: (ev: Event) => any; - onspeechstart: (ev: Event) => any; - onspeechend: (ev: Event) => any; - onsoundend: (ev: Event) => any; - onresult: (ev: SpeechRecognitionEvent) => any; - onnomatch: (ev: SpeechRecognitionEvent) => any; - onerror: (ev: SpeechRecognitionError) => any; - onstart: (ev: Event) => any; - onend: (ev: Event) => any; + onaudiostart(ev: Event): any; + onsoundstart(ev: Event): any; + onspeechstart(ev: Event): any; + onspeechend(ev: Event): any; + onsoundend(ev: Event): any; + onresult(ev: SpeechRecognitionEvent): any; + onnomatch(ev: SpeechRecognitionEvent): any; + onerror(ev: SpeechRecognitionError): any; + onstart(ev: Event): any; + onend(ev: Event): any; } interface SpeechRecognitionStatic { @@ -106,7 +106,7 @@ interface SpeechSynthesis extends EventTarget { speaking: boolean; paused: boolean; - onvoiceschanged: (ev: Event) => any; + onvoiceschanged(ev: Event): any; speak(utterance: SpeechSynthesisUtterance): void; cancel(): void; pause(): void; @@ -128,13 +128,13 @@ interface SpeechSynthesisUtterance extends EventTarget { rate: number; pitch: number; - onstart: (ev: SpeechSynthesisEvent) => any; - onend: (ev: SpeechSynthesisEvent) => any; - onerror: (ev: SpeechSynthesisErrorEvent) => any; - onpause: (ev: SpeechSynthesisEvent) => any; - onresume: (ev: SpeechSynthesisEvent) => any; - onmark: (ev: SpeechSynthesisEvent) => any; - onboundary: (ev: SpeechSynthesisEvent) => any; + onstart(ev: SpeechSynthesisEvent): any; + onend(ev: SpeechSynthesisEvent): any; + onerror(ev: SpeechSynthesisErrorEvent): any; + onpause(ev: SpeechSynthesisEvent): any; + onresume(ev: SpeechSynthesisEvent): any; + onmark(ev: SpeechSynthesisEvent): any; + onboundary(ev: SpeechSynthesisEvent): any; } interface SpeechSynthesisUtteranceStatic { @@ -211,7 +211,7 @@ declare namespace Artyom { /** Triggers of the command */ indexes: string[]; /** Logic to execute when the command is triggered */ - action: (i: number, wildcard?: string, full?: string) => void; + action(i: number, wildcard?: string, full?: string): void; /** Description of the command */ description?: string; /** Flag to specify is a command is either normal or smart */ @@ -502,7 +502,7 @@ declare namespace Artyom { /** * Method to bla, bla, bla... */ - static getInstance(): ArtyomJS + static getInstance(): ArtyomJS; } } diff --git a/types/bigi/bigi-tests.ts b/types/bigi/bigi-tests.ts index 70569bb919..ef9d7421d3 100644 --- a/types/bigi/bigi-tests.ts +++ b/types/bigi/bigi-tests.ts @@ -1,9 +1,9 @@ import BigInteger = require('bigi'); -var b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"); -var b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); +const b1 = BigInteger.fromHex("188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"); +const b2 = BigInteger.fromHex("07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); -var b3 = b1.multiply(b2); +const b3 = b1.multiply(b2); console.log(b3.toHex()); -// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132 \ No newline at end of file +// => ae499bfe762edfb416d0ce71447af67ff33d1760cbebd70874be1d7a5564b0439a59808cb1856a91974f7023f72132 diff --git a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts index bdaee3ee83..7267fe5d26 100644 --- a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts +++ b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -3,9 +3,9 @@ import bigi = require('bigi'); import bitcoin = require('bitcoinjs-lib'); -declare var it: any; -declare var describe: any; -declare var assert: any; +declare const it: any; +declare const describe: any; +declare const assert: any; describe('bitcoinjs-lib (basic)', () => { it('can generate a random bitcoin address', () => { @@ -13,18 +13,18 @@ describe('bitcoinjs-lib (basic)', () => { function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } // generate random keyPair - var keyPair = bitcoin.ECPair.makeRandom({ rng }); - var address = keyPair.getAddress(); + const keyPair = bitcoin.ECPair.makeRandom({ rng }); + const address = keyPair.getAddress(); assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64'); }); it('can generate an address from a SHA256 hash', () => { - var hash = bitcoin.crypto.sha256('correct horse battery staple'); - var d = bigi.fromBuffer(hash); + const hash = bitcoin.crypto.sha256('correct horse battery staple'); + const d = bigi.fromBuffer(hash); - var keyPair = new bitcoin.ECPair(d); - var address = keyPair.getAddress(); + const keyPair = new bitcoin.ECPair(d); + const address = keyPair.getAddress(); assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8'); }); @@ -33,26 +33,26 @@ describe('bitcoinjs-lib (basic)', () => { // for testing only function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } - var litecoin = bitcoin.networks.litecoin; + const litecoin = bitcoin.networks.litecoin; - var keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng }); - var wif = keyPair.toWIF(); - var address = keyPair.getAddress(); + const keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng }); + const wif = keyPair.toWIF(); + const address = keyPair.getAddress(); assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn'); assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS'); }); it('can import an address via WIF', () => { - var keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct'); - var address = keyPair.getAddress(); + const keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct'); + const address = keyPair.getAddress(); assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31'); }); it('can create a Transaction', () => { - var keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'); - var tx = new bitcoin.TransactionBuilder(); + const keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'); + const tx = new bitcoin.TransactionBuilder(); tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0); tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000); diff --git a/types/blacklist/blacklist-tests.ts b/types/blacklist/blacklist-tests.ts index 0f465dd62a..5c5803c45c 100644 --- a/types/blacklist/blacklist-tests.ts +++ b/types/blacklist/blacklist-tests.ts @@ -1,4 +1,4 @@ -var someInput = { a: 1, b: 2, c: 3 }; +const someInput = { a: 1, b: 2, c: 3 }; import blacklist = require('blacklist'); @@ -10,4 +10,4 @@ blacklist(someInput, { b: false, // b will be in the result c: 1 > 2 // false, therefore c will be in the result }); -// => { b: 2, c: 3 } \ No newline at end of file +// => { b: 2, c: 3 } diff --git a/types/clndr/clndr-tests.ts b/types/clndr/clndr-tests.ts index 018d9a6000..07bff7f9e4 100644 --- a/types/clndr/clndr-tests.ts +++ b/types/clndr/clndr-tests.ts @@ -89,4 +89,4 @@ myCalendar .setEvents([]) .addEvents([]) .removeEvents(event => event.id === 'idToRemove') - .destroy(); \ No newline at end of file + .destroy(); diff --git a/types/cookies/cookies-tests.ts b/types/cookies/cookies-tests.ts index 112246907c..c65bcbd4aa 100644 --- a/types/cookies/cookies-tests.ts +++ b/types/cookies/cookies-tests.ts @@ -3,9 +3,9 @@ import * as http from 'http'; const server = http.createServer((req, res) => { const cookies = new Cookies(req, res); - let unsigned: string, - signed: string, - tampered: string; + let unsigned: string; + let signed: string; + let tampered: string; if (req.url === "/set") { cookies diff --git a/types/cpy/cpy-tests.ts b/types/cpy/cpy-tests.ts index 047c9943bf..3bc0cbb32a 100644 --- a/types/cpy/cpy-tests.ts +++ b/types/cpy/cpy-tests.ts @@ -4,7 +4,6 @@ cpy(['src/*.png', '!src/goat.png'], 'dist').then(() => { console.log('files copied'); }); - cpy('foo.js', 'destination', { rename: basename => `prefix-${basename}` -}); \ No newline at end of file +}); diff --git a/types/cpy/index.d.ts b/types/cpy/index.d.ts index 039d0b84fb..8ef585250b 100644 --- a/types/cpy/index.d.ts +++ b/types/cpy/index.d.ts @@ -4,4 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = cpy; -declare function cpy(src: string | string[], dest: string, opts?: { cwd?: string, parents?: boolean, rename?: (s: string) => string }): Promise; +declare function cpy( + src: string | string[], + dest: string, + opts?: { cwd?: string, parents?: boolean, rename?(s: string): string }): Promise; diff --git a/types/csvtojson/index.d.ts b/types/csvtojson/index.d.ts index 504311f47a..c0ff659dd3 100644 --- a/types/csvtojson/index.d.ts +++ b/types/csvtojson/index.d.ts @@ -183,7 +183,7 @@ declare namespace csvtojson { * @param {string} str the string to convert * @return {Converter} returns this object for chaining */ - fromString(str: string): this + fromString(str: string): this; /** * Reads in a CSV from a string. @@ -197,7 +197,7 @@ declare namespace csvtojson { * @param {string} filePath the path to the CSV file * @return {Converter} returns this object for chaining */ - fromFile(filePath: string): this + fromFile(filePath: string): this; /** * Reads in a CSV from a file. @@ -211,7 +211,7 @@ declare namespace csvtojson { * @param {Stream} stream the stream * @return {Converter} returns this object for chaining */ - fromStream(stream: NodeJS.ReadableStream): this + fromStream(stream: NodeJS.ReadableStream): this; /** * Reads in a CSV from a stream. diff --git a/types/csvtojson/tslint.json b/types/csvtojson/tslint.json index 377cc837d4..b0e7084e94 100644 --- a/types/csvtojson/tslint.json +++ b/types/csvtojson/tslint.json @@ -1 +1,6 @@ -{ "extends": "../tslint.json" } +{ + "extends": "../tslint.json", + "rules": { + "ban-types": false + } +} diff --git a/types/del/del-tests.ts b/types/del/del-tests.ts index 071fdcc3ad..09702c4b39 100644 --- a/types/del/del-tests.ts +++ b/types/del/del-tests.ts @@ -1,6 +1,6 @@ import del = require("del"); -var paths = ["build", "dist/**/*.js"]; +let paths = ["build", "dist/**/*.js"]; del(["tmp/*.js", "!tmp/unicorn.js"]); @@ -26,7 +26,6 @@ del("tmp/*.js", {force: true}).then((paths: string[]) => { console.log('Deleted files/folders:\n', paths.join('\n')); }); -var paths: string[]; paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"]); paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); diff --git a/types/dockerode/dockerode-tests.ts b/types/dockerode/dockerode-tests.ts index 3bd1c30097..b010b68fe0 100644 --- a/types/dockerode/dockerode-tests.ts +++ b/types/dockerode/dockerode-tests.ts @@ -55,4 +55,4 @@ docker.createContainer({ Tty: true }, (err, container) => { container.start((err, data) => { // NOOP }); -}); \ No newline at end of file +}); diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index 968199436a..e35cd8b466 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -8,7 +8,6 @@ import * as stream from 'stream'; import * as events from 'events'; - declare namespace Dockerode { interface Container { inspect(options: {}, callback: Callback): void; diff --git a/types/ecurve/ecurve-tests.ts b/types/ecurve/ecurve-tests.ts index ced84ef8aa..e7f730446b 100644 --- a/types/ecurve/ecurve-tests.ts +++ b/types/ecurve/ecurve-tests.ts @@ -4,8 +4,7 @@ import crypto = require('crypto'); import BigInteger = require('bigi'); import cs = require('coinstring'); - -var ecparams = ecurve.getCurveByName('secp256k1'); +let ecparams = ecurve.getCurveByName('secp256k1'); console.log(ecparams.n.toString(16)); // => fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 console.log(ecparams.G.getEncoded().toString('hex')); // getEncoded() returns type 'Buffer' instead of 'BigInteger' @@ -13,15 +12,14 @@ console.log(ecparams.G.getEncoded().toString('hex')); // getEncoded() returns ty console.log(ecparams.h.toString(16)); // => 1 +const privateKey = new Buffer("1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd", 'hex'); -var privateKey = new Buffer("1184cd2cdd640ca42cfc3a091c51d549b2f016d454b2774019c2b2d2e08529fd", 'hex'); +ecparams = ecurve.getCurveByName('secp256k1'); +const curvePt = ecparams.G.multiply(BigInteger.fromBuffer(privateKey)); +const x = curvePt.affineX.toBuffer(32); +const y = curvePt.affineY.toBuffer(32); -var ecparams = ecurve.getCurveByName('secp256k1'); -var curvePt = ecparams.G.multiply(BigInteger.fromBuffer(privateKey)); -var x = curvePt.affineX.toBuffer(32); -var y = curvePt.affineY.toBuffer(32); - -var publicKey = Buffer.concat([new Buffer([0x04]), x, y]); +let publicKey = Buffer.concat([new Buffer([0x04]), x, y]); console.log(publicKey.toString('hex')); // => 04d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495 @@ -35,8 +33,8 @@ publicKey = curvePt.getEncoded(true); // true forces compressed public key console.log(publicKey.toString('hex')); // => 03d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6f -var sha = crypto.createHash('sha256').update(publicKey).digest(); -var pubkeyHash = crypto.createHash('rmd160').update(sha).digest(); +const sha = crypto.createHash('sha256').update(publicKey).digest(); +const pubkeyHash = crypto.createHash('rmd160').update(sha).digest(); // pubkeyHash of compressed public key console.log(pubkeyHash.toString('hex')); @@ -50,4 +48,4 @@ console.log(cs.encode(privateKey, 0x80)); // <--- 0x80 is for private addresses // => 5Hx15HFGyep2CfPxsJKe2fXJsCVn5DEiyoeGGF6JZjGbTRnqfiD console.log(cs.encode(Buffer.concat([privateKey, new Buffer([0])]), 0x80)); // <-- compressed private address -// => KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5aqzCxDY \ No newline at end of file +// => KwomKti1X3tYJUUMb1TGSM2mrZk1wb1aHisUNHCQXTZq5aqzCxDY diff --git a/types/f1/f1-tests.ts b/types/f1/f1-tests.ts index 8bfbbfb080..0934b097e3 100644 --- a/types/f1/f1-tests.ts +++ b/types/f1/f1-tests.ts @@ -1,5 +1,5 @@ import F1 = require("f1"); -var ui = F1(); +const ui = F1(); ui.states({ out: { @@ -23,8 +23,6 @@ ui.states({ } }); - - ui.transitions( [ { from: 'idle', to: 'rollOver', animation: { duration: 0.25 } }, { from: 'rollOver', to: 'idle', animation: { duration: 0.1 } } diff --git a/types/f1/index.d.ts b/types/f1/index.d.ts index 82c5cf8c4d..f463c1e97e 100644 --- a/types/f1/index.d.ts +++ b/types/f1/index.d.ts @@ -6,8 +6,8 @@ /// interface F1Options { - onState?: (...args: any[]) => void; - onUpdate?: (...args: any[]) => void; + onState?(...args: any[]): void; + onUpdate?(...args: any[]): void; name: string; diff --git a/types/falcor/index.d.ts b/types/falcor/index.d.ts index 44d9118ca2..f5cea280a0 100644 --- a/types/falcor/index.d.ts +++ b/types/falcor/index.d.ts @@ -39,21 +39,21 @@ export { * Every DataSource is associated with a single JSON Graph object. * Models execute JSON Graph operations (get, set, and call) to retrieve values from the DataSource’s JSON Graph object. * DataSources may retrieve JSON Graph information from anywhere, including device memory, a remote machine, or even a lazily-run computation. - **/ + */ export abstract class DataSource { /** * The get method retrieves values from the DataSource's associated JSONGraph object. - **/ + */ get(pathSets: PathSet[]): Observable; /** * The set method accepts values to set in the DataSource's associated JSONGraph object. - **/ + */ set(jsonGraphEnvelope: JSONGraphEnvelope): Observable; /** * Invokes a function in the DataSource's JSONGraph object. - **/ + */ call(functionPath: Path, args?: any[], refSuffixes?: PathSet[], thisPaths?: PathSet[]): Observable; } @@ -73,30 +73,30 @@ interface ModelOptions { /** * This callback is invoked when the Model's cache is changed. - **/ + */ type ModelOnChange = () => void; /** * This function is invoked on every JSONGraph Error retrieved from the DataSource. This function allows Error objects to be transformed before being stored in the Model's cache. - **/ + */ type ModelErrorSelector = (jsonGraphError: any) => any; /** * This function is invoked every time a value in the Model cache is about to be replaced with a new value. * If the function returns true, the existing value is replaced with a new value and the version flag on all of the value's ancestors in the tree are incremented. - **/ + */ type ModelComparator = (existingValue: any, newValue: any) => boolean; /** * A Model object is used to execute commands against a {@link JSONGraph} object * {@link Model}s can work with a local JSONGraph cache, or it can work with a remote {@link JSONGraph} object through a {@link DataSource}. - **/ + */ export class Model { constructor(options?: ModelOptions); /** * The get method retrieves several {@link Path}s or {@link PathSet}s from a {@link Model}. The get method loads each value into a JSON object and returns in a ModelResponse. - **/ + */ get(...path: Array): ModelResponse>; get(...path: Array): ModelResponse>; @@ -104,7 +104,7 @@ export class Model { * Sets the value at one or more places in the JSONGraph model. * The set method accepts one or more {@link PathValue}s, each of which is a combination of a location in the document and the value to place there. * In addition to accepting {@link PathValue}s, the set method also returns the values after the set operation is complete. - **/ + */ set(...args: PathValue[]): ModelResponse>; set(...args: PathValue[]): ModelResponse>; set(jsonGraph: JSONGraph): ModelResponse>; @@ -112,12 +112,12 @@ export class Model { /** * The preload method retrieves several {@link Path}s or {@link PathSet}s from a {@link Model} and loads them into the Model cache. - **/ + */ preload(...path: PathSet[]): void; /** * Invokes a function in the JSON Graph. - **/ + */ // NOTE: In http://netflix.github.io/falcor/doc/Model.html#call, it says that refPaths should be an PathSet[]. // However, model implementation returns an error with setting refPaths as PathSet[] and it works with refPaths as PathSet. // So refPaths is defined as a PathSet in this .d.ts. @@ -126,7 +126,7 @@ export class Model { /** * The invalidate method synchronously removes several {@link Path}s or {@link PathSet}s from a {@link Model} cache. - **/ + */ invalidate(...path: PathSet[]): void; /** @@ -136,78 +136,78 @@ export class Model { * - Expose only a fragment of the {@link JSONGraph} to components, rather than the entire graph * - Hide the location of a {@link JSONGraph} fragment from components * - Optimize for executing multiple operations and path looksup at/below the same location in the {@link JSONGraph} - **/ + */ deref(responseObject: any): Model; /** * Get data for a single {@link Path}. - **/ + */ getValue(path: string | Path): ModelResponse; getValue(path: string | Path): ModelResponse; /** * Set value for a single {@link Path}. - **/ + */ setValue(path: string | Path, value: any): ModelResponse; setValue(path: string | Path, value: any): ModelResponse; /** * Set the local cache to a {@link JSONGraph} fragment. This method can be a useful way of mocking a remote document, or restoring the local cache from a previously stored state. - **/ + */ setCache(jsonGraph: JSONGraph): void; /** * Get the local {@link JSONGraph} cache. This method can be a useful to store the state of the cache. - **/ + */ getCache(...path: PathSet[]): JSONGraph; /** * Retrieves a number which is incremented every single time a value is changed underneath the Model or the object at an optionally-provided Path beneath the Model. - **/ + */ getVersion(path?: Path): number; /** * Returns a clone of the {@link Model} that enables batching. Within the configured time period, paths for get operations are collected and sent to the {@link DataSource} in a batch. * Batching can be more efficient if the {@link DataSource} access the network, potentially reducing the number of HTTP requests to the server. - **/ + */ batch(schedulerOrDelay?: number | Scheduler): Model; // FIXME what's a valid type for scheduler? /** * Returns a clone of the {@link Model} that disables batching. This is the default mode. Each get operation will be executed on the {@link DataSource} separately. - **/ + */ unbatch(): Model; /** * Returns a clone of the {@link Model} that treats errors as values. Errors will be reported in the same callback used to report data. * Errors will appear as objects in responses, rather than being sent to the {@link Observable~onErrorCallback} callback of the {@link ModelResponse}. - **/ + */ treatErrorsAsValues(): Model; /** * Adapts a Model to the {@link DataSource} interface. - **/ + */ asDataSource(): DataSource; /** * Returns a clone of the {@link Model} that boxes values returning the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the value inside it. * This allows any metadata attached to the wrapper to be inspected. - **/ + */ boxValues(): Model; /** * Returns a clone of the {@link Model} that unboxes values, returning the value inside of the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the wrapper itself. * This is the default mode. - **/ + */ unboxValues(): Model; /** * Returns a clone of the {@link Model} that only uses the local {@link JSONGraph} and never uses a {@link DataSource} to retrieve missing paths. - **/ + */ withoutDataSource(): Model; /** * Returns the {@link Path} to the object within the JSON Graph that this Model references. - **/ + */ getPath(): Path; } @@ -237,38 +237,38 @@ export class Observable{ * An Observable is like a pipe of water that is closed. * When forEach is called, we open the valve and the values within are pushed at us. * These values can be received using either callbacks or an {@link Observer} object. - **/ + */ forEach(onNext?: ObservableOnNextCallback, onError?: ObservableOnErrorCallback , onCompleted?: ObservableOnCompletedCallback ): Subscription; /** * The subscribe method is a synonym for {@link Observable.prototype.forEach} and triggers the execution of the Observable, causing the values within to be pushed to a callback. * An Observable is like a pipe of water that is closed. * When forEach is called, we open the valve and the values within are pushed at us. These values can be received using either callbacks or an {@link Observer} object. - **/ + */ subscribe(onNext?: ObservableOnNextCallback, onError?: ObservableOnErrorCallback , onCompleted?: ObservableOnCompletedCallback ): Subscription; } /** * This callback accepts a value that was emitted while evaluating the operation underlying the {@link Observable} stream. - **/ + */ type ObservableOnNextCallback = (value: T) => void; /** * This callback accepts an error that occurred while evaluating the operation underlying the {@link Observable} stream. * When this callback is invoked, the {@link Observable} stream ends and no more values will be received by the {@link Observable~onNextCallback}. - **/ + */ type ObservableOnErrorCallback = (error: Error) => void; /** * This callback is invoked when the {@link Observable} stream ends. * When this callback is invoked the {@link Observable} stream has ended, and therefore the {@link Observable~onNextCallback} will not receive any more values. - **/ + */ type ObservableOnCompletedCallback = () => void; export class Subscription { /** * When this method is called on the Subscription, the Observable that created the Subscription will stop sending values to the callbacks passed when the Subscription was created. - **/ + */ dispose(): void; } diff --git a/types/fetch.io/index.d.ts b/types/fetch.io/index.d.ts index 966925b68f..2071e18a51 100644 --- a/types/fetch.io/index.d.ts +++ b/types/fetch.io/index.d.ts @@ -30,7 +30,7 @@ interface Options extends RequestInit { afterJSON?(body: any): void; } -declare class Request { +export class Request { constructor(method: TMethod, url: TUrl, options: Options) /** @@ -66,51 +66,51 @@ declare class Request { /** * Set Options */ - config(key: string, value: any): this + config(key: string, value: any): this; - config(opts: {[key: string]: any}): this + config(opts: {[key: string]: any}): this; /** * Set Header */ - set(key: string, value: any): this + set(key: string, value: any): this; - set(opts: {[key: string]: any}): this + set(opts: {[key: string]: any}): this; /** * Set Content-Type */ - type(type: 'json' | 'form' | 'urlencoded'): this + type(type: 'json' | 'form' | 'urlencoded'): this; /** * Add query string */ - query(object: {[key: string]: any}): this + query(object: {[key: string]: any}): this; /** * Send data */ - send(data: {[key: string]: any}): this + send(data: {[key: string]: any}): this; /** * ppend formData */ - append(key: string, value: string): this + append(key: string, value: string): this; /** * Get Response directly */ - then(resolve: (value?: Response) => void, reject?: (reason?: any) => void): Promise + then(resolve: (value?: Response) => void, reject?: (reason?: any) => void): Promise; /** * Make Response to JSON */ - json(strict?: boolean): Promise + json(strict?: boolean): Promise; /** * Make Response to string */ - text(): Promise + text(): Promise; } export default class Fetch extends Request { diff --git a/types/globule/index.d.ts b/types/globule/index.d.ts index 08f00ec082..7918acbeae 100644 --- a/types/globule/index.d.ts +++ b/types/globule/index.d.ts @@ -21,7 +21,7 @@ interface MappingOptions extends FindOptions { ext?: string; extDot?: 'first' | 'last'; flatten?: boolean; - rename?: (p: string) => string; + rename?(p: string): string; } interface OneMapping { diff --git a/types/google-protobuf/tslint.json b/types/google-protobuf/tslint.json index fdc7cdc370..a980701dab 100644 --- a/types/google-protobuf/tslint.json +++ b/types/google-protobuf/tslint.json @@ -1,3 +1,16 @@ { - "extends": "../tslint.json" + "extends": "../tslint.json", + "rules": { + "align": false, + "array-type": false, + "new-parens": false, + "no-consecutive-blank-lines": false, + "no-redundant-modifiers": false, + "interface-over-type-literal": false, + "no-relative-import-in-test": false, + "no-var": false, + "prefer-declare-function": false, + "semicolon": false, + "trim-file": false + } } \ No newline at end of file diff --git a/types/inert/index.d.ts b/types/inert/index.d.ts index fdd3d91bcd..9acbd6f1a7 100644 --- a/types/inert/index.d.ts +++ b/types/inert/index.d.ts @@ -12,4 +12,4 @@ /// -export var inert: any; \ No newline at end of file +export const inert: any; diff --git a/types/is-absolute-url/is-absolute-url-tests.ts b/types/is-absolute-url/is-absolute-url-tests.ts index 47c5f007ed..4f8a225dad 100644 --- a/types/is-absolute-url/is-absolute-url-tests.ts +++ b/types/is-absolute-url/is-absolute-url-tests.ts @@ -7,4 +7,4 @@ isAbsoluteUrl('//sindresorhus.com'); // => false isAbsoluteUrl('foo/bar'); -// => false \ No newline at end of file +// => false diff --git a/types/isbn-utils/index.d.ts b/types/isbn-utils/index.d.ts index fe2ac4dae9..f0e1fe5515 100644 --- a/types/isbn-utils/index.d.ts +++ b/types/isbn-utils/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Jørgen Elgaard Larsen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - type IGroups = any; export class ISBNcodes { diff --git a/types/isbn-utils/isbn-utils-tests.ts b/types/isbn-utils/isbn-utils-tests.ts index 91f72a0359..24a91ffa6a 100644 --- a/types/isbn-utils/isbn-utils-tests.ts +++ b/types/isbn-utils/isbn-utils-tests.ts @@ -1,6 +1,5 @@ import * as isbn from 'isbn-utils'; - const isbn10a: isbn.ISBN|null = isbn.parse('4873113369'); let b: boolean; let s: string; diff --git a/types/jsnlog/index.d.ts b/types/jsnlog/index.d.ts index 4d1c707b4f..62a0d355ae 100644 --- a/types/jsnlog/index.d.ts +++ b/types/jsnlog/index.d.ts @@ -9,16 +9,16 @@ // ------------------------------- /** -* Copyright 2016 Mattijs Perdeck. -* -* This project is licensed under the MIT license. -* -* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ + * Copyright 2016 Mattijs Perdeck. + * + * This project is licensed under the MIT license. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ // Declarations of all interfaces and ambient objects, except for JL itself. // Provides strong typing in both jsnlog.ts itself and in TypeScript programs that use @@ -31,8 +31,8 @@ declare namespace JL { defaultAjaxUrl?: string; clientIP?: string; requestId?: string; - defaultBeforeSend?: (xhr: XMLHttpRequest) => void; - serialize?: (obj: any) => string; + defaultBeforeSend?(xhr: XMLHttpRequest): void; + serialize?(obj: any): string; } interface JSNLogFilterOptions { @@ -57,7 +57,7 @@ declare namespace JL { interface JSNLogAjaxAppenderOptions extends JSNLogAppenderOptions { url?: string; - beforeSend?: (xhr: XMLHttpRequest) => void; + beforeSend?(xhr: XMLHttpRequest): void; } interface JSNLogLogger { diff --git a/types/koa-json-error/index.d.ts b/types/koa-json-error/index.d.ts index dfe23c26b0..5fc9618edf 100644 --- a/types/koa-json-error/index.d.ts +++ b/types/koa-json-error/index.d.ts @@ -10,17 +10,17 @@ interface JSONErrorOptions { /** * Perform some task before calling `options.format`. Must be a function with the original err as its only argument. */ - preFormat?: (err: Error) => any; + preFormat?(err: Error): any; /** * Runs inmediatly after `options.preFormat`. It receives two arguments: the original `err` and the output of `options.preFormat`. It should `return` a newly formatted error. */ - format?: (err: Error, obj: any) => any; + format?(err: Error, obj: any): any; /** * Runs inmediatly after `options.format`. It receives two arguments: the original `err` and the output of `options.format`. It should `return` a newly formatted error. */ - postFormat?: (err: Error, obj: any) => any; + postFormat?(err: Error, obj: any): any; } /** diff --git a/types/koa-jwt/index.d.ts b/types/koa-jwt/index.d.ts index ba60bd8e61..a355d44ce2 100644 --- a/types/koa-jwt/index.d.ts +++ b/types/koa-jwt/index.d.ts @@ -13,7 +13,7 @@ declare namespace jwt { interface Options { secret: string | Buffer; key?: string; - getToken?: (opts: jwt.Options) => string; + getToken?(opts: jwt.Options): string; passthrough?: boolean; cookie?: string; debug?: boolean; diff --git a/types/later/index.d.ts b/types/later/index.d.ts index 5dd68ec90a..2e0d4de386 100644 --- a/types/later/index.d.ts +++ b/types/later/index.d.ts @@ -4,9 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace later { - interface ScheduleData { - /** * A list of recurrence information as a composite schedule. */ @@ -25,7 +23,6 @@ declare namespace later { } interface Recurrence { - /** Time in seconds from midnight. */ t?: number[]; @@ -142,11 +139,10 @@ declare namespace later { * For acces to custom time periods created as extension to the later static type * and modifiers created on the later modifier static type. */ - [ timeperiodAndModifierName: string ]: number[] | undefined; + [timeperiodAndModifierName: string]: number[] | undefined; } interface ParseStatic { - /** * Create a recurrence builder for building schedule data. */ @@ -168,7 +164,6 @@ declare namespace later { } interface Timer { - /** * Clear the timer and end execution. */ @@ -176,58 +171,56 @@ declare namespace later { } interface Schedule { - /** - * Finds the next valid instance or instances of the current schedule, - * optionally between a specified start and end date. Start date is - * Date.now() by default, end date is unspecified. Start date must be - * smaller than end date. - * - * @param {number} numberOfInst: The number of instances to return - * @param {Date} dateFrom: The earliest a valid instance can occur - * @param {Date} dateTo: The latest a valid instance can occur - */ + * Finds the next valid instance or instances of the current schedule, + * optionally between a specified start and end date. Start date is + * Date.now() by default, end date is unspecified. Start date must be + * smaller than end date. + * + * @param {number} numberOfInst: The number of instances to return + * @param {Date} dateFrom: The earliest a valid instance can occur + * @param {Date} dateTo: The latest a valid instance can occur + */ next(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[]; /** - * Finds the next valid range or ranges of the current schedule, - * optionally between a specified start and end date. Start date is - * Date.now() by default, end date is unspecified. Start date must be - * greater than end date. - * - * @param {number} numberOfInst: The number of ranges to return - * @param {Date} dateFrom: The earliest a valid range can occur - * @param {Date} dateTo: The latest a valid range can occur - */ + * Finds the next valid range or ranges of the current schedule, + * optionally between a specified start and end date. Start date is + * Date.now() by default, end date is unspecified. Start date must be + * greater than end date. + * + * @param {number} numberOfInst: The number of ranges to return + * @param {Date} dateFrom: The earliest a valid range can occur + * @param {Date} dateTo: The latest a valid range can occur + */ nextRange(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[]; /** - * Finds the previous valid instance or instances of the current schedule, - * optionally between a specified start and end date. Start date is - * Date.now() by default, end date is unspecified. Start date must be - * greater than end date. - * - * @param {number} numberOfInst: The number of instances to return - * @param {Date} dateFrom: The earliest a valid instance can occur - * @param {Date} dateTo: The latest a valid instance can occur - */ + * Finds the previous valid instance or instances of the current schedule, + * optionally between a specified start and end date. Start date is + * Date.now() by default, end date is unspecified. Start date must be + * greater than end date. + * + * @param {number} numberOfInst: The number of instances to return + * @param {Date} dateFrom: The earliest a valid instance can occur + * @param {Date} dateTo: The latest a valid instance can occur + */ prev(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[]; /** - * Finds the previous valid range or ranges of the current schedule, - * optionally between a specified start and end date. Start date is - * Date.now() by default, end date is unspecified. Start date must be - * greater than end date. - * - * @param {number} numberOfInst: The number of ranges to return - * @param {Date} dateFrom: The earliest a valid range can occur - * @param {Date} dateTo: The latest a valid range can occur - */ + * Finds the previous valid range or ranges of the current schedule, + * optionally between a specified start and end date. Start date is + * Date.now() by default, end date is unspecified. Start date must be + * greater than end date. + * + * @param {number} numberOfInst: The number of ranges to return + * @param {Date} dateFrom: The earliest a valid range can occur + * @param {Date} dateTo: The latest a valid range can occur + */ prevRange(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[]; } interface RecurrenceBuilder extends ScheduleData { - /** a time period */ second(): RecurrenceBuilder; @@ -268,7 +261,6 @@ declare namespace later { /** a time period */ fullDate(): RecurrenceBuilder; - /** * Specifies one or more specific vals of a time period information provider. * When used to specify a time, a string indicating the 24-hour time may be used. @@ -371,7 +363,6 @@ declare namespace later { } interface DateProvider { - /** * Set later to use UTC time. */ @@ -434,7 +425,6 @@ declare namespace later { } interface TimePeriod { - /** * The name of the time period information provider. */ @@ -515,7 +505,6 @@ declare namespace later { } interface ModifierStatic { - /** * After Modifier */ @@ -528,7 +517,6 @@ declare namespace later { } interface Static { - /** * Schedule * Generates instances from schedule data. diff --git a/types/later/later-tests.ts b/types/later/later-tests.ts index 1ecd1d6d0e..ea21977c5b 100644 --- a/types/later/later-tests.ts +++ b/types/later/later-tests.ts @@ -1,16 +1,15 @@ import later = require("later"); namespace LaterTest_DefineSchedule { - // define a new schedule - var textSched = later.parse.text('at 10:15am every weekday'); - var cronSched = later.parse.cron('0 0/5 14,18 * * ?'); - var recurSched = later.parse.recur().last().dayOfMonth(); - var manualSched = { schedules: [ { M: [ 3 ], D: [ 21 ] } ] }; + const textSched = later.parse.text('at 10:15am every weekday'); + const cronSched = later.parse.cron('0 0/5 14,18 * * ?'); + const recurSched = later.parse.recur().last().dayOfMonth(); + const manualSched = { schedules: [ { M: [ 3 ], D: [ 21 ] } ] }; // this schedule will fire on the closest weekday to the 15th // every month at 2:00 am except in March - var complexSched = later.parse.recur() + const complexSched = later.parse.recur() .on(15).dayOfMonth().onWeekday().on(2).hour() .and() .on(14).dayOfMonth().on(6).dayOfWeek().on(2).hour() @@ -21,7 +20,6 @@ namespace LaterTest_DefineSchedule { } namespace LaterTest_ConfigureTimezone { - // set later to use UTC (the default) later.date.UTC(); @@ -31,7 +29,7 @@ namespace LaterTest_ConfigureTimezone { namespace LaterTest_TimePeriods { export function second() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.second.name; // 'second' @@ -62,7 +60,7 @@ namespace LaterTest_TimePeriods { } export function minute() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.minute.name; // 'minute' @@ -93,7 +91,7 @@ namespace LaterTest_TimePeriods { } export function hour() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.hour.name; // 'hour' @@ -124,7 +122,7 @@ namespace LaterTest_TimePeriods { } export function time() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.time.name; // 'time' @@ -155,7 +153,7 @@ namespace LaterTest_TimePeriods { } export function day() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.day.name; // 'day' @@ -186,7 +184,7 @@ namespace LaterTest_TimePeriods { } export function day_of_week() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.dayOfWeek.name; // 'day of week' @@ -217,7 +215,7 @@ namespace LaterTest_TimePeriods { } export function day_of_week_count() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.dayOfWeekCount.name; // 'day of week count' @@ -252,7 +250,7 @@ namespace LaterTest_TimePeriods { } export function day_of_year() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.dayOfYear.name; // 'day of year' @@ -283,7 +281,7 @@ namespace LaterTest_TimePeriods { } export function week_of_month() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.weekOfMonth.name; // 'week of month' @@ -314,7 +312,7 @@ namespace LaterTest_TimePeriods { } export function week_of_year() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.weekOfYear.name; // 'week of year' @@ -345,7 +343,7 @@ namespace LaterTest_TimePeriods { } export function month() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.month.name; // 'month' @@ -376,7 +374,7 @@ namespace LaterTest_TimePeriods { } export function year() { - var d = new Date('2013-03-22T10:02:05Z'); + const d = new Date('2013-03-22T10:02:05Z'); later.year.name; // 'year' @@ -411,11 +409,9 @@ namespace LaterTest_TimePeriods { } export function custom() { - - var customLater = later; + const customLater = later; customLater.partOfDay = { - name: 'part of day', range: later.hour.range * 6, @@ -437,7 +433,7 @@ namespace LaterTest_TimePeriods { }, start(date: Date) { - var hour = customLater.partOfDay.val(date) === 0 + const hour = customLater.partOfDay.val(date) === 0 ? 0 : customLater.partOfDay.val(date) === 1 ? 12 @@ -452,7 +448,7 @@ namespace LaterTest_TimePeriods { }, end(date: Date) { - var hour = customLater.partOfDay.val(date) === 0 + const hour = customLater.partOfDay.val(date) === 0 ? 11 : customLater.partOfDay.val(date) === 1 ? 5 @@ -467,7 +463,7 @@ namespace LaterTest_TimePeriods { }, next(date: Date, val: any) { - var hour = val === 0 + const hour = val === 0 ? 0 : val === 1 ? 12 @@ -483,7 +479,7 @@ namespace LaterTest_TimePeriods { }, prev(date: Date, val: any) { - var hour = val === 0 + const hour = val === 0 ? 11 : val === 1 ? 5 @@ -502,7 +498,6 @@ namespace LaterTest_TimePeriods { } namespace LaterTest_GenerateRecurences { - export function on_method() { // fires on the 2nd minute every hour later.parse.recur().on(2).minute(); @@ -575,7 +570,7 @@ namespace LaterTest_GenerateRecurences { export function and_method() { // fires every 2 hours on the first day of every month // and 8:00am and 8:00pm on the last day of every month - var sched = later.parse.recur() + const sched = later.parse.recur() .every(2).hour().first().dayOfMonth() .and() .on(8, 20).hour().last().dayOfMonth(); @@ -583,42 +578,39 @@ namespace LaterTest_GenerateRecurences { export function except_method() { // fires every minute of every hour except on multiples of 2 and 3 - var sched = later.parse.recur() + const sched = later.parse.recur() .every().minute() .except() .every(2).minute().between(2, 59) .and() .every(3).minute().between(3, 59); } - } namespace LaterTest_CalculateOccurences { - // Initialise next variable. - var next: Date[] = []; + let next: Date[] = []; // calculate the next 10 occurrences of a recur schedule - var recurSched = later.parse.recur().last().dayOfMonth(); + const recurSched = later.parse.recur().last().dayOfMonth(); next = later.schedule(recurSched).next(10); // calculate the previous occurrence starting from March 21, 2013 - var cronSched = later.parse.cron('0 0/5 14,18 * * ?'); + const cronSched = later.parse.cron('0 0/5 14,18 * * ?'); next = later.schedule(cronSched).prev(1, new Date(2013, 2, 21)); } namespace LaterTest_ExecuteCodeUsingSchedule { - // will fire every 5 minutes - var textSched = later.parse.text('every 5 min'); + const textSched = later.parse.text('every 5 min'); // execute logTime one time on the next occurrence of the text schedule - var timer = later.setTimeout(logTime, textSched); + const timer = later.setTimeout(logTime, textSched); // execute logTime for each successive occurrence of the text schedule - var timer2 = later.setInterval(logTime, textSched); + const timer2 = later.setInterval(logTime, textSched); // function to execute function logTime() { diff --git a/types/memcached/memcached-tests.ts b/types/memcached/memcached-tests.ts index fc11bd9d27..9101471a8a 100644 --- a/types/memcached/memcached-tests.ts +++ b/types/memcached/memcached-tests.ts @@ -6,32 +6,32 @@ namespace main { if (expected !== undefined && typeof expected !== 'string') { throw new Error(); } - }; + } function isArray(expected?: any[]): void { if (expected !== undefined && !Array.isArray(expected)) { throw new Error(); } - }; + } function isNumber(expected?: number): void { if (expected !== undefined && typeof expected !== 'number') { throw new Error(); } - }; + } function isBoolean(expected?: boolean): void { if (expected !== undefined && typeof expected !== 'boolean') { throw new Error(); } - }; + } function isFunction(expected?: (...args: any[]) => void): void { if (expected !== undefined && typeof expected !== 'function') { throw new Error(); } - }; + } function isVoid(expected?: undefined): void { if (expected !== undefined) { throw new Error(); } - }; + } namespace test_global_options { Memcached.config.maxKeySize = 250; @@ -116,11 +116,11 @@ namespace main { isNumber(expected.totalReconnectsFailed); isNumber(expected.totalDownTime); } - memcached.on('issue', err => isIssue(err)); - memcached.on('failure', err => isIssue(err)); - memcached.on('reconnecting', err => isIssue(err)); - memcached.on('reconnect', err => isIssue(err)); - memcached.on('remove', err => isIssue(err)); + memcached.on('issue', isIssue); + memcached.on('failure', isIssue); + memcached.on('reconnecting', isIssue); + memcached.on('reconnect', isIssue); + memcached.on('remove', isIssue); } function isCommandData(expected: Memcached.CommandData) { @@ -372,7 +372,7 @@ namespace main { isString(stat.server); } }); - }; + } namespace test_settings { memcached.settings((err: any, data: Memcached.StatusData[]) => { isArray(data); @@ -380,7 +380,7 @@ namespace main { isString(setting.server); } }); - }; + } namespace test_slabs { memcached.slabs((err: any, data: Memcached.StatusData[]) => { isArray(data); @@ -388,7 +388,7 @@ namespace main { isString(setting.server); } }); - }; + } let promise: Promise; namespace test_items { promise = new Promise(resolve => { @@ -400,7 +400,7 @@ namespace main { resolve(data); }); }); - }; + } namespace test_cachedump { promise.then(data => { for (const node of data) { @@ -418,12 +418,12 @@ namespace main { }); } }); - }; + } namespace test_flush { memcached.flush(function(err, results) { isVoid(this); isArray(results); }); - }; + } } diff --git a/types/mock-raf/index.d.ts b/types/mock-raf/index.d.ts index bbcbe5e444..9c8ab664bd 100644 --- a/types/mock-raf/index.d.ts +++ b/types/mock-raf/index.d.ts @@ -4,9 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace MockRaf { - interface Options { - /** The time that should pass during each requestAnimationFrame step in milliseconds. Default is roughly equivalent to default browser behavior. */ time?: number; @@ -16,7 +14,6 @@ declare namespace MockRaf { /** Creates a mockRaf instance, exposing the functions you'll use to interact with the mock. */ interface Creator { - /** * Returns the current now value of the mock. Starts at 0 and increases with each step() taken. * Useful for stubbing out performance.now() or a polyfill when using requestAnimationFrame with timers. @@ -32,9 +29,8 @@ declare namespace MockRaf { /** Takes requestAnimationFrame steps. Fires currently queued callbacks for each step and increments now time for each step. The primary way to interact with a mockRaf instance for testing. */ step(options?: Options): void; } - } declare function MockRaf(): MockRaf.Creator; -export = MockRaf; \ No newline at end of file +export = MockRaf; diff --git a/types/mock-raf/mock-raf-tests.ts b/types/mock-raf/mock-raf-tests.ts index 96ba9531d5..d773d1c760 100644 --- a/types/mock-raf/mock-raf-tests.ts +++ b/types/mock-raf/mock-raf-tests.ts @@ -6,4 +6,4 @@ const id = mockRaf.raf(() => { }); mockRaf.step({ count: 10 }); mockRaf.cancel(id); -console.log(mockRaf.now()); \ No newline at end of file +console.log(mockRaf.now()); diff --git a/types/nedb/index.d.ts b/types/nedb/index.d.ts index ea5a9e8d4e..d85016493e 100644 --- a/types/nedb/index.d.ts +++ b/types/nedb/index.d.ts @@ -181,11 +181,11 @@ declare namespace Nedb { nodeWebkitAppName?: boolean; // Optional, specify the name of your NW app if you want options.filename to be relative to the directory where autoload?: boolean; // Optional, defaults to false // Optional, if autoload is used this will be called after the load database with the error object as parameter. If you don't pass it the error will be thrown - onload?: (error: Error) => any; + onload?(error: Error): any; // (optional): hook you can use to transform data after it was serialized and before it is written to disk. // Can be used for example to encrypt data before writing database to disk. // This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which must absolutely not contain a \n character (or data will be lost) - afterSerialization?: (line: string) => string; + afterSerialization?(line: string): string; // (optional): reverse of afterSerialization. // Make sure to include both and not just one or you risk data loss. // For the same reason, make sure both functions are inverses of one another. @@ -193,7 +193,7 @@ declare namespace Nedb { // NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths. // In addition, if too much data is detected as corrupt, // NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below) - beforeDeserialization?: (line: string) => string; + beforeDeserialization?(line: string): string; // (optional): between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt. // 0 means you don't tolerate any corruption, 1 means you don't care corruptAlertThreshold?: number; diff --git a/types/optics-agent/index.d.ts b/types/optics-agent/index.d.ts index 4d27ac71ae..902e8e8379 100644 --- a/types/optics-agent/index.d.ts +++ b/types/optics-agent/index.d.ts @@ -21,7 +21,7 @@ export interface Options { * * You shouldn't need to set this unless you are debugging. */ - normalizeQuery?: (graphQLResolveInfo: any) => string; + normalizeQuery?(graphQLResolveInfo: any): string; /** * Where to send the reports. Defaults to the production Optics endpoint, or the OPTICS_ENDPOINT_URL environment variable if it is set. diff --git a/types/parsimmon/index.d.ts b/types/parsimmon/index.d.ts index 718fc1246d..21cd77ce2f 100644 --- a/types/parsimmon/index.d.ts +++ b/types/parsimmon/index.d.ts @@ -75,7 +75,7 @@ declare namespace Parsimmon { interface Parser { /** * parse the string - */ + */ parse(input: string): Result; /** * Like parser.parse(input) but either returns the parsed value or throws @@ -91,7 +91,7 @@ declare namespace Parsimmon { * returns a new parser which tries parser, and on success calls the given function * with the result of the parse, which is expected to return another parser, which * will be tried next - */ + */ chain(next: (result: T) => Parser): Parser; /** * returns a new parser which tries parser, and on success calls the given function @@ -254,8 +254,8 @@ declare namespace Parsimmon { type SuccessFunctionType = (index: number, result: U) => Result; type FailureFunctionType = (index: number, msg: string) => Result; type ParseFunctionType = (stream: StreamType, index: number) => Result; - /** - * allows to add custom primitive parsers. + /** + * allows to add custom primitive parsers. */ function custom(parsingFunction: (success: SuccessFunctionType, failure: FailureFunctionType) => ParseFunctionType): Parser; diff --git a/types/progressbar/progressbar-tests.ts b/types/progressbar/progressbar-tests.ts index 46dcc60732..b75e110adb 100644 --- a/types/progressbar/progressbar-tests.ts +++ b/types/progressbar/progressbar-tests.ts @@ -1,8 +1,8 @@ import { Progressbar, create } from 'progressbar'; -let str: string = '', - progressbar: Progressbar, - num: number = 1; +let str: string = ''; +let progressbar: Progressbar; +let num: number = 1; const fn: () => void = () => {}; progressbar = create(); diff --git a/types/pump/index.d.ts b/types/pump/index.d.ts index 7361399a6a..6e8cc7fc8e 100644 --- a/types/pump/index.d.ts +++ b/types/pump/index.d.ts @@ -11,8 +11,8 @@ declare function pump(streams: pump.Stream[], callback?: pump.Callback): pump.St declare function pump(...streams: Array): pump.Stream[]; declare namespace pump { - export type Callback = (err: Error) => any; - export type Stream = NodeJS.ReadableStream | NodeJS.WritableStream; + type Callback = (err: Error) => any; + type Stream = NodeJS.ReadableStream | NodeJS.WritableStream; } export = pump; diff --git a/types/raven/index.d.ts b/types/raven/index.d.ts index 2d9da8ccaf..359ead4608 100644 --- a/types/raven/index.d.ts +++ b/types/raven/index.d.ts @@ -8,26 +8,25 @@ import { IncomingMessage, ServerResponse } from 'http'; import { EventEmitter } from 'events'; +export const version: string; +export function config(dsn: string | false, options?: ConstructorOptions): Client; +export function wrap(func: () => void, onErr?: () => void): () => void; +export function wrap(options: any, func: () => void, onErr?: () => void): () => void; +export function interceptErr(ctx: any): Client; +export function setContext(ctx: any): Client; +export function captureException(e: Error, cb?: CaptureCallback): Client; +export function captureException(e: Error, options?: CaptureOptions, cb?: CaptureCallback): Client; +export function mergeContext(ctx: any): Client; +export function getContext(): any; +export function errorHandler(): (e: Error, req: IncomingMessage, res: ServerResponse, next: () => void) => void; +export function context(ctx: any, func: () => void, onErr?: () => void): Client; +export function context(func: () => void, onErr?: () => void): Client; +export function captureBreadcrumb(breadcrumb: any): void; +export function disableConsoleAlerts(): void; +export function consoleAlert(msg: string): void; +export function parseDSN(dsn: string | false): parsedDSN; -declare const version: string; -declare function config(dsn: string | false, options?: ConstructorOptions): Client; -declare function wrap(func: () => void, onErr?: () => void): () => void; -declare function wrap(options: any, func: () => void, onErr?: () => void): () => void; -declare function interceptErr(ctx: any): Client; -declare function setContext(ctx: any): Client; -declare function captureException(e: Error, cb?: CaptureCallback): Client; -declare function captureException(e: Error, options?: CaptureOptions, cb?: CaptureCallback): Client; -declare function mergeContext(ctx: any): Client; -declare function getContext(): any; -declare function errorHandler(): (e: Error, req: IncomingMessage, res: ServerResponse, next: () => void) => void; -declare function context(ctx: any, func: () => void, onErr?: () => void): Client; -declare function context(func: () => void, onErr?: () => void): Client; -declare function captureBreadcrumb(breadcrumb: any): void; -declare function disableConsoleAlerts(): void; -declare function consoleAlert(msg: string): void; -declare function parseDSN(dsn: string | false): parsedDSN; - -declare class Client extends EventEmitter { +export class Client extends EventEmitter { constructor(options: ConstructorOptions); constructor(dsn: string, options?: ConstructorOptions); config(dsn: string, options?: ConstructorOptions): Client; @@ -48,7 +47,7 @@ declare class Client extends EventEmitter { process(eventId: string, kwargs: any, cb?: () => void): void; } -declare interface ConstructorOptions { +export interface ConstructorOptions { name?: string; logger?: string; release?: string; @@ -56,17 +55,17 @@ declare interface ConstructorOptions { tags?: { string: string }; extra?: { string: any }; dataCallback?: DataCallback; - transport?: () => void; + transport?(): void; captureUnhandledRejections?: boolean; autoBreadcrumbs?: boolean | any; } -declare interface UserData { +export interface UserData { id: string; handle?: string; } -declare interface parsedDSN { +export interface parsedDSN { protocol: string; public_key: string; private_key: string; @@ -76,19 +75,13 @@ declare interface parsedDSN { port: number; } -declare interface CaptureCallback { - (err: { string: any }, eventId: any): void; -} +export type CaptureCallback = (err: { string: any }, eventId: any) => void; -declare interface DataCallback { - (data: { string: any }): void; -} +export type DataCallback = (data: { string: any }) => void; -declare interface TransportCallback { - (options: { string: any }): void; -} +export type TransportCallback = (options: { string: any }) => void; -declare interface CaptureOptions { +export interface CaptureOptions { tags?: { string: string }; extra?: { string: any }; fingerprint?: string; diff --git a/types/raven/raven-tests.ts b/types/raven/raven-tests.ts index ae493c0dd8..d419b32d12 100644 --- a/types/raven/raven-tests.ts +++ b/types/raven/raven-tests.ts @@ -16,7 +16,7 @@ new Raven.Client(dsn); try { throw new Error(); } catch (e) { - var eventId = Raven.captureException(e, (sendErr, eventId) => { }); + const eventId = Raven.captureException(e, (sendErr, eventId) => { }); } Raven.setContext({}); @@ -24,6 +24,5 @@ Raven.mergeContext({}); Raven.context(() => { Raven.captureBreadcrumb({}); }); -var doIt = () => { } -setTimeout(Raven.wrap(doIt), 1000) -Raven.parseDSN('https://8769c40cf49c4cc58b51fa45d8e2d166:296768aa91084e17b5ac02d3ad5bc7e7@app.getsentry.com/269') +setTimeout(Raven.wrap(() => {}), 1000); +Raven.parseDSN('https://8769c40cf49c4cc58b51fa45d8e2d166:296768aa91084e17b5ac02d3ad5bc7e7@app.getsentry.com/269'); diff --git a/types/rheostat/index.d.ts b/types/rheostat/index.d.ts index 372e5c6f1b..86312c4fb3 100644 --- a/types/rheostat/index.d.ts +++ b/types/rheostat/index.d.ts @@ -20,13 +20,13 @@ export interface PublicState { } export interface Events { - onClick?: () => any; - onChange?: (publicState: PublicState) => any; - onKeyPress?: () => any; - onSliderDragEnd?: () => any; - onSliderDragMove?: () => any; - onSliderDragStart?: () => any; - onValuesUpdated?: (publicState: PublicState) => any; + onClick?(): any; + onChange?(publicState: PublicState): any; + onKeyPress?(): any; + onSliderDragEnd?(): any; + onSliderDragMove?(): any; + onSliderDragStart?(): any; + onValuesUpdated?(publicState: PublicState): any; } export interface Props extends Events { @@ -46,4 +46,3 @@ export interface Props extends Events { } export default class Rheostat extends React.Component {} - diff --git a/types/sha1/sha1-tests.ts b/types/sha1/sha1-tests.ts index 22467632c8..6ce833b10b 100644 --- a/types/sha1/sha1-tests.ts +++ b/types/sha1/sha1-tests.ts @@ -1,29 +1,6 @@ import fs = require("fs"); import sha1 = require("sha1"); -/** - * API - * sha1(message) - * message -- String or Buffer - * returns String - * - * Usage - **************************************************** - * var sha1 = require('sha1'); * - * console.log(sha1('message')); * - **************************************************** - * This will print the following - * 6f9b9af3cd6e8b8a73c2cdced37fe9f59226e27d - * - * It supports buffers, too - **************************************************** - * var fs = require('fs'); * - * var sha1 = require('sha1'); * - * * - * fs.readFile('example.txt', function(err, buf) { * - * console.log(sha1(buf)); * - * }); * - * ************************************************** - */ + console.log(sha1('message')); // should print 6f9b9af3cd6e8b8a73c2cdced37fe9f59226e27d const testTwo = sha1('message', {asString: true}); diff --git a/types/sharp/sharp-tests.ts b/types/sharp/sharp-tests.ts index 2ca348620a..86d01066dc 100644 --- a/types/sharp/sharp-tests.ts +++ b/types/sharp/sharp-tests.ts @@ -47,7 +47,7 @@ sharp('input.jpg') // containing a scaled and cropped version of input.jpg }); -var transformer = sharp() +let transformer = sharp() .resize(300) .on('info', (info: sharp.OutputInfo) => { console.log('Image height is ' + info.height); diff --git a/types/slimerjs/index.d.ts b/types/slimerjs/index.d.ts index 7fc8c2dfa7..784f814f57 100644 --- a/types/slimerjs/index.d.ts +++ b/types/slimerjs/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Alex Wall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare var phantom: Phantom; declare var slimer: Slimer; @@ -19,7 +18,6 @@ interface Slimer { } interface Phantom { - // Properties args: string[]; // DEPRECATED cookies: Cookie[]; @@ -40,7 +38,7 @@ interface Phantom { injectJs(filename: string): boolean; // Callbacks - onError: (msg: string, trace: string[]) => any; + onError(msg: string, trace: string[]): any; } interface Std { @@ -69,11 +67,10 @@ interface SystemModule { interface HttpConf { operation: string; data: any; - headers: any + headers: any; } interface WebPage { - // Properties canGoBack: boolean; canGoForward: boolean; @@ -106,7 +103,7 @@ interface WebPage { viewportSize: Size; windowName: string; zoomFactor: number; - captureContent: Array; // slimerjs only + captureContent: RegExp[]; // slimerjs only // Functions addCookie(cookie: Cookie): boolean; @@ -142,9 +139,9 @@ interface WebPage { release(): void; // DEPRECATED reload(): void; // render(filename: string): Promise; + render(filename: string): void; render(filename: string, options?: { format?: string; quality?: string; ratio?: number; onlyViewport?: boolean }): Promise; renderBase64(type: string): Promise; - render(filename: string): void; renderBase64(format: string): string; sendEvent(mouseEventType: string, mouseX?: number, mouseY?: number, button?: string): Promise; sendEvent(keyboardEventType: string, key: string, null1?: null, null2?: null, modifier?: number): Promise; @@ -163,23 +160,23 @@ interface WebPage { uploadFile(selector: string, filename: string): void; // Callbacks - onAlert: (msg: string) => any; - onCallback: () => void; // EXPERIMENTAL - onClosing: (closingPage: WebPage) => any; - onConfirm: (msg: string) => boolean; - onConsoleMessage: (msg: string, lineNum?: number, sourceId?: string) => any; - onError: (msg: string, trace: string[]) => any; - onFilePicker: (oldFile: string) => string; - onInitialized: () => any; - onLoadFinished: (status: string) => any; - onLoadStarted: () => any; - onNavigationRequested: (url: string, type: string, willNavigate: boolean, main: boolean) => any; - onPageCreated: (newPage: WebPage) => any; - onPrompt: (msg: string, defaultVal: string) => string; - onResourceError: (resourceError: ResourceError) => any; - onResourceReceived: (response: ResourceResponse) => any; - onResourceRequested: (requestData: ResourceRequest, networkRequest: NetworkRequest) => any; - onUrlChanged: (targetUrl: string) => any; + onAlert(msg: string): any; + onCallback(): void; // EXPERIMENTAL + onClosing(closingPage: WebPage): any; + onConfirm(msg: string): boolean; + onConsoleMessage(msg: string, lineNum?: number, sourceId?: string): any; + onError(msg: string, trace: string[]): any; + onFilePicker(oldFile: string): string; + onInitialized(): any; + onLoadFinished(status: string): any; + onLoadStarted(): any; + onNavigationRequested(url: string, type: string, willNavigate: boolean, main: boolean): any; + onPageCreated(newPage: WebPage): any; + onPrompt(msg: string, defaultVal: string): string; + onResourceError(resourceError: ResourceError): any; + onResourceReceived(response: ResourceResponse): any; + onResourceRequested(requestData: ResourceRequest, networkRequest: NetworkRequest): any; + onUrlChanged(targetUrl: string): any; // Callback triggers closing(closingPage: WebPage): void; @@ -203,8 +200,8 @@ interface ResourceError { } interface HttpVersion { - major: number, - minor: number + major: number; + minor: number; } interface ResourceResponse { @@ -261,7 +258,6 @@ interface WebPageSettings { } interface FileSystem { - // Properties separator: string; workingDirectory: string; @@ -316,12 +312,11 @@ interface Stream { interface WebServerModule { registerDirectory(urlpath: string, directoryPath: string): void; registerFile(urlpath: string, filePath: string): void; - registerPathHandler(urlpath: string, handlerCallback: (request: WebServerRequest, response: WebServerResponse) => void): void + registerPathHandler(urlpath: string, handlerCallback: (request: WebServerRequest, response: WebServerResponse) => void): void; port: number; listen(port: number | string, cb?: (request: WebServerRequest, response: WebServerResponse) => void): boolean; // listen(ipAddressPort: string, cb?: (request: IWebServerRequest, response: IWebServerResponse) => void): boolean; close(): void; - } interface WebServerRequest { @@ -359,14 +354,14 @@ interface ClipRect extends TopLeft, Size { } interface Cookie { - name: string, - value: string, - domain?: string, - path: string, - httponly?: boolean, - secure?: boolean, - expires?: string, - expiry: number + name: string; + value: string; + domain?: string; + path: string; + httponly?: boolean; + secure?: boolean; + expires?: string; + expiry: number; } interface WebPageModule { diff --git a/types/slimerjs/slimerjs-tests.ts b/types/slimerjs/slimerjs-tests.ts index 604bd4f6f6..da40531769 100644 --- a/types/slimerjs/slimerjs-tests.ts +++ b/types/slimerjs/slimerjs-tests.ts @@ -1,21 +1,17 @@ -var webpageMod = require('webpage'); -var webserverMod = require('webserver') +const webpageMod = require('webpage'); // tslint:disable-line no-var-requires +const webserverMod = require('webserver'); // tslint:disable-line no-var-requires let page = webpageMod.create(); let vUrl = 'https://www.w3c.org'; - -function testWebserver () { - - webserverMod.close() +function testWebserver() { + webserverMod.close(); webserverMod.listen(1234); webserverMod.registerFile("urlPath", "filePath"); webserverMod.registerDirectory("urlPath", "dirPath"); - } - -let vUserAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8' +let vUserAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8'; page.settings.userAgent = vUserAgent; page.onConsoleMessage = (vMsg) => { @@ -27,7 +23,7 @@ page.onAlert = (vMsg) => { page.onLoadStarted = () => { }; -page.captureContent = [ /json/ ] +page.captureContent = [/json/]; page.onResourceReceived = (oResponse) => { oResponse.id; @@ -45,7 +41,6 @@ page.onResourceRequested = (oRequestData, oNetworkRequest) => { oRequestData.url; }; - page.onLoadFinished = (vStatus) => { phantom.exit(); }; @@ -54,18 +49,16 @@ page.onInitialized = () => { }; page.onPageCreated = (oPage) => { - let oCookie: Cookie + let oCookie: Cookie; oPage.addCookie(oCookie); }; - page.open(vUrl) // loads a page .then(() => { // executed after loading page.viewportSize = { width: 414, height: 736 }; - let vFilename = `../data/page01.png`; - page.render(vFilename, {onlyViewport: true}) + page.render(vFilename, {onlyViewport: true}); // then open a second page return page.open('http://'); @@ -73,5 +66,5 @@ page.open(vUrl) // loads a page .then(() => { // click somewhere on the second page page.sendEvent("click", 5, 5, 'left', 0); - slimer.exit() + slimer.exit(); }); diff --git a/types/sshpk/index.d.ts b/types/sshpk/index.d.ts index 0bc2274120..6089dd930b 100644 --- a/types/sshpk/index.d.ts +++ b/types/sshpk/index.d.ts @@ -5,19 +5,16 @@ /// -declare class SshPK { -} +declare class SshPK {} declare namespace SshPK { - - export class Algo { + class Algo { parts: string[]; sizePart?: string; normalize?: boolean; } - - export class algInfo { + class algInfo { dsa: Algo; rsa: Algo; ecdsa: Algo; @@ -25,7 +22,7 @@ declare namespace SshPK { curve25519: Algo; } - export class algPrivInfo { + class algPrivInfo { dsa: Algo; rsa: Algo; ecdsa: Algo; @@ -33,7 +30,7 @@ declare namespace SshPK { curve25519: Algo; } - export class hashAlgs { + class hashAlgs { md5: boolean; sha1: boolean; sha256: boolean; @@ -41,7 +38,7 @@ declare namespace SshPK { sha512: boolean; } - export class Curve { + class Curve { size: number; pkcs8oid: string; p: Buffer; @@ -52,21 +49,20 @@ declare namespace SshPK { G: Buffer; } - export class curves { + class curves { nistp256: Curve; nistp384: Curve; nistp512: Curve; } - export class algs { + class algs { info: algInfo; privInfo: algPrivInfo; hashAlgs: hashAlgs; curves: curves; } - - export class Certificate { + class Certificate { subjects: Identity[]; issuer: string; subjectKey: string; @@ -101,12 +97,9 @@ declare namespace SshPK { static parse(data: string|Buffer, format: string, options: any): Certificate; static isCertificate(data: string|Buffer, ver: string): boolean; - } - - export class DiffieHellman { - + class DiffieHellman { constructor(key: Key); getPublicKey(): Key; @@ -121,24 +114,23 @@ declare namespace SshPK { generateKeys(): PrivateKey; } - export class X9ECParameters { + class X9ECParameters { G: any; g: any; n: any; h: any; } - export class ECPublic { + class ECPublic { constructor(params: X9ECParameters, buffer: Buffer); } - export class ECPrivate { + class ECPrivate { constructor(params: X9ECParameters, buffer: Buffer); deriveSharedSecret(pk: Key): Buffer; } - - export class Verifier { + class Verifier { constructor(key: Key, hashAlgo: string); update(chunk: string|Buffer): void; @@ -146,53 +138,50 @@ declare namespace SshPK { verify(signature: string): boolean; } - export class Signer { - + class Signer { constructor(key: Key, hashAlgo: string); update(chunk: string|Buffer): void; sign(): Signature; } - - export class FingerprintFormatError implements Error { + class FingerprintFormatError implements Error { name: string; message: string; constructor(fp: Fingerprint, format: string); } - export class InvalidAlgorithmError implements Error { + class InvalidAlgorithmError implements Error { name: string; message: string; constructor(algo: string); } - export class KeyParseError implements Error { + class KeyParseError implements Error { name: string; message: string; constructor(name: string, format: string, innerErr: any); } - export class SignatureParseError implements Error { + class SignatureParseError implements Error { name: string; message: string; constructor(type: string, format: string, innerErr: any); } - export class CertificateParseError implements Error { + class CertificateParseError implements Error { name: string; message: string; constructor(name: string, format: string, innerErr: any); } - export class KeyEncryptedError implements Error { + class KeyEncryptedError implements Error { name: string; message: string; constructor(name: string, format: string); } - - export class Fingerprint { + class Fingerprint { algorithm: string; hash: string; type: string; @@ -206,10 +195,9 @@ declare namespace SshPK { isFingerprint(obj: string|Buffer, ver: string): boolean; static parse(fp: string, options: any): Fingerprint; - } - export class Identity { + class Identity { cn: string; components: string[]; componentLookup: any; @@ -233,13 +221,12 @@ declare namespace SshPK { static isIdentity(dn: Buffer|string, ver: string): boolean; } - - export class Format { + class Format { read: (buf: Buffer, options?: any) => Buffer; write: (key: Key, options?: any) => Buffer; } - export class Formats { + class Formats { auto: Format; pem: Format; pkcs1: Format; @@ -250,11 +237,11 @@ declare namespace SshPK { openssh: Format; } - export class Verify { + class Verify { verify(data: string, fmt: string): boolean; } - export class Key { + class Key { type: string; parts: string; part: string; @@ -278,10 +265,9 @@ declare namespace SshPK { static parse(data: string|Buffer, format: string, options: any): Key; static isKey(obj: string|Buffer, ver: string): boolean; - } - export class PrivateKey { + class PrivateKey { constructor(opts: any); static formats: Formats; toBuffer(format: string, options: any): Buffer; @@ -293,11 +279,9 @@ declare namespace SshPK { static parse(data: string|Buffer, format: string, options: any): PrivateKey; static isPrivateKey(data: string|Buffer, ver: string): boolean; - } - - export class Signature { + class Signature { constructor(opts: any); toBuffer(format: string): Buffer; toString(format: string): string; @@ -305,14 +289,13 @@ declare namespace SshPK { static parse(data: string|Buffer, type: string, format: string): Signature; static isSignature(obj: string|Buffer, ver: string): boolean; - } - export class SSHPart { + class SSHPart { data: Buffer; } - export class SSHBuffer { + class SSHBuffer { constructor(opts: any); toBuffer(): Buffer; atEnd(): boolean; @@ -333,47 +316,44 @@ declare namespace SshPK { writeChar(buf: string): void; writePart(buf: SSHPart): void; write(buf: Buffer): void; - } - - export function bufferSplit(buf: Buffer, chr: string): Buffer[]; - export function addRSAMissing(key: PrivateKey): void; - export function calculateDSAPublic(g: Buffer, p: Buffer, x: Buffer): Buffer; - export function mpNormalize(buf: Buffer): Buffer; - export function ecNormalize(buf: Buffer, addZero: boolean): Buffer; - export function countZeros(buf: Buffer): number; - export function assertCompatible(obj: any, klass: any, needVer: string, name: string): void; - export function isCompatible(obj: any, klass: any, needVer: string): boolean; - export class OpenSllKeyDeriv { + function bufferSplit(buf: Buffer, chr: string): Buffer[]; + function addRSAMissing(key: PrivateKey): void; + function calculateDSAPublic(g: Buffer, p: Buffer, x: Buffer): Buffer; + function mpNormalize(buf: Buffer): Buffer; + function ecNormalize(buf: Buffer, addZero: boolean): Buffer; + function countZeros(buf: Buffer): number; + function assertCompatible(obj: any, klass: any, needVer: string, name: string): void; + function isCompatible(obj: any, klass: any, needVer: string): boolean; + class OpenSllKeyDeriv { key: Buffer; iv: Buffer; } - export function opensslKeyDeriv(cipher: string, salt: string, passphrase: string, count: number): OpenSllKeyDeriv; + function opensslKeyDeriv(cipher: string, salt: string, passphrase: string, count: number): OpenSllKeyDeriv; - export class OpensshCipherInfo { + class OpensshCipherInfo { keySize: number; blockSize: number; opensslName: string; } - export function opensshCipherInfo(cipber: string): OpensshCipherInfo; + function opensshCipherInfo(cipber: string): OpensshCipherInfo; - export function parseKey(data: string|Buffer, format: string, options?: any): Key; - export function parseFingerprint(fp: string, options?: any): Fingerprint; - export function parseSignature(data: string|Buffer, type: string, format: string): Signature; - export function parsePrivateKey(data: string|Buffer, format: string, options?: any): PrivateKey; + function parseKey(data: string|Buffer, format: string, options?: any): Key; + function parseFingerprint(fp: string, options?: any): Fingerprint; + function parseSignature(data: string|Buffer, type: string, format: string): Signature; + function parsePrivateKey(data: string|Buffer, format: string, options?: any): PrivateKey; - export function parseCertificate(data: string|Buffer, format: string, options?: any): Certificate; - export function createSelfSignedCertificate(subjectOrSubjects: string, key: Key, options?: any): Certificate; - export function createCertificate( + function parseCertificate(data: string|Buffer, format: string, options?: any): Certificate; + function createSelfSignedCertificate(subjectOrSubjects: string, key: Key, options?: any): Certificate; + function createCertificate( subjectOrSubjects: string, key: Key, issuer: string, issuerKey: PrivateKey, options?: any): Certificate; - export function identityFromDN(dn: string): Identity; - export function identityForHost(hostname: string): Identity; - export function identityForUser(uid: string): Identity; - export function identityForEmail(email: string): Identity; - + function identityFromDN(dn: string): Identity; + function identityForHost(hostname: string): Identity; + function identityForUser(uid: string): Identity; + function identityForEmail(email: string): Identity; } export = SshPK; diff --git a/types/sshpk/sshpk-tests.ts b/types/sshpk/sshpk-tests.ts index 301534d908..9caf27160d 100644 --- a/types/sshpk/sshpk-tests.ts +++ b/types/sshpk/sshpk-tests.ts @@ -1,4 +1,3 @@ - import * as sshpk from 'sshpk'; const cert = sshpk.parseCertificate("", "pem"); diff --git a/types/strip-bom/strip-bom-tests.ts b/types/strip-bom/strip-bom-tests.ts index 79aaa3daae..29e544db98 100644 --- a/types/strip-bom/strip-bom-tests.ts +++ b/types/strip-bom/strip-bom-tests.ts @@ -1,4 +1,4 @@ import stripBom = require('strip-bom'); stripBom('\uFEFFunicorn'); -// => 'unicorn' \ No newline at end of file +// => 'unicorn' diff --git a/types/swiper/index.d.ts b/types/swiper/index.d.ts index 99cdc714d9..e74fc923f9 100644 --- a/types/swiper/index.d.ts +++ b/types/swiper/index.d.ts @@ -97,10 +97,10 @@ interface SwiperOptions { paginationHide?: boolean; paginationClickable?: boolean; paginationElement?: string; - paginationBulletRender?: (swiper: Swiper, index: number, className: string) => void; - paginationFractionRender?: (swiper: Swiper, currentClassName: string, totalClassName: string) => void; - paginationProgressRender?: (swiper: Swiper, progressbarClass: string) => void; - paginationCustomRender?: (swiper: Swiper, current: number, total: number) => void; + paginationBulletRender?(swiper: Swiper, index: number, className: string): void; + paginationFractionRender?(swiper: Swiper, currentClassName: string, totalClassName: string): void; + paginationProgressRender?(swiper: Swiper, progressbarClass: string): void; + paginationCustomRender?(swiper: Swiper, current: number, total: number): void; // Navigation Buttons nextButton?: string | Element; @@ -112,7 +112,6 @@ interface SwiperOptions { scrollbarDraggable?: boolean; scrollbarSnapOnRelease?: boolean; - // Accessibility a11y?: boolean; prevSlideMessage?: string; @@ -121,7 +120,6 @@ interface SwiperOptions { lastSlideMessage?: string; paginationBulletMessage?: string; - // Keyboard / Mousewheel keyboardControl?: boolean; mousewheelControl?: boolean; @@ -135,7 +133,6 @@ interface SwiperOptions { hashnavWatchState?: boolean; history?: string; - // Images preloadImages?: boolean; updateOnImagesReady?: boolean; @@ -165,36 +162,36 @@ interface SwiperOptions { // Callbacks runCallbacksOnInit?: boolean; - onInit?: (swiper: Swiper) => void; - onSlideChangeStart?: (swiper: Swiper) => void; - onSlideChangeEnd?: (swiper: Swiper) => void; - onSlideNextStart?: (swiper: Swiper) => void; - onSlideNextEnd?: (swiper: Swiper) => void; - onSlidePrevStart?: (swiper: Swiper) => void; - onSlidePrevEnd?: (swiper: Swiper) => void; - onTransitionStart?: (swiper: Swiper) => void; - onTransitionEnd?: (swiper: Swiper) => void; - onTouchStart?: (swiper: Swiper, event: Event) => void; - onTouchMove?: (swiper: Swiper, event: Event) => void; - onTouchMoveOpposite?: (swiper: Swiper, event: Event) => void; - onSliderMove?: (swiper: Swiper, event: Event) => void; - onTouchEnd?: (swiper: Swiper, event: Event) => void; - onClick?: (swiper: Swiper, event: Event) => void; - onTap?: (swiper: Swiper, event: Event) => void; - onDoubleTap?: (swiper: Swiper, event: Event) => void; - onImagesReady?: (swiper: Swiper) => void; - onProgress?: (swiper: Swiper, progress: number) => void; - onReachBeginning?: (swiper: Swiper) => void; - onReachEnd?: (swiper: Swiper) => void; - onDestroy?: (swiper: Swiper) => void; - onSetTranslate?: (swiper: Swiper, translate: any) => void; - onSetTransition?: (swiper: Swiper, transition: any) => void; - onAutoplay?: (swiper: Swiper) => void; - onAutoplayStart?: (swiper: Swiper) => void; - onAutoplayStop?: (swiper: Swiper) => void; - onLazyImageLoad?: (swiper: Swiper, slide: any, image: any) => void; - onLazyImageReady?: (swiper: Swiper, slide: any, image: any) => void; - onPaginationRendered?: (swiper: Swiper, paginationContainer: any) => void; + onInit?(swiper: Swiper): void; + onSlideChangeStart?(swiper: Swiper): void; + onSlideChangeEnd?(swiper: Swiper): void; + onSlideNextStart?(swiper: Swiper): void; + onSlideNextEnd?(swiper: Swiper): void; + onSlidePrevStart?(swiper: Swiper): void; + onSlidePrevEnd?(swiper: Swiper): void; + onTransitionStart?(swiper: Swiper): void; + onTransitionEnd?(swiper: Swiper): void; + onTouchStart?(swiper: Swiper, event: Event): void; + onTouchMove?(swiper: Swiper, event: Event): void; + onTouchMoveOpposite?(swiper: Swiper, event: Event): void; + onSliderMove?(swiper: Swiper, event: Event): void; + onTouchEnd?(swiper: Swiper, event: Event): void; + onClick?(swiper: Swiper, event: Event): void; + onTap?(swiper: Swiper, event: Event): void; + onDoubleTap?(swiper: Swiper, event: Event): void; + onImagesReady?(swiper: Swiper): void; + onProgress?(swiper: Swiper, progress: number): void; + onReachBeginning?(swiper: Swiper): void; + onReachEnd?(swiper: Swiper): void; + onDestroy?(swiper: Swiper): void; + onSetTranslate?(swiper: Swiper, translate: any): void; + onSetTransition?(swiper: Swiper, transition: any): void; + onAutoplay?(swiper: Swiper): void; + onAutoplayStart?(swiper: Swiper): void; + onAutoplayStop?(swiper: Swiper): void; + onLazyImageLoad?(swiper: Swiper, slide: any, image: any): void; + onLazyImageReady?(swiper: Swiper, slide: any, image: any): void; + onPaginationRendered?(swiper: Swiper, paginationContainer: any): void; // Namespace slideClass?: string; @@ -321,7 +318,7 @@ declare class Swiper { setGrabCursor(): void; plugins?: { - debugger?: (swiper: any, params: any) => void; + debugger?(swiper: any, params: any): void; }; } diff --git a/types/swiper/swiper-tests.ts b/types/swiper/swiper-tests.ts index 6decd155e0..7e772a2742 100644 --- a/types/swiper/swiper-tests.ts +++ b/types/swiper/swiper-tests.ts @@ -1,4 +1,3 @@ - /// // @@ -7,18 +6,18 @@ // 01-default.html function defaultDemo() { - var swiper = new Swiper('.swiper-container'); + const swiper = new Swiper('.swiper-container'); } // 02-responsive.html function responsive() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true }); } // 03-vertical.html function vertical() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, direction: 'vertical' @@ -26,7 +25,7 @@ function vertical() { } // 04-space-between.html function spaceBetween() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, spaceBetween: 30, @@ -34,7 +33,7 @@ function spaceBetween() { } // 05-slides-per-view.html function slidesPerView() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', slidesPerView: 3, paginationClickable: true, @@ -43,7 +42,7 @@ function slidesPerView() { } // 06-slides-per-view-auto.html function slidesPerViewAuto() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', slidesPerView: 'auto', paginationClickable: true, @@ -52,7 +51,7 @@ function slidesPerViewAuto() { } // 07-centered.html function centered() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', slidesPerView: 4, centeredSlides: true, @@ -62,7 +61,7 @@ function centered() { } // 08-centered-auto.html function centeredAuto() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', slidesPerView: 'auto', centeredSlides: true, @@ -72,7 +71,7 @@ function centeredAuto() { } // 09-freemode.html function freemode() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', slidesPerView: 3, paginationClickable: true, @@ -82,7 +81,7 @@ function freemode() { } // 10-slides-per-column.html function slidesPerColumn() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', slidesPerView: 3, slidesPerColumn: 2, @@ -92,12 +91,12 @@ function slidesPerColumn() { } // 11-nested.html function nested() { - var swiperH = new Swiper('.swiper-container-h', { + const swiperH = new Swiper('.swiper-container-h', { pagination: '.swiper-pagination-h', paginationClickable: true, spaceBetween: 50 }); - var swiperV = new Swiper('.swiper-container-v', { + const swiperV = new Swiper('.swiper-container-v', { pagination: '.swiper-pagination-v', paginationClickable: true, direction: 'vertical', @@ -106,7 +105,7 @@ function nested() { } // 12-grab-cursor.html function grabCursor() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', slidesPerView: 4, centeredSlides: true, @@ -117,7 +116,7 @@ function grabCursor() { } // 13-scrollbar.html function scrollbar() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { scrollbar: '.swiper-scrollbar', scrollbarHide: true, slidesPerView: 'auto', @@ -128,7 +127,7 @@ function scrollbar() { } // 14-nav-arrows.html function navArrows() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', @@ -138,7 +137,7 @@ function navArrows() { } // 15-infinite-loop.html function infiniteLoop() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', @@ -150,7 +149,7 @@ function infiniteLoop() { } // 16-effect-fade.html function effectFade() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', @@ -161,7 +160,7 @@ function effectFade() { } // 17-effect-cube.html function effectCube() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', effect: 'cube', grabCursor: true, @@ -175,7 +174,7 @@ function effectCube() { } // 18-effect-coverflow.html function effectCoverflow() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', effect: 'coverflow', grabCursor: true, @@ -192,7 +191,7 @@ function effectCoverflow() { } // 19-keyboard-control.html function keyboardControl() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', slidesPerView: 1, paginationClickable: true, @@ -204,7 +203,7 @@ function keyboardControl() { } // 20-mousewheel-control.html function mousewheelControl() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', direction: 'vertical', slidesPerView: 1, @@ -215,7 +214,7 @@ function mousewheelControl() { } // 21-autoplay.html function autoplay() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', @@ -228,9 +227,9 @@ function autoplay() { } // 22-dynamic-slides.html function dynamicSlides() { - var appendNumber = 4; - var prependNumber = 1; - var swiper = new Swiper('.swiper-container', { + let appendNumber = 4; + let prependNumber = 1; + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', @@ -264,14 +263,14 @@ function dynamicSlides() { } // 23-thumbs-gallery-loop.html function thumbsGalleryLoop() { - var galleryTop = new Swiper('.gallery-top', { + const galleryTop = new Swiper('.gallery-top', { nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', spaceBetween: 10, loop: true, loopedSlides: 5, // looped slides should be the same }); - var galleryThumbs = new Swiper('.gallery-thumbs', { + const galleryThumbs = new Swiper('.gallery-thumbs', { spaceBetween: 10, slidesPerView: 4, touchRatio: 0.2, @@ -281,16 +280,15 @@ function thumbsGalleryLoop() { }); galleryTop.params.control = galleryThumbs; galleryThumbs.params.control = galleryTop; - } // 23-thumbs-gallery.html function thumbsGallery() { - var galleryTop = new Swiper('.gallery-top', { + const galleryTop = new Swiper('.gallery-top', { nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', spaceBetween: 10, }); - var galleryThumbs = new Swiper('.gallery-thumbs', { + const galleryThumbs = new Swiper('.gallery-thumbs', { spaceBetween: 10, centeredSlides: true, slidesPerView: 'auto', @@ -299,21 +297,20 @@ function thumbsGallery() { }); galleryTop.params.control = galleryThumbs; galleryThumbs.params.control = galleryTop; - } // 24-multiple-swipers.html function multipleSwipers() { - var swiper1 = new Swiper('.swiper1', { + const swiper1 = new Swiper('.swiper1', { pagination: '.swiper-pagination1', paginationClickable: true, spaceBetween: 30, }); - var swiper2 = new Swiper('.swiper2', { + const swiper2 = new Swiper('.swiper2', { pagination: '.swiper-pagination2', paginationClickable: true, spaceBetween: 30, }); - var swiper3 = new Swiper('.swiper3', { + const swiper3 = new Swiper('.swiper3', { pagination: '.swiper-pagination3', paginationClickable: true, spaceBetween: 30, @@ -321,7 +318,7 @@ function multipleSwipers() { } // 25-hash-navigation.html function hashNavigation() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', @@ -333,7 +330,7 @@ function hashNavigation() { } // 26-rtl.html function rtl() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', @@ -342,7 +339,7 @@ function rtl() { } // 27-jquery.html function jquery() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', @@ -351,7 +348,7 @@ function jquery() { } // 28-parallax.html function parallax() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', @@ -362,7 +359,7 @@ function parallax() { } // 29-custom-pagination.html function customPagination() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, paginationBulletRender(swiper, index, className) { @@ -372,7 +369,7 @@ function customPagination() { } // 30-lazy-load-images.html function lazyLoadImages() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', pagination: '.swiper-pagination', @@ -430,7 +427,7 @@ function customPlugin() { } // 32-scroll-container.html function scrollContainer() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { scrollbar: '.swiper-scrollbar', direction: 'vertical', slidesPerView: 'auto', @@ -440,34 +437,34 @@ function scrollContainer() { } // 32-slideable-menu.html function slideableMenu() { - var toggleMenu = () => { + const toggleMenu = () => { if (swiper.previousIndex === 0) swiper.slidePrev(); - } - , menuButton = document.getElementsByClassName('menu-button')[0] - , swiper = new Swiper('.swiper-container', { - slidesPerView: 'auto' - , initialSlide: 1 - , resistanceRatio: .00000000000001 - , onSlideChangeStart: (slider) => { - if (slider.activeIndex === 0) { - menuButton.classList.add('cross'); - menuButton.removeEventListener('click', toggleMenu, false); - } else - menuButton.classList.remove('cross'); - } - , onSlideChangeEnd: (slider) => { - if (slider.activeIndex === 0) - menuButton.removeEventListener('click', toggleMenu, false); - else - menuButton.addEventListener('click', toggleMenu, false); - } - , slideToClickedSlide: true - }); + }; + const menuButton = document.getElementsByClassName('menu-button')[0]; + const swiper = new Swiper('.swiper-container', { + slidesPerView: 'auto', + initialSlide: 1, + resistanceRatio: .00000000000001, + onSlideChangeStart: (slider) => { + if (slider.activeIndex === 0) { + menuButton.classList.add('cross'); + menuButton.removeEventListener('click', toggleMenu, false); + } else + menuButton.classList.remove('cross'); + }, + onSlideChangeEnd: (slider) => { + if (slider.activeIndex === 0) + menuButton.removeEventListener('click', toggleMenu, false); + else + menuButton.addEventListener('click', toggleMenu, false); + }, + slideToClickedSlide: true + }); } // 33-responsive-breakpoints.html function responsiveBreakpoints() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, slidesPerView: 5, @@ -494,7 +491,7 @@ function responsiveBreakpoints() { } // 34-autoheight.html function autoheight() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', paginationClickable: true, nextButton: '.swiper-button-next', @@ -504,7 +501,7 @@ function autoheight() { } // 35-effect-flip.html function effectFlip() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { pagination: '.swiper-pagination', effect: 'flip', grabCursor: true, @@ -514,7 +511,7 @@ function effectFlip() { } // 36-pagination-fraction.html function paginationFraction() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', pagination: '.swiper-pagination', @@ -523,7 +520,7 @@ function paginationFraction() { } // 37-pagination-progress.html function paginationProgress() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { nextButton: '.swiper-button-next', prevButton: '.swiper-button-prev', pagination: '.swiper-pagination', @@ -532,7 +529,7 @@ function paginationProgress() { } // 38-history.html function historyDemo() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { spaceBetween: 50, slidesPerView: 2, centeredSlides: true, @@ -547,7 +544,7 @@ function historyDemo() { } // 38-jquery-ie9-loop.html function jqueryIe9Loop() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { loop: true, pagination: '.swiper-pagination', paginationClickable: true, @@ -557,7 +554,7 @@ function jqueryIe9Loop() { } // 39-zoom.html function zoom() { - var swiper = new Swiper('.swiper-container', { + const swiper = new Swiper('.swiper-container', { zoom: true, pagination: '.swiper-pagination', nextButton: '.swiper-button-next', diff --git a/types/swiper/v2/index.d.ts b/types/swiper/v2/index.d.ts index a5a98b691f..446b104aba 100644 --- a/types/swiper/v2/index.d.ts +++ b/types/swiper/v2/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Sebastián Galiano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - interface SwiperOptions { speed?: number; autoplay?: number; @@ -77,18 +76,18 @@ interface SwiperOptions { // Callbacks queueStartCallbacks?: boolean; queueEndCallbacks?: boolean; - onTouchStart?: (swiper: Swiper) => void; - onTouchMove?: (swiper: Swiper) => void; - onTouchEnd?: (swiper: Swiper) => void; - onSlideReset?: (swiper: Swiper) => void; - onSlideChangeStart?: (swiper: Swiper) => void; - onSlideChangeEnd?: (swiper: Swiper) => void; - onSlideClick?: (swiper: Swiper) => void; - onSlideTouch?: (swiper: Swiper) => void; - onImagesReady?: (swiper: Swiper) => void; - onMomentumBounce?: (swiper: Swiper) => void; - onResistanceBefore?: (swiper: Swiper, distance: any) => void; - onResistanceAfter?: (swiper: Swiper, distance: any) => void; + onTouchStart?(swiper: Swiper): void; + onTouchMove?(swiper: Swiper): void; + onTouchEnd?(swiper: Swiper): void; + onSlideReset?(swiper: Swiper): void; + onSlideChangeStart?(swiper: Swiper): void; + onSlideChangeEnd?(swiper: Swiper): void; + onSlideClick?(swiper: Swiper): void; + onSlideTouch?(swiper: Swiper): void; + onImagesReady?(swiper: Swiper): void; + onMomentumBounce?(swiper: Swiper): void; + onResistanceBefore?(swiper: Swiper, distance: any): void; + onResistanceAfter?(swiper: Swiper, distance: any): void; // Slides Loader loader?: { diff --git a/types/swiper/v2/swiper-tests.ts b/types/swiper/v2/swiper-tests.ts index ad1180a352..d4b0160098 100644 --- a/types/swiper/v2/swiper-tests.ts +++ b/types/swiper/v2/swiper-tests.ts @@ -1,4 +1,3 @@ - /// // @@ -7,7 +6,7 @@ // 01-default.html function defaultDemo() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', loop: true, grabCursor: true, @@ -27,7 +26,7 @@ function defaultDemo() { // 02-vertical-mode.html function verticalMode() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, mode: 'vertical' @@ -36,17 +35,17 @@ function verticalMode() { // 03-dynamic-slides.html function dynamicSlides() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true }); function randomColor() { - var colors = ('blue red green orange pink').split(' '); + const colors = ('blue red green orange pink').split(' '); return colors[Math.floor(Math.random() * colors.length)]; } - var count = 4; + let count = 4; $('.sdl-append').click(e => { e.preventDefault(); @@ -90,7 +89,7 @@ function dynamicSlides() { // 04-scroll-container.html function scrollContainer() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { scrollContainer: true, scrollbar: { container: '.swiper-scrollbar' @@ -100,7 +99,7 @@ function scrollContainer() { // 05-free-mode.html function freeMode() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, freeMode: true, @@ -110,7 +109,7 @@ function freeMode() { // 06-carousel-mode.html function carouselMode() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, slidesPerView: 3 @@ -119,7 +118,7 @@ function carouselMode() { // 07-carousel-loop.html function carouselLoop() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, slidesPerView: 3, @@ -129,20 +128,20 @@ function carouselLoop() { // 08-nested.html function nested() { - var swiperParent = new Swiper('.swiper-parent', { + const swiperParent = new Swiper('.swiper-parent', { pagination: '.pagination-parent', paginationClickable: true, slidesPerView: 3 }); - var swiperNested1 = new Swiper('.swiper-nested-1', { + const swiperNested1 = new Swiper('.swiper-nested-1', { mode: 'vertical', pagination: '.pagination-nested-1', paginationClickable: true, slidesPerView: 2 }); - var swiperNested2 = new Swiper('.swiper-nested-2', { + const swiperNested2 = new Swiper('.swiper-nested-2', { mode: 'vertical', pagination: '.pagination-nested-2', paginationClickable: true, @@ -152,14 +151,14 @@ function nested() { // 09-nested-loop.html function nestedLoop() { - var swiperParent = new Swiper('.swiper-parent', { + const swiperParent = new Swiper('.swiper-parent', { pagination: '.pagination-parent', paginationClickable: true, loop: true, slidesPerView: 3 }); - var swiperNested1 = new Swiper('.swiper-nested', { + const swiperNested1 = new Swiper('.swiper-nested', { mode: 'vertical', pagination: '.pagination-nested', paginationClickable: true, @@ -169,7 +168,7 @@ function nestedLoop() { // 10-tabs.html function tabs() { - var tabsSwiper = new Swiper('.swiper-container', { + const tabsSwiper = new Swiper('.swiper-container', { onlyExternal: true, speed: 500 }); @@ -188,7 +187,7 @@ function tabs() { // 11-tabs-feedback.html function tabsFeedback() { - var tabsSwiper = new Swiper('.swiper-container', { + const tabsSwiper = new Swiper('.swiper-container', { speed: 500, onSlideChangeStart: () => { $(".tabs .active").removeClass('active'); @@ -210,7 +209,7 @@ function tabsFeedback() { // 12-partial-display.html function partialDisplay() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, slidesPerView: 'auto' @@ -219,7 +218,7 @@ function partialDisplay() { // 13-threshold.html function threshold() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, moveStartThreshold: 100 @@ -228,7 +227,7 @@ function threshold() { // 14-different-widths.html function differentWidths() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, slidesPerView: 'auto' @@ -237,7 +236,7 @@ function differentWidths() { // 15-centered-slides.html function centeredSlides() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, centeredSlides: true, @@ -247,7 +246,7 @@ function centeredSlides() { // 16-visibility-api.html function visibilityApi() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true, centeredSlides: true, @@ -258,20 +257,19 @@ function visibilityApi() { // 17 - responsive.html function responsive() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { pagination: '.pagination', paginationClickable: true }); } - // // Scrollbar // // demo-1.html function demo1() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { scrollbar: { container: '.swiper-scrollbar', hide: false, @@ -282,7 +280,7 @@ function demo1() { // demo-2.html function demo2() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { scrollbar: { container: '.swiper-scrollbar', hide: false, @@ -293,7 +291,7 @@ function demo2() { // demo-3.html function demo3() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { scrollbar: { container: '.swiper-scrollbar', hide: true, @@ -304,7 +302,7 @@ function demo3() { // demo-4.html function demo4() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { slidesPerView: 3, scrollbar: { container: '.swiper-scrollbar', @@ -317,7 +315,7 @@ function demo4() { // demo-5.html function demo5() { - var mySwiper = new Swiper('.swiper-container', { + const mySwiper = new Swiper('.swiper-container', { scrollContainer: true, mousewheelControl: true, mode: 'vertical', @@ -327,4 +325,4 @@ function demo5() { draggable: false } }); -} \ No newline at end of file +} diff --git a/types/tcomb/tcomb-tests.ts b/types/tcomb/tcomb-tests.ts index ab3e6ec20e..2219bb3c95 100644 --- a/types/tcomb/tcomb-tests.ts +++ b/types/tcomb/tcomb-tests.ts @@ -861,7 +861,7 @@ describe('struct', () => { }); it('should support prototypal inheritance', () => { - interface Rectangle { w: number; h: number; area(): number; }; + interface Rectangle { w: number; h: number; area(): number; } const Rectangle = struct({ w: Num, h: Num diff --git a/types/uikit/index.d.ts b/types/uikit/index.d.ts index 11a68c1848..de14822d28 100644 --- a/types/uikit/index.d.ts +++ b/types/uikit/index.d.ts @@ -153,7 +153,7 @@ declare namespace UIkit { * Parameter * Description * - + * * * show.uk.modal * event @@ -168,15 +168,14 @@ declare namespace UIkit { * @example *

      * $('.modalSelector').on({
-	 *
-	 *	'show.uk.modal': function(){
-	 *    console.log("Modal is visible.");
-	 *	},
-	 *
-	 *   'hide.uk.modal': function(){
-	 *    console.log("Element is not visible.");
-	 *  }
-	 *	});
+     *     'show.uk.modal': function(){
+     *         console.log("Modal is visible.");
+     *     },
+     *
+     *     'hide.uk.modal': function(){
+     *         console.log("Element is not visible.");
+     *     }
+     * });
      * 
*/ interface Modal { @@ -227,10 +226,10 @@ declare namespace UIkit { * var modal = UIkit.modal(".modalSelector"); * * if ( modal.isActive() ) { - * modal.hide(); - * } else { - * modal.show(); - * } + * modal.hide(); + * } else { + * modal.show(); + * } * */ (selector: string|JQuery, options?: ModalOptions): ModalElement; @@ -326,7 +325,6 @@ declare namespace UIkit { * Init element manually */ (element: string|JQuery, options?: LightBoxOptions): LightBoxElement; - } type CallbackAutoComplete = () => string; interface AutoCompleteOptions { @@ -420,7 +418,6 @@ declare namespace UIkit { * @default 'auto' */ pos?: string; - } /** * Create a toggleable dropdown with an datepicker @@ -711,7 +708,6 @@ declare namespace UIkit { */ type SlideShow = (element: string|JQuery, options: SlideShowOptions) => any; interface ParallaxOptions { - /** * Animation velocity during scrolling * @default 0.5 @@ -736,7 +732,6 @@ declare namespace UIkit { * integer / string */ media?: number|string; - } /** * Animate CSS properties depending on the scroll position of the document. @@ -899,7 +894,6 @@ declare namespace UIkit { * integer */ delay?: number; - } /** * Easily create a nicely looking search. @@ -1020,7 +1014,6 @@ declare namespace UIkit { * string */ emptyClass?: string; - } /** * Create nestable lists that can be sorted by drag and drop. @@ -1091,7 +1084,6 @@ declare namespace UIkit { * string */ dragCustomClass?: string; - } /** * Create sortable grids and lists to rearrange the order of its elements. @@ -1197,7 +1189,6 @@ declare namespace UIkit { * mixed */ boundary?: boolean|string; - } /** * Make elements remain at the top of the viewport, like a sticky navbar. @@ -1244,7 +1235,6 @@ declare namespace UIkit { * Integer between 0 and 24 */ end?: number; - } /** * Create a timepicker which can easily be used by selecting a time value from a pre filled dropdown. @@ -1294,7 +1284,6 @@ declare namespace UIkit { * string */ activeClass?: string; - } /** * Easily create a nicely looking tooltip. @@ -1351,19 +1340,19 @@ declare namespace UIkit { * (text|json) */ "type"?: string; - before?: (settings: UploadOptions, files: string|string[]) => any; - beforeAll?: (files: string|string[]) => any; - beforeSend?: (xhr: XMLHttpRequest) => any; - progress?: (percent: number) => any; - complete?: (response: any, xhr: XMLHttpRequest) => any; - allcomplete?: (response: any, xhr: XMLHttpRequest) => any; - notallowed?: (file: string|string[], settings: UploadOptions) => any; - loadstart?: (event: any) => any; - load?: (event: any) => any; - loadend?: (event: any) => any; - error?: (event: any) => any; - abort?: (event: any) => any; - readystatechange?: (event: any) => any; + before?(settings: UploadOptions, files: string|string[]): any; + beforeAll?(files: string|string[]): any; + beforeSend?(xhr: XMLHttpRequest): any; + progress?(percent: number): any; + complete?(response: any, xhr: XMLHttpRequest): any; + allcomplete?(response: any, xhr: XMLHttpRequest): any; + notallowed?(file: string|string[], settings: UploadOptions): any; + loadstart?(event: any): any; + load?(event: any): any; + loadend?(event: any): any; + error?(event: any): any; + abort?(event: any): any; + readystatechange?(event: any): any; } /** @@ -1430,25 +1419,25 @@ declare namespace UIkit { * */ type Upload = (element: string|JQuery, options: UploadOptions) => any; - var dropdown: Dropdown; - var modal: Modal; - var lightbox: LightBox; - var offcanvas: OffCanvas; - var autocomplete: AutoComplete; - var datepicker: DatePicker; - var htmleditor: HtmlEditor; - var slider: Slider; - var slideset: SlideSet; - var slideshow: SlideShow; - var parallax: Parallax; - var accordion: Accordion; - var notify: Notify; - var search: Search; - var nestable: Nestable; - var sortable: Sortable; - var sticky: Sticky; - var timepicker: Timepicker; - var tooltip: Tooltip; - var uploadSelect: Upload; - var uploadDrop: Upload; + const dropdown: Dropdown; + const modal: Modal; + const lightbox: LightBox; + const offcanvas: OffCanvas; + const autocomplete: AutoComplete; + const datepicker: DatePicker; + const htmleditor: HtmlEditor; + const slider: Slider; + const slideset: SlideSet; + const slideshow: SlideShow; + const parallax: Parallax; + const accordion: Accordion; + const notify: Notify; + const search: Search; + const nestable: Nestable; + const sortable: Sortable; + const sticky: Sticky; + const timepicker: Timepicker; + const tooltip: Tooltip; + const uploadSelect: Upload; + const uploadDrop: Upload; } diff --git a/types/uikit/uikit-tests.ts b/types/uikit/uikit-tests.ts index 5a28b61682..a33780085e 100644 --- a/types/uikit/uikit-tests.ts +++ b/types/uikit/uikit-tests.ts @@ -13,7 +13,7 @@ function testDropdown() { hoverDelayIdle: 200, preventflip: 'x' }; - var dropdown = UIkit.dropdown("$parent", options); + const dropdown = UIkit.dropdown("$parent", options); dropdown.show(); dropdown.hide(); @@ -40,10 +40,10 @@ function testModal() { UIkit.modal.prompt("Name:", 'value', (newvalue: string) => { // will be executed on submit. }); - var modal = UIkit.modal.blockUI("Any content..."); + let modal = UIkit.modal.blockUI("Any content..."); modal.hide(); modal.show(); - var modal = UIkit.modal(".modalSelector"); + modal = UIkit.modal(".modalSelector"); if (modal.isActive()) { modal.hide(); @@ -59,14 +59,14 @@ function testOffCanvas() { } function testLightBox() { - var element = "#group"; - var lightbox = UIkit.lightbox(element, {/* options */}); - var lightbox2 = UIkit.lightbox.create([ + const element = "#group"; + const lightbox = UIkit.lightbox(element, {/* options */}); + const lightbox2 = UIkit.lightbox.create([ {source: 'http://url/to/video.mp4', type: 'video'}, {source: 'http://url/to/image.jpg', type: 'image'} ]); lightbox2.show(); - var lightbox3 = UIkit.lightbox(element); + const lightbox3 = UIkit.lightbox(element); } function testAutoComplete() { @@ -75,31 +75,30 @@ function testAutoComplete() { } function testDatepicker() { - var datepicker = UIkit.datepicker("#element", {}); + const datepicker = UIkit.datepicker("#element", {}); } function testHtmlEditor() { - var htmleditor = UIkit.htmleditor("textarea", {/* options */}); + const htmleditor = UIkit.htmleditor("textarea", {/* options */}); } function testSlider() { - var slider = UIkit.slider("element", {}); + const slider = UIkit.slider("element", {}); } function testSlideSet() { - var slideset = UIkit.slideset("element", {}); + const slideset = UIkit.slideset("element", {}); } function testSlideShow() { - var slideshow = UIkit.slideshow("element", {}); + const slideshow = UIkit.slideshow("element", {}); } function testParallax() { - var parallax = UIkit.parallax("element", {}); + const parallax = UIkit.parallax("element", {}); } function testAccordion() { - var accordion = UIkit.accordion("element", {}); + const accordion = UIkit.accordion("element", {}); } - function testNotify() { UIkit.notify({ message: 'Bazinga!', @@ -108,8 +107,7 @@ function testNotify() { pos: 'top-center' }); - -// Shortcuts + // Shortcuts UIkit.notify('My message'); UIkit.notify('My message', status); UIkit.notify('My message', {/* options */}); @@ -119,100 +117,70 @@ function testNotify() { UIkit.notify("...", {status: 'info'}); } - function testSearch() { - var search = UIkit.search("element", {}); + const search = UIkit.search("element", {}); } function testNestable() { - var nestable = UIkit.nestable('element', {}); + const nestable = UIkit.nestable('element', {}); } function testSortable() { - var sortable = UIkit.sortable('element', {}); + const sortable = UIkit.sortable('element', {}); } function testStick() { - var sticky = UIkit.sticky('element', {}); + const sticky = UIkit.sticky('element', {}); } function testTimePicker() { - var timepicker = UIkit.timepicker('element', {}); + const timepicker = UIkit.timepicker('element', {}); } function testTooltip() { - var tooltip = UIkit.tooltip('element', {}); + const tooltip = UIkit.tooltip('element', {}); } function testUpload() { $(() => { + const progressbar = $("#progressbar"); + const bar = progressbar.find('.uk-progress-bar'); + const settings = { + action: '/', // upload url + allow : '*.(jpg|jpeg|gif|png)', // allow only images + loadstart() { + bar.css("width", "0%").text("0%"); + progressbar.removeClass("uk-hidden"); + }, + progress(percent: number) { + percent = Math.ceil(percent); + bar.css("width", percent + "%").text(percent + "%"); + }, + allcomplete(response: any) { + bar.css("width", "100%").text("100%"); - var progressbar = $("#progressbar"), - bar = progressbar.find('.uk-progress-bar'), - settings = { + setTimeout(() => { + progressbar.addClass("uk-hidden"); + }, 250); - action: '/', // upload url + alert("Upload Completed"); + } + }; - allow : '*.(jpg|jpeg|gif|png)', // allow only images - - loadstart() { - bar.css("width", "0%").text("0%"); - progressbar.removeClass("uk-hidden"); - }, - - progress(percent: number) { - percent = Math.ceil(percent); - bar.css("width", percent + "%").text(percent + "%"); - }, - - allcomplete(response: any) { - - bar.css("width", "100%").text("100%"); - - setTimeout(() => { - progressbar.addClass("uk-hidden"); - }, 250); - - alert("Upload Completed"); - } - }; - - var select = UIkit.uploadSelect($("#upload-select"), settings), - drop = UIkit.uploadDrop($("#upload-drop"), settings); + const select = UIkit.uploadSelect($("#upload-select"), settings); + const drop = UIkit.uploadDrop($("#upload-drop"), settings); }); // Test with object literal - var select2 = UIkit.uploadSelect($("#upload-select"), { - + const select2 = UIkit.uploadSelect($("#upload-select"), { action: '/', // upload url - allow: '*.(jpg|jpeg|gif|png)', // allow only images - - loadstart: () => { - - }, - - progress: (percent: number) => { - - }, - - allcomplete: (response: any) => { - - } + loadstart: () => {}, + progress: (percent: number) => {}, + allcomplete: (response: any) => {} }); - var drop2 = UIkit.uploadDrop($("#upload-drop"), { - + const drop2 = UIkit.uploadDrop($("#upload-drop"), { action: '/', // upload url - allow: '*.(jpg|jpeg|gif|png)', // allow only images - - loadstart: () => { - - }, - - progress: (percent: number) => { - - }, - - allcomplete: (response: any) => { - } + loadstart: () => {}, + progress: (percent: number) => {}, + allcomplete: (response: any) => {} }); - } diff --git a/types/uuid-js/uuid-js-tests.ts b/types/uuid-js/uuid-js-tests.ts index 67ef73ba68..6662bb6cd8 100644 --- a/types/uuid-js/uuid-js-tests.ts +++ b/types/uuid-js/uuid-js-tests.ts @@ -1,28 +1,24 @@ import UUID = require('uuid-js'); - // Generate a V4 UUID -var uuid4 = UUID.create(); +const uuid4 = UUID.create(); console.log(uuid4.toString()); // Prints: 896b677f-fb14-11e0-b14d-d11ca798dbac - // Generate a V1 TimeUUID -var uuid1 = UUID.create(1); +const uuid1 = UUID.create(1); console.log(uuid1.toString()); - // First and last possible v1 TimeUUID for a given timestamp: -var date = new Date().getTime(); -var uuidFirst = UUID.fromTime(date, false); -var uuidLast = UUID.fromTime(date, true); +const date = new Date().getTime(); +const uuidFirst = UUID.fromTime(date, false); +const uuidLast = UUID.fromTime(date, true); console.log(uuidFirst.toString(), uuidLast.toString()); // Prints: aa0f9af0-0e1f-11e1-0000-000000000000 aa0f9af0-0e1f-11e1-c0ff-ffffffffffff - // Use these TimeUUID's to perform range queries in cassandra: -var today = new Date().getTime(); -var last30days = (new Date().setDate(today - 30)); +const today = new Date().getTime(); +const last30days = (new Date().setDate(today - 30)); -var rangeStart = UUID.firstFromTime(last30days); -var rangeEnd = UUID.lastFromTime(today); +const rangeStart = UUID.firstFromTime(last30days); +const rangeEnd = UUID.lastFromTime(today); diff --git a/types/vis/index.d.ts b/types/vis/index.d.ts index 0d94a44354..e4f8fe0dfd 100644 --- a/types/vis/index.d.ts +++ b/types/vis/index.d.ts @@ -71,7 +71,6 @@ interface PointItem extends DataItem { y: number; } - interface DataGroup { className?: string; content: string; @@ -154,14 +153,14 @@ interface TimelineOptions { groupEditable?: TimelineOptionsGroupEditableType; groupOrder?: TimelineOptionsGroupOrderType; groupOrderSwap?: TimelineOptionsGroupOrderSwapFunction; - groupTemplate?: () => void; // TODO + groupTemplate?(): void; // TODO height?: HeightWidthType; hiddenDates?: any; // TODO horizontalScroll?: boolean; itemsAlwaysDraggable?: boolean; locale?: string; locales?: any; // TODO - moment?: () => void; // TODO + moment?(): void; // TODO margin?: TimelineOptionsMarginType; max?: DateType; maxHeight?: HeightWidthType; @@ -171,15 +170,15 @@ interface TimelineOptions { moveable?: boolean; multiselect?: boolean; multiselectPerGroup?: boolean; - onAdd?: () => void; // TODO - onAddGroup?: () => void; // TODO - onUpdate?: () => void; // TODO - onMove?: () => void; // TODO - onMoveGroup?: () => void; // TODO - onMoving?: () => void; // TODO - onRemove?: () => void; // TODO - onRemoveGroup?: () => void; // TODO - order?: () => void; // TODO + onAdd?(): void; // TODO + onAddGroup?(): void; // TODO + onUpdate?(): void; // TODO + onMove?(): void; // TODO + onMoveGroup?(): void; // TODO + onMoving?(): void; // TODO + onRemove?(): void; // TODO + onRemoveGroup?(): void; // TODO + order?(): void; // TODO orientation?: TimelineOptionsOrientationType; rollingMode: boolean; selectable?: boolean; @@ -189,11 +188,11 @@ interface TimelineOptions { stack?: boolean; snap?: TimelineOptionsSnapFunction; start?: DateType; - template?: () => void; // TODO + template?(): void; // TODO throttleRedraw?: number; timeAxis?: TimelineTimeAxisOption; type?: string; - tooltipOnItemUpdateTime?: boolean | { template: (item: any) => any }; + tooltipOnItemUpdateTime?: boolean | { template(item: any): any }; verticalScroll?: boolean; width?: HeightWidthType; zoomable?: boolean; @@ -276,7 +275,6 @@ interface DataSetQueueOptions { } export class DataSet { - /** * Creates an instance of DataSet. * @@ -539,7 +537,7 @@ interface DataSelectionOptions { * * @memberOf DataSelectionOptions */ - filter?: (item: T) => boolean; + filter?(item: T): boolean; /** * Order the items by a field name or custom sort function. @@ -581,7 +579,7 @@ interface RangeType { interface DataAxisSideOption { range?: RangeType; - format?: () => string; + format?(): string; title?: TitleOption; } @@ -611,7 +609,7 @@ interface Graph2dDataAxisOption { interface Graph2dDrawPointsOption { enabled?: boolean; - onRender?: () => boolean; // TODO + onRender?(): boolean; // TODO size?: number; style: Graph2dDrawPointsStyle; } @@ -642,7 +640,7 @@ interface Graph2dOptions { legend?: Graph2dLegendOption; locale?: string; locales?: any; // TODO - moment?: () => void; // TODO + moment?(): void; // TODO max?: DateType; maxHeight?: HeightWidthType; maxMinorChars?: number; @@ -840,7 +838,6 @@ type NetworkEvents = * @implements {INetwork} */ export class Network { - /** * Creates an instance of Network. * @@ -1476,12 +1473,12 @@ export interface ViewPortOptions { offset?: Position; /** - * For animation you can either use a Boolean to use it with the default options or - * disable it or you can define the duration (in milliseconds) and easing function manually. - * - * @type {(IAnimationOptions | boolean)} - * @memberOf IFitOptions - */ + * For animation you can either use a Boolean to use it with the default options or + * disable it or you can define the duration (in milliseconds) and easing function manually. + * + * @type {(IAnimationOptions | boolean)} + * @memberOf IFitOptions + */ animation?: AnimationOptions | boolean; } @@ -1510,7 +1507,6 @@ export interface MoveToOptions extends ViewPortOptions { * @interface IAnimationOptions */ export interface AnimationOptions { - /** * The duration (in milliseconds). * @@ -1539,7 +1535,6 @@ export interface AnimationOptions { * @interface IFitOptions */ export interface FitOptions { - /** * The nodes can be used to zoom to fit only specific nodes in the view. * @@ -1583,7 +1578,6 @@ export interface BoundingBox { * @interface IClusterOptions */ export interface ClusterOptions { - /** * Optional for all but the cluster method. * The cluster module loops over all nodes that are selected to be in the cluster @@ -1593,7 +1587,7 @@ export interface ClusterOptions { * * @memberOf IClusterOptions */ - joinCondition?: (nodeOptions: any) => boolean; + joinCondition?(nodeOptions: any): boolean; /** * Optional. @@ -1605,7 +1599,7 @@ export interface ClusterOptions { * @type {(clusterOptions: any, childNodesOptions: any[], childEdgesOptions: any[])} * @memberOf IClusterOptions */ - processProperties?: (clusterOptions: any, childNodesOptions: any[], childEdgesOptions: any[]) => any; + processProperties?(clusterOptions: any, childNodesOptions: any[], childEdgesOptions: any[]): any; /** * Optional. @@ -1641,7 +1635,6 @@ export interface ClusterOptions { * @interface IOpenClusterOptions */ export interface OpenClusterOptions { - /** * A function that can be used to manually position the nodes after the cluster is opened. * The containedNodesPositions contain the positions of the nodes in the cluster at the @@ -1656,9 +1649,9 @@ export interface OpenClusterOptions { * * @memberOf IOpenClusterOptions */ - releaseFunction: ( + releaseFunction( clusterPosition: Position, - containedNodesPositions: { [nodeId: string]: Position }) => { [nodeId: string]: Position }; + containedNodesPositions: { [nodeId: string]: Position }): { [nodeId: string]: Position }; } export interface Position { @@ -1667,7 +1660,6 @@ export interface Position { } export interface Properties { - nodes: string[]; edges: string[]; @@ -1686,7 +1678,7 @@ export interface Properties { } export interface Callback { - callback?: (params?: any) => void; + callback?(params?: any): void; } export interface Data { diff --git a/types/vis/vis-tests.ts b/types/vis/vis-tests.ts index 2b3b28fb7b..354f766cb0 100644 --- a/types/vis/vis-tests.ts +++ b/types/vis/vis-tests.ts @@ -21,8 +21,8 @@ interface TestData { } // create a DataSet -var options = {}; -var data = new vis.DataSet(options); +let options = {}; +let data = new vis.DataSet(options); // add items // note that the data items can contain different properties and data formats @@ -45,15 +45,15 @@ data.update({ id: 2, group: 1 }); data.remove(4); // get all ids -var ids = data.getIds(); +const ids = data.getIds(); console.log('ids', ids); // get a specific item -var item1 = data.get(1); +const item1 = data.get(1); console.log('item1', item1); // retrieve a filtered subset of the data -var items = data.get({ +let items = data.get({ filter: (item) => { return item.group === 1; } @@ -61,7 +61,7 @@ var items = data.get({ console.log('filtered items', items); // retrieve formatted items -var items = data.get({ +items = data.get({ fields: ['id', 'date'], type: { date: 'ISODate' @@ -74,7 +74,7 @@ console.log('formatted items', items); // // create a DataSet -var data = new vis.DataSet(); +data = new vis.DataSet(); // subscribe to any change in the DataSet data.on('*', (event, properties, senderId) => { @@ -91,7 +91,7 @@ data.remove(1); // triggers an 'remove' event // // create a DataSet -var data = new vis.DataSet(); +data = new vis.DataSet(); // add items data.add([ @@ -111,7 +111,7 @@ data.remove(3); // // create a DataSet -var data = new vis.DataSet(); +data = new vis.DataSet(); data.add([ { id: 1, text: 'item 1', date: '2013-06-20', group: 1, first: true }, { id: 2, text: 'item 2', date: '2013-06-23', group: 2 }, @@ -120,7 +120,7 @@ data.add([ ]); // retrieve formatted items -var items = data.get({ +items = data.get({ fields: ['id', 'date', 'group'], // output the specified fields only type: { date: 'Date', // convert the date fields to Date objects @@ -128,19 +128,19 @@ var items = data.get({ } }); -var dataset = new vis.DataSet(); +const dataset = new vis.DataSet(); // retrieve all items having a property group with value 2 -var group2 = dataset.get({ +const group2 = dataset.get({ filter: (item) => { return (item.group === 2); } }); // retrieve all items having a property balance with a value above zero -var positiveBalance = dataset.get({ +const positiveBalance = dataset.get({ filter: (item) => { - return (item.balance > 0); + return item.balance !== undefined && item.balance > 0; } }); @@ -149,7 +149,7 @@ var positiveBalance = dataset.get({ // // create an array with nodes -var nodes = new vis.DataSet([ +const nodes = new vis.DataSet([ { id: 1, label: 'Node 1' }, { id: 2, label: 'Node 2' }, { id: 3, label: 'Node 3' }, @@ -158,7 +158,7 @@ var nodes = new vis.DataSet([ ]); // create an array with edges -var edges = new vis.DataSet([ +const edges = new vis.DataSet([ { from: 1, to: 3 }, { from: 1, to: 2 }, { from: 2, to: 4 }, @@ -166,21 +166,21 @@ var edges = new vis.DataSet([ ]); // create a network -var container = document.getElementById('mynetwork'); +const container = document.getElementById('mynetwork'); // provide the data in the vis format -var data2 = { nodes, edges }; -var options = {}; +const data2 = { nodes, edges }; +options = {}; // initialize your network! -var network = new vis.Network(container, data2, options); +const network = new vis.Network(container, data2, options); // // Test code sample from http://visjs.org/docs/network/configure.html# // // these are all options in full. -var options2 = { +const options2 = { configure: { enabled: true, filter: 'nodes,edges', @@ -189,4 +189,4 @@ var options2 = { } }; -network.setOptions(options2); \ No newline at end of file +network.setOptions(options2); diff --git a/types/webpack-chain/index.d.ts b/types/webpack-chain/index.d.ts index f6cfc40b25..dd7b0b0d63 100644 --- a/types/webpack-chain/index.d.ts +++ b/types/webpack-chain/index.d.ts @@ -9,187 +9,187 @@ import * as https from 'https'; export = Config; declare class Config { - devServer: Config.DevServer - entryPoints: Config.EntryPoints - module: Config.Module - node: Config.ChainedMap - output: Config.Output - performance: Config.Performance - plugins: Config.Plugins - resolve: Config.Resolve - resolveLoader: Config.ResolveLoader + devServer: Config.DevServer; + entryPoints: Config.EntryPoints; + module: Config.Module; + node: Config.ChainedMap; + output: Config.Output; + performance: Config.Performance; + plugins: Config.Plugins; + resolve: Config.Resolve; + resolveLoader: Config.ResolveLoader; - amd(value: { [moduleName: string]: boolean }): this - bail(value: boolean): this - cache(value: boolean | any): this - devtool(value: Config.DevTool): this - context(value: string): this - externals(value: webpack.ExternalsElement | webpack.ExternalsElement[]): this - loader(value: any): this - profile(value: boolean): this - recordsPath(value: string): this - recordsInputPath(value: string): this - recordsOutputPath(value: string): this - stats(value: webpack.Options.Stats): this - target(value: string): this - watch(value: boolean): this - watchOptions(value: webpack.Options.WatchOptions): this + amd(value: { [moduleName: string]: boolean }): this; + bail(value: boolean): this; + cache(value: boolean | any): this; + devtool(value: Config.DevTool): this; + context(value: string): this; + externals(value: webpack.ExternalsElement | webpack.ExternalsElement[]): this; + loader(value: any): this; + profile(value: boolean): this; + recordsPath(value: string): this; + recordsInputPath(value: string): this; + recordsOutputPath(value: string): this; + stats(value: webpack.Options.Stats): this; + target(value: string): this; + watch(value: boolean): this; + watchOptions(value: webpack.Options.WatchOptions): this; - entry(name: string): Config.ChainedSet - plugin(name: string): Config.Plugin + entry(name: string): Config.ChainedSet; + plugin(name: string): Config.Plugin; - toConfig(): webpack.Configuration - merge(obj: any): this + toConfig(): webpack.Configuration; + merge(obj: any): this; } declare namespace Config { - export class Chained { - end(): Parent + class Chained { + end(): Parent; } - export class TypedChainedMap extends Chained { - clear(): this - delete(key: string): this - has(key: string): boolean - get(key: string): Value - set(key: string, value: Value): this - merge(obj: { [key: string]: Value }): this - entries(): { [key: string]: Value } - values(): Array + class TypedChainedMap extends Chained { + clear(): this; + delete(key: string): this; + has(key: string): boolean; + get(key: string): Value; + set(key: string, value: Value): this; + merge(obj: { [key: string]: Value }): this; + entries(): { [key: string]: Value }; + values(): Value[]; } - export class ChainedMap extends TypedChainedMap {} + class ChainedMap extends TypedChainedMap {} - export class TypedChainedSet extends Chained { - add(value: Value): this - prepend(value: Value): this - clear(): this - delete(key: string): this - has(key: string): boolean - merge(arr: Array): this - values(): Array + class TypedChainedSet extends Chained { + add(value: Value): this; + prepend(value: Value): this; + clear(): this; + delete(key: string): this; + has(key: string): boolean; + merge(arr: Value[]): this; + values(): Value[]; } - export class ChainedSet extends TypedChainedSet {} + class ChainedSet extends TypedChainedSet {} - export class Plugins extends TypedChainedMap> {} + class Plugins extends TypedChainedMap> {} - export class Plugin extends ChainedMap { - init(value: (plugin: PluginClass, args: any[]) => webpack.Plugin): this - use(plugin: PluginClass, args?: any[]): this - tap(f: (args: any[]) => any[]): this + class Plugin extends ChainedMap { + init(value: (plugin: PluginClass, args: any[]) => webpack.Plugin): this; + use(plugin: PluginClass, args?: any[]): this; + tap(f: (args: any[]) => any[]): this; } - export class Module extends ChainedMap { - rules: TypedChainedMap - rule(name: string): Rule + class Module extends ChainedMap { + rules: TypedChainedMap; + rule(name: string): Rule; } - export class Output extends ChainedMap { - chunkFilename(value: string): this - crossOriginLoading(value: boolean | string): this - filename(value: string): this - library(value: string): this - libraryTarget(value: string): this - devtoolFallbackModuleFilenameTemplate(value: any): this - devtoolLineToLine(value: any): this - devtoolModuleFilenameTemplate(value: any): this - hashFunction(value: string): this - hashDigest(value: string): this - hashDigestLength(value: number): this - hashSalt(value: any): this - hotUpdateChunkFilename(value: string): this - hotUpdateFunction(value: any): this - hotUpdateMainFilename(value: string): this - jsonpFunction(value: string): this - path(value: string): this - pathinfo(value: boolean): this - publicPath(value: string): this - sourceMapFilename(value: string): this - sourcePrefix(value: string): this - strictModuleExceptionHandling(value: boolean): this - umdNamedDefine(value: boolean): this + class Output extends ChainedMap { + chunkFilename(value: string): this; + crossOriginLoading(value: boolean | string): this; + filename(value: string): this; + library(value: string): this; + libraryTarget(value: string): this; + devtoolFallbackModuleFilenameTemplate(value: any): this; + devtoolLineToLine(value: any): this; + devtoolModuleFilenameTemplate(value: any): this; + hashFunction(value: string): this; + hashDigest(value: string): this; + hashDigestLength(value: number): this; + hashSalt(value: any): this; + hotUpdateChunkFilename(value: string): this; + hotUpdateFunction(value: any): this; + hotUpdateMainFilename(value: string): this; + jsonpFunction(value: string): this; + path(value: string): this; + pathinfo(value: boolean): this; + publicPath(value: string): this; + sourceMapFilename(value: string): this; + sourcePrefix(value: string): this; + strictModuleExceptionHandling(value: boolean): this; + umdNamedDefine(value: boolean): this; } - export class DevServer extends ChainedMap { - clientLogLevel(value: 'none' | 'error' | 'warning' | 'info'): this - compress(value: boolean): this - contentBase(value: boolean | string | string[]): this - filename(value: string): this - headers(value: { [header: string]: string }): this - historyApiFallback(value: boolean | any): this - host(value: string): this - hot(value: boolean): this - hotOnly(value: boolean): this - https(value: boolean | https.ServerOptions): this - inline(value: boolean): this - lazy(value: boolean): this - noInfo(value: boolean): this - overlay(value: boolean | { warnings?: boolean, errors?: boolean }): this - port(value: number): this - proxy(value: any): this - quiet(value: boolean): this - setup(value: (expressApp: any) => void): this - stats(value: webpack.Options.Stats): this - watchContentBase(value: boolean): this + class DevServer extends ChainedMap { + clientLogLevel(value: 'none' | 'error' | 'warning' | 'info'): this; + compress(value: boolean): this; + contentBase(value: boolean | string | string[]): this; + filename(value: string): this; + headers(value: { [header: string]: string }): this; + historyApiFallback(value: boolean | any): this; + host(value: string): this; + hot(value: boolean): this; + hotOnly(value: boolean): this; + https(value: boolean | https.ServerOptions): this; + inline(value: boolean): this; + lazy(value: boolean): this; + noInfo(value: boolean): this; + overlay(value: boolean | { warnings?: boolean, errors?: boolean }): this; + port(value: number): this; + proxy(value: any): this; + quiet(value: boolean): this; + setup(value: (expressApp: any) => void): this; + stats(value: webpack.Options.Stats): this; + watchContentBase(value: boolean): this; } - export class Performance extends ChainedMap { - hints(value: boolean | 'error' | 'warning'): this - maxEntrypointSize(value: number): this - maxAssetSize(value: number): this - assetFilter(value: (assetFilename: string) => boolean): this + class Performance extends ChainedMap { + hints(value: boolean | 'error' | 'warning'): this; + maxEntrypointSize(value: number): this; + maxAssetSize(value: number): this; + assetFilter(value: (assetFilename: string) => boolean): this; } - export class EntryPoints extends TypedChainedMap> {} + class EntryPoints extends TypedChainedMap> {} - export class Resolve extends ChainedMap { - alias: TypedChainedMap - aliasFields: TypedChainedSet - descriptionFiles: TypedChainedSet - extensions: TypedChainedSet - mainFields: TypedChainedSet - mainFiles: TypedChainedSet - modules: TypedChainedSet - plugins: TypedChainedMap> + class Resolve extends ChainedMap { + alias: TypedChainedMap; + aliasFields: TypedChainedSet; + descriptionFiles: TypedChainedSet; + extensions: TypedChainedSet; + mainFields: TypedChainedSet; + mainFiles: TypedChainedSet; + modules: TypedChainedSet; + plugins: TypedChainedMap>; - enforceExtension(value: boolean): this - enforceModuleExtension(value: boolean): this - unsafeCache(value: boolean | RegExp | RegExp[]): this - symlinks(value: boolean): this - cachePredicate(value: (data: { path: string, request: string }) => boolean): this + enforceExtension(value: boolean): this; + enforceModuleExtension(value: boolean): this; + unsafeCache(value: boolean | RegExp | RegExp[]): this; + symlinks(value: boolean): this; + cachePredicate(value: (data: { path: string, request: string }) => boolean): this; - plugin(name: string): Plugin + plugin(name: string): Plugin; } - export class ResolveLoader extends ChainedMap { - extensions: TypedChainedSet - modules: TypedChainedSet - moduleExtensions: TypedChainedSet - packageMains: TypedChainedSet + class ResolveLoader extends ChainedMap { + extensions: TypedChainedSet; + modules: TypedChainedSet; + moduleExtensions: TypedChainedSet; + packageMains: TypedChainedSet; } - export class Rule extends ChainedMap { - uses: TypedChainedMap - include: TypedChainedSet - exclude: TypedChainedSet + class Rule extends ChainedMap { + uses: TypedChainedMap; + include: TypedChainedSet; + exclude: TypedChainedSet; - parser(value: { [optName: string]: any }): this - test(value: webpack.Condition | webpack.Condition[]): this - enforce(value: 'pre' | 'post'): this + parser(value: { [optName: string]: any }): this; + test(value: webpack.Condition | webpack.Condition[]): this; + enforce(value: 'pre' | 'post'): this; - use(name: string): Use - pre(): this - post(): this + use(name: string): Use; + pre(): this; + post(): this; } - type LoaderOptions = { [name: string]: any } + interface LoaderOptions { [name: string]: any; } - export class Use extends ChainedMap { - loader(value: string): this - options(value: LoaderOptions): this + class Use extends ChainedMap { + loader(value: string): this; + options(value: LoaderOptions): this; - tap(f: (options: LoaderOptions) => LoaderOptions): this + tap(f: (options: LoaderOptions) => LoaderOptions): this; } type DevTool = 'eval' | 'inline-source-map' | 'cheap-eval-source-map' | 'cheap-source-map' | @@ -204,9 +204,9 @@ declare namespace Config { '#@eval' | '#@inline-source-map' | '#@cheap-eval-source-map' | '#@cheap-source-map' | '#@cheap-module-eval-source-map' | '#@cheap-module-source-map' | '#@eval-source-map' | '#@source-map' | '#@nosources-source-map' | '#@hidden-source-map' | '#@nosources-source-map' | - boolean + boolean; interface PluginClass { - new (...opts: any[]): webpack.Plugin + new (...opts: any[]): webpack.Plugin; } } diff --git a/types/webpack-chain/webpack-chain-tests.ts b/types/webpack-chain/webpack-chain-tests.ts index da72bc6f9f..f955decd38 100644 --- a/types/webpack-chain/webpack-chain-tests.ts +++ b/types/webpack-chain/webpack-chain-tests.ts @@ -13,7 +13,7 @@ config .context('') .externals('foo') .externals(/node_modules/) - .externals({ 'test': false, 'foo': 'bar' }) + .externals({ test: false, foo: 'bar' }) .externals(['foo', 'bar']) .externals((context, request, cb) => cb(null, true)) .loader({}) From f2b6506ba550e909224e43ecd07e15bbfbfbfce3 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 30 Mar 2017 17:42:07 -0700 Subject: [PATCH 31/31] Fix various lint errors (#15530) --- types/assert-plus/index.d.ts | 2 - types/awesomplete/awesomplete-tests.ts | 10 +- types/awesomplete/index.d.ts | 20 +- types/babel-code-frame/index.d.ts | 2 +- types/base-64/index.d.ts | 2 +- types/bignumber.js/bignumber.js-tests.ts | 18 +- types/bignumber.js/index.d.ts | 2 +- types/charm/charm-tests.ts | 3 +- types/core-js/index.d.ts | 306 +++++++++--------- types/html-webpack-plugin/index.d.ts | 2 +- types/js-md5/index.d.ts | 28 +- types/lodash/tslint.json | 8 +- types/massive/index.d.ts | 21 +- types/massive/massive-tests.ts | 2 +- types/navigo/index.d.ts | 10 +- types/navigo/navigo-tests.ts | 13 +- types/node-hid/node-hid-tests.ts | 9 +- types/phonon/phonon-tests.ts | 32 +- types/sparkpost/index.d.ts | 147 ++++----- types/sparkpost/sparkpost-tests.ts | 151 +++++---- types/sparkpost/tslint.json | 9 +- types/spatialite/index.d.ts | 1 - types/spatialite/spatialite-tests.ts | 15 +- types/stringify-object/index.d.ts | 2 +- types/strip-ansi/strip-ansi-tests.ts | 2 +- .../supertest-as-promised-tests.ts | 7 +- .../swagger-express-mw-tests.ts | 2 - types/swagger-hapi/swagger-hapi-tests.ts | 8 +- types/swagger-node-runner/index.d.ts | 41 ++- .../swagger-node-runner-tests.ts | 12 +- .../swagger-restify-mw-tests.ts | 2 - types/swagger-sails-hook/index.d.ts | 10 +- types/table/index.d.ts | 3 +- types/transducers-js/index.d.ts | 16 +- types/transducers-js/transducers-js-tests.ts | 9 +- types/update-notifier/index.d.ts | 2 +- .../update-notifier/update-notifier-tests.ts | 4 +- types/user-home/user-home-tests.ts | 2 +- types/verror/index.d.ts | 2 +- types/verror/verror-tests.ts | 21 +- types/videojs/index.d.ts | 1 - types/videojs/videojs-tests.ts | 27 +- types/vkbeautify/index.d.ts | 2 +- types/vkbeautify/vkbeautify-tests.ts | 3 +- types/web-animations-js/index.d.ts | 10 +- .../web-animations-js-tests.ts | 18 +- .../index.d.ts | 28 +- .../webappsec-credential-management-tests.ts | 4 +- types/webgl2/tslint.json | 3 + types/webpack/index.d.ts | 16 +- types/webpack/webpack-tests.ts | 20 +- 51 files changed, 517 insertions(+), 573 deletions(-) diff --git a/types/assert-plus/index.d.ts b/types/assert-plus/index.d.ts index 5de187cb85..d79172bc49 100644 --- a/types/assert-plus/index.d.ts +++ b/types/assert-plus/index.d.ts @@ -122,7 +122,6 @@ export function AssertionError(options: any, message ?: string): void; */ export function fail(actual: any, expected: any, message: any, operator: any): void; - /** * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. * @@ -353,5 +352,4 @@ export function doesNotThrow(block: any, error ?: any, message ?: string): void; */ export function ifError(value: any): void; - export as namespace AssertPlus; diff --git a/types/awesomplete/awesomplete-tests.ts b/types/awesomplete/awesomplete-tests.ts index 5a33aeb135..6cea0e1bca 100644 --- a/types/awesomplete/awesomplete-tests.ts +++ b/types/awesomplete/awesomplete-tests.ts @@ -1,6 +1,6 @@ import * as Awesomplete from 'awesomplete'; -var input = document.getElementById("myinput"); +const input = document.getElementById("myinput"); new Awesomplete(input, {list: "#mylist"}); new Awesomplete(input, {list: document.querySelector("#mylist")}); @@ -9,7 +9,7 @@ new Awesomplete(input, { list: ["Ada", "Java", "JavaScript", "LOLCODE", "Node.js", "Ruby on Rails"] }); -var awesomplete = new Awesomplete(input); +const awesomplete = new Awesomplete(input); awesomplete.list = ["Ada", "Java", "JavaScript", "LOLCODE", "Node.js", "Ruby on Rails"]; new Awesomplete(input, { @@ -46,15 +46,15 @@ new Awesomplete('input[data-multiple]', { }, replace: (text: string) => { - var before = this.input.value.match(/^.+,\s*|/)[0]; + const before = this.input.value.match(/^.+,\s*|/)[0]; this.input.value = before + text + ", "; } }); -var ajax = new XMLHttpRequest(); +const ajax = new XMLHttpRequest(); ajax.open("GET", "https://restcountries.eu/rest/v1/lang/fr", true); ajax.onload = () => { - var list = JSON.parse(ajax.responseText).map((i: any) => i.name); + const list = JSON.parse(ajax.responseText).map((i: any) => i.name); new Awesomplete(document.querySelector("#ajax-example input"), { list }); }; ajax.send(); diff --git a/types/awesomplete/index.d.ts b/types/awesomplete/index.d.ts index 41abc36be6..4612d66210 100644 --- a/types/awesomplete/index.d.ts +++ b/types/awesomplete/index.d.ts @@ -6,14 +6,14 @@ declare class Awesomplete { constructor(input: Element | HTMLElement | string, o?: Awesomplete.Options); static all: any[]; - static $$: (expr: string | NodeSelector, con?: any) => NodeList; + static $$(expr: string | NodeSelector, con?: any): NodeList; static ITEM: (text: string, input: string) => HTMLElement; static $: { (expr: string|Element, con?: NodeSelector): string | Element; - regExpEscape: (s: { replace: (arg0: RegExp, arg1: string) => void }) => any; - create: (tag: string, o: any) => HTMLElement; - fire: (target: EventTarget, type: string, properties: any) => any; - siblingIndex: (el: Element) => number; + regExpEscape(s: { replace(arg0: RegExp, arg1: string): void }): any; + create(tag: string, o: any): HTMLElement; + fire(target: EventTarget, type: string, properties: any): any; + siblingIndex(el: Element): number; }; static FILTER_STARTSWITH: (text: string, input: string) => boolean; static FILTER_CONTAINS: (text: string, input: string) => boolean; @@ -45,11 +45,11 @@ declare namespace Awesomplete { minChars?: number; maxItems?: number; autoFirst?: boolean; - data?: (item: Suggestion, input: string) => string; - filter?: (text: string, input: string) => boolean; - sort?: (left: number | any[], right: number | any[]) => number; - item?: (text: string, input: string) => HTMLElement; - replace?: (text: string) => void; + data?(item: Suggestion, input: string): string; + filter?(text: string, input: string): boolean; + sort?(left: number | any[], right: number | any[]): number; + item?(text: string, input: string): HTMLElement; + replace?(text: string): void; } } diff --git a/types/babel-code-frame/index.d.ts b/types/babel-code-frame/index.d.ts index ebfde63c4c..19d18b6df8 100644 --- a/types/babel-code-frame/index.d.ts +++ b/types/babel-code-frame/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface BabelCodeFrameOptions { - /** Syntax highlight the code as JavaScript for terminals. default: false*/ + /** Syntax highlight the code as JavaScript for terminals. default: false */ highlightCode?: boolean; /** The number of lines to show above the error. default: 2 */ linesBelow?: number; diff --git a/types/base-64/index.d.ts b/types/base-64/index.d.ts index ddd10db17b..26cb9c4a41 100644 --- a/types/base-64/index.d.ts +++ b/types/base-64/index.d.ts @@ -22,4 +22,4 @@ export function encode(input: string): string; * with atob() as described in the HTML Standard. * see: https://html.spec.whatwg.org/multipage/webappapis.html#dom-windowbase64-atob */ -export function decode(input: string): string; \ No newline at end of file +export function decode(input: string): string; diff --git a/types/bignumber.js/bignumber.js-tests.ts b/types/bignumber.js/bignumber.js-tests.ts index 9dc96dd7ea..8ea0775dba 100644 --- a/types/bignumber.js/bignumber.js-tests.ts +++ b/types/bignumber.js/bignumber.js-tests.ts @@ -1,5 +1,5 @@ -var x: BigNumber.BigNumber = new BigNumber(9); -var y = new BigNumber(x); +let x: BigNumber.BigNumber = new BigNumber(9); +let y = new BigNumber(x); BigNumber(435.345); @@ -27,7 +27,7 @@ new BigNumber(1.23456789); new BigNumber(1.23456789, 10); BigNumber.config({ DECIMAL_PLACES: 5 }); -var BN = BigNumber.another({ DECIMAL_PLACES: 9 }); +let BN = BigNumber.another({ DECIMAL_PLACES: 9 }); x = new BigNumber(1); y = new BN(1); @@ -112,14 +112,14 @@ BigNumber.config({ BigNumber.config(40, 7, [-10, 20], 500, 1, 1, 3, 80); -var obj = BigNumber.config(); +const obj = BigNumber.config(); obj.ERRORS; obj.RANGE; x = new BigNumber('3257869345.0378653'); BigNumber.max(4e9, x, '123456789.9'); -var arr = [12, '13', new BigNumber(14)]; +let arr = [12, '13', new BigNumber(14)]; BigNumber.max(arr); x = new BigNumber('3257869345.0378653'); @@ -137,7 +137,7 @@ BigNumber.config({ ROUNDING_MODE: 2 }); x = new BigNumber(-0.8); y = x.absoluteValue(); -var z = y.abs(); +let z = y.abs(); x = new BigNumber(1.3); x.ceil(); @@ -300,7 +300,7 @@ y.toFixed(2); y.toFixed(2, 1); y.toFixed(5); -var format = { +const format = { decimalSeparator: '.', groupSeparator: ',', groupSize: 3, @@ -332,7 +332,7 @@ x.toFormat(6); x = new BigNumber(1.75); x.toFraction(); -var pi = new BigNumber('3.14159265358'); +const pi = new BigNumber('3.14159265358'); pi.toFraction(); pi.toFraction(100000); pi.toFraction(10000); @@ -344,7 +344,7 @@ x = new BigNumber('177.7e+457'); y = new BigNumber(235.4325); z = new BigNumber('0.0098074'); -var str = JSON.stringify([x, y, z]); +const str = JSON.stringify([x, y, z]); JSON.parse(str, (key, val) => key === '' ? val : new BigNumber(val)); diff --git a/types/bignumber.js/index.d.ts b/types/bignumber.js/index.d.ts index 10423b1ed3..d627ad136c 100644 --- a/types/bignumber.js/index.d.ts +++ b/types/bignumber.js/index.d.ts @@ -673,4 +673,4 @@ declare namespace BigNumber { */ isBigNumber: true; } -} \ No newline at end of file +} diff --git a/types/charm/charm-tests.ts b/types/charm/charm-tests.ts index d87a360084..09dc93184e 100644 --- a/types/charm/charm-tests.ts +++ b/types/charm/charm-tests.ts @@ -8,7 +8,8 @@ const text = 'Always after me lucky charms.'; let offset = 0; const iv = setInterval(() => { - let y = 0, dy = 1; + let y = 0; + let dy = 1; for (let i = 0; i < 40; i++) { const color = colors[(i + offset) % colors.length]; const c = text[(i + offset) % text.length]; diff --git a/types/core-js/index.d.ts b/types/core-js/index.d.ts index dc37560d4d..9593bc7a76 100644 --- a/types/core-js/index.d.ts +++ b/types/core-js/index.d.ts @@ -26,13 +26,13 @@ and limitations under the License. interface SymbolConstructor { /** - * Non-standard. Use simple mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill - */ + * Non-standard. Use simple mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill + */ useSimple(): void; /** - * Non-standard. Use setter mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill - */ + * Non-standard. Use setter mode for core-js symbols. See https://github.com/zloirock/core-js/#caveats-when-using-symbol-polyfill + */ userSetter(): void; } @@ -80,202 +80,202 @@ interface Set { interface ArrayConstructor { /** - * Appends new elements to an array, and returns the new length of the array. - * @param items New elements of the Array. - */ + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ push(array: ArrayLike, ...items: T[]): number; /** - * Removes the last element from an array and returns it. - */ + * Removes the last element from an array and returns it. + */ pop(array: ArrayLike): T; /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ concat(array: ArrayLike, ...items: Array): T[]; /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - */ + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ join(array: ArrayLike, separator?: string): string; /** - * Reverses the elements in an Array. - */ + * Reverses the elements in an Array. + */ reverse(array: ArrayLike): T[]; /** - * Removes the first element from an array and returns it. - */ + * Removes the first element from an array and returns it. + */ shift(array: ArrayLike): T; /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ slice(array: ArrayLike, start?: number, end?: number): T[]; /** - * Sorts an array. - * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. - */ + * Sorts an array. + * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. + */ sort(array: ArrayLike, compareFn?: (a: T, b: T) => number): T[]; /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @param items Elements to insert into the array in place of the deleted elements. - */ + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ splice(array: ArrayLike, start: number, deleteCount?: number, ...items: T[]): T[]; /** - * Inserts new elements at the start of an array. - * @param items Elements to insert at the start of the Array. - */ + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ unshift(array: ArrayLike, ...items: T[]): number; /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ indexOf(array: ArrayLike, searchElement: T, fromIndex?: number): number; /** - * Returns the index of the last occurrence of a specified value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - */ + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ lastIndexOf(array: ArrayLike, earchElement: T, fromIndex?: number): number; /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. - * The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. + * The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ every(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. - * The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. + * The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ some(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ forEach(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ map(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ filter(array: ArrayLike, callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; /** - * Calls the specified callback function for all the elements in an array. - * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. - * The first call to the callbackfn function provides this value as an argument instead of an array value. - */ + * Calls the specified callback function for all the elements in an array. + * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. + * The first call to the callbackfn function provides this value as an argument instead of an array value. + */ reduce(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; /** - * Calls the specified callback function for all the elements in an array. - * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. - * The first call to the callbackfn function provides this value as an argument instead of an array value. - */ + * Calls the specified callback function for all the elements in an array. + * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. + * The first call to the callbackfn function provides this value as an argument instead of an array value. + */ reduce(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. - * The first call to the callbackfn function provides this value as an argument instead of an array value. - */ + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. + * The first call to the callbackfn function provides this value as an argument instead of an array value. + */ reduceRight(array: ArrayLike, callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. - * The first call to the callbackfn function provides this value as an argument instead of an array value. - */ + * Calls the specified callback function for all the elements in an array, in descending order. + * The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. + * The first call to the callbackfn function provides this value as an argument instead of an array value. + */ reduceRight(array: ArrayLike, callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; /** - * Returns an array of key, value pairs for every entry in the array - */ + * Returns an array of key, value pairs for every entry in the array + */ entries(array: ArrayLike): IterableIterator<[number, T]>; /** - * Returns an list of keys in the array - */ + * Returns an list of keys in the array + */ keys(array: ArrayLike): IterableIterator; /** - * Returns an list of values in the array - */ + * Returns an list of values in the array + */ values(array: ArrayLike): IterableIterator; /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ + * Returns the value of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ find(array: ArrayLike, predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T; /** - * Returns the index of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ + * Returns the index of the first element in the array where predicate is true, and undefined + * otherwise. + * @param predicate find calls predicate once for each element of the array, in ascending + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ findIndex(array: ArrayLike, predicate: (value: T) => boolean, thisArg?: any): number; /** - * Returns the this object after filling the section identified by start and end with value - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ + * Returns the this object after filling the section identified by start and end with value + * @param value value to fill array section with + * @param start index to start filling the array at. If start is negative, it is treated as + * length+start where length is the length of the array. + * @param end index to stop filling the array at. If end is negative, it is treated as + * length+end. + */ fill(array: ArrayLike, value: T, start?: number, end?: number): T[]; /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ + * Returns the this object after copying a section of the array identified by start and end + * to the same array starting at position target + * @param target If target is negative, it is treated as length+target where length is the + * length of the array. + * @param start If start is negative, it is treated as length+start. If end is negative, it + * is treated as length+end. + * @param end If not specified, length of the this object is used as its default value. + */ copyWithin(array: ArrayLike, target: number, start: number, end?: number): T[]; includes(array: ArrayLike, value: T, fromIndex?: number): boolean; @@ -290,23 +290,23 @@ interface ArrayConstructor { interface ObjectConstructor { /** - * Non-standard. - */ + * Non-standard. + */ isObject(value: any): boolean; /** - * Non-standard. - */ + * Non-standard. + */ classof(value: any): string; /** - * Non-standard. - */ + * Non-standard. + */ define(target: T, mixin: any): T; /** - * Non-standard. - */ + * Non-standard. + */ make(proto: T, mixin?: any): T; } @@ -322,8 +322,8 @@ interface Log extends Console { } /** - * Non-standard. - */ + * Non-standard. + */ declare var log: Log; // ############################################################################################# @@ -369,8 +369,8 @@ interface DictConstructor { } /** - * Non-standard. - */ + * Non-standard. + */ declare var Dict: DictConstructor; // ############################################################################################# @@ -380,8 +380,8 @@ declare var Dict: DictConstructor; interface Function { /** - * Non-standard. - */ + * Non-standard. + */ part(...args: any[]): any; } @@ -392,13 +392,13 @@ interface Function { interface Date { /** - * Non-standard. - */ + * Non-standard. + */ format(template: string, locale?: string): string; /** - * Non-standard. - */ + * Non-standard. + */ formatUTC(template: string, locale?: string): string; } @@ -409,13 +409,13 @@ interface Date { interface Array { /** - * Non-standard. - */ + * Non-standard. + */ turn(callbackfn: (memo: U, value: T, index: number, array: T[]) => void, memo?: U): U; /** - * Non-standard. - */ + * Non-standard. + */ turn(callbackfn: (memo: T[], value: T, index: number, array: T[]) => void, memo?: T[]): T[]; } @@ -426,8 +426,8 @@ interface Array { interface Number { /** - * Non-standard. - */ + * Non-standard. + */ [Symbol.iterator](): IterableIterator; } @@ -438,13 +438,13 @@ interface Number { interface String { /** - * Non-standard. - */ + * Non-standard. + */ escapeHTML(): string; /** - * Non-standard. - */ + * Non-standard. + */ unescapeHTML(): string; } diff --git a/types/html-webpack-plugin/index.d.ts b/types/html-webpack-plugin/index.d.ts index 792c7a2dc0..797fce3388 100644 --- a/types/html-webpack-plugin/index.d.ts +++ b/types/html-webpack-plugin/index.d.ts @@ -84,5 +84,5 @@ declare namespace HtmlWebpackPlugin { /** @deprecated use MinifyOptions */ type MinifyConfig = MinifyOptions; /** @deprecated use Options */ - type Config = Options; + type Config = Options; } diff --git a/types/js-md5/index.d.ts b/types/js-md5/index.d.ts index 690279bbe4..43057e147b 100644 --- a/types/js-md5/index.d.ts +++ b/types/js-md5/index.d.ts @@ -7,24 +7,24 @@ declare namespace md5 { type message = string | any[] | Uint8Array | ArrayBuffer; interface Md5 { - array: () => number[]; - arrayBuffer: () => ArrayBuffer; - buffer: () => ArrayBuffer; - digest: () => number[]; - hex: () => string; - toString: () => string; - update: (message: message) => Md5; + array(): number[]; + arrayBuffer(): ArrayBuffer; + buffer(): ArrayBuffer; + digest(): number[]; + hex(): string; + toString(): string; + update(message: message): Md5; } interface md5 { (message: message): string; - hex: (message: message) => string; - array: (message: message) => number[]; - digest: (message: message) => number[]; - arrayBuffer: (message: message) => ArrayBuffer; - buffer: (message: message) => ArrayBuffer; - create: () => Md5; - update: (message: message) => Md5; + hex(message: message): string; + array(message: message): number[]; + digest(message: message): number[]; + arrayBuffer(message: message): ArrayBuffer; + buffer(message: message): ArrayBuffer; + create(): Md5; + update(message: message): Md5; } } diff --git a/types/lodash/tslint.json b/types/lodash/tslint.json index 7805e0387d..7e8d4b911a 100644 --- a/types/lodash/tslint.json +++ b/types/lodash/tslint.json @@ -1,16 +1,22 @@ { "extends": "../tslint.json", "rules": { + "adjacent-overload-signatures": false, + "align": false, "array-type": false, + "ban-types": false, "callable-types": false, "comment-format": false, - "ban-types": false, + "eofline": false, "interface-name": false, "interface-over-type-literal": false, + "jsdoc-format": false, "max-line-length": false, "no-empty-interface": false, + "no-trailing-whitespace": false, "object-literal-key-quotes": false, "one-line": false, + "one-variable-per-declaration": false, "prefer-const": false, "semicolon": false, "triple-equals": false, diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index 53e857e689..512c9067e2 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Pascal Birchler // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace massive { +export namespace massive { interface ConnectionOptions { connectionString?: string; db?: string; @@ -11,10 +11,9 @@ declare namespace massive { interface Doc { findDoc(context: any, callback: ResultCallback): void; - searchDoc(options: { - keys: string[]; - term: string; - }, callback: ResultCallback): void; + searchDoc( + options: { keys: string[], term: string }, + callback: ResultCallback): void; saveDoc(context: string, callback: ResultCallback): void; destroy(context: any, callback: ResultCallback): void; } @@ -32,7 +31,7 @@ declare namespace massive { } interface QueryFunction { - find: (params: any|any[], callback: ResultCallback) => void; + find(params: any|any[], callback: ResultCallback): void; } interface QueryArguments { @@ -52,16 +51,16 @@ export interface Massive { practice: Table; practicesession: Table; sport: Table; - testdata: (callback: ResultCallback) => void; + testdata(callback: ResultCallback): void; team: Table; teammember: Table; teamsport: Table; scriptsDir: string; connectionString: string; - query: () => void; - stream: () => void; - executeSqlFile: (args: any, next: ResultCallback) => void; - end: () => void; + query(): void; + stream(): void; + executeSqlFile(args: any, next: ResultCallback): void; + end(): void; tables: Array; views: any[]; queryFiles: massive.QueryFile[]; diff --git a/types/massive/massive-tests.ts b/types/massive/massive-tests.ts index 2978440f4a..cb53e3e7c8 100644 --- a/types/massive/massive-tests.ts +++ b/types/massive/massive-tests.ts @@ -2,4 +2,4 @@ import * as Massive from 'massive'; Massive.connect({connectionString: 'foo'}, (err: Error, db: Massive.Massive) => {}); -Massive.run('foo', 123, (err: Error, db: Massive.Massive) => {}); \ No newline at end of file +Massive.run('foo', 123, (err: Error, db: Massive.Massive) => {}); diff --git a/types/navigo/index.d.ts b/types/navigo/index.d.ts index 35c9f009f6..138d0c043f 100644 --- a/types/navigo/index.d.ts +++ b/types/navigo/index.d.ts @@ -4,13 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface NavigoHooks { - before?: ((done: (suppress?: boolean) => void) => void); - after?: () => void; + before?(done: (suppress?: boolean) => void): void; + after?(): void; } -type RouteHandler = ((parametersObj: any, query: string) => void) | { as: string; uses: (parametersObj: any) => void }; +type RouteHandler = ((parametersObj: any, query: string) => void) | { as: string; uses(parametersObj: any): void }; declare class Navigo { - /** * Constructs the router * @param root The main URL of your application. @@ -18,7 +17,6 @@ declare class Navigo { */ constructor(root?: string | null, useHash?: boolean); - on(location: string, handler: RouteHandler, hooks?: NavigoHooks): Navigo; on(location: RegExp, handler: (...parameters: string[]) => void, hooks?: NavigoHooks): Navigo; on(routes: { [key: string]: RouteHandler }): Navigo; @@ -46,4 +44,4 @@ declare class Navigo { destroy(): void; } export = Navigo; -export as namespace Navigo; \ No newline at end of file +export as namespace Navigo; diff --git a/types/navigo/navigo-tests.ts b/types/navigo/navigo-tests.ts index 73ea91f416..762c97b6de 100644 --- a/types/navigo/navigo-tests.ts +++ b/types/navigo/navigo-tests.ts @@ -1,9 +1,9 @@ import Navigo = require("navigo"); -var root = null; -var useHash = false; +const root = null; +const useHash = false; -var router = new Navigo(root, useHash); +let router = new Navigo(root, useHash); router .on('/products/list', () => { @@ -33,7 +33,7 @@ router 'products/:id': () => { // do something }, - 'products': () => { + products: () => { // do something }, '*': () => { @@ -42,7 +42,6 @@ router }) .resolve(); - router .on('/user/:id/:action', (params: { id: string; action: string }) => { // If we have http://site.com/user/42/save as a url then @@ -89,7 +88,7 @@ router.navigate('/products/list'); router.navigate('http://site.com/products/list', true); router = new Navigo('http://site.com/', true); -var handler = () => { +const handler = () => { // do something }; router.on({ @@ -97,7 +96,7 @@ router.on({ '/trip/save': { as: 'trip.save', uses: handler }, '/trip/:action/:tripId': { as: 'trip.action', uses: handler } }); -var a: string = (router.generate('trip.edit', { tripId: 42 })); // --> /trip/42/edit +let a: string = (router.generate('trip.edit', { tripId: 42 })); // --> /trip/42/edit a = (router.generate('trip.action', { tripId: 42, action: 'save' })); // --> /trip/save/42 a = (router.generate('trip.save')); // --> /trip/save diff --git a/types/node-hid/node-hid-tests.ts b/types/node-hid/node-hid-tests.ts index ef1f0c7e03..27d0f1f45d 100644 --- a/types/node-hid/node-hid-tests.ts +++ b/types/node-hid/node-hid-tests.ts @@ -1,13 +1,12 @@ import HID = require('node-hid'); -var devices = HID.devices(); +const devices = HID.devices(); +let device = new HID.HID("path"); -var device = new HID.HID("path"); - -var device = new HID.HID(12, 22); +device = new HID.HID(12, 22); device.on("data", data => {}); device.on("error", err => {}); -device.write([0x00, 0x01, 0x01, 0x05, 0xff, 0xff]); \ No newline at end of file +device.write([0x00, 0x01, 0x01, 0x05, 0xff, 0xff]); diff --git a/types/phonon/phonon-tests.ts b/types/phonon/phonon-tests.ts index 6b9851b642..c31fcbbabb 100644 --- a/types/phonon/phonon-tests.ts +++ b/types/phonon/phonon-tests.ts @@ -42,7 +42,6 @@ phonon.navigator().changePage('page-name', 'optional-parameter'); let page: string = phonon.navigator().currentPage; page = phonon.navigator().previousPage; - let ev = document.createEvent(''); document.on('pagecreated', event => { console.log('global state pagecreated: ' + event.detail.page); @@ -71,7 +70,7 @@ phonon.i18n().getPreference(); phonon.i18n().getLocale(); // Code examples from http://phonon.quarkdev.com/docs/ajax -var req = phonon.ajax({ +const req = phonon.ajax({ method: 'GET', url: 'http://mysite.com/api/', crossDomain: true, @@ -127,7 +126,7 @@ phonon.sidePanel('#side-panel-id').close(); let pAlert = phonon.alert("text", "title", true, "textOk"); pAlert.on('confirm', () => {}); -var pconfirm = phonon.confirm("text", "title", true, "textOk", "textCancel"); +const pconfirm = phonon.confirm("text", "title", true, "textOk", "textCancel"); pconfirm.on('confirm', () => {}); pconfirm.on('cancel', () => {}); @@ -166,8 +165,8 @@ popover.setList([ } ]); popover.setList(['a', 'b', 'c'], item => { - var text = typeof item === 'string' ? item : item.text; - var value = typeof item === 'string' ? item : item.value; + const text = typeof item === 'string' ? item : item.text; + const value = typeof item === 'string' ? item : item.value; return '
  • ' + text + '
  • '; }); @@ -196,7 +195,6 @@ popover = phonon.popover() phonon.preloader('#my-preloader').show(); phonon.preloader('#my-preloader').hide(); - // Code examples from http://phonon.quarkdev.com/docs/tabs let tabNumber = 2; phonon.tab().setCurrentTab('pageName', tabNumber); @@ -219,8 +217,8 @@ let app = phonon.navigator(); app.on({page: 'home', preventClose: false, content: null}); app.on({page: 'pagetwo', preventClose: true, content: 'pagetwo.html', readyDelay: 1}, activity => { let action: string | null = null; - var onAction = (evt: any) => { - var target = evt.target; + const onAction = (evt: any) => { + const target = evt.target; action = 'ok'; if (target.getAttribute('data-order') === 'order') { phonon.alert('Thank you for your order!', 'Dear customer'); @@ -272,7 +270,7 @@ phonon.options({ } }); -var app2 = phonon.navigator(); +const app2 = phonon.navigator(); app2.on({page: 'home', content: 'home.html'}); app2.on({page: 'pagedialog', content: 'pagedialog.html'}, activity => { activity.onCreate(() => { @@ -299,7 +297,7 @@ app2.on({page: 'pagedialog', content: 'pagedialog.html'}, activity => { const showPrompt = document.querySelector('#show-prompt'); if (showPrompt) { showPrompt.on('tap', () => { - var prompt = phonon.prompt('Example', 'Hello'); + const prompt = phonon.prompt('Example', 'Hello'); prompt.on('confirm', value => { phonon.alert(value, 'Inserted Value'); }); @@ -417,7 +415,7 @@ phonon.navigator().on({ page: 'home' }, activity => { const input = document.querySelector( '#searchJS' ); let list = ''; // external autocomplete - var req = phonon.ajax({ + const req = phonon.ajax({ method: "GET", url: 'https://restcountries.eu/rest/v1/lang/en', dataType: "json", @@ -461,7 +459,7 @@ app3.on({page: 'home', content: null}, activity => { element = document.querySelector('#show-confirm'); if (element) { element.on('tap', () => { - var confirm = phonon.confirm('Example', 'Hello'); + const confirm = phonon.confirm('Example', 'Hello'); confirm.on('confirm', () => { phonon.alert('Confirmed!'); }); @@ -474,7 +472,7 @@ app3.on({page: 'home', content: null}, activity => { element = document.querySelector('#show-prompt'); if (element) { element.on('tap', () => { - var prompt = phonon.prompt('Example', 'Hello'); + const prompt = phonon.prompt('Example', 'Hello'); prompt.on('confirm', value => { phonon.alert(value, 'Inserted Value'); }); @@ -487,7 +485,7 @@ app3.on({page: 'home', content: null}, activity => { element = document.querySelector('#show-indicator'); if (element) { element.on('tap', () => { - var indicator = phonon.indicator('Please wait 3 seconds', false); + const indicator = phonon.indicator('Please wait 3 seconds', false); window.setTimeout(() => { indicator.close(); }, 3000); @@ -523,9 +521,9 @@ function setupHTML() { phonon.i18n().bind(); } -var setPreference = (evt: any) => { - var target = evt.target; - var lang = target.getAttribute('data-l'); +const setPreference = (evt: any) => { + const target = evt.target; + const lang = target.getAttribute('data-l'); if (lang) { phonon.updateLocale(lang); } diff --git a/types/sparkpost/index.d.ts b/types/sparkpost/index.d.ts index fc6e408949..24ac0efbcc 100644 --- a/types/sparkpost/index.d.ts +++ b/types/sparkpost/index.d.ts @@ -490,9 +490,11 @@ declare class SparkPost { * @param options The create options. If true, directly overwrite the existing published template. If false, create a new draft * @param callback The request callback with template id results */ - update(id: string, template: SparkPost.UpdateTemplate, options: { - update_published?: boolean; - }, callback: SparkPost.ResultsCallback<{ id: string }>): void; + update( + id: string, + template: SparkPost.UpdateTemplate, + options: { update_published?: boolean }, + callback: SparkPost.ResultsCallback<{ id: string }>): void; /** * Update an existing template * @@ -500,7 +502,9 @@ declare class SparkPost { * @param {SparkPost.UpdateTemplate} template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes} * @param {SparkPost.ResultsCallback<{ id: string }>} callback The request callback with template id results */ - update(id: string, template: SparkPost.UpdateTemplate, + update( + id: string, + template: SparkPost.UpdateTemplate, callback: SparkPost.ResultsCallback<{ id: string }>): void; /** * Update an existing template @@ -759,12 +763,12 @@ declare class SparkPost { * @param options An optional limit that specifies the maximum number of results to return. Defaults to 1000 * @param callback The request callback with status results */ - getBatchStatus(id: string, options: { limit?: number }, callback: SparkPost.ResultsCallback<{ + getBatchStatus(id: string, options: { limit?: number }, callback: SparkPost.ResultsCallback): void; + }>>): void; /** * Gets recent status information about a webhook. * @@ -776,12 +780,12 @@ declare class SparkPost { * response_code: number; * }[]>} callback The request callback with status results */ - getBatchStatus(id: string, callback: SparkPost.ResultsCallback<{ + getBatchStatus(id: string, callback: SparkPost.ResultsCallback): void; + }>>): void; /** * Gets recent status information about a webhook. * @@ -794,12 +798,12 @@ declare class SparkPost { * response_code: number; * }[]>} The status results */ - getBatchStatus(id: string, options: { limit?: number }): SparkPost.ResultsPromise<{ + getBatchStatus(id: string, options: { limit?: number }): SparkPost.ResultsPromise; + }>>; /** * Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL. * @param callback The request callback containing documentation results @@ -852,44 +856,41 @@ declare class SparkPost { } declare namespace SparkPost { - - export interface ErrorWithDescription { + interface ErrorWithDescription { message: string; code: string; description: string; } - export interface ErrorWithParam { + interface ErrorWithParam { message: string; param: string; value: string | null; } - export interface SparkPostError extends Error { + interface SparkPostError extends Error { name: "SparkPostError"; errors: ErrorWithDescription[] | ErrorWithParam[]; statusCode: number; } - export interface ConstructorOptions { + interface ConstructorOptions { origin?: string; endpoint?: string; apiVersion?: string; headers?: any; } - export interface Response extends Http.IncomingMessage { + interface Response extends Http.IncomingMessage { body: T; } - export interface Callback { - (err: Error | SparkPostError | null, res: Response): void; - } - export type ResultsCallback = Callback<{ results: T }>; - export type ResultsPromise = Promise<{ results: T }>; + type Callback = (err: Error | SparkPostError | null, res: Response) => void; + type ResultsCallback = Callback<{ results: T }>; + type ResultsPromise = Promise<{ results: T }>; - export interface Domain { + interface Domain { domain: string; } - export interface MessageEvent { + interface MessageEvent { /** Type of event this record describes */ type: string; /** Classification code for a given message (see [Bounce Classification Codes](https://support.sparkpost.com/customer/portal/articles/1929896)) */ @@ -940,7 +941,7 @@ declare namespace SparkPost { transmission_id: string; } - export interface MessageEventParameters { + interface MessageEventParameters { /** delimited list of bounce classification codes to search. (See Bounce Classification Codes.) */ bounce_classes?: Array | string | number; /** delimited list of campaign ID’s to search (i.e. the campaign id used during creation of a transmission). */ @@ -975,14 +976,14 @@ declare namespace SparkPost { transmission_ids?: string[] | string; } - export interface RecipientListMetadata { + interface RecipientListMetadata { total_rejected_recipients: number; total_accepted_recipients: number; id: string; name: string; } - export interface RecipientList { + interface RecipientList { /** Short, unique, recipient list identifier */ id: string; /** Short, pretty/readable recipient list display name, not required to be unique */ @@ -994,12 +995,12 @@ declare namespace SparkPost { /** Number of accepted recipients */ total_accepted_recipients: number; } - export interface RecipientListWithRecipients extends RecipientList { + interface RecipientListWithRecipients extends RecipientList { /** Array of recipient objects */ recipients: Recipient[]; } - export interface CreateRecipientList { + interface CreateRecipientList { /** Short, unique, recipient list identifier */ id?: string; /** Short, pretty/readable recipient list display name, not required to be unique */ @@ -1013,7 +1014,7 @@ declare namespace SparkPost { /** Array of recipient objects */ recipients: Recipient[]; } - export interface UpdateRecipientList { + interface UpdateRecipientList { /** Short, unique, recipient list identifier */ id?: string; /** Short, pretty/readable recipient list display name, not required to be unique */ @@ -1026,7 +1027,7 @@ declare namespace SparkPost { recipients: Recipient[]; } - export interface BaseRecipient { + interface BaseRecipient { /** SparkPost Enterprise API only. Email to use for envelope FROM. */ return_path?: string; /** Array of text labels associated with a recipient. */ @@ -1036,11 +1037,11 @@ declare namespace SparkPost { /** Key/value pairs associated with a recipient that are provided to the substitution engine. */ substitution_data?: any; } - export interface RecipientWithAddress { + interface RecipientWithAddress { /** Address information for a recipient At a minimum, address or multichannel_addresses is required. */ address: Address | string; } - export interface RecipientWithMultichannelAddresses { + interface RecipientWithMultichannelAddresses { /** * Address information for a recipient. At a minimum, address or multichannel_addresses is required. * If both address and multichannel_addresses are specified only multichannel_addresses will be used. @@ -1058,9 +1059,9 @@ declare namespace SparkPost { */ multichannel_addresses: MultichannelAddress[]; } - export type Recipient = (RecipientWithAddress | RecipientWithMultichannelAddresses) & BaseRecipient; + type Recipient = (RecipientWithAddress | RecipientWithMultichannelAddresses) & BaseRecipient; - export interface Address { + interface Address { /** Valid email address */ email: string; /** User-friendly name for the email address */ @@ -1069,7 +1070,7 @@ declare namespace SparkPost { header_to?: string; } - export interface MultichannelAddress { + interface MultichannelAddress { /** The communication channel used to reach recipient. Valid values are “email”, “gcm”, “apns”. */ channel: string; /** Valid email address. Required if channel is “email”. */ @@ -1084,7 +1085,7 @@ declare namespace SparkPost { app_id: string; } - export interface RelayWebhook { + interface RelayWebhook { /** User-friendly name no example: Inbound Customer Replies */ name?: string; /** URL of the target to which to POST relay batches */ @@ -1095,7 +1096,7 @@ declare namespace SparkPost { match: Match; } - export interface UpdateRelayWebhook { + interface UpdateRelayWebhook { /** User-friendly name no example: Inbound Customer Replies */ name?: string; /** URL of the target to which to POST relay batches */ @@ -1106,7 +1107,7 @@ declare namespace SparkPost { match?: Match; } - export interface Match { + interface Match { /** Inbound messaging protocol associated with this webhook. Defaults to “SMTP” */ protocol?: string; /** Inbound domain associated with this webhook. Required when protocol is “SMTP”. */ @@ -1115,7 +1116,7 @@ declare namespace SparkPost { esme_address?: string; } - export interface SendingDomain { + interface SendingDomain { /** Name of the sending domain. */ domain: string; /** Associated tracking domain. */ @@ -1132,7 +1133,7 @@ declare namespace SparkPost { shared_with_subaccounts: boolean; } - export interface CreateSendingDomain { + interface CreateSendingDomain { /** Name of the sending domain. */ domain: string; /** Associated tracking domain. */ @@ -1149,7 +1150,7 @@ declare namespace SparkPost { shared_with_subaccounts?: boolean; } - export interface UpdateSendingDomain { + interface UpdateSendingDomain { /** Associated tracking domain. */ tracking_domain?: string; /** JSON object in which DKIM key configuration is defined. */ @@ -1162,7 +1163,7 @@ declare namespace SparkPost { shared_with_subaccounts?: boolean; } - export interface DKIM { + interface DKIM { /** Signing Domain Identifier (SDID). SparkPost Enterprise API only. */ signing_domain?: string; /** DKIM private key. */ @@ -1175,7 +1176,7 @@ declare namespace SparkPost { headers?: string; } - export interface Status { + interface Status { /** Whether domain ownership has been verified */ ownership_verified: boolean; /** Verification status of SPF configuration */ @@ -1190,7 +1191,7 @@ declare namespace SparkPost { postmaster_at_status: "valid" | "invalid" | "unverified" | "pending"; } - export interface VerifyOptions { + interface VerifyOptions { /** * Request verification of DKIM record * @@ -1236,14 +1237,14 @@ declare namespace SparkPost { abuse_at_token?: string; } - export interface VerifyResults extends Status { + interface VerifyResults extends Status { dns?: { dkim_record: string; spf_record: string; }; } - export interface CreateSubaccount { + interface CreateSubaccount { /** user-friendly name */ name: string; /** user-friendly identifier for subaccount API key */ @@ -1256,14 +1257,14 @@ declare namespace SparkPost { ip_pool?: string; } - export interface CreateSubaccountResponse { + interface CreateSubaccountResponse { subaccount_id: number; key: string; label: string; short_key: string; } - export interface UpdateSubaccount { + interface UpdateSubaccount { /** user-friendly name */ name: string; /** status of the subaccount */ @@ -1272,7 +1273,7 @@ declare namespace SparkPost { ip_pool?: string; } - export interface SubaccountInformation { + interface SubaccountInformation { /** ID of subaccount */ id: number; /** User friendly identifier for a specific subaccount */ @@ -1284,7 +1285,7 @@ declare namespace SparkPost { compliance_status: string; } - export interface CreateSupressionListEntry { + interface CreateSupressionListEntry { /** * Email address to be suppressed * @@ -1329,7 +1330,7 @@ declare namespace SparkPost { description?: string; } - export interface SupressionListEntry { + interface SupressionListEntry { /** * Email address to be suppressed * @@ -1372,7 +1373,7 @@ declare namespace SparkPost { updated: string; } - export interface SupressionSearchParameters { + interface SupressionSearchParameters { /** Datetime the entries were last updated, in the format of YYYY-MM-DDTHH:mm:ssZ */ to?: string; /** Datetime the entries were last updated, in the format YYYY-MM-DDTHH:mm:ssZ */ @@ -1431,7 +1432,7 @@ declare namespace SparkPost { limit?: number; } - export interface TemplateContent { + interface TemplateContent { /** HTML content for the email’s text/html MIME part */ html: string; /** Text content for the email’s text/plain MIME part */ @@ -1452,7 +1453,7 @@ declare namespace SparkPost { headers?: any; } - export interface CreateTemplateContent { + interface CreateTemplateContent { /** HTML content for the email’s text/html MIME part */ html?: string; /** Text content for the email’s text/plain MIME part */ @@ -1473,7 +1474,7 @@ declare namespace SparkPost { headers?: any; } - export interface TemplateMeta { + interface TemplateMeta { /** Unique template ID */ id: string; /** Template name */ @@ -1484,7 +1485,7 @@ declare namespace SparkPost { description: string; } - export interface Template { + interface Template { /** * Short, unique, alphanumeric ID used to reference the template. * At a minimum, id or name is required upon creation. @@ -1511,7 +1512,7 @@ declare namespace SparkPost { last_use?: string; } - export interface CreateTemplate { + interface CreateTemplate { /** * Short, unique, alphanumeric ID used to reference the template. * At a minimum, id or name is required upon creation. @@ -1534,7 +1535,7 @@ declare namespace SparkPost { options?: CreateTemplateOptions; } - export interface UpdateTemplate { + interface UpdateTemplate { /** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */ content?: CreateTemplateContent | { email_rfc822: string }; /** Whether the template is published or is a draft version no - defaults to false A template cannot be changed from published to draft. */ @@ -1547,7 +1548,7 @@ declare namespace SparkPost { options?: CreateTemplateOptions; } - export interface TemplateOptions { + interface TemplateOptions { /** Enable or disable open tracking */ open_tracking: boolean; /** Enable or disable click tracking */ @@ -1556,7 +1557,7 @@ declare namespace SparkPost { transactional: boolean; } - export interface CreateTemplateOptions { + interface CreateTemplateOptions { /** Enable or disable open tracking */ open_tracking?: boolean; /** Enable or disable click tracking */ @@ -1565,7 +1566,7 @@ declare namespace SparkPost { transactional?: boolean; } - export interface CreateTransmission { + interface CreateTransmission { /** JSON object in which transmission options are defined */ options?: TransmissionOptions; /** @@ -1598,7 +1599,7 @@ declare namespace SparkPost { content: InlineContent | { template_id: string, use_draft_template?: boolean } | { email_rfc822: string }; } - export interface TransmissionSummary { + interface TransmissionSummary { /** ID of the transmission */ id: string; /** State of the transmission */ @@ -1611,7 +1612,7 @@ declare namespace SparkPost { content: { template_id: string }; } - export interface Transmission { + interface Transmission { /** ID of the transmission */ id: string; /** State of the transmission */ @@ -1638,7 +1639,7 @@ declare namespace SparkPost { rcpt_list_total_chunks: number; } - export interface TransmissionOptions { + interface TransmissionOptions { /** Delay generation of messages until this datetime. */ start_time?: string; /** Whether open tracking is enabled for this transmission */ @@ -1657,7 +1658,7 @@ declare namespace SparkPost { inline_css?: boolean; } - export interface InlineContent { + interface InlineContent { /** HTML content for the email’s text/html MIME part At a minimum, html, text, or push is required. */ html?: string; /** Text content for the email’s text/plain MIME part At a minimum, html, text, or push is required. */ @@ -1678,14 +1679,14 @@ declare namespace SparkPost { inline_images?: Attachment[]; } - export interface PushData { + interface PushData { /** payload for APNs messages */ apns?: any; /** payload for GCM messages */ gcm?: any; } - export interface Attachment { + interface Attachment { /** * The MIME type of the attachment; e.g., “text/plain”, “image/jpeg”, “audio/mp3”, “video/mp4”, “application/msword”, “application/pdf”, etc., * including the “charset” parameter (text/html; charset=“UTF-8”) if needed. @@ -1708,7 +1709,7 @@ declare namespace SparkPost { data: string; } - export interface Webhook { + interface Webhook { /** User-friendly name for webhook */ name: string; /** URL of the target to which to POST event batches */ @@ -1733,7 +1734,7 @@ declare namespace SparkPost { auth_token?: string; } - export interface UpdateWebhook { + interface UpdateWebhook { /** User-friendly name for webhook */ name?: string; /** URL of the target to which to POST event batches */ @@ -1751,15 +1752,15 @@ declare namespace SparkPost { auth_token?: string; } - export interface WebhookLinks { - links: { + interface WebhookLinks { + links: Array<{ href: string; rel: string; method: string[]; - }[]; + }>; } - export interface CreateOpts { + interface CreateOpts { /** * Domain (or subdomain) name for which SparkPost will receive inbound emails * diff --git a/types/sparkpost/sparkpost-tests.ts b/types/sparkpost/sparkpost-tests.ts index d3fef264f0..409fbeac43 100644 --- a/types/sparkpost/sparkpost-tests.ts +++ b/types/sparkpost/sparkpost-tests.ts @@ -6,7 +6,7 @@ let client = new SparkPost(key); // Callback client.get({ uri: "metrics/domains" -}, function(err, data) { +}, (err, data) => { if (err) { console.log(err); return; @@ -27,7 +27,7 @@ client.get({ }); // Callback -client.inboundDomains.create({ domain: 'example1.com' }, function(err, res) { +client.inboundDomains.create({ domain: 'example1.com' }, (err, res) => { if (err) { console.log(err); } else { @@ -48,7 +48,7 @@ client.inboundDomains.create({ domain: 'example1.com' }) }); // Callback -client.inboundDomains.delete("example1.com", function(err, res) { +client.inboundDomains.delete("example1.com", (err, res) => { if (err) { console.log(err); } else { @@ -69,7 +69,7 @@ client.inboundDomains.delete('example1.com') }); // Callback -client.inboundDomains.get("example1.com", function(err, res) { +client.inboundDomains.get("example1.com", (err, res) => { if (err) { console.log(err); } else { @@ -90,7 +90,7 @@ client.inboundDomains.get('example1.com') }); // Callback -client.inboundDomains.list(function(err, res) { +client.inboundDomains.list((err, res) => { if (err) { console.log(err); } else { @@ -111,7 +111,7 @@ client.inboundDomains.list() }); // Callback -client.messageEvents.search({}, function(err, res) { +client.messageEvents.search({}, (err, res) => { if (err) { console.log(err); } else { @@ -124,7 +124,7 @@ client.messageEvents.search({}, function(err, res) { client.messageEvents.search({ events: "click", campaign_ids: "monday_mailshot" -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -141,7 +141,7 @@ client.messageEvents.search({ per_page: 5, events: ["bounce", "out_of_band"], bounce_classes: [10] -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -212,7 +212,7 @@ client.recipientLists.create({ } } ] -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -251,7 +251,7 @@ client.recipientLists.create({ }); // Callback -client.recipientLists.delete("UNIQUE_TEST_ID", function(err, res) { +client.recipientLists.delete("UNIQUE_TEST_ID", (err, res) => { if (err) { console.log(err); } else { @@ -272,7 +272,7 @@ client.recipientLists.delete('UNIQUE_TEST_ID') }); // Callback -client.recipientLists.list(function(err, res) { +client.recipientLists.list((err, res) => { if (err) { console.log(err); } else { @@ -293,7 +293,7 @@ client.recipientLists.list() }); // Callback -client.recipientLists.get('UNIQUE_TEST_ID', function(err, res) { +client.recipientLists.get('UNIQUE_TEST_ID', (err, res) => { if (err) { console.log(err); } else { @@ -305,7 +305,7 @@ client.recipientLists.get('UNIQUE_TEST_ID', function(err, res) { // Callback client.recipientLists.get('UNIQUE_TEST_ID', { show_recipients: true -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -356,7 +356,7 @@ client.recipientLists.update('EXISTING_TEST_ID', { } } ] -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -399,7 +399,7 @@ client.relayWebhooks.create({ match: { domain: "inbound.example.com" } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -426,7 +426,7 @@ client.relayWebhooks.create({ }); // Callback -client.relayWebhooks.delete("123456789", function(err, res) { +client.relayWebhooks.delete("123456789", (err, res) => { if (err) { console.log(err); } else { @@ -447,7 +447,7 @@ client.relayWebhooks.delete('123456789') }); // Callback -client.relayWebhooks.get('123456789', function(err, res) { +client.relayWebhooks.get('123456789', (err, res) => { if (err) { console.log(err); } else { @@ -467,7 +467,7 @@ client.relayWebhooks.get('123456789') console.log(err); }); -client.relayWebhooks.list(function(err, res) { +client.relayWebhooks.list((err, res) => { if (err) { console.log(err); } else { @@ -490,7 +490,7 @@ client.relayWebhooks.list() // Callback client.relayWebhooks.update('123456789', { target: "http://client.test.com/test-webhook" -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -516,12 +516,12 @@ client.relayWebhooks.update('123456789', { client.sendingDomains.create({ domain: "example1.com", dkim: { - "private": "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/==", - "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==", + private: "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/==", + public: "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==", selector: "brisbane", headers: "from:to:subject:date" } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -534,8 +534,8 @@ client.sendingDomains.create({ client.sendingDomains.create({ domain: 'example1.com', dkim: { - 'private': 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/==', - 'public': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==', + private: 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/==', + public: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==', selector: 'brisbane', headers: 'from:to:subject:date' } @@ -550,7 +550,7 @@ client.sendingDomains.create({ }); // Callback -client.sendingDomains.delete("example1.com", function(err, data) { +client.sendingDomains.delete("example1.com", (err, data) => { if (err) { console.log(err); } else { @@ -571,7 +571,7 @@ client.sendingDomains.delete('example1.com') }); // Callback -client.sendingDomains.list(function(err, res) { +client.sendingDomains.list((err, res) => { if (err) { console.log(err); } else { @@ -592,7 +592,7 @@ client.sendingDomains.list() }); // Callback -client.sendingDomains.get('example1.com', function(err, res) { +client.sendingDomains.get('example1.com', (err, res) => { if (err) { console.log(err); } else { @@ -615,12 +615,12 @@ client.sendingDomains.get('example1.com') // Callback client.sendingDomains.update('example1.com', { dkim: { - "private": "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/Y1g==", - "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==", + private: "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/Y1g==", + public: "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==", selector: "hello_selector", headers: "from:to:subject:date" } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -631,8 +631,8 @@ client.sendingDomains.update('example1.com', { client.sendingDomains.update('example1.com', { dkim: { - 'private': 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/Y1g==', - 'public': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==', + private: 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/Y1g==', + public: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==', selector: 'hello_selector', headers: 'from:to:subject:date' } @@ -652,7 +652,7 @@ client.sendingDomains.verify('example1.com', { spf_verify: true, abuse_at_verify: true, postmaster_at_verify: true -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -664,7 +664,7 @@ client.sendingDomains.verify('example1.com', { // Callback client.sendingDomains.verify('example1.com', { dkim_verify: false -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -697,7 +697,7 @@ client.subaccounts.create({ "smtp/inject", "transmissions/modify" ] -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -725,7 +725,7 @@ client.subaccounts.create({ }); // Callback -client.subaccounts.list(function(err, res) { +client.subaccounts.list((err, res) => { if (err) { console.log(err); } else { @@ -746,7 +746,7 @@ client.subaccounts.list() }); // Callback -client.subaccounts.get(123, function(err, res) { +client.subaccounts.get(123, (err, res) => { if (err) { console.log(err); } else { @@ -770,7 +770,7 @@ client.subaccounts.get('123') client.subaccounts.update('123', { name: "Test Subaccount", status: "suspended" -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -794,7 +794,7 @@ client.subaccounts.update('123', { }); // Callback -client.suppressionList.delete('test@test.com', function(err, data) { +client.suppressionList.delete('test@test.com', (err, data) => { if (err) { console.log('Whoops! Something went wrong'); console.log(err); @@ -827,7 +827,7 @@ client.suppressionList.get('test@test.com') }); // Callback -client.suppressionList.get('test@test.com', function(err, data) { +client.suppressionList.get('test@test.com', (err, data) => { if (err) { console.log('Whoops! Something went wrong'); console.log(err); @@ -857,7 +857,7 @@ client.suppressionList.list({ from: '2015-05-07T00:00:00+0000', to: '2015-05-07T23:59:59+0000', limit: 5 -}, function(err, data) { +}, (err, data) => { if (err) { console.log('Whoops! Something went wrong'); console.log(err); @@ -868,7 +868,7 @@ client.suppressionList.list({ }); // Callback -client.suppressionList.list(function(err, data) { +client.suppressionList.list((err, data) => { if (err) { console.log('Whoops! Something went wrong'); console.log(err); @@ -900,7 +900,7 @@ client.suppressionList.upsert({ transactional: false, non_transactional: true, description: 'Test description 1' -}, function(err, data) { +}, (err, data) => { if (err) { console.log('Whoops! Something went wrong'); console.log(err); @@ -960,7 +960,7 @@ client.suppressionList.upsert([ non_transactional: false, description: 'Test description 3' } -], function(err, data) { +], (err, data) => { if (err) { console.log('Whoops! Something went wrong'); console.log(err); @@ -979,7 +979,7 @@ client.templates.create({ subject: "Test email template!", html: "This is a test email template!" } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1008,7 +1008,7 @@ client.templates.create({ }); // Callback -client.templates.delete("TEST_ID", function(err, res) { +client.templates.delete("TEST_ID", (err, res) => { if (err) { console.log(err); } else { @@ -1029,7 +1029,7 @@ client.templates.delete('TEST_ID') }); // Callback -client.templates.list(function(err, res) { +client.templates.list((err, res) => { if (err) { console.log(err); } else { @@ -1052,7 +1052,7 @@ client.templates.list() // Callback client.templates.get('TEST_ID', { draft: true -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1062,7 +1062,7 @@ client.templates.get('TEST_ID', { }); // Callback -client.templates.get('TEST_ID', function(err, res) { +client.templates.get('TEST_ID', (err, res) => { if (err) { console.log(err); } else { @@ -1085,7 +1085,7 @@ client.templates.get('TEST_ID') // Callback client.templates.preview('TEST_ID', { substitution_data: {} -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1120,7 +1120,7 @@ client.templates.update('TEST_ID', { html: "This is a published test email template! Updated!" }, }, { update_published: true }, -function(err, res) { +(err, res) => { if (err) { console.log(err); } else { @@ -1136,7 +1136,7 @@ client.templates.update('TEST_ID', { subject: "Updated Test email template!", html: "This is a test email template! Updated!" } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1163,7 +1163,7 @@ client.templates.update('TEST_ID', { }); // Callback -client.transmissions.list(function(err, res) { +client.transmissions.list((err, res) => { if (err) { console.log(err); } else { @@ -1184,7 +1184,7 @@ client.transmissions.list() client.transmissions.list({ campaign_id: "my_campaign" -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1195,7 +1195,7 @@ client.transmissions.list({ client.transmissions.list({ template_id: "my_template" -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1205,7 +1205,7 @@ client.transmissions.list({ }); // Callback -client.transmissions.get("YOUR-TRANSMISSION-KEY", function(err, res) { +client.transmissions.get("YOUR-TRANSMISSION-KEY", (err, res) => { if (err) { console.log(err); } else { @@ -1238,7 +1238,7 @@ client.transmissions.send({ open_tracking: true, click_tracking: true } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1253,7 +1253,7 @@ client.transmissions.send({ content: { email_rfc822: "Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World" } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1310,7 +1310,7 @@ client.transmissions.send({ text: "Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{customer_type}}\n {{sender}}", html: "

    Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n

    " } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1350,7 +1350,7 @@ client.transmissions.send({ text: "An example email using bcc with SparkPost to the {{recipient_type}} recipient.", html: "

    An example email using bcc with SparkPost to the {{recipient_type}} recipient.

    " } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1388,13 +1388,13 @@ client.transmissions.send({ email: "from@example.com" }, headers: { - "CC": "\"Carbon Copy Recipient\" " + CC: "\"Carbon Copy Recipient\" " }, subject: "Example email using cc", text: "An example email using cc with SparkPost to the {{recipient_type}} recipient.", html: "

    An example email using cc with SparkPost to the {{recipient_type}} recipient.

    " } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1414,7 +1414,7 @@ client.transmissions.send({ html: "

    Hello World

    ", text: "Hello World!" } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1433,7 +1433,7 @@ client.transmissions.send({ subject: "Example Email for Stored List and Template", template_id: "my-template" } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1451,7 +1451,7 @@ client.transmissions.send({ recipients: [{ address: { email: "rick.sanchez@rickandmorty100years.com", name: "Rick Sanchez" } }] }, { num_rcpt_errors: 3 -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1460,7 +1460,6 @@ client.transmissions.send({ } }); - // Promise client.transmissions.send({ options: { @@ -1548,7 +1547,7 @@ client.transmissions.send({ email: 'from@example.com' }, headers: { - 'CC': '"Carbon Copy Recipient" ' + CC: '"Carbon Copy Recipient" ' }, subject: 'Example email using cc', text: 'An example email using cc with SparkPost to the {{recipient_type}} recipient.', @@ -1575,7 +1574,7 @@ client.webhooks.create({ "open", "click" ] -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1606,7 +1605,7 @@ client.webhooks.create({ }); // Callback -client.webhooks.delete("TEST_WEBHOOK_UUID", function(err, res) { +client.webhooks.delete("TEST_WEBHOOK_UUID", (err, res) => { if (err) { console.log(err); } else { @@ -1629,7 +1628,7 @@ client.webhooks.delete('TEST_WEBHOOK_UUID') // Callback client.webhooks.get('TEST_WEBHOOK_UUID', { timezone: 'America/New_York' -}, function(err, data) { +}, (err, data) => { if (err) { console.log('Whoops! Something went wrong'); console.log(err); @@ -1655,7 +1654,7 @@ client.webhooks.get('TEST_WEBHOOK_UUID', { // Callback client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', { limit: 1000 -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1678,7 +1677,7 @@ client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', { }); // Callback -client.webhooks.getDocumentation(function(err, res) { +client.webhooks.getDocumentation((err, res) => { if (err) { console.log(err); } else { @@ -1701,7 +1700,7 @@ client.webhooks.getDocumentation() // Callback client.webhooks.getSamples({ events: "bounce" -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1724,7 +1723,7 @@ client.webhooks.getSamples({ }); // Callback -client.webhooks.list(function(err, res) { +client.webhooks.list((err, res) => { if (err) { console.log(err); } else { @@ -1751,7 +1750,7 @@ client.webhooks.update('TEST_WEBHOOK_UUID', { "policy_rejection", "delay" ] -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { @@ -1782,7 +1781,7 @@ client.webhooks.validate('TEST_WEBHOOK_UUID', { message: { msys: {} } -}, function(err, res) { +}, (err, res) => { if (err) { console.log(err); } else { diff --git a/types/sparkpost/tslint.json b/types/sparkpost/tslint.json index e77aa7b0ee..377cc837d4 100644 --- a/types/sparkpost/tslint.json +++ b/types/sparkpost/tslint.json @@ -1,8 +1 @@ -{ - "extends": "../tslint.json", - "rules": { - "only-arrow-functions-2": [ - false - ] - } -} +{ "extends": "../tslint.json" } diff --git a/types/spatialite/index.d.ts b/types/spatialite/index.d.ts index 28a4a1ae70..3edcc663c6 100644 --- a/types/spatialite/index.d.ts +++ b/types/spatialite/index.d.ts @@ -18,4 +18,3 @@ import { export class Database extends OriginalDatabase { spatialite(cb: (err: Error) => void): void; } - diff --git a/types/spatialite/spatialite-tests.ts b/types/spatialite/spatialite-tests.ts index 0edf111cc1..bac1bef4e9 100644 --- a/types/spatialite/spatialite-tests.ts +++ b/types/spatialite/spatialite-tests.ts @@ -1,9 +1,8 @@ - import spatialite = require("spatialite"); function applySpatialFunctions() { console.log(""); - var spatialDb: spatialite.Database = new spatialite.Database('spatialite', () => { + const spatialDb: spatialite.Database = new spatialite.Database('spatialite', () => { spatialDb.spatialite((err) => { if (err) { console.error(err); @@ -12,14 +11,12 @@ function applySpatialFunctions() { }); } - // Following tests taken from the sqlite3 typings spatialite.verbose(); // This line is enhanced to fulfill the `strictNullChecks` option -var db: spatialite.Database = new spatialite.Database('chain.sqlite3', () => {}); -// var db: spatialite.Database +let db: spatialite.Database = new spatialite.Database('chain.sqlite3', () => {}); function createDb() { console.log("createDb chain"); @@ -33,9 +30,9 @@ function createTable() { function insertRows() { console.log("insertRows Ipsum i"); - var stmt = db.prepare("INSERT INTO lorem VALUES (?)"); + const stmt = db.prepare("INSERT INTO lorem VALUES (?)"); - for (var i = 0; i < 10; i++) { + for (let i = 0; i < 10; i++) { stmt.run("Ipsum " + i); } @@ -73,8 +70,8 @@ runChainExample(); db.serialize(() => { db.run("CREATE TABLE lorem (info TEXT)"); - var stmt = db.prepare("INSERT INTO lorem VALUES (?)"); - for (var i = 0; i < 10; i++) { + const stmt = db.prepare("INSERT INTO lorem VALUES (?)"); + for (let i = 0; i < 10; i++) { stmt.run("Ipsum " + i); } stmt.finalize(); diff --git a/types/stringify-object/index.d.ts b/types/stringify-object/index.d.ts index bfccb83300..3380fc3672 100644 --- a/types/stringify-object/index.d.ts +++ b/types/stringify-object/index.d.ts @@ -8,7 +8,7 @@ declare namespace stringifyObject { } declare function stringifyObject(o: any, options?: { indent?: string, singleQuotes?: boolean, - filter?: (o: any, prop: string) => boolean, + filter?(o: any, prop: string): boolean, inlineCharacterLimit?: number }): string; diff --git a/types/strip-ansi/strip-ansi-tests.ts b/types/strip-ansi/strip-ansi-tests.ts index 12e60b5e82..a39d45bd86 100644 --- a/types/strip-ansi/strip-ansi-tests.ts +++ b/types/strip-ansi/strip-ansi-tests.ts @@ -1,4 +1,4 @@ import stripAnsi = require('strip-ansi'); stripAnsi('\u001b[4mcake\u001b[0m'); -// => 'cake' \ No newline at end of file +// => 'cake' diff --git a/types/supertest-as-promised/supertest-as-promised-tests.ts b/types/supertest-as-promised/supertest-as-promised-tests.ts index 23e47ee319..b86bdafbc9 100644 --- a/types/supertest-as-promised/supertest-as-promised-tests.ts +++ b/types/supertest-as-promised/supertest-as-promised-tests.ts @@ -4,7 +4,7 @@ import * as express from 'express'; declare function describe(desc: string, f: () => void): void; declare function it(desc: string, f: () => void): void; -var app = express(); +const app = express(); // chain your requests like you were promised: request(app) @@ -20,7 +20,6 @@ request(app) // ... }); - // Usage request(app) .get("/kittens") @@ -29,11 +28,10 @@ request(app) // ... }); - request(app).get("/kittens").expect(200); // Agents -var agent = request.agent(app); +const agent = request.agent(app); agent .get("/ugly-kitteh") .expect(404) @@ -41,7 +39,6 @@ agent // ... }); - // Promisey goodness request(app) .get("/kittens") diff --git a/types/swagger-express-mw/swagger-express-mw-tests.ts b/types/swagger-express-mw/swagger-express-mw-tests.ts index a066071758..617e331e1c 100644 --- a/types/swagger-express-mw/swagger-express-mw-tests.ts +++ b/types/swagger-express-mw/swagger-express-mw-tests.ts @@ -16,12 +16,10 @@ SwaggerExpress.create(config, (err, middleware) => { app.listen(port); }); - const swaggerSecurityHandlerCb = (err: Error) => { // do nothing }; - const configComplex: SwaggerExpress.Config = { appRoot: __dirname, configDir: "some/directory", diff --git a/types/swagger-hapi/swagger-hapi-tests.ts b/types/swagger-hapi/swagger-hapi-tests.ts index 3d894aafba..1793887ec3 100644 --- a/types/swagger-hapi/swagger-hapi-tests.ts +++ b/types/swagger-hapi/swagger-hapi-tests.ts @@ -1,18 +1,18 @@ import * as SwaggerHapi from "swagger-hapi"; import * as Hapi from "hapi"; -var app = new Hapi.Server(); +const app = new Hapi.Server(); module.exports = app; // for testing -var config = { +const config = { appRoot: __dirname // required config } as SwaggerHapi.Config; SwaggerHapi.create(config, (err, swaggerHapi) => { if (err) { throw err; } - var port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; app.connection({ port }); // app.address = function() { // return { port }; @@ -28,12 +28,10 @@ SwaggerHapi.create(config, (err, swaggerHapi) => { }); }); - const swaggerSecurityHandlerCb = (err: Error) => { // do nothing }; - const configComplex: SwaggerHapi.Config = { appRoot: __dirname, configDir: "some/directory", diff --git a/types/swagger-node-runner/index.d.ts b/types/swagger-node-runner/index.d.ts index 61880b3f8d..abb0d991ef 100644 --- a/types/swagger-node-runner/index.d.ts +++ b/types/swagger-node-runner/index.d.ts @@ -45,19 +45,19 @@ export interface Config { /** If `true` API is in mock mode * * default is `false` - */ + */ mockMode?: boolean; /** If `true` resonse is validated * * default is `true` - */ + */ validateResponse?: boolean; /** Sets `NODE_CONFIG_DIR` env if not set yet */ configDir?: string; /** Swagger controller directories * * default is array with `/api/controllers` relative to `appRoot` - */ + */ controllersDirs?: string[]; /** Swagger mock controller directories * @@ -126,9 +126,9 @@ interface SwaggerSecurityHandlers { export interface Runner extends EventEmitter { /** Resolves path (relative to `config.appRoot`) */ resolveAppPath(...to: any[]): string; - defaultErrorHandler: () => any; + defaultErrorHandler(): any; /** Fetch a _bagpipe_ pipe */ - getPipe: (req: { swagger: { path: any } }) => any; + getPipe(req: { swagger: { path: any } }): any; config: ConfigInternal; /** * Current OpenAPI Specification (formaly known as Swagger RESTful API Documentation Specification) @@ -148,7 +148,7 @@ export interface Runner extends EventEmitter { * * @see {@link https://github.com/apigee-127/swagger-tools/blob/master/middleware/swagger-metadata.js|Git Source} */ - swaggerMetadata: (rlOrSO: any, apiDeclarations: any[]) => SwaggerToolsMiddleware + swaggerMetadata(rlOrSO: any, apiDeclarations: any[]): SwaggerToolsMiddleware /** * Middleware for using Swagger information to route requests to handlers. * @param [{any}] options - The configuration options @@ -156,14 +156,14 @@ export interface Runner extends EventEmitter { * @see {@link https://github.com/apigee-127/swagger-tools/blob/master/docs/Middleware.md#swaggerrouteroptions|Docs} * @see {@link https://github.com/apigee-127/swagger-tools/blob/master/middleware/swagger-router.js|Github Source} */ - swaggerRouter: (options?: any) => SwaggerToolsMiddleware + swaggerRouter(options?: any): SwaggerToolsMiddleware /** * Middleware for using Swagger security information to authenticate requests. * @param [{any}] options - The configuration options * * @see {@link https://github.com/apigee-127/swagger-tools/blob/master/middleware/swagger-security.js|Github Source} */ - swaggerSecurity: (options?: SwaggerSecurityHandlers) => SwaggerToolsMiddleware + swaggerSecurity(options?: SwaggerSecurityHandlers): SwaggerToolsMiddleware /** * Middleware for serving the Swagger documents and Swagger UI. * @@ -173,14 +173,14 @@ export interface Runner extends EventEmitter { * * @see {@link https://github.com/apigee-127/swagger-tools/blob/master/middleware/swagger-ui.js|Github Source} */ - swaggerUi: (rlOrSO: any, apiDeclarations: any[], options?: any) => SwaggerToolsMiddleware + swaggerUi(rlOrSO: any, apiDeclarations: any[], options?: any): SwaggerToolsMiddleware /** * Middleware for using Swagger information to validate API requests/responses.type * @param [{any}] options - The configuration options * * @see {@link https://github.com/apigee-127/swagger-tools/blob/master/middleware/swagger-validator.js|Github Source} */ - swaggerValidator: (options?: any) => SwaggerToolsMiddleware + swaggerValidator(options?: any): SwaggerToolsMiddleware }; swaggerSecurityHandlers: SwaggerSecurityHandlers | undefined; /** @@ -189,15 +189,15 @@ export interface Runner extends EventEmitter { */ bagpipes: { [name: string]: any }; /** Create new Connect middleware */ - connectMiddleware: () => ConnectMiddleware; + connectMiddleware(): ConnectMiddleware; /** Create new Express middleware */ - expressMiddleware: () => ExpressMiddleware; + expressMiddleware(): ExpressMiddleware; /** Create new Restify middleware */ - restifyMiddleware: () => RestifyMiddleware; + restifyMiddleware(): RestifyMiddleware; /** Create new Sails middleware */ - sailsMiddleware: () => SailsMiddleware; + sailsMiddleware(): SailsMiddleware; /** Create new Hapi middleware */ - hapiMiddleware: () => HapiMiddleware; + hapiMiddleware(): HapiMiddleware; } /** base used by all middleware versions */ @@ -208,9 +208,9 @@ interface Middleware { /** Connect/Express specific Middleware */ export interface ConnectMiddleware extends Middleware { - middleware: () => (req: Express.Request, res: Express.Response, next: NextFunction) => void; + middleware(): (req: Express.Request, res: Express.Response, next: NextFunction) => void; /** Register this Middleware with `app` */ - register: (app: Express.Application) => void; + register(app: Express.Application): void; } /** Express specific Middleware * @@ -222,7 +222,7 @@ export interface ExpressMiddleware extends ConnectMiddleware { } /** Sails specific Middleware */ export interface SailsMiddleware extends Middleware { /** Express style middleware */ - chain: () => (req: Express.Request, res: Express.Response, next: NextFunction) => void; + chain(): (req: Express.Request, res: Express.Response, next: NextFunction) => void; } /** Hapi specific Middleware */ @@ -249,7 +249,7 @@ export interface HapiMiddleware extends Middleware { attributes: { /** Name of Plugin (e.g. `swagger-node-runner`) */ name: string - /** Version of Plugin*/ + /** Version of Plugin */ version: string } } @@ -259,10 +259,9 @@ export interface HapiMiddleware extends Middleware { /** Restify specific Middleware */ export interface RestifyMiddleware extends Middleware { /** Register this Middleware with `app` */ - register: (app: Restify.Server) => void; + register(app: Restify.Server): void; } - /** * Create new SwaggerNodeRunner Instance * diff --git a/types/swagger-node-runner/swagger-node-runner-tests.ts b/types/swagger-node-runner/swagger-node-runner-tests.ts index cff8e9d570..c0fd698df1 100644 --- a/types/swagger-node-runner/swagger-node-runner-tests.ts +++ b/types/swagger-node-runner/swagger-node-runner-tests.ts @@ -22,7 +22,6 @@ SwaggerNodeRunner.create(config, (err, runner) => { expressApp.listen(port); }); - // Connect middleware const connectApp = connect(); SwaggerNodeRunner.create(config, (err, runner) => { @@ -31,11 +30,10 @@ SwaggerNodeRunner.create(config, (err, runner) => { const connectMiddleware = runner.connectMiddleware(); connectMiddleware.register(connectApp); - var port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; connectApp.listen(port); }); - // Sails Middleware (chain) test SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } @@ -46,13 +44,12 @@ SwaggerNodeRunner.create(config, (err, runner) => { } }); - // Hapi Middleware -var hapiapp = new Hapi.Server(); +const hapiapp = new Hapi.Server(); SwaggerNodeRunner.create(config, (err, runner) => { if (err) { throw err; } - var port = process.env.PORT || 10010; + const port = process.env.PORT || 10010; hapiapp.connection({ port }); // hapiapp.address = function() { // return { port }; @@ -71,7 +68,6 @@ SwaggerNodeRunner.create(config, (err, runner) => { }); }); - // Restify Middelware const app = restify.createServer(); SwaggerNodeRunner.create(config, (err, runner) => { @@ -85,12 +81,10 @@ SwaggerNodeRunner.create(config, (err, runner) => { app.listen(port); }); - const swaggerSecurityHandlerCb = (err: Error) => { // do nothing }; - const configComplex: SwaggerNodeRunner.Config = { appRoot: __dirname, configDir: "some/directory", diff --git a/types/swagger-restify-mw/swagger-restify-mw-tests.ts b/types/swagger-restify-mw/swagger-restify-mw-tests.ts index 73568b2153..629c85ecf3 100644 --- a/types/swagger-restify-mw/swagger-restify-mw-tests.ts +++ b/types/swagger-restify-mw/swagger-restify-mw-tests.ts @@ -16,12 +16,10 @@ SwaggerRestify.create(config, (err, swaggerRestify) => { app.listen(port); }); - const swaggerSecurityHandlerCb = (err: Error) => { // do nothing }; - const configComplex: SwaggerRestify.Config = { appRoot: __dirname, configDir: "some/directory", diff --git a/types/swagger-sails-hook/index.d.ts b/types/swagger-sails-hook/index.d.ts index 6d474c1907..b2e54f10a0 100644 --- a/types/swagger-sails-hook/index.d.ts +++ b/types/swagger-sails-hook/index.d.ts @@ -21,11 +21,11 @@ declare function SwaggerHook(sails: any): SwaggerHook.SailsHook; declare namespace SwaggerHook { /** - * `swagger-sails-hook` object implementing the Sails' hook specification. - * - * @see {@link http://sailsjs.com/documentation/concepts/extending-sails/hooks/hook-specification|Sails Hook Docs} - * @see {@link http://sailsjs.com/documentation/anatomy/api/hooks/my-hook/index-js|Sails Hook Example} - */ + * `swagger-sails-hook` object implementing the Sails' hook specification. + * + * @see {@link http://sailsjs.com/documentation/concepts/extending-sails/hooks/hook-specification|Sails Hook Docs} + * @see {@link http://sailsjs.com/documentation/anatomy/api/hooks/my-hook/index-js|Sails Hook Example} + */ interface SailsHook { /** * Perform startup tasks. diff --git a/types/table/index.d.ts b/types/table/index.d.ts index b5beffb524..6bc42bacdf 100644 --- a/types/table/index.d.ts +++ b/types/table/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Evan Shortiss // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - export type borderType = 'honeywell' | 'norc' | 'ramac' | 'void'; export interface ColumnConfig { @@ -39,7 +38,7 @@ export interface TableUserConfig { columns?: { [index: number]: ColumnConfig }; - drawJoin?: (index: number, size: number) => boolean; + drawJoin?(index: number, size: number): boolean; border?: JoinStruct; columnDefault?: ColumnConfig; } diff --git a/types/transducers-js/index.d.ts b/types/transducers-js/index.d.ts index 0ac1d18235..cfed8fbbbe 100644 --- a/types/transducers-js/index.d.ts +++ b/types/transducers-js/index.d.ts @@ -178,8 +178,8 @@ export function dropWhile(pred: (input: TInput) => boolean): Tr export class PartitionBy implements Transformer { constructor(f: (input: TInput) => any, xf: Transformer); ['@@transducer/init'](): TResult; - ['@@transducer/step'](result: TResult, input: TInput): TResult - ['@@transducer/result'](result: TResult): TResult + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; } /** @@ -192,8 +192,8 @@ export function partitionBy(f: (input: TInput) => any): Transdu export class PartitionAll implements Transformer { constructor(n: number, xf: Transformer); ['@@transducer/init'](): TResult; - ['@@transducer/step'](result: TResult, input: TInput): TResult - ['@@transducer/result'](result: TResult): TResult + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; } /** @@ -205,8 +205,8 @@ export function partitionAll(n: number): Transducer implements CompletingTransformer { constructor(cf: (result: TResult) => TCompleteResult, xf: Transformer); ['@@transducer/init'](): TResult; - ['@@transducer/step'](result: TResult, input: TInput): TResult - ['@@transducer/result'](result: TResult): TCompleteResult + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TCompleteResult; } /** @@ -218,8 +218,8 @@ export function completing(cf: (result: TResul export class Wrap implements Transformer { constructor(stepFn: Reducer, xf: Transformer); ['@@transducer/init'](): TResult; - ['@@transducer/step'](result: TResult, input: TInput): TResult - ['@@transducer/result'](result: TResult): TResult + ['@@transducer/step'](result: TResult, input: TInput): TResult; + ['@@transducer/result'](result: TResult): TResult; } /** diff --git a/types/transducers-js/transducers-js-tests.ts b/types/transducers-js/transducers-js-tests.ts index 30b91d8f47..634309a2b5 100644 --- a/types/transducers-js/transducers-js-tests.ts +++ b/types/transducers-js/transducers-js-tests.ts @@ -2,15 +2,12 @@ import * as t from 'transducers-js'; -const map = t.map, - filter = t.filter, - comp = t.comp, - into = t.into; +const { map, filter, comp, into } = t; // basic usage -function inc(n: number) { return n + 1; }; -function isEven(n: number) { return n % 2 === 0; }; +function inc(n: number) { return n + 1; } +function isEven(n: number) { return n % 2 === 0; } let xf = comp(map(inc), filter(isEven)); into([], xf, [0, 1, 2, 3, 4]); // [2, 4] diff --git a/types/update-notifier/index.d.ts b/types/update-notifier/index.d.ts index d9d6c8a4cc..625f93f591 100644 --- a/types/update-notifier/index.d.ts +++ b/types/update-notifier/index.d.ts @@ -19,7 +19,7 @@ declare namespace UpdateNotifier { interface Settings { pkg?: Package; - callback?: (update?: UpdateInfo) => any; + callback?(update?: UpdateInfo): any; packageName?: string; packageVersion?: string; updateCheckInterval?: number; // in milliseconds, default 1000 * 60 * 60 * 24 (1 day) diff --git a/types/update-notifier/update-notifier-tests.ts b/types/update-notifier/update-notifier-tests.ts index a39ead18ea..49f16a3dc3 100644 --- a/types/update-notifier/update-notifier-tests.ts +++ b/types/update-notifier/update-notifier-tests.ts @@ -1,6 +1,6 @@ import UpdateNotifier = require("update-notifier"); -var notifier = UpdateNotifier(); +let notifier = UpdateNotifier(); if (notifier.update) { notifier.notify(); @@ -9,7 +9,7 @@ if (notifier.update) { console.log(notifier.update); // Also exposed as a class -var notifier = new UpdateNotifier.UpdateNotifier({ +notifier = new UpdateNotifier.UpdateNotifier({ updateCheckInterval: 1000 * 60 * 60 * 24 * 7 // 1 week }); diff --git a/types/user-home/user-home-tests.ts b/types/user-home/user-home-tests.ts index 056a31095e..fa08b6fe49 100644 --- a/types/user-home/user-home-tests.ts +++ b/types/user-home/user-home-tests.ts @@ -1,4 +1,4 @@ import userHome = require('user-home'); console.log(userHome); -// => '/Users/sindresorhus' \ No newline at end of file +// => '/Users/sindresorhus' diff --git a/types/verror/index.d.ts b/types/verror/index.d.ts index 78bd4920f6..b8a14ae425 100644 --- a/types/verror/index.d.ts +++ b/types/verror/index.d.ts @@ -39,7 +39,7 @@ declare namespace VError { cause?: Error | null | undefined; name?: string; strict?: boolean; - constructorOpt?: (...args: any[]) => void; + constructorOpt?(...args: any[]): void; info?: Info; } diff --git a/types/verror/verror-tests.ts b/types/verror/verror-tests.ts index 8a243d2fab..efb52c9178 100644 --- a/types/verror/verror-tests.ts +++ b/types/verror/verror-tests.ts @@ -1,14 +1,14 @@ import VError = require("verror"); import { VError as VError2, MultiError, SError, WError } from "verror"; -var error = new Error("foo"); -var verror1 = new VError(error, "bar"); -var verror2 = new VError2(error, "bar"); -var serror = new SError(error, "bar"); -var multiError = new MultiError([verror1, verror2]); -var werror = new WError(verror1, "foobar"); +const error = new Error("foo"); +const verror1 = new VError(error, "bar"); +const verror2 = new VError2(error, "bar"); +const serror = new SError(error, "bar"); +const multiError = new MultiError([verror1, verror2]); +const werror = new WError(verror1, "foobar"); -var verror3 = new VError({ +const verror3 = new VError({ name: "fooError", cause: error, info: { @@ -16,13 +16,12 @@ var verror3 = new VError({ } }, "bar"); -var verror4 = new VError({ cause: null }, "bar"); +const verror4 = new VError({ cause: null }, "bar"); -var cause1: Error | undefined = verror1.cause(); -var cause2: Error | undefined = werror.cause(); +const cause1: Error | undefined = verror1.cause(); +const cause2: Error | undefined = werror.cause(); const info: { [k: string]: any } = VError.info(verror3); const namedCause: Error | null = VError.findCauseByName(verror3, "fooError"); const stack: string = VError.fullStack(verror3); const cause3: Error | null = VError.cause(verror3); - diff --git a/types/videojs/index.d.ts b/types/videojs/index.d.ts index 5b894b0912..892390094d 100644 --- a/types/videojs/index.d.ts +++ b/types/videojs/index.d.ts @@ -12,7 +12,6 @@ export = videojs; export as namespace videojs; declare namespace videojs { - interface PlayerOptions { techOrder?: string[]; html5?: any; diff --git a/types/videojs/videojs-tests.ts b/types/videojs/videojs-tests.ts index 6f9907ea1c..b3140e8ea7 100644 --- a/types/videojs/videojs-tests.ts +++ b/types/videojs/videojs-tests.ts @@ -8,8 +8,8 @@ videojs("example_video_1").ready(function() { this.pause(); - var isPaused: boolean = this.paused(); - var isPlaying: boolean = !this.paused(); + const isPaused: boolean = this.paused(); + const isPlaying: boolean = !this.paused(); this.src("http://www.example.com/path/to/video.mp4"); @@ -21,37 +21,37 @@ videojs("example_video_1").ready(function() { { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } ]); - var whereYouAt: number = this.currentTime(); + const whereYouAt: number = this.currentTime(); this.currentTime(120); // 2 minutes into the video - var howLongIsThis: number = this.duration(); + const howLongIsThis: number = this.duration(); - var bufferedTimeRange: TimeRanges = this.buffered(); + const bufferedTimeRange: TimeRanges = this.buffered(); // Number of different ranges of time have been buffered. Usually 1. - var numberOfRanges: number = bufferedTimeRange.length; + const numberOfRanges: number = bufferedTimeRange.length; // Time in seconds when the first range starts. Usually 0. - var firstRangeStart: number = bufferedTimeRange.start(0); + const firstRangeStart: number = bufferedTimeRange.start(0); // Time in seconds when the first range ends - var firstRangeEnd: number = bufferedTimeRange.end(0); + const firstRangeEnd: number = bufferedTimeRange.end(0); // Length in seconds of the first time range - var firstRangeLength: number = firstRangeEnd - firstRangeStart; + const firstRangeLength: number = firstRangeEnd - firstRangeStart; - var howMuchIsDownloaded: number = this.bufferedPercent(); + const howMuchIsDownloaded: number = this.bufferedPercent(); - var howLoudIsIt: number = this.volume(); + const howLoudIsIt: number = this.volume(); this.volume(0.5); // Set volume to half - var howWideIsIt: number = this.width(); + const howWideIsIt: number = this.width(); this.width(640); - var howTallIsIt: number = this.height(); + const howTallIsIt: number = this.height(); this.height(480); @@ -70,7 +70,6 @@ function testEvents(myPlayer: videojs.Player) { // Removes the specified listener only. myPlayer.off("error", myFunc); - const myFuncWithArg = function(this: videojs.Player, e: Event) { // Do something when the event is fired }; diff --git a/types/vkbeautify/index.d.ts b/types/vkbeautify/index.d.ts index 259fc3e058..292f0ce4e7 100644 --- a/types/vkbeautify/index.d.ts +++ b/types/vkbeautify/index.d.ts @@ -42,4 +42,4 @@ export function cssmin(text: string, preserveComments?: boolean): string; /** * Minifiy an sql string */ -export function sqlmin(text: string): string; \ No newline at end of file +export function sqlmin(text: string): string; diff --git a/types/vkbeautify/vkbeautify-tests.ts b/types/vkbeautify/vkbeautify-tests.ts index a7fd0c4839..4e506049e2 100644 --- a/types/vkbeautify/vkbeautify-tests.ts +++ b/types/vkbeautify/vkbeautify-tests.ts @@ -68,7 +68,6 @@ function sqlWithStringPattern() { VKBeautify.sql(exampleContent, ' '); } - /* * Minifying * @@ -116,4 +115,4 @@ function cssminAndRemoveComments() { // sql function sqlmin() { VKBeautify.sqlmin(exampleContent); -} \ No newline at end of file +} diff --git a/types/web-animations-js/index.d.ts b/types/web-animations-js/index.d.ts index e0124cefd3..cb2222ce20 100644 --- a/types/web-animations-js/index.d.ts +++ b/types/web-animations-js/index.d.ts @@ -3,9 +3,9 @@ // Definitions by: Kristian Moerch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare type AnimationEffectTimingFillMode = "none" | "forwards" | "backwards" | "both" | "auto"; -declare type AnimationEffectTimingPlaybackDirection = "normal" | "reverse" | "alternate" | "alternate-reverse"; -declare type AnimationPlayState = "idle" | "pending" | "running" | "paused" | "finished"; +type AnimationEffectTimingFillMode = "none" | "forwards" | "backwards" | "both" | "auto"; +type AnimationEffectTimingPlaybackDirection = "normal" | "reverse" | "alternate" | "alternate-reverse"; +type AnimationPlayState = "idle" | "pending" | "running" | "paused" | "finished"; declare class AnimationPlaybackEvent { constructor(target: Animation, currentTime: number, timelineTime: number); @@ -53,9 +53,7 @@ declare class KeyframeEffect { getFrames(): AnimationKeyFrame[]; remove(): void; } -interface AnimationEventListener { - (evt: AnimationPlaybackEvent): void; -} +type AnimationEventListener = (evt: AnimationPlaybackEvent) => void; declare class Animation { constructor(effect: KeyframeEffect, timeline?: AnimationTimeline); diff --git a/types/web-animations-js/web-animations-js-tests.ts b/types/web-animations-js/web-animations-js-tests.ts index d27a922a98..263c117353 100644 --- a/types/web-animations-js/web-animations-js-tests.ts +++ b/types/web-animations-js/web-animations-js-tests.ts @@ -33,7 +33,7 @@ function test_AnimationsApiNext() { 'scale(0)'; const steps = [ { visibility: 'visible', opacity: 1, transform: 'none' }, - { visibility: 'visible', opacity: 0, transform: transform } + { visibility: 'visible', opacity: 0, transform } ]; return new KeyframeEffect(target, steps, { duration: 1500, @@ -64,9 +64,9 @@ function test_AnimationsApiNext() { // https://developer.mozilla.org/en-US/docs/Web/API/Animation/Animation // http://codepen.io/rachelnabors/pen/eJyWzm/?editors=0010 function test_whiteRabbit() { - var whiteRabbit = document.getElementById("rabbit"); + const whiteRabbit = document.getElementById("rabbit"); if (whiteRabbit) { - var rabbitDownKeyframes = new KeyframeEffect( + const rabbitDownKeyframes = new KeyframeEffect( whiteRabbit, [ { transform: 'translateY(0%)' }, @@ -74,30 +74,26 @@ function test_whiteRabbit() { ], { duration: 3000, fill: 'forwards' } ); - var rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline); + const rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline); // On tap or click, whiteRabbit.addEventListener("mousedown", downHeGoes, false); whiteRabbit.addEventListener("touchstart", downHeGoes, false); // Trigger a single-fire animation function downHeGoes(event: Event) { - // Remove those event listeners whiteRabbit!.removeEventListener("mousedown", downHeGoes, false); whiteRabbit!.removeEventListener("touchstart", downHeGoes, false); // Play rabbit animation rabbitDownAnimation.play(); - } } - - } // Testing onsample // https://github.com/web-animations/web-animations-js/releases function test_onsample_And_addEventListener() { - var elem = document.createElement("div"); + const elem = document.createElement("div"); if (elem) { elem.style.width = '150px'; elem.style.color = 'black'; @@ -113,9 +109,9 @@ function test_onsample_And_addEventListener() { }; // onsample is write only console.log(myEffect.onsample); // => undefined - var myAnimation = document.timeline.play(myEffect); + const myAnimation = document.timeline.play(myEffect); myAnimation.addEventListener("finish", (e) => { console.log("finished", e); - }) + }); } } diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index 491efb3829..1851eddba7 100644 --- a/types/webappsec-credential-management/index.d.ts +++ b/types/webappsec-credential-management/index.d.ts @@ -109,36 +109,36 @@ interface Body { interface URLSearchParams { /** - * Appends a specified key/value pair as a new search parameter. - */ + * Appends a specified key/value pair as a new search parameter. + */ append(name: string, value: string): void; /** - * Deletes the given search parameter, and its associated value, from the list of all search parameters. - */ + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + */ delete(name: string): void; /** - * Returns the first value associated to the given search parameter. - */ + * Returns the first value associated to the given search parameter. + */ get(name: string): string | null; /** - * Returns all the values association with a given search parameter. - */ + * Returns all the values association with a given search parameter. + */ getAll(name: string): string[]; /** - * Returns a Boolean indicating if such a search parameter exists. - */ + * Returns a Boolean indicating if such a search parameter exists. + */ has(name: string): boolean; /** - * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. - */ + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + */ set(name: string, value: string): void; } declare var URLSearchParams: { prototype: URLSearchParams; /** - * Constructor returning a URLSearchParams object. - */ + * Constructor returning a URLSearchParams object. + */ new (init?: string | URLSearchParams): URLSearchParams; }; diff --git a/types/webappsec-credential-management/webappsec-credential-management-tests.ts b/types/webappsec-credential-management/webappsec-credential-management-tests.ts index 69cae46daf..148b604a69 100644 --- a/types/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/types/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -71,7 +71,7 @@ function passwordPostSignInConfirmation() { e.preventDefault(); const formElem = (e.target as HTMLFormElement); - var c = new PasswordCredential(formElem); + const c = new PasswordCredential(formElem); fetch(formElem.action, {method: 'POST', credentials: c}).then(r => { if (r.status === 200) { navigator.credentials!.store(c); @@ -89,13 +89,11 @@ function federationPostSignInConfirmation() { } } - // The change password example from Section 1.2.4 is essentially the same // as in 1.2.4, but the form element has different autocomplete annotations. // Therefore, we don't duplicate it here. // https://www.w3.org/TR/credential-management-1/#examples-change-password - // layering on top of a legacy system examples, from Section 1.2.5 // https://www.w3.org/TR/credential-management-1/#examples-legacy function existingFormPost(credential: PasswordCredential) { diff --git a/types/webgl2/tslint.json b/types/webgl2/tslint.json index 3bcd4abbe9..e9136418da 100644 --- a/types/webgl2/tslint.json +++ b/types/webgl2/tslint.json @@ -2,8 +2,11 @@ "extends": "../tslint.json", "rules": { "dt-header": false, + "align": false, "adjacent-overload-signatures": false, + "comment-format": false, "unified-signatures": false, + "no-consecutive-blank-lines": false, "no-empty-interface": false } } diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 81085d39d8..dfdfb669a1 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -262,7 +262,7 @@ declare namespace webpack { * * Defaults to `() => true`. */ - cachePredicate?: (data: { path: string, request: string }) => boolean; + cachePredicate?(data: { path: string, request: string }): boolean; } interface OldResolve { @@ -933,7 +933,6 @@ declare namespace webpack { } namespace loader { - interface Loader extends Function { (this: LoaderContext, source: string | Buffer, sourceMap: string | Buffer): string | Buffer | void | undefined; @@ -968,36 +967,30 @@ declare namespace webpack { */ version: string; - /** * The directory of the module. Can be used as context for resolving other stuff. * In the example: /abc because resource.js is in this directory */ context: string; - /** * The resolved request string. * In the example: "/abc/loader1.js?xyz!/abc/node_modules/loader2/index.js!/abc/resource.js?rrr" */ request: string; - /** * A string or any object. The query of the request for the current loader. */ query: any; - /** * A data object shared between the pitch and the normal phase. */ data?: any; - callback: loaderCallback; - /** * Make this loader async. */ @@ -1076,7 +1069,6 @@ declare namespace webpack { */ exec(code: string, filename: string): any; - /** * Resolve a request like a require expression. * @param context @@ -1092,7 +1084,6 @@ declare namespace webpack { */ resolveSync(context: string, request: string): string; - /** * Adds a file as dependency of the loader result in order to make them watchable. * For example, html-loader uses this technique as it finds src and src-set attributes. @@ -1120,7 +1111,6 @@ declare namespace webpack { */ clearDependencies(): void; - /** * Pass values to the next loader. * If you know what your result exports if executed as module, set this value here (as a only element array). @@ -1153,7 +1143,6 @@ declare namespace webpack { */ sourceMap: boolean; - /** * Target of compilation. Passed from configuration options. * Example values: "web", "node" @@ -1169,7 +1158,6 @@ declare namespace webpack { */ webpack: boolean; - /** * Emit a file. This is webpack-specific. * @param name @@ -1178,7 +1166,6 @@ declare namespace webpack { */ emitFile(name: string, content: Buffer|string, sourceMap: any): void; - /** * Access to the compilation's inputFileSystem property. */ @@ -1194,7 +1181,6 @@ declare namespace webpack { */ _compiler: Compiler; - /** * Hacky access to the Module object being loaded. */ diff --git a/types/webpack/webpack-tests.ts b/types/webpack/webpack-tests.ts index e29df7cefb..d7c4b45007 100644 --- a/types/webpack/webpack-tests.ts +++ b/types/webpack/webpack-tests.ts @@ -230,8 +230,8 @@ rule = { loader: "babel-loader" }; -declare var require: any; -declare var path: any; +declare const require: any; +declare const path: any; configuration = { plugins: [ function(this: webpack.Compiler) { @@ -383,9 +383,9 @@ plugin = new CommonsChunkPlugin({ }); plugin = new webpack.DefinePlugin(definitions); plugin = new webpack.DefinePlugin({ - "VERSION": JSON.stringify("5fa3b9"), - "BROWSER_SUPPORTS_HTML5": true, - "TWO": "1+1", + VERSION: JSON.stringify("5fa3b9"), + BROWSER_SUPPORTS_HTML5: true, + TWO: "1+1", "typeof window": JSON.stringify("object") }); plugin = new webpack.ProvidePlugin(definitions); @@ -437,7 +437,7 @@ webpack({ }); // returns a Compiler instance -var compiler = webpack({ +let compiler = webpack({ // configuration }); @@ -475,8 +475,8 @@ webpack({ }, (err, stats) => { if (err) return handleFatalError(err); - var jsonStats = stats.toJson(); - var jsonStatsWithAllOptions = stats.toJson({ + const jsonStats = stats.toJson(); + const jsonStatsWithAllOptions = stats.toJson({ assets: true, assetsSort: "field", cached: true, @@ -505,13 +505,13 @@ webpack({ successfullyCompiled(); }); -declare var fs: any; +declare const fs: any; compiler = webpack({ }); compiler.outputFileSystem = fs; compiler.run((err, stats) => { // ... - var fileContent = fs.readFileSync("..."); + const fileContent = fs.readFileSync("..."); }); //