From 9079b29eb4c833ff7dea4fb09b22ea9052b001f7 Mon Sep 17 00:00:00 2001 From: Jason Unger Date: Mon, 30 Jul 2018 11:37:42 -0400 Subject: [PATCH 001/129] Updates for react-toggle V2 types (#27552) * Updates for react-toggle V2 types * Bump minimum TypeScript version * Fix contributor url formatting --- types/react-toggle/v2/index.d.ts | 26 +++++++++++--------- types/react-toggle/v2/react-toggle-tests.tsx | 12 +++++++++ types/react-toggle/v2/tsconfig.json | 5 ++-- 3 files changed, 30 insertions(+), 13 deletions(-) diff --git a/types/react-toggle/v2/index.d.ts b/types/react-toggle/v2/index.d.ts index 2b0774de2d..e2d2d5f0b2 100644 --- a/types/react-toggle/v2/index.d.ts +++ b/types/react-toggle/v2/index.d.ts @@ -1,20 +1,24 @@ // Type definitions for react-toggle 2.2 // Project: https://github.com/aaronshaf/react-toggle // Definitions by: Karol Janyst +// Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.7 -import { Component, HTMLAttributes, ReactNode } from "react"; +import { ComponentClass, InputHTMLAttributes, ReactNode } from "react"; -export interface ToggleIcons { - checked?: ReactNode; - unchecked?: ReactNode; +declare namespace Toggle { + interface ToggleIcons { + checked?: ReactNode; + unchecked?: ReactNode; + } + + interface ToggleProps extends InputHTMLAttributes { + icons?: boolean | ToggleIcons; + defaultChecked?: boolean; + } } -export interface ToggleProps extends HTMLAttributes { - "aria-labelledby"?: string; - "aria-label"?: string; - icons?: boolean | ToggleIcons; -} +declare const Toggle: ComponentClass; -export default class Toggle extends Component {} +export = Toggle; diff --git a/types/react-toggle/v2/react-toggle-tests.tsx b/types/react-toggle/v2/react-toggle-tests.tsx index f02cf447e4..ac86a3ea7e 100644 --- a/types/react-toggle/v2/react-toggle-tests.tsx +++ b/types/react-toggle/v2/react-toggle-tests.tsx @@ -8,3 +8,15 @@ class Test extends React.Component { ); } } + +class TestControlled extends React.Component<{}, {checked: boolean}> { + state = { + checked: false + }; + + render() { + return ( + this.setState({ checked: e.target.checked })} /> + ); + } +} diff --git a/types/react-toggle/v2/tsconfig.json b/types/react-toggle/v2/tsconfig.json index 996290fe7b..122fd7a4b3 100644 --- a/types/react-toggle/v2/tsconfig.json +++ b/types/react-toggle/v2/tsconfig.json @@ -21,10 +21,11 @@ }, "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" + "jsx": "react", + "esModuleInterop": true }, "files": [ "index.d.ts", "react-toggle-tests.tsx" ] -} \ No newline at end of file +} From fc1247301cec087154d3f7f6dc5a6e53fb1cd570 Mon Sep 17 00:00:00 2001 From: JFGHT Date: Mon, 30 Jul 2018 17:38:45 +0200 Subject: [PATCH 002/129] Updated Keypair (#27574) * Updated Keypair https://stellar.github.io/js-stellar-sdk/Keypair.html#rawPublicKey * Updated xdr and Transaction https://github.com/stellar/js-stellar-base/blob/master/src/generated/stellar-xdr_generated.js * Fixed signatures signatures is an array of DecoratedSignatures not Signatures --- types/stellar-sdk/index.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index d07309eae5..3f963ab18d 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -825,6 +825,7 @@ export class Transaction { fee: number; source: string; memo: Memo; + signatures: xdr.DecoratedSignature[]; } export class TransactionBuilder { @@ -862,9 +863,11 @@ export class Keypair { publicKey(): string; secret(): string; + rawPublicKey(): Buffer; rawSecretKey(): Buffer; canSign(): boolean; sign(data: Buffer): Buffer; + signatureHint(): xdr.SignatureHint; verify(data: Buffer, signature: Buffer): boolean; } @@ -876,4 +879,9 @@ export namespace xdr { class Asset extends XDRStruct { } class Memo extends XDRStruct { } class TransactionEnvelope extends XDRStruct { } + class DecoratedSignature extends XDRStruct { + constructor(keys: { hint: SignatureHint, signature: Signature }) + } + class SignatureHint { } + class Signature { } } From e4902dd43e6c917b992540a2b770828b6a60d930 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Mon, 30 Jul 2018 18:40:28 +0300 Subject: [PATCH 003/129] [web3] Updated `web3.utils.toWei()` Unit list and added default Unit value (#27528) * Updated `web3.utils.toWei()` Unit list and added default Unit value * edit tests for tslint * web3: reordered ether Unit list to match official docs * web3 tests improvement --- types/web3/index.d.ts | 1 + types/web3/utils.d.ts | 22 ++++++++++++++-------- types/web3/web3-tests.ts | 4 ++++ 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/types/web3/index.d.ts b/types/web3/index.d.ts index 7d3797873e..c93e9c2ebd 100644 --- a/types/web3/index.d.ts +++ b/types/web3/index.d.ts @@ -13,6 +13,7 @@ // Baris Gumustas // André Vitor de Lima Matos // Levin Keller +// Dmitry Radkovskiy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import BigNumber = require("bn.js"); diff --git a/types/web3/utils.d.ts b/types/web3/utils.d.ts index 61869e327a..659110faa6 100644 --- a/types/web3/utils.d.ts +++ b/types/web3/utils.d.ts @@ -2,21 +2,26 @@ import BigNumber = require("bn.js"); import * as us from "underscore"; type Unit = + | "noether" + | "wei" | "kwei" - | "femtoether" + | "Kwei" | "babbage" + | "femtoether" | "mwei" - | "picoether" + | "Mwei" | "lovelace" - | "qwei" - | "nanoether" + | "picoether" + | "gwei" + | "Gwei" | "shannon" - | "microether" - | "szabo" + | "nanoether" | "nano" + | "szabo" + | "microether" | "micro" - | "milliether" | "finney" + | "milliether" | "milli" | "ether" | "kether" @@ -66,6 +71,7 @@ export default interface Utils { toDecimal(val: any): number; toHex(val: any): string; toUtf8(val: any): string; - toWei(val: string | number | BigNumber, unit: Unit): string | BigNumber; + toWei(val: string | number, unit?: Unit): string; + toWei(val: BigNumber, unit?: Unit): BigNumber; unitMap: any; } diff --git a/types/web3/web3-tests.ts b/types/web3/web3-tests.ts index 88e05028dd..85e4bc9b0a 100644 --- a/types/web3/web3-tests.ts +++ b/types/web3/web3-tests.ts @@ -1,4 +1,5 @@ import Web3 = require("web3"); +import BigNumber = require("bn.js"); const web3 = new Web3(); const myProvider = new web3.providers.HttpProvider("http://localhost:5454"); web3.setProvider(myProvider); @@ -16,3 +17,6 @@ const myContract = new web3.eth.Contract( myContract.options.from = "0x1234567890123456789012345678901234567891"; myContract.options.gasPrice = "20000000000000"; myContract.options.gas = 5000000; + +const weiStr: string = web3.utils.toWei("100", "gwei"); +const weiBn: BigNumber = web3.utils.toWei(web3.utils.toBN("1")); From 34dd46de385b62c3000881914ed78dac2524ddb8 Mon Sep 17 00:00:00 2001 From: bryanjjohnson Date: Mon, 30 Jul 2018 09:46:35 -0600 Subject: [PATCH 004/129] update mapbox-gl typings to 0.47.0 (#27548) --- types/mapbox-gl/index.d.ts | 114 +++++++++++++++++++++++++++++-------- 1 file changed, 89 insertions(+), 25 deletions(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 5f64b7470b..d85af4fd5a 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.45.0 +// Type definitions for Mapbox GL JS v0.47.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,17 +26,15 @@ declare namespace mapboxgl { export class Map extends Evented { constructor(options?: MapboxOptions); - addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + addControl(control: Control | IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; - addControl(control: IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + removeControl(control: Control | IControl): this; - removeControl(control: Control): this; + resize(eventData?: EventData): this; - removeControl(control: IControl): this; + getBounds(): LngLatBounds; - resize(): this; - - getBounds(): mapboxgl.LngLatBounds; + getMaxBounds(): LngLatBounds; setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; @@ -48,6 +46,10 @@ declare namespace mapboxgl { getMaxZoom(): number; + getRenderWorldCopies(): boolean; + + setRenderWorldCopies(renderWorldCopies?: boolean): this; + project(lnglat: LngLatLike): mapboxgl.Point; unproject(point: PointLike): mapboxgl.LngLat; @@ -62,13 +64,13 @@ declare namespace mapboxgl { querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: any[] }): GeoJSON.Feature[]; - setStyle(style: mapboxgl.Style | string): this; + setStyle(style: mapboxgl.Style | string, options?: { diff?: boolean, localIdeographFontFamily?: string }): this; getStyle(): mapboxgl.Style; isStyleLoaded(): boolean; - addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + addSource(id: string, source: VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; isSourceLoaded(id: string): boolean; @@ -76,9 +78,9 @@ declare namespace mapboxgl { removeSource(id: string): this; - getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + getSource(id: string): VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource; - addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: { width?: number, height?: number, pixelRatio?: number }): this; + addImage(name: string, image: HTMLImageElement | ArrayBufferView | { width: number, height: number, data: Uint8Array | Uint8ClampedArray } | ImageData, options?: { pixelRatio?: number, sdf?: any }): this; hasImage(name: string): boolean; @@ -86,6 +88,8 @@ declare namespace mapboxgl { loadImage(url: string, callback: Function): this; + listImages(): string[]; + addLayer(layer: mapboxgl.Layer, before?: string): this; moveLayer(id: string, beforeId?: string): this; @@ -96,7 +100,7 @@ declare namespace mapboxgl { setFilter(layer: string, filter?: any[]): this; - setLayerZoomRange(layerId: string, minzoom?: number, maxzoom?: number): this; + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; getFilter(layer: string): any[]; @@ -108,10 +112,14 @@ declare namespace mapboxgl { getLayoutProperty(layer: string, name: string, klass?: string): any; - setLight(options: mapboxgl.Light, lightOptions: any): this; + setLight(options: mapboxgl.Light, lightOptions?: any): this; getLight(): mapboxgl.Light; + setFeatureState(feature: {source?: string, sourceLayer?: string, id?: string}, state: any): void; + + getFeatureState(feature: {source?: string, sourceLayer?: string, id?: string}): any; + getContainer(): HTMLElement; getCanvasContainer(): HTMLElement; @@ -134,7 +142,7 @@ declare namespace mapboxgl { setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; - panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + panBy(offset: PointLike, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; @@ -162,6 +170,8 @@ declare namespace mapboxgl { setPitch(pitch: number, eventData?: EventData): this; + cameraForBounds(bounds: LngLatBoundsLike, options?: {padding?: number | PaddingOptions, offset?: PointLike, maxZoom?: number}): CameraOptions; + fitBounds(bounds: LngLatBoundsLike, options?: mapboxgl.FitBoundsOptions, eventData?: mapboxgl.EventData): this; jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; @@ -204,6 +214,12 @@ declare namespace mapboxgl { /** initial map center */ center?: LngLatLike; + clickTolerance?: number; + + collectResourceTiming?: boolean; + + crossSourceCollisions?: boolean; + /** ID of the container element */ container?: string | Element; @@ -219,6 +235,8 @@ declare namespace mapboxgl { /** If true, the map will track and update the page URL according to map position */ hash?: boolean; + fadeDuration?: number; + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ failIfMajorPerformanceCaveat?: boolean; @@ -228,6 +246,8 @@ declare namespace mapboxgl { /** If true, enable keyboard shortcuts (see KeyboardHandler). */ keyboard?: boolean; + localIdeographFontFamily?: string; + logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; /** If set, the map is constrained to the given bounds. */ @@ -244,6 +264,8 @@ declare namespace mapboxgl { pitch?: number; + pitchWithRotate?: boolean; + refreshExpiredTiles?: boolean; renderWorldCopies?: boolean; @@ -257,6 +279,8 @@ declare namespace mapboxgl { /** If true, the map will automatically resize when the browser window resizes */ trackResize?: boolean; + transformRequest?: Function; + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ touchZoomRotate?: boolean; @@ -500,7 +524,7 @@ declare namespace mapboxgl { } export interface Source { - type: 'vector' | 'raster' | 'geojson' | 'image' | 'video' | 'canvas'; + type: 'vector' | 'raster' | 'raster-dem' | 'geojson' | 'image' | 'video' | 'canvas'; } export type GeoJSONGeometry = GeoJSON.Point | GeoJSON.LineString | GeoJSON.MultiPoint | GeoJSON.Polygon | GeoJSON.MultiLineString | GeoJSON.MultiPolygon | GeoJSON.GeometryCollection; @@ -519,6 +543,12 @@ declare namespace mapboxgl { constructor(options?: mapboxgl.GeoJSONSourceOptions); setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + + getClusterExpansionZoom(clusterId: number, callback: (error: any, zoom: number) => void): this; + + getClusterChildren(clusterId: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; + + getClusterLeaves(cluserId: number, limit: number, offset: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; } export interface GeoJSONSourceOptions { @@ -526,6 +556,8 @@ declare namespace mapboxgl { maxzoom?: number; + attribution?: string; + buffer?: number; tolerance?: number; @@ -591,6 +623,10 @@ declare namespace mapboxgl { canvas: string | HTMLCanvasElement; + play(): void; + + pause(): void; + getCanvas(): HTMLCanvasElement; setCoordinates(coordinates: number[][]): this; @@ -608,17 +644,35 @@ declare namespace mapboxgl { type: 'vector'; url?: string; tiles?: string[]; + bounds?: number[]; + scheme?: 'xyz' | 'tms'; minzoom?: number; maxzoom?: number; + attribution?: string; } interface RasterSource extends Source { type: 'raster'; url?: string; tiles?: string[]; + bounds?: number[]; minzoom?: number; maxzoom?: number; tileSize?: number; + scheme?: 'xyz' | 'tms'; + attribution?: string; + } + + interface RasterDemSource extends Source { + type: 'raster-dem'; + url?: string; + tiles?: string[]; + bounds?: number[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + attribution?: string; + encoding?: 'terrarium' | 'mapbox'; } /** @@ -752,7 +806,7 @@ declare namespace mapboxgl { /** * Marker */ - export class Marker { + export class Marker extends Evented { constructor(options?: mapboxgl.MarkerOptions); constructor(element?: HTMLElement, options?: mapboxgl.MarkerOptions); @@ -765,15 +819,21 @@ declare namespace mapboxgl { setLngLat(lngLat: LngLatLike): this; + getElement(): HTMLElement; + setPopup(popup?: Popup): this; getPopup(): Popup; + togglePopup(): this; + getOffset(): PointLike; setOffset(offset: PointLike): this; - togglePopup(): this; + setDraggable(shouldBeDraggable: boolean): this; + + isDraggable(): boolean; } export interface MarkerOptions { @@ -784,6 +844,8 @@ declare namespace mapboxgl { anchor?: Anchor; color?: string + + draggable?: boolean; } /** @@ -831,6 +893,7 @@ declare namespace mapboxgl { export class MapTouchEvent { type: string; + target: Map; map: Map; originalEvent: TouchEvent; point: mapboxgl.Point; @@ -967,7 +1030,7 @@ declare namespace mapboxgl { metadata?: any; ref?: string; - source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; + source?: string | VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; 'source-layer'?: string; @@ -1008,14 +1071,14 @@ declare namespace mapboxgl { } export interface FillPaint { - 'fill-antialias'?: boolean; + 'fill-antialias'?: boolean | Expression; 'fill-opacity'?: number | StyleFunction | Expression; 'fill-opacity-transition'?: Transition; 'fill-color'?: string | StyleFunction | Expression; 'fill-color-transition'?: Transition; 'fill-outline-color'?: string | StyleFunction | Expression; 'fill-outline-color-transition'?: Transition; - 'fill-translate'?: number[] | Expression; + 'fill-translate'?: number[]; 'fill-translate-transition'?: Transition; 'fill-translate-anchor'?: 'map' | 'viewport'; 'fill-pattern'?: string; @@ -1046,7 +1109,7 @@ declare namespace mapboxgl { visibility?: 'visible' | 'none'; 'line-cap'?: 'butt' | 'round' | 'square'; - 'line-join'?: 'bevel' | 'round' | 'miter'; + 'line-join'?: 'bevel' | 'round' | 'miter' | Expression; 'line-miter-limit'?: number | Expression; 'line-round-limit'?: number | Expression; } @@ -1077,7 +1140,7 @@ declare namespace mapboxgl { export interface SymbolLayout { visibility?: 'visible' | 'none'; - 'symbol-placement'?: 'point' | 'line'; + 'symbol-placement'?: 'point' | 'line' | 'line-center'; 'symbol-spacing'?: number | Expression; 'symbol-avoid-edges'?: boolean; 'icon-allow-overlap'?: boolean | StyleFunction; @@ -1092,7 +1155,7 @@ declare namespace mapboxgl { 'icon-padding'?: number | Expression; 'icon-keep-upright'?: boolean; 'icon-offset'?: number[] | StyleFunction | Expression; - 'icon-anchor'?: Anchor; + 'icon-anchor'?: Anchor | StyleFunction | Expression; 'icon-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-rotation-alignment'?: 'map' | 'viewport' | 'auto'; @@ -1103,7 +1166,7 @@ declare namespace mapboxgl { 'text-line-height'?: number | Expression; 'text-letter-spacing'?: number | Expression; 'text-justify'?: 'left' | 'center' | 'right'; - 'text-anchor'?: Anchor; + 'text-anchor'?: Anchor | StyleFunction | Expression; 'text-max-angle'?: number | Expression; 'text-rotate'?: number | StyleFunction | Expression; 'text-padding'?: number | Expression; @@ -1162,6 +1225,7 @@ declare namespace mapboxgl { 'raster-contrast'?: number | Expression; 'raster-contrast-transition'?: Transition; 'raster-fade-duration'?: number | Expression; + 'raster-resample'?: 'linear' | 'nearest'; } export interface CircleLayout { From 3d30be9059159b1a2e357cdb30bdcaada0aa7aa9 Mon Sep 17 00:00:00 2001 From: Ferdy Budhidharma Date: Mon, 30 Jul 2018 10:47:27 -0500 Subject: [PATCH 005/129] fix(find): fix typos in exported functions (#27538) --- types/find/find-tests.ts | 12 ++++++------ types/find/index.d.ts | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/types/find/find-tests.ts b/types/find/find-tests.ts index c6c1cd04f5..3ca401f69a 100644 --- a/types/find/find-tests.ts +++ b/types/find/find-tests.ts @@ -16,9 +16,9 @@ find.file(regexPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); find.fileSync(rootDir); // $ExpectType string[] find.fileSync(stringPattern, rootDir); // $ExpectType string[] find.fileSync(regexPattern, rootDir); // $ExpectType string[] -find.eachFile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachFile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachFile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(emptyCb); // $ExpectType void find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void @@ -27,6 +27,6 @@ find.dir(rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType find.dirSync(rootDir); // $ExpectType string[] find.dirSync(stringPattern, rootDir); // $ExpectType string[] find.dirSync(regexPattern, rootDir); // $ExpectType string[] -find.eachDir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachDir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachDir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream diff --git a/types/find/index.d.ts b/types/find/index.d.ts index 61166669db..1ffb2f8aee 100644 --- a/types/find/index.d.ts +++ b/types/find/index.d.ts @@ -45,7 +45,7 @@ export function file(pattern: string | RegExp, root: string, callback: (files: s * @param root The root directory * @param callback A callback that accepts each file separately */ -export function eachFile(root: string, callback: (file: string) => void): FindEachStream; +export function eachfile(root: string, callback: (file: string) => void): FindEachStream; /** * Find all files that match a glob pattern in a given directory asynchronously. @@ -53,7 +53,7 @@ export function eachFile(root: string, callback: (file: string) => void): FindEa * @param root The root directory * @param callback A callback that accepts an array of the found files */ -export function eachFile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; +export function eachfile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; /** * Find all files in a given directory synchronously. @@ -105,7 +105,7 @@ export function dirSync(pattern: string | RegExp, root: string): string[]; * @param root The root directory * @param callback A callback that accepts each of the found directories separately */ -export function eachDir(root: string, callback: (directory: string) => void): FindEachStream; +export function eachdir(root: string, callback: (directory: string) => void): FindEachStream; /** * Find all directories that match a glob pattern in a given directory asynchronously. @@ -113,4 +113,4 @@ export function eachDir(root: string, callback: (directory: string) => void): Fi * @param root The root directory * @param callback A callback that accepts each of the found directories separately */ -export function eachDir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; +export function eachdir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; From f1fc698b58bd5b3d5d91fdcda61a7b137fa1acf3 Mon Sep 17 00:00:00 2001 From: Adrien Samson Date: Mon, 30 Jul 2018 17:49:58 +0200 Subject: [PATCH 006/129] Luxon: Interval.set allows partial object (#27526) * luxon: Interval.set allows partial object * luxon: fix Interval.merge/xor array notation --- types/luxon/index.d.ts | 8 ++++---- types/luxon/luxon-tests.ts | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 17706a9002..e96e389894 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -319,8 +319,8 @@ declare module 'luxon' { } type IntervalObject = { - start: DateTime; - end: DateTime; + start?: DateTime; + end?: DateTime; }; class Interval { @@ -338,8 +338,8 @@ declare module 'luxon' { ): Interval; static fromISO(string: string, options?: DateTimeOptions): Interval; static invalid(reason?: string): Interval; - static merge(intervals: Interval[]): [Interval]; - static xor(intervals: Interval[]): [Interval]; + static merge(intervals: Interval[]): Interval[]; + static xor(intervals: Interval[]): Interval[]; end: DateTime; invalidReason: string; isValid: boolean; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index de0aca9bfd..017f07b0c6 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -78,6 +78,7 @@ const i = Interval.fromDateTimes(now, later); i.length(); i.length('years'); i.contains(DateTime.local(2019)); +i.set({end: DateTime.local(2020)}); i.toISO(); i.toString(); From b9578b93cbae32ea2f1a8ec5cfde0bcf9435cc92 Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Mon, 30 Jul 2018 16:50:48 +0100 Subject: [PATCH 007/129] Recompose: fix `...WithConfig` module locations (#27530) --- types/recompose/index.d.ts | 21 +++------------------ types/recompose/recompose-tests.tsx | 9 +++------ 2 files changed, 6 insertions(+), 24 deletions(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 0c893486c3..e202e85d44 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -661,39 +661,24 @@ declare module 'recompose/hoistStatics' { // https://github.com/acdlite/recompose/blob/master/docs/API.md#componentfromstream declare module 'recompose/componentFromStream' { import { componentFromStream } from 'recompose'; + export { componentFromStreamWithConfig } from 'recompose'; export default componentFromStream; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#componentfromstreamwithconfig -declare module 'recompose/componentFromStreamWithConfig' { - import { componentFromStreamWithConfig } from 'recompose'; - export default componentFromStreamWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#mappropsstream declare module 'recompose/mapPropsStream' { import { mapPropsStream } from 'recompose'; + export { mapPropsStreamWithConfig } from 'recompose'; export default mapPropsStream; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#mappropsstreamwithconfig -declare module 'recompose/mapPropsStreamWithConfig' { - import { mapPropsStreamWithConfig } from 'recompose'; - export default mapPropsStreamWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#createeventhandler declare module 'recompose/createEventHandler' { import { createEventHandler } from 'recompose'; + export { createEventHandlerWithConfig } from 'recompose'; export default createEventHandler; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#createeventhandlerwithconfig -declare module 'recompose/createEventHandlerWithConfig' { - import { createEventHandlerWithConfig } from 'recompose'; - export default createEventHandlerWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#setobservableconfig declare module 'recompose/setObservableConfig' { import { setObservableConfig } from 'recompose'; diff --git a/types/recompose/recompose-tests.tsx b/types/recompose/recompose-tests.tsx index c30f5fb8f9..b89bd5e2c9 100644 --- a/types/recompose/recompose-tests.tsx +++ b/types/recompose/recompose-tests.tsx @@ -62,12 +62,9 @@ import createSinkStandalone from "recompose/createSink"; import componentFromPropStandalone from "recompose/componentFromProp"; import nestStandalone from "recompose/nest"; import hoistStaticsStandalone from "recompose/hoistStatics"; -import componentFromStreamStandalone from "recompose/componentFromStream"; -import componentFromStreamWithConfigStandalone from "recompose/componentFromStreamWithConfig"; -import mapPropsStreamStandalone from "recompose/mapPropsStream"; -import mapPropsStreamWithConfigStandalone from "recompose/mapPropsStreamWithConfig"; -import createEventHandlerStandalone from "recompose/createEventHandler"; -import createEventHandlerWithConfigStandalone from "recompose/createEventHandlerWithConfig"; +import componentFromStreamStandalone, { componentFromStreamWithConfig as componentFromStreamWithConfigStandalone } from "recompose/componentFromStream"; +import mapPropsStreamStandalone, { mapPropsStreamWithConfig as mapPropsStreamWithConfigStandalone } from "recompose/mapPropsStream"; +import createEventHandlerStandalone, { createEventHandlerWithConfig as createEventHandlerWithConfigStandalone } from "recompose/createEventHandler"; import setObservableConfigStandalone from "recompose/setObservableConfig"; function testMapProps() { From 6aacac05323d9378a144b23bd98f6a1a736391b9 Mon Sep 17 00:00:00 2001 From: Simon Werner Date: Tue, 31 Jul 2018 03:52:05 +1200 Subject: [PATCH 008/129] `setDefault()` actually returns a MomentTimezone object (#27518) --- types/moment-timezone/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/moment-timezone/index.d.ts b/types/moment-timezone/index.d.ts index fac79f728f..395ab77c82 100644 --- a/types/moment-timezone/index.d.ts +++ b/types/moment-timezone/index.d.ts @@ -53,7 +53,7 @@ declare module "moment" { names(): string[]; guess(ignoreCache?: boolean): string; - setDefault(timezone: string): void; + setDefault(timezone: string): MomentTimezone; } interface Moment { From 7f40149f8d61bee99b79742734484edb0985afcb Mon Sep 17 00:00:00 2001 From: Ali Mavrakis Date: Mon, 30 Jul 2018 12:24:44 -0400 Subject: [PATCH 009/129] Select2: added nextSearchTerm to Select2Options v3 (#27534) --- types/select2/v3/index.d.ts | 1 + types/select2/v3/select2-tests.ts | 3 +++ 2 files changed, 4 insertions(+) diff --git a/types/select2/v3/index.d.ts b/types/select2/v3/index.d.ts index 21bb2611c7..771d997384 100644 --- a/types/select2/v3/index.d.ts +++ b/types/select2/v3/index.d.ts @@ -75,6 +75,7 @@ interface Select2Options { dropdownCss?: any; dropdownCssClass?: any; escapeMarkup?: (markup: string) => string; + nextSearchTerm?: (selectedObject: object, currentSearchTerm: string) => string; } interface Select2JQueryEventObject extends JQueryEventObject { diff --git a/types/select2/v3/select2-tests.ts b/types/select2/v3/select2-tests.ts index 3b331cec3b..2d5a400352 100644 --- a/types/select2/v3/select2-tests.ts +++ b/types/select2/v3/select2-tests.ts @@ -210,6 +210,9 @@ $("#e17_2").select2({ }); $("#e18,#e18_2").select2(); alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); +$("#e19").select2({nextSearchTerm: function(selectedObject: object, currentSearchTerm: string) { + return currentSearchTerm; +}}); $("#e8").select2("val"); $("#e8").select2("val", "CA"); From 439099c83c4c02855591572401bd73ed8761a955 Mon Sep 17 00:00:00 2001 From: James Jensen Date: Mon, 30 Jul 2018 10:25:24 -0600 Subject: [PATCH 010/129] Added the container property to clipboardjs options. (#27514) Per https://github.com/zenorocha/clipboard.js/#advanced-options --- types/clipboard/clipboard-tests.ts | 6 ++++++ types/clipboard/index.d.ts | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/types/clipboard/clipboard-tests.ts b/types/clipboard/clipboard-tests.ts index a2ae8f9354..1a9a170087 100644 --- a/types/clipboard/clipboard-tests.ts +++ b/types/clipboard/clipboard-tests.ts @@ -14,6 +14,12 @@ const cb5 = new ClipboardJS(".btn", { action: elem => "copy", target: elem => null }); +const cb6 = new ClipboardJS(".btn", { + action: elem => "copy", + text: trigger => trigger.getAttribute('aria-label'), + target: trigger => trigger.nextElementSibling, + container: document.getElementById('modal') +}); cb1.destroy(); ClipboardJS.isSupported(); diff --git a/types/clipboard/index.d.ts b/types/clipboard/index.d.ts index 2405c0c6f0..ceb15b885b 100644 --- a/types/clipboard/index.d.ts +++ b/types/clipboard/index.d.ts @@ -49,6 +49,14 @@ declare namespace ClipboardJS { * @returns Text to be copied. */ text?(elem: Element): string; + + /** + * For use in Bootstrap Modals or with any + * other library that changes the focus + * you'll want to set the focused element + * as the container value. + */ + container?: Element; } interface Event { From 8b576a265db0be388c521c5143fe7f39ea4b0989 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=ADn=20=28Netux=29=20Rodr=C3=ADguez?= Date: Mon, 30 Jul 2018 13:33:21 -0300 Subject: [PATCH 011/129] simple-oauth2: Update typings to 1.6 and add 2.2 typings (#27458) * simple-oauth2: updated typings to 1.6 and added v2 (2.2) typings * simple-oauth2: swapped version folders --- types/simple-oauth2/index.d.ts | 62 +++--- types/simple-oauth2/simple-oauth2-tests.ts | 146 ++++++-------- types/simple-oauth2/v1/index.d.ts | 133 +++++++++++++ types/simple-oauth2/v1/simple-oauth2-tests.ts | 188 ++++++++++++++++++ types/simple-oauth2/v1/tsconfig.json | 32 +++ types/simple-oauth2/v1/tslint.json | 1 + 6 files changed, 452 insertions(+), 110 deletions(-) create mode 100644 types/simple-oauth2/v1/index.d.ts create mode 100644 types/simple-oauth2/v1/simple-oauth2-tests.ts create mode 100644 types/simple-oauth2/v1/tsconfig.json create mode 100644 types/simple-oauth2/v1/tslint.json diff --git a/types/simple-oauth2/index.d.ts b/types/simple-oauth2/index.d.ts index 21718c0722..19a1ff2698 100644 --- a/types/simple-oauth2/index.d.ts +++ b/types/simple-oauth2/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for simple-oauth2 1.1 +// Type definitions for simple-oauth2 2.2 // Project: https://github.com/lelylan/simple-oauth2 // Definitions by: Michael Müller , // Troy Lamerton +// Martín Rodriguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import Bluebird = require("bluebird"); +// TypeScript Version: 2.9 /** Creates a new simple-oauth2 client with the passed configuration */ export function create(options: ModuleOptions): OAuthClient; @@ -33,13 +32,21 @@ export interface ModuleOptions { /** String path to request an authorization code. Default to /oauth/authorize. */ authorizePath?: string }; - /** optional object used to set global options to the internal http library (request-js). */ + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ http?: {}; options?: { - /** Whether or not the client.id/client.secret params are sent in the request body. Defaults to true. */ - useBodyAuth?: boolean, - /** Whether or not the Basic Authorization header should be sent at the token request. */ - useBasicAuthorizationHeader?: boolean + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header + */ + authorizationMethod?: "header" | "body" }; } @@ -55,17 +62,19 @@ export interface AccessToken { /** Check if the access token is expired or not */ expired(): boolean; /** Refresh the access token */ - refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; - refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + refresh(params?: {}): Promise; /** Revoke access or refresh token */ - revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; + revoke(tokenType: TokenType): Promise; + /** Revoke both the existing access and refresh tokens */ + revokeAll(): Promise; } export type AuthorizationCode = string; export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ code: AuthorizationCode; + /** A string that represents the callback uri */ redirect_uri: string; - scope?: string | string[]; } export interface PasswordTokenConfig { @@ -88,27 +97,32 @@ export interface OAuthClient { * Redirect the user to the autorization page * @return the absolute authorization url */ - authorizeURL(params?: { - /** A string that represents the registered application URI where the user is redirected after authentication */ - redirect_uri?: string, - /** A string or array of strings that represents the application privileges */ - scope?: string | string[], - /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ - state?: string - }): string, + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, /** Returns the Access Token object */ - getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: AuthorizationTokenConfig): Promise; }; ownerPassword: { /** Returns the Access Token Object */ - getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: PasswordTokenConfig): Promise; }; clientCredentials: { /** Returns the Access Token Object */ - getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: ClientCredentialTokenConfig): Promise; }; accessToken: { diff --git a/types/simple-oauth2/simple-oauth2-tests.ts b/types/simple-oauth2/simple-oauth2-tests.ts index f83a616681..e066ad41c0 100644 --- a/types/simple-oauth2/simple-oauth2-tests.ts +++ b/types/simple-oauth2/simple-oauth2-tests.ts @@ -1,8 +1,11 @@ // off https://github.com/lelylan/simple-oauth2/blob/master/README.md // slightly changed to remove external dependencies +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + // Set the configuration settings -const credentials = { +const credentials: oauth2lib.ModuleOptions = { client: { id: '', secret: '' @@ -12,13 +15,10 @@ const credentials = { } }; -// Initialize the OAuth2 Library -// const oauth2 = require('simple-oauth2').create(credentials); -import oauth2lib = require("simple-oauth2"); const oauth2 = oauth2lib.create(credentials); // #Authorization Code flow -(() => { +(async () => { // Authorization oauth2 URI const authorizationUri = oauth2.authorizationCode.authorizeURL({ redirect_uri: 'http://localhost:3000/callback', @@ -36,57 +36,47 @@ const oauth2 = oauth2lib.create(credentials); scope: ['', ''] }; - // Callbacks // Save the access token - oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } + try { + const result = await oauth2.authorizationCode.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } +})(); - const token = oauth2.accessToken.create(result); - }); +// #Password Credentials Flow +(async () => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; - // Promises // Save the access token - oauth2.authorizationCode.getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token Error', error.message); - }); + try { + const result = await oauth2.ownerPassword.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } })(); // #Client Credentials Flow -(() => { +(async () => { const tokenConfig = {}; - // Callbacks // Get the access token object for the client - oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } - - const token = oauth2.accessToken.create(result); - }); - - // Promises - // Get the access token object for the client - oauth2.clientCredentials - .getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token error', error.message); - }); + try { + const result = await oauth2.clientCredentials.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token error', error.message); + } })(); // #Access Token object -(() => { +(async () => { // Sample of a JSON access token (you got it through previous steps) const tokenObject = { access_token: '', @@ -95,62 +85,46 @@ const oauth2 = oauth2lib.create(credentials); }; // Create the access token wrapper - let token = oauth2.accessToken.create(tokenObject); + let accessToken = oauth2.accessToken.create(tokenObject); // Check if the token is expired. If expired it is refreshed. - if (token.expired()) { - // Callbacks - token.refresh((error, result) => { - token = result; - }); - - // Promises - token.refresh() - .then((result) => { - token = result; - }); + if (accessToken.expired()) { + try { + accessToken = await accessToken.refresh(); + } catch (error) { + console.log('Error refreshing access token: ', error.message); + } } - // Callbacks - // Revoke only the access token - token.revoke('access_token', (error) => { + // Revoke both access and refresh tokens + try { + // Revoke only the access token + await accessToken.revoke('access_token'); + // Session ended. But the refresh_token is still valid. + // Revoke the refresh token + await accessToken.revoke('refresh_token'); - // Revoke the refresh_token - token.revoke('refresh_token', (error) => { - console.log('token revoked.'); - }); - }); + console.log('Token revoked'); + } catch (error) { + console.log('Error revoking token: ', error.message); + } - // Promises - // Revoke only the access token - token.revoke('access_token') - .then(() => { - // Revoke the refresh token - return token.revoke('refresh_token'); - }) - .then(() => { - console.log('Token revoked'); - }) - .catch((error) => { - console.log('Error revoking token.', error.message); - }); + // or... + + try { + // Revokes both tokens, refresh token is only revoked if the access_token is properly revoked + await accessToken.revokeAll(); + } catch (error) { + console.log('Error revoking token: ', error.message); + } })(); // #Errors // not applicable, as those errors about missing authentication codes are already found by the typescript compiler // (function () { -// // Callbacks -// oauth2.authorizationCode.getToken({}, (error, token) => { -// if (error) { -// return console.log(error.message); -// } -// }); - -// // Promises -// oauth2.authorizationCode -// .getToken({}) +// oauth2.authorizationCode.getToken({}) // .catch((error) => { // console.log(error.message); // }); diff --git a/types/simple-oauth2/v1/index.d.ts b/types/simple-oauth2/v1/index.d.ts new file mode 100644 index 0000000000..30b1a72d98 --- /dev/null +++ b/types/simple-oauth2/v1/index.d.ts @@ -0,0 +1,133 @@ +// Type definitions for simple-oauth2 1.6 +// Project: https://github.com/lelylan/simple-oauth2 +// Definitions by: Michael Müller , +// Troy Lamerton +// Martín Rodriguez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import Bluebird = require("bluebird"); + +/** Creates a new simple-oauth2 client with the passed configuration */ +export function create(options: ModuleOptions): OAuthClient; + +export interface ModuleOptions { + client: { + /** Service registered client id. Required. */ + id: string, + /** Service registered client secret. Required. */ + secret: string, + /** Parameter name used to send the client secret. Default to client_secret. */ + secretParamName?: string, + /** Parameter name used to send the client id. Default to client_id. */ + idParamName?: string + }; + auth: { + /** String used to set the host to request the tokens to. Required. */ + tokenHost: string, + /** String path to request an access token. Default to /oauth/token. */ + tokenPath?: string, + /** String path to revoke an access token. Default to /oauth/revoke. */ + revokePath?: string, + /** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */ + authorizeHost?: string, + /** String path to request an authorization code. Default to /oauth/authorize. */ + authorizePath?: string + }; + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ + http?: {}; + options?: { + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header. + */ + authorizationMethod?: "header" | "body" + }; +} + +export type TokenType = "access_token" | "refresh_token"; + +export interface Token { + [x: string]: any; +} + +export interface AccessToken { + token: Token; + + /** Check if the access token is expired or not */ + expired(): boolean; + /** Refresh the access token */ + refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; + refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + /** Revoke access or refresh token */ + revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; +} + +export type AuthorizationCode = string; +export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ + code: AuthorizationCode; + /** A string that represents the callback uri */ + redirect_uri: string; +} + +export interface PasswordTokenConfig { + /** A string that represents the registered username */ + username: string; + /** A string that represents the registered password. */ + password: string; + /** A string or array of strings that represents the application privileges */ + scope: string | string[]; +} + +export interface ClientCredentialTokenConfig { + /** A string that represents the application privileges */ + scope?: string | string[]; +} + +export interface OAuthClient { + authorizationCode: { + /** + * Redirect the user to the autorization page + * @return the absolute authorization url + */ + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, + + /** Returns the Access Token object */ + getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + ownerPassword: { + /** Returns the Access Token Object */ + getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + clientCredentials: { + /** Returns the Access Token Object */ + getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + accessToken: { + /** Creates an OAuth2.AccessToken instance */ + create(tokenToUse: Token): AccessToken; + }; +} diff --git a/types/simple-oauth2/v1/simple-oauth2-tests.ts b/types/simple-oauth2/v1/simple-oauth2-tests.ts new file mode 100644 index 0000000000..b3a8b2f952 --- /dev/null +++ b/types/simple-oauth2/v1/simple-oauth2-tests.ts @@ -0,0 +1,188 @@ +// off https://github.com/lelylan/simple-oauth2/blob/master/README.md +// slightly changed to remove external dependencies + +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + +// Set the configuration settings +const credentials: oauth2lib.ModuleOptions = { + client: { + id: '', + secret: '' + }, + auth: { + tokenHost: 'https://api.oauth.com' + } +}; + +const oauth2 = oauth2lib.create(credentials); + +// #Authorization Code flow +(() => { + // Authorization oauth2 URI + const authorizationUri = oauth2.authorizationCode.authorizeURL({ + redirect_uri: 'http://localhost:3000/callback', + scope: '', + state: '' + }); + + // Redirect example using Express (see http://expressjs.com/api.html#res.redirect) + // res.redirect(authorizationUri); + + // Get the access token object (the authorization code is given from the previous step). + const tokenConfig = { + code: '', + redirect_uri: 'http://localhost:3000/callback', + scope: ['', ''] + }; + + // Callbacks + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Password Credentials Flow +(() => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; + + // Callbacks + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Client Credentials Flow +(() => { + const tokenConfig = {}; + + // Callbacks + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token error', error.message); + }); +})(); + +// #Access Token object +(() => { + // Sample of a JSON access token (you got it through previous steps) + const tokenObject = { + access_token: '', + refresh_token: '', + expires_in: '7200' + }; + + // Create the access token wrapper + let accessToken = oauth2.accessToken.create(tokenObject); + + // Check if the token is expired. If expired it is refreshed. + if (accessToken.expired()) { + // Callbacks + accessToken.refresh((error, result) => { + accessToken = result; + }); + + // Promises + accessToken.refresh() + .then((result) => { + accessToken = result; + }); + } + + // Callbacks + // Revoke only the access token + accessToken.revoke('access_token', (error) => { + // Session ended. But the refresh_token is still valid. + + // Revoke the refresh_token + accessToken.revoke('refresh_token', (error) => { + console.log('token revoked.'); + }); + }); + + // Promises + // Revoke only the access token + accessToken.revoke('access_token') + .then(() => { + // Revoke the refresh token + return accessToken.revoke('refresh_token'); + }) + .then(() => { + console.log('Token revoked'); + }) + .catch((error) => { + console.log('Error revoking token.', error.message); + }); +})(); + +// #Errors +// not applicable, as those errors about missing authentication codes are already found by the typescript compiler + +// (function () { +// // Callbacks +// oauth2.authorizationCode.getToken({}, (error, token) => { +// if (error) { +// return console.log(error.message); +// } +// }); + +// // Promises +// oauth2.authorizationCode +// .getToken({}) +// .catch((error) => { +// console.log(error.message); +// }); + +// // => { "status": "401", "message": "Unauthorized" } +// })(); diff --git a/types/simple-oauth2/v1/tsconfig.json b/types/simple-oauth2/v1/tsconfig.json new file mode 100644 index 0000000000..f19c003707 --- /dev/null +++ b/types/simple-oauth2/v1/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "simple-oauth2": [ + "simple-oauth2/v1" + ], + "simple-oauth2/*": [ + "simple-oauth2/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "simple-oauth2-tests.ts" + ] +} diff --git a/types/simple-oauth2/v1/tslint.json b/types/simple-oauth2/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/simple-oauth2/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3228beff2ff519e85e16c0a9d6933ba8bffe58f9 Mon Sep 17 00:00:00 2001 From: Sosuke Suzuki Date: Tue, 31 Jul 2018 01:34:35 +0900 Subject: [PATCH 012/129] Update url-regex for strict option. (#27487) * Update url-regex/index.d.ts * Add my name as comment * Increase the version number * Remove patch version --- types/url-regex/index.d.ts | 5 ++++- types/url-regex/url-regex-tests.ts | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/types/url-regex/index.d.ts b/types/url-regex/index.d.ts index ed51c6e34d..58f3793baa 100644 --- a/types/url-regex/index.d.ts +++ b/types/url-regex/index.d.ts @@ -1,12 +1,15 @@ -// Type definitions for url-regex 4.0 +// Type definitions for url-regex 4.1 // Project: https://github.com/kevva/url-regex // Definitions by: Daniel Perez Alvarez +// sosukesuzuki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** Regular expression for matching URLs. */ declare function urlRegex(options?: { /** Only match an exact string. Useful with RegExp#test to check if a string is a URL. */ exact?: boolean; + /** Force URLs to start with a valid protocol or www. If set to false it'll match the TLD against a list of valid TLDs(https://github.com/stephenmathieson/node-tlds). */ + strict?: boolean; }): RegExp; export = urlRegex; diff --git a/types/url-regex/url-regex-tests.ts b/types/url-regex/url-regex-tests.ts index 2a2db45a28..de62d9a796 100644 --- a/types/url-regex/url-regex-tests.ts +++ b/types/url-regex/url-regex-tests.ts @@ -8,4 +8,6 @@ urlRegex({exact: true}).test('https://github.com foo bar'); urlRegex({exact: true}).test('https://github.com'); +urlRegex({exact: true, strict: false}).test('github.com'); + 'foo https://github.com bar //google.com'.match(urlRegex()); From 451ab05774ad35e2e4eee6666eba8b9999a01e21 Mon Sep 17 00:00:00 2001 From: Igor Babkin Date: Mon, 30 Jul 2018 19:35:06 +0300 Subject: [PATCH 013/129] Remove recalc function (it's private) and add getCentroid() (#27488) --- types/sat/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/sat/index.d.ts b/types/sat/index.d.ts index 538228049c..901c0814f2 100644 --- a/types/sat/index.d.ts +++ b/types/sat/index.d.ts @@ -59,10 +59,10 @@ declare namespace SAT { setPoints(points: Vector[]): Polygon; setAngle(angle: number): Polygon; setOffset(offset: Vector): Polygon; - recalc(): Polygon; rotate(angle: number): Polygon; translate(x: number, y: number): Polygon; getAABB(): Polygon; + getCentroid(): Vector; } export class Box { From 0e67e6c7827c13658790b1de087bbe7514e787b0 Mon Sep 17 00:00:00 2001 From: Art Date: Mon, 30 Jul 2018 17:35:46 +0100 Subject: [PATCH 014/129] Add node-zopfli-es types (#27634) * Add node-zopfli-es types * Set typescript version * Replace index.d.ts with actual type definition instead of an export * Update index.d.ts --- types/node-zopfli-es/index.d.ts | 69 ++++++++++++++++++++ types/node-zopfli-es/node-zopfli-es-tests.ts | 51 +++++++++++++++ types/node-zopfli-es/tsconfig.json | 23 +++++++ types/node-zopfli-es/tslint.json | 1 + 4 files changed, 144 insertions(+) create mode 100644 types/node-zopfli-es/index.d.ts create mode 100644 types/node-zopfli-es/node-zopfli-es-tests.ts create mode 100644 types/node-zopfli-es/tsconfig.json create mode 100644 types/node-zopfli-es/tslint.json diff --git a/types/node-zopfli-es/index.d.ts b/types/node-zopfli-es/index.d.ts new file mode 100644 index 0000000000..e015655d8b --- /dev/null +++ b/types/node-zopfli-es/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for node-zopfli-es 0.0 +// Project: https://github.com/jaeh/node-zopfli-es +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Transform } from 'stream'; + +declare class Zopfli extends Transform { + constructor(format?: Zopfli.Format, options?: Zopfli.Options); + + static createGzip(options?: Zopfli.Options): Zopfli; + static createDeflate(options?: Zopfli.Options): Zopfli; + static createZlib(options?: Zopfli.Options): Zopfli; + + static gzipSync(options?: Zopfli.Options): Buffer; + static deflateSync(options?: Zopfli.Options): Buffer; + static zlibSync(options?: Zopfli.Options): Buffer; + + static deflate(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, options?: Zopfli.Options): Promise; + + static gzip(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, options?: Zopfli.Options): Promise; + + static zlib(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, options?: Zopfli.Options): Promise; + + static compress(input: Buffer, format: Zopfli.Format, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, options?: Zopfli.Options): Promise; +} + +declare namespace Zopfli { + type Format = 'deflate' | 'gzip' | 'zlib'; + + interface Options { + verbose?: boolean; + verbose_more?: boolean; + /** + * Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. + * Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. + */ + numiterations?: number; + /** + * If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. + * Block splitting gives better compression. + */ + blocksplitting?: boolean; + /** + * If true, chooses the optimal block split points only after doing the iterative LZ77 compression. + * If false, chooses the block split points first, then does iterative LZ77 on each individual block. + * Depending on the file, either first or last gives the best compression. + */ + blocksplittinglast?: boolean; + /** + * Maximum amount of blocks to split into (0 for unlimited, + * but this can give extreme results that hurt compression on some files). + */ + blocksplittingmax?: number; + } +} + +export = Zopfli; diff --git a/types/node-zopfli-es/node-zopfli-es-tests.ts b/types/node-zopfli-es/node-zopfli-es-tests.ts new file mode 100644 index 0000000000..3f3294cf3f --- /dev/null +++ b/types/node-zopfli-es/node-zopfli-es-tests.ts @@ -0,0 +1,51 @@ +import * as Zopfli from 'node-zopfli-es'; +import * as fs from 'fs'; + +const opts: Zopfli.Options = { + verbose: true, + numiterations: 1 +}; +let input: Buffer = Buffer.from('foo'); +const read = fs.createReadStream('foo'); +const write = fs.createWriteStream('foo'); + +function cb(e: Error, b: Buffer): void {} +function then(b: Buffer): void {} + +Zopfli.zlib(input, cb); +Zopfli.zlib(input, opts, cb); +Zopfli.zlib(input, opts).then(then); +Zopfli.zlib(input).then(then); + +Zopfli.gzip(input, cb); +Zopfli.gzip(input, opts, cb); +Zopfli.gzip(input, opts).then(then); +Zopfli.gzip(input).then(then); + +Zopfli.deflate(input, cb); +Zopfli.deflate(input, opts, cb); +Zopfli.deflate(input, opts).then(then); +Zopfli.deflate(input).then(then); + +Zopfli.compress(input, 'zlib', cb); +Zopfli.compress(input, 'zlib', opts, cb); +Zopfli.compress(input, 'zlib', opts).then(then); +Zopfli.compress(input, 'zlib').then(then); + +input = Zopfli.gzipSync(); +input = Zopfli.gzipSync(opts); + +input = Zopfli.deflateSync(); +input = Zopfli.deflateSync(opts); + +input = Zopfli.zlibSync(); +input = Zopfli.zlibSync(opts); + +read.pipe(Zopfli.createGzip()).pipe(write); +read.pipe(Zopfli.createGzip(opts)).pipe(write); + +read.pipe(Zopfli.createDeflate()).pipe(write); +read.pipe(Zopfli.createDeflate(opts)).pipe(write); + +read.pipe(Zopfli.createZlib()).pipe(write); +read.pipe(Zopfli.createZlib(opts)).pipe(write); diff --git a/types/node-zopfli-es/tsconfig.json b/types/node-zopfli-es/tsconfig.json new file mode 100644 index 0000000000..bbd6de30e8 --- /dev/null +++ b/types/node-zopfli-es/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-zopfli-es-tests.ts" + ] +} diff --git a/types/node-zopfli-es/tslint.json b/types/node-zopfli-es/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-zopfli-es/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From aa115293b8dd2540fd3a4b6871b68375840c007a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 30 Jul 2018 11:00:29 -0700 Subject: [PATCH 015/129] Make `Props` default to `never` in 'moonjs'. (#27667) * Make `Props` default to `never` in 'moonjs'. * Update test for missing props. --- types/moonjs/index.d.ts | 4 ++-- types/moonjs/moonjs-tests.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/moonjs/index.d.ts b/types/moonjs/index.d.ts index 13dcbbe04e..c003f7ad58 100644 --- a/types/moonjs/index.d.ts +++ b/types/moonjs/index.d.ts @@ -22,11 +22,11 @@ declare namespace Moon { } interface MoonConstructor { - new (options?: ConstructorOptions): Instance>; + new (options?: ConstructorOptions): Instance>; } interface MoonStatic extends MoonConstructor { - component(name: string, options: ComponentOptions): MoonConstructor; + component(name: string, options: ComponentOptions): MoonConstructor; config: MoonConfig; use(plugin: object): void; compile(template: string): void; diff --git a/types/moonjs/moonjs-tests.ts b/types/moonjs/moonjs-tests.ts index aa6527ea82..34d1d8d359 100644 --- a/types/moonjs/moonjs-tests.ts +++ b/types/moonjs/moonjs-tests.ts @@ -17,6 +17,7 @@ const count = app.get("count"); count; // $ExpectType number app.get("increment")(); // $ExpectType void app.callMethod("increment"); // $ExpectType any +app.get("blahblahblah"); // $ExpectError app.destroy(); From 5c0fd82860b50651004c9e632e4a080e59edafba Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Mon, 30 Jul 2018 20:02:05 +0200 Subject: [PATCH 016/129] stylelint: update to v9.4 (#27659) * stylelint: update to v9.4 * styleline: add `compact` to `formatters` --- types/stylelint/index.d.ts | 5 +- types/stylelint/tslint.json | 78 +-------------------------- types/stylelint/v7/index.d.ts | 51 ++++++++++++++++++ types/stylelint/v7/stylelint-tests.ts | 24 +++++++++ types/stylelint/v7/tsconfig.json | 29 ++++++++++ types/stylelint/v7/tslint.json | 3 ++ 6 files changed, 111 insertions(+), 79 deletions(-) create mode 100644 types/stylelint/v7/index.d.ts create mode 100644 types/stylelint/v7/stylelint-tests.ts create mode 100644 types/stylelint/v7/tsconfig.json create mode 100644 types/stylelint/v7/tslint.json diff --git a/types/stylelint/index.d.ts b/types/stylelint/index.d.ts index 67316843a9..2068aff709 100644 --- a/types/stylelint/index.d.ts +++ b/types/stylelint/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for stylelint 7.11 +// Type definitions for stylelint 9.4 // Project: https://github.com/stylelint/stylelint // Definitions by: Alan Agius // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export type FormatterType = "json" | "string" | "verbose"; +export type FormatterType = "json" | "string" | "verbose" | "compact"; export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; @@ -45,6 +45,7 @@ export interface LintResult { export namespace formatters { function json(results: LintResult[]): string; function string(results: LintResult[]): string; + function compact(results: LintResult[]): string; function verbose(results: LintResult[]): string; } diff --git a/types/stylelint/tslint.json b/types/stylelint/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/stylelint/tslint.json +++ b/types/stylelint/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/stylelint/v7/index.d.ts b/types/stylelint/v7/index.d.ts new file mode 100644 index 0000000000..67316843a9 --- /dev/null +++ b/types/stylelint/v7/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for stylelint 7.11 +// Project: https://github.com/stylelint/stylelint +// Definitions by: Alan Agius +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type FormatterType = "json" | "string" | "verbose"; + +export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; + +export interface LinterOptions { + code?: string; + codeFilename?: string; + config?: JSON; + configBasedir?: string; + configFile?: string; + configOverrides?: JSON; + cache?: boolean; + cacheLocation?: string; + files?: string | string[]; + fix?: boolean; + formatter?: FormatterType; + ignoreDisables?: boolean; + reportNeedlessDisables?: boolean; + ignorePath?: boolean; + syntax?: SyntaxType; + customSyntax?: string; +} + +export interface LinterResult { + errored: boolean; + output: string; + postcssResults: any[]; + results: LintResult[]; +} + +export interface LintResult { + source: string; + errored: boolean | undefined; + ignored: boolean | undefined; + warnings: string[]; + deprecations: string[]; + invalidOptionWarnings: any[]; +} + +export namespace formatters { + function json(results: LintResult[]): string; + function string(results: LintResult[]): string; + function verbose(results: LintResult[]): string; +} + +export function lint(options?: LinterOptions): Promise; diff --git a/types/stylelint/v7/stylelint-tests.ts b/types/stylelint/v7/stylelint-tests.ts new file mode 100644 index 0000000000..785eb2e425 --- /dev/null +++ b/types/stylelint/v7/stylelint-tests.ts @@ -0,0 +1,24 @@ +import { LinterOptions, FormatterType, SyntaxType, lint, LintResult, LinterResult } from "stylelint"; + +const options: LinterOptions = { + code: "div { color: red }", + files: ["**/**.scss"], + formatter: "json", + cache: true, + cacheLocation: "./stylelint.cache.json", + ignoreDisables: true, + reportNeedlessDisables: true, + ignorePath: true, + syntax: "scss" +}; + +lint(options).then((x: LinterResult) => { + const err: boolean = x.errored; + const output: string = x.output; + const postcssResults: any[] = x.postcssResults; + const results: LintResult[] = x.results; +}); + +const formatter: FormatterType = "json"; + +const syntax: SyntaxType = "scss"; diff --git a/types/stylelint/v7/tsconfig.json b/types/stylelint/v7/tsconfig.json new file mode 100644 index 0000000000..b6f6796252 --- /dev/null +++ b/types/stylelint/v7/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "stylelint": [ + "stylelint/v7" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stylelint-tests.ts" + ] +} diff --git a/types/stylelint/v7/tslint.json b/types/stylelint/v7/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/stylelint/v7/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From ba36179b1921bd3ee3682e2af3c121f0f16b5f46 Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 30 Jul 2018 11:02:15 -0700 Subject: [PATCH 017/129] Allow non-factories to be registered with .register (#27661) --- types/ember/index.d.ts | 4 ++-- types/ember/test/application-instance.ts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 3583889a74..babca01879 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -328,11 +328,11 @@ declare module 'ember' { */ resolveRegistration(fullName: string): Function; /** - * Registers a factory that can be used for dependency injection (with + * Registers a factory or value that can be used for dependency injection (with * `inject`) or for service lookup. Each factory is registered with * a full name including two parts: `type:name`. */ - register(fullName: string, factory: Function, options?: { singleton?: boolean, instantiate?: boolean }): any; + register(fullName: string, factory: any, options?: { singleton?: boolean, instantiate?: boolean }): any; /** * Unregister a factory. */ diff --git a/types/ember/test/application-instance.ts b/types/ember/test/application-instance.ts index 9881e4815a..9ae22e5f26 100644 --- a/types/ember/test/application-instance.ts +++ b/types/ember/test/application-instance.ts @@ -1,4 +1,5 @@ import ApplicationInstance from '@ember/application/instance'; +import hbs from 'htmlbars-inline-precompile'; const appInstance = ApplicationInstance.create(); appInstance.register('some:injection', class Foo {}); @@ -11,6 +12,8 @@ appInstance.register('some:injection', class Foo {}, { instantiate: false, }); +appInstance.register('templates:foo/bar', hbs`

Hello World

`); + appInstance.register('some:injection', class Foo {}, { singleton: false, instantiate: true, From ab5b7b9449657620af7faab06e1caff3540eb1a7 Mon Sep 17 00:00:00 2001 From: Sebastian Silbermann Date: Mon, 30 Jul 2018 20:03:01 +0200 Subject: [PATCH 018/129] [react-big-calendar] add definitions for header component (#27655) --- types/react-big-calendar/index.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index b73ffcc0d9..9275511fc9 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -86,11 +86,23 @@ export interface Format { eventTimeRangeEndFormat?: string; } +export interface HeaderProps { + culture: BigCalendarProps['culture']; + date: Date; + format: string; + label: string; + localizer: object; +} + export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + /** + * component used as a header for each column in the TimeGridHeader + */ + header?: React.ComponentType; toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; From 0dcfb2b4836606bf3bdace6ce688a8883cb0af7d Mon Sep 17 00:00:00 2001 From: Matthew Gabeler-Lee Date: Mon, 30 Jul 2018 14:04:48 -0400 Subject: [PATCH 019/129] pino accepts NodeJS.WritableStream streams too (#27635) --- types/pino/index.d.ts | 4 ++-- types/pino/pino-tests.ts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 0f98e0a622..27d0f51fc6 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -19,7 +19,7 @@ export = P; * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; /** * @param [options]: an options object @@ -27,7 +27,7 @@ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream. * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; declare namespace P { /** diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 6d226a1d92..6959a6cd97 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -93,3 +93,6 @@ log.level = 'info'; pino.levels.values.error === 50; pino.levels.labels[50] === 'error'; + +const logstderr: pino.Logger = pino(process.stderr); +logstderr.error('on stderr instead of stdout'); From e0bc7a1f62b32963a5e29e514aee39d949a595ad Mon Sep 17 00:00:00 2001 From: lsg-braymon <40968250+lsg-braymon@users.noreply.github.com> Date: Tue, 31 Jul 2018 06:05:40 +1200 Subject: [PATCH 020/129] [@types/ember] Add `currentRouteName` to Ember RouterService (#27590) * Add currentRouteName property * Fix placement of RouterService property. Add test. --- types/ember/index.d.ts | 48 +++++++++++++++++++++++++++++++++++++- types/ember/test/router.ts | 7 ++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index babca01879..93babaa0a7 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -3372,7 +3372,48 @@ declare module 'ember' { /** * The Router service is the public API that provides component/view layer access to the router. */ - class RouterService extends Ember.Service { + export class RouterService extends Ember.Service { + // + /** + Name of the current route. + This property represent the logical name of the route, + which is comma separated. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `index` when you visit `/` + * `about` when you visit `/about` + * `blog.index` when you visit `/blog` + * `blog.post` when you visit `/blog/some-post-id` + */ + readonly currentRouteName: string; + // + /** + Current URL for the application. + This property represent the URL path for this route. + For the following router: + ```app/router.js + Router.map(function() { + this.route('about'); + this.route('blog', function () { + this.route('post', { path: ':post_id' }); + }); + }); + ``` + It will return: + * `/` when you visit `/` + * `/about` when you visit `/about` + * `/blog` when you visit `/blog` + * `/blog/some-post-id` when you visit `/blog/some-post-id` + */ + readonly currentURL: string; // /** * Determines whether a route is active. @@ -3776,6 +3817,11 @@ declare module '@ember/routing/router' { export default class EmberRouter extends Ember.Router { } } +declare module '@ember/routing/router-service' { + import { RouterService } from 'ember'; + export default class extends RouterService { } +} + declare module '@ember/runloop' { import Ember from 'ember'; export const begin: typeof Ember.run.begin; diff --git a/types/ember/test/router.ts b/types/ember/test/router.ts index ff5f4c554f..760e9ed5bc 100755 --- a/types/ember/test/router.ts +++ b/types/ember/test/router.ts @@ -1,4 +1,5 @@ import Ember from 'ember'; +import { assertType } from './lib/assert'; const AppRouter = Ember.Router.extend({ }); @@ -25,6 +26,12 @@ AppRouter.map(function() { const RouterServiceConsumer = Ember.Service.extend({ router: Ember.inject.service('router'), + currentRouteName() { + const x: string = Ember.get(this, 'router').currentRouteName; + }, + currentURL() { + const x: string = Ember.get(this, 'router').currentURL; + }, transitionWithoutModel() { Ember.get(this, 'router') .transitionTo('some-route'); From 1922994873e2af17a2937453aa7ef2cae65aa737 Mon Sep 17 00:00:00 2001 From: process-execution Date: Tue, 31 Jul 2018 02:06:00 +0800 Subject: [PATCH 021/129] Fix Primitive constructor (#27668) Made shadows property optional in Primitive constructor config object. --- types/cesium/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/cesium/index.d.ts b/types/cesium/index.d.ts index f2bb11479c..6c34023eae 100644 --- a/types/cesium/index.d.ts +++ b/types/cesium/index.d.ts @@ -3593,7 +3593,7 @@ declare namespace Cesium { cull?: boolean; asynchronous?: boolean; debugShowBoundingVolume?: boolean; - shadows: ShadowMode + shadows?: ShadowMode }); destroy(): void; getGeometryInstanceAttributes(id: any): any; From 15ec8386fcceabe6df0bd421463f5ac5c88f1751 Mon Sep 17 00:00:00 2001 From: Paul-Louis HERY Date: Mon, 30 Jul 2018 20:07:49 +0200 Subject: [PATCH 022/129] add params include_user_entities and stringify_ids (#27678) --- types/twit/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/twit/index.d.ts b/types/twit/index.d.ts index 9918d58470..ce8484bbe1 100644 --- a/types/twit/index.d.ts +++ b/types/twit/index.d.ts @@ -4,6 +4,7 @@ // sapphiredev // abraham // siwalik +// plhery // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -271,6 +272,8 @@ declare module 'twit' { include_rts?: boolean, skip_status?: boolean, url?: string, + include_user_entities?: boolean, + stringify_ids?: boolean, } export interface PromiseResponse { data: Response, From d0bd4443df62dc038f61624fb2a2c7f6951b1441 Mon Sep 17 00:00:00 2001 From: Rinze Date: Mon, 30 Jul 2018 20:07:58 +0200 Subject: [PATCH 023/129] Updated sanitize-html type definitions for version 1.18.2 (#27676) * Updated sanitize-html type definitions for version 1.18.2 * Augemented sanitize-html test file --- types/sanitize-html/index.d.ts | 6 +++++- types/sanitize-html/sanitize-html-tests.ts | 11 ++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/types/sanitize-html/index.d.ts b/types/sanitize-html/index.d.ts index bdd70f956a..2e7527e3fc 100644 --- a/types/sanitize-html/index.d.ts +++ b/types/sanitize-html/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for sanitize-html 1.14.1 +// Type definitions for sanitize-html 1.18.2 // Project: https://github.com/punkave/sanitize-html // Definitions by: Rogier Schouten // Afshin Darian // BehindTheMath +// Rinze de Laat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = sanitize; @@ -38,9 +39,12 @@ declare namespace sanitize { interface IOptions { allowedAttributes?: { [index: string]: string[] } | boolean; + allowedStyles?: { [index: string]: { [index: string]: RegExp[] } }; allowedClasses?: { [index: string]: string[] } | boolean; + allowedIframeHostnames?: string[]; allowedSchemes?: string[] | boolean; allowedSchemesByTag?: { [index: string]: string[] } | boolean; + allowedSchemesAppliedToAttributes?: string[]; allowProtocolRelative?: boolean; allowedTags?: string[] | boolean; exclusiveFilter?: (frame: IFrame) => boolean; diff --git a/types/sanitize-html/sanitize-html-tests.ts b/types/sanitize-html/sanitize-html-tests.ts index cc43d64fcb..b02a5a6653 100644 --- a/types/sanitize-html/sanitize-html-tests.ts +++ b/types/sanitize-html/sanitize-html-tests.ts @@ -4,8 +4,17 @@ let options: sanitize.IOptions = { allowedTags: sanitize.defaults.allowedTags.concat('h1', 'h2', 'img'), allowedAttributes: { 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'), - 'img': ['src', 'height', 'width', 'alt'] + 'img': ['src', 'height', 'width', 'alt', 'style'] }, + allowedStyles: { + '*': { + color: [/^red$/], + background: [/^green$/], + 'background-color': [/^#0000FF$/] + } + }, + allowedIframeHostnames: ['www.youtube.com'], + allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], transformTags: { 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' }), 'img': (tagName: string, attribs: sanitize.Attributes) => { From 43de02ea1d87534427c0b1ae95e13a26d11e4e42 Mon Sep 17 00:00:00 2001 From: error Date: Mon, 30 Jul 2018 13:08:07 -0500 Subject: [PATCH 024/129] add bson/Int32 to exports (#27662) --- types/mongodb/v2/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/v2/index.d.ts b/types/mongodb/v2/index.d.ts index 4c26149d81..a7d45ac2d0 100644 --- a/types/mongodb/v2/index.d.ts +++ b/types/mongodb/v2/index.d.ts @@ -22,7 +22,7 @@ export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; -export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef } from 'bson'; +export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef, Int32 } from 'bson'; // Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html export class MongoClient { From 3e8a84c2818c917619f313846358d9c2ebd977d2 Mon Sep 17 00:00:00 2001 From: slyrz Date: Mon, 30 Jul 2018 20:10:22 +0200 Subject: [PATCH 025/129] Update API to version 1.6 (#27658) --- types/puppeteer/index.d.ts | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 4859b86fc1..a5e85f802e 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.5 +// Type definitions for puppeteer 1.6 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -727,6 +727,10 @@ export interface ElementHandle extends JSHandle, Ev * If the element is detached from DOM, the method throws an error. */ hover(): Promise; + /** + * Resolves to true if the element is visible in the current viewport. + */ + isIntersectingViewport(): Promise; /** * Focuses the element, and then uses keyboard.down and keyboard.up. * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names. @@ -860,6 +864,8 @@ export type ErrorCode = | "aborted" | "accessdenied" | "addressunreachable" + | "blockedbyclient" + | "blockedbyresponse" | "connectionaborted" | "connectionclosed" | "connectionfailed" @@ -1107,16 +1113,6 @@ export interface FrameBase extends Evalable { ...args: any[] ): Promise; - waitForRequest( - urlOrPredicate: string | ((req: Request) => boolean), - options?: { timeout?: number } - ): Promise; - - waitForResponse( - urlOrPredicate: string | ((res: Response) => boolean), - options?: { timeout?: number } - ): Promise; - waitForSelector( selector: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number } @@ -1447,6 +1443,16 @@ export interface Page extends EventEmitter, FrameBase { */ waitForNavigation(options?: NavigationOptions): Promise; + waitForRequest( + urlOrPredicate: string | ((req: Request) => boolean), + options?: { timeout?: number } + ): Promise; + + waitForResponse( + urlOrPredicate: string | ((res: Response) => boolean), + options?: { timeout?: number } + ): Promise; + /** This method returns all of the dedicated WebWorkers associated with the page. */ workers(): Worker[]; } @@ -1705,6 +1711,8 @@ export interface Coverage { export interface StartCoverageOptions { /** Whether to reset coverage on every navigation. Defaults to `true`. */ resetOnNavigation?: boolean; + /** Whether anonymous scripts generated by the page should be reported. Defaults to `false`. */ + reportAnonymousScripts?: boolean; } export interface CoverageEntry { From 9e7f1e9d6fb81e236403242704016259baa7e82b Mon Sep 17 00:00:00 2001 From: Vinay Raikar Date: Mon, 30 Jul 2018 23:41:25 +0530 Subject: [PATCH 026/129] Correct the promise resolution type for jobs method (#27649) --- types/agenda/agenda-tests.ts | 3 +++ types/agenda/index.d.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/types/agenda/agenda-tests.ts b/types/agenda/agenda-tests.ts index e4de026c0e..2c011efaf7 100644 --- a/types/agenda/agenda-tests.ts +++ b/types/agenda/agenda-tests.ts @@ -67,6 +67,9 @@ var mongoConnectionString = "mongodb://127.0.0.1/agenda"; await job.save(); const jobs = await agenda.jobs({ name: 'printAnalyticsReport' }); + jobs.forEach((job) => { + job.save(); + }); let numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' }); diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index d728a76032..be07b84aaf 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -96,7 +96,7 @@ declare class Agenda extends EventEmitter { * Find all Jobs matching `query` and pass same back in cb(). * @param query */ - jobs(query: any): Promise; + jobs(query: any): Promise[]>; /** * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want From 16b85f0e2f623fd107ccf55edbac1e0558b97e48 Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Mon, 30 Jul 2018 20:19:01 +0200 Subject: [PATCH 027/129] [@types/gulp-imagemin] Add type definitions (#27692) * Add koa-router's Router to koa's Context * [@types/gulp-imagemin] Add type definitions --- types/gulp-imagemin/gulp-imagemin-tests.ts | 20 ++++++++++++++++ types/gulp-imagemin/index.d.ts | 27 ++++++++++++++++++++++ types/gulp-imagemin/tsconfig.json | 23 ++++++++++++++++++ types/gulp-imagemin/tslint.json | 1 + 4 files changed, 71 insertions(+) create mode 100644 types/gulp-imagemin/gulp-imagemin-tests.ts create mode 100644 types/gulp-imagemin/index.d.ts create mode 100644 types/gulp-imagemin/tsconfig.json create mode 100644 types/gulp-imagemin/tslint.json diff --git a/types/gulp-imagemin/gulp-imagemin-tests.ts b/types/gulp-imagemin/gulp-imagemin-tests.ts new file mode 100644 index 0000000000..7fc1d86311 --- /dev/null +++ b/types/gulp-imagemin/gulp-imagemin-tests.ts @@ -0,0 +1,20 @@ +import * as GulpImagemin from 'gulp-imagemin'; + +GulpImagemin(); + +GulpImagemin([ + GulpImagemin.gifsicle({ interlaced: true }), + GulpImagemin.jpegtran({ progressive: true }), + GulpImagemin.optipng({ optimizationLevel: 5 }), + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }, { cleanupIDs: false }] + }) +]); + +GulpImagemin({ verbose: true }); + +GulpImagemin([ + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }] + }) +], { verbose: true }); diff --git a/types/gulp-imagemin/index.d.ts b/types/gulp-imagemin/index.d.ts new file mode 100644 index 0000000000..42c1ef8d5c --- /dev/null +++ b/types/gulp-imagemin/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for gulp-imagemin 4.1 +// Project: https://github.com/sindresorhus/gulp-imagemin#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +declare function imagemin(pluginsOrOptions?: imagemin.Plugin[] | imagemin.Options): Transform; +declare function imagemin(plugins?: imagemin.Plugin[], options?: imagemin.Options): Transform; + +declare namespace imagemin { + interface Options { + verbose?: boolean; + } + + type Plugin = (input: any) => Promise; + type PluginFactory = (options?: any) => Plugin; + + const gifsicle: PluginFactory; + const jpegtran: PluginFactory; + const optipng: PluginFactory; + const svgo: PluginFactory; +} + +export = imagemin; diff --git a/types/gulp-imagemin/tsconfig.json b/types/gulp-imagemin/tsconfig.json new file mode 100644 index 0000000000..1b35a74382 --- /dev/null +++ b/types/gulp-imagemin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-imagemin-tests.ts" + ] +} diff --git a/types/gulp-imagemin/tslint.json b/types/gulp-imagemin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-imagemin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 057310a95d998b7d238ffe73c0cb082c782dac5c Mon Sep 17 00:00:00 2001 From: Jiayu Liu Date: Tue, 31 Jul 2018 02:20:51 +0800 Subject: [PATCH 028/129] addint definitions for @tinajs/tina-redux (#27231) --- .github/CODEOWNERS | 1 + types/tinajs__tina-redux/index.d.ts | 23 +++++++++ types/tinajs__tina-redux/package.json | 6 +++ .../tinajs__tina-redux-tests.ts | 51 +++++++++++++++++++ types/tinajs__tina-redux/tsconfig.json | 21 ++++++++ types/tinajs__tina-redux/tslint.json | 3 ++ 6 files changed, 105 insertions(+) create mode 100644 types/tinajs__tina-redux/index.d.ts create mode 100644 types/tinajs__tina-redux/package.json create mode 100644 types/tinajs__tina-redux/tinajs__tina-redux-tests.ts create mode 100644 types/tinajs__tina-redux/tsconfig.json create mode 100644 types/tinajs__tina-redux/tslint.json diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0380b02e1e..8c7f823a07 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4293,6 +4293,7 @@ /types/timer-machine/ @dolanmiu /types/timezone-js/ @bonnici /types/tinajs__tina/ @Jimexist +/types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec /types/tiny-slider-react/ @screendriver /types/tinycolor2/ @M-Zuber @geertjansen @nvh diff --git a/types/tinajs__tina-redux/index.d.ts b/types/tinajs__tina-redux/index.d.ts new file mode 100644 index 0000000000..e48665e696 --- /dev/null +++ b/types/tinajs__tina-redux/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for @tinajs/tina-redux 1.4 +// Project: https://github.com/tinajs/tina-redux +// Definitions by: Jiayu Liu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tinajs__tina-redux +// TypeScript Version: 2.3 + +import { Store, Dispatch } from "redux"; + +type MapStateToProps = (state: any) => any; +type mapDispatchToProps = (dispatch: Dispatch) => any; + +interface HOC { + onLoad: () => void; + onUnload: () => void; + methods: object; +} + +declare class TinaRedux { + constructor(reduxStore: Store); + connect(mapState?: MapStateToProps, mapDispatch?: mapDispatchToProps): HOC; +} + +export = TinaRedux; diff --git a/types/tinajs__tina-redux/package.json b/types/tinajs__tina-redux/package.json new file mode 100644 index 0000000000..7f5b19d45b --- /dev/null +++ b/types/tinajs__tina-redux/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "redux": "^4.0.0" + } +} diff --git a/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts new file mode 100644 index 0000000000..d4a7c2225f --- /dev/null +++ b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts @@ -0,0 +1,51 @@ +import { createStore, combineReducers, Action } from "redux"; +import TinaRedux from "@tinajs/tina-redux"; + +interface Todo { + id: number; + text: string; + completed: boolean; +} + +interface TodoAction extends Action, Todo {} + +const intialState: Todo[] = [ + { id: 1, text: "Star Tina.js", completed: false }, + { id: 2, text: "Star Tina-Redux", completed: true }, + { id: 3, text: "Build a mini-program with Tina.js", completed: false }, + { id: 4, text: "Add to Showcase of Tina.js", completed: false } +]; + +const todos = (state = intialState, action: TodoAction) => { + switch (action.type) { + case "ADD_TODO": + return [ + ...state, + { + id: action.id, + text: action.text, + completed: false + } + ]; + case "TOGGLE_TODO": + return state.map( + todo => + todo.id === action.id + ? { ...todo, completed: !todo.completed } + : todo + ); + case "CLEAR_COMPLETED_TODOS": + return state.filter(todo => !todo.completed); + default: + return state; + } +}; + +const todoApp = combineReducers({ + todos +}); + +const reduxStore = createStore(todoApp); +const store = new TinaRedux(reduxStore); + +export default store; diff --git a/types/tinajs__tina-redux/tsconfig.json b/types/tinajs__tina-redux/tsconfig.json new file mode 100644 index 0000000000..c3b4905b15 --- /dev/null +++ b/types/tinajs__tina-redux/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "allowSyntheticDefaultImports": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@tinajs/tina": ["tinajs__tina"], + "@tinajs/tina-redux": ["tinajs__tina-redux"] + } + }, + "files": ["index.d.ts", "tinajs__tina-redux-tests.ts"] +} diff --git a/types/tinajs__tina-redux/tslint.json b/types/tinajs__tina-redux/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/tinajs__tina-redux/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 46ef7e1ffc4cdd0f7b96f4a72a0290592c8738f8 Mon Sep 17 00:00:00 2001 From: Endurance Idehen <40364466+ls-endurance@users.noreply.github.com> Date: Mon, 30 Jul 2018 13:22:32 -0500 Subject: [PATCH 029/129] @types/React-Select: Add ability for arrow renderer prop to be set to null (#27342) * Add ability for arrow renderer prop to be set to null In this issue, arrow rendering would keep the functionality even if no arrow was being rendered. The PR below fixed the issue. https://github.com/JedWatson/react-select/pull/1761 In this PR, the guys added the ability to set the arrowRenderer option to null, which disables all arrow related operation. The types repo needs to reflect this change. Thanks! * Add my name to list --- types/react-select/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index bde3c3c6a0..b3d5490d9f 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -13,6 +13,7 @@ // David Schkalee // Arthur Udalov // Sebastian Silbermann +// Endurance Idehen // Guillaume Chartier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -241,7 +242,7 @@ export interface ReactSelectProps extends React.Props Date: Tue, 31 Jul 2018 01:24:58 +0700 Subject: [PATCH 030/129] [slack-mock] New typings for slack-mock (#27440) * Add types for slack-mock * Add library specific types * Fix lint * Reorganize imports --- types/slack-mock/index.d.ts | 200 +++++++++++++++++++++++++++ types/slack-mock/slack-mock-tests.ts | 103 ++++++++++++++ types/slack-mock/tsconfig.json | 23 +++ types/slack-mock/tslint.json | 3 + 4 files changed, 329 insertions(+) create mode 100644 types/slack-mock/index.d.ts create mode 100644 types/slack-mock/slack-mock-tests.ts create mode 100644 types/slack-mock/tsconfig.json create mode 100644 types/slack-mock/tslint.json diff --git a/types/slack-mock/index.d.ts b/types/slack-mock/index.d.ts new file mode 100644 index 0000000000..2289e554b4 --- /dev/null +++ b/types/slack-mock/index.d.ts @@ -0,0 +1,200 @@ +// Type definitions for slack-mock 1.1 +// Project: https://github.com/Skellington-Closet/slack-mock +// Definitions by: Kris Kalavantavanich +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { IncomingHttpHeaders } from "http"; +import * as nock from "nock"; +import { Url } from "url"; +import * as WebSocket from "ws"; + +export = SlackMock; + +declare function SlackMock(config?: SlackMock.ConfigOptions): SlackMock.Instance; + +declare namespace SlackMock { + let instance: Instance; + + interface Instance { + events: Events; + incomingWebhooks: IncomingWebhooks; + interactiveButtons: InteractiveButtons; + outgoingWebhooks: OutgoingWebhooks; + rtm: Rtm; + slashCommands: SlashCommands; + web: Web; + + reset: () => void; + } + + interface ConfigOptions { + rtmPort?: number; + logLevel?: string; + } + + // Events + + type EventUrl = string | Url; + type EventHttpHeaders = IncomingHttpHeaders; + + interface Events { + send: (targetUrl: EventUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface EventCall { + url: EventUrl; + params: T; + headers: EventHttpHeaders; + statusCode: number; + } + + // Incoming Webhooks + + type IncomingWebhookUrl = string; + type IncomingWebhookHttpHeaders = nock.HttpHeaders; + + interface IncomingWebhooks { + addResponse: (opts: IncomingWebhookOptions) => void; + reset: () => void; + calls: Array>; + } + + interface IncomingWebhookOptions { + url?: IncomingWebhookUrl; + statusCode ?: number; + body ?: T; + headers ?: IncomingWebhookHttpHeaders; + } + + interface IncomingWebhookCall { + url: IncomingWebhookUrl; + params: T; + headers: IncomingWebhookHttpHeaders; + } + + // Interactive Buttons + + type InteractiveButtonUrl = string | Url; + type InteractiveButtonHttpHeaders = nock.HttpHeaders; + + interface InteractiveButtons { + send: (targetUrl: InteractiveButtonUrl, body: T) => Promise; + addResponse: (opts: InteractiveButtonOptions) => void; + reset: () => void; + calls: Array>; + } + + interface InteractiveButtonOptions { + url?: InteractiveButtonUrl; + statusCode ?: number; + body ?: T; + headers ?: InteractiveButtonHttpHeaders; + } + + interface InteractiveButtonCall { + url: InteractiveButtonUrl; + params: T; + headers: InteractiveButtonHttpHeaders; + statusCode: number; + type: InteractiveButtonCallType; + } + + enum InteractiveButtonCallType { + response = 'response', + response_url = 'response_url' + } + + // Outgoing Webhooks + + type OutgoingWebhookUrl = string | Url; + type OutgoingWebhookHttpHeaders = IncomingHttpHeaders; + + interface OutgoingWebhooks { + send: (targetUrl: OutgoingWebhookUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface OutgoingWebhookCall { + url: OutgoingWebhookUrl; + params: T; + headers: OutgoingWebhookHttpHeaders; + statusCode: number; + } + + // RTM + + interface Rtm { + clients: WebSocket[]; + send: (token: string, message: T) => Promise; + reset: () => void; + calls: Array>; + startServer: (token: string) => void; + stopServer: (token: string) => void; + } + + interface RtmCall { + message: T; + token: string; + rawMessage: WebSocket.Data; + } + + // Slash Commands + + type SlashCommandUrl = string | Url; + type SlashCommandHttpHeaders = IncomingHttpHeaders; + + interface SlashCommands { + send: (targetUrl: SlashCommandUrl, body: T) => Promise; + addResponse: (opts: SlashCommandOptions) => void; + reset: () => void; + calls: Array>; + } + + interface SlashCommandOptions { + url?: SlashCommandUrl; + statusCode ?: number; + body ?: T; + headers ?: SlashCommandHttpHeaders; + } + + interface SlashCommandCall { + url: SlashCommandUrl; + params: T; + headers: SlashCommandHttpHeaders; + statusCode: number; + type: SlashCommandCallType; + } + + enum SlashCommandCallType { + response = 'response', + response_url = 'response_url' + } + + // Web + + type WebUrl = string; + type WebHttpHeaders = nock.HttpHeaders; + + interface Web { + addResponse: (opts: WebOptions) => void; + reset: () => void; + calls: Array>; + } + + interface WebOptions { + url?: WebUrl; + statusCode ?: number; + body ?: T; + headers ?: WebHttpHeaders; + } + + interface WebCall { + url: WebUrl; + params: T; + headers: WebHttpHeaders; + } +} diff --git a/types/slack-mock/slack-mock-tests.ts b/types/slack-mock/slack-mock-tests.ts new file mode 100644 index 0000000000..5b5dabb9c1 --- /dev/null +++ b/types/slack-mock/slack-mock-tests.ts @@ -0,0 +1,103 @@ +import SlackMock = require("slack-mock"); + +// Initialization + +const slackMock = SlackMock.instance; +SlackMock({ + logLevel: "error", + rtmPort: 9090 +}); +SlackMock(); + +// Events +const eventPayload = { }; +slackMock.events.send('http://localhost:9000/event', eventPayload) + .then(() => { + slackMock.events.calls.length; + slackMock.events.calls[0].statusCode; + slackMock.events.calls[0].headers; + slackMock.events.calls[0].params; + slackMock.events.calls[0].url; + }); + +slackMock.events.reset(); + +// Incoming Webhooks +slackMock.incomingWebhooks.calls.length; +slackMock.incomingWebhooks.calls[0].params.text; + +// Interactive Buttons +slackMock.interactiveButtons.addResponse({ + statusCode: 201 +}); + +const interactiveButtonPayload = {text: 'abc'}; +slackMock.interactiveButtons.send('http://localhost:9000/button', interactiveButtonPayload) + .then(() => { + slackMock.interactiveButtons.calls.length; + slackMock.interactiveButtons.calls[0].params.text; + }); + +// Outgoing Webhooks +const outgoingWebhookPayload = {text: 'abc'}; +slackMock.outgoingWebhooks.send('http://localhost:9000/outgoing', outgoingWebhookPayload) + .then(() => { + slackMock.outgoingWebhooks.calls.length; + slackMock.outgoingWebhooks.calls[0].params.text; + }); + +// RTM +slackMock.rtm.send('1234', { + type: 'message', + channel: 'mockChannel', + user: 'usr', + text: 'hello'}) + .then(() => { + slackMock.rtm.calls.length; + slackMock.rtm.calls[0].message.text; + }); +slackMock.rtm.startServer('1234'); +slackMock.rtm.stopServer('1234'); + +// Slash Commands +const slashCommandPayload = { }; +slackMock.slashCommands.send('http://localhost:9000/slash', slashCommandPayload) + .then(() => { + slackMock.slashCommands.calls.length; + slackMock.slashCommands.calls[0].params.text; + slackMock.slashCommands.calls[0].params.response_type; + }); + +// Web (OAuth Example) + +const botToken = 'xoxb-XXXXXXXXXXXX-TTTTTTTTTTTTTT'; +slackMock.web.addResponse({ + url: 'https://slack.com/api/oauth.access', + statusCode: 200, + body: { + access_token: 'xoxp-XXXXXXXX-XXXXXXXX-XXXXX', + scope: 'incoming-webhook,commands,bot', + team_name: 'mockTeam', + team_id: 'Tmock', + bot: { + bot_user_id: 'Bmock', + bot_access_token: botToken + } + } +}); + +slackMock.web.addResponse({ + url: 'https://slack.com/api/rtm.start', + statusCode: 200, + body: { + ok: true, + self: { + name: 'mockSelf', + id: 'Bmock' + }, + team: { + name: 'mockTeam', + id: 'Tmock' + } + } +}); diff --git a/types/slack-mock/tsconfig.json b/types/slack-mock/tsconfig.json new file mode 100644 index 0000000000..e012cc79b1 --- /dev/null +++ b/types/slack-mock/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "slack-mock-tests.ts" + ] +} \ No newline at end of file diff --git a/types/slack-mock/tslint.json b/types/slack-mock/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/slack-mock/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From bbd49ba4ed08cf2778dc7d10410f918f7ed2c593 Mon Sep 17 00:00:00 2001 From: confususs Date: Mon, 30 Jul 2018 20:26:04 +0200 Subject: [PATCH 031/129] [backbone.marionette] Added parameter for model to childview function of CollectionView (#27441) * Added model param to childview function of CollectionView * Added private property to MyOtherView to ensure type difference --- .../backbone.marionette-tests.ts | 23 +++++++++++++++++-- types/backbone.marionette/index.d.ts | 7 +++--- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/types/backbone.marionette/backbone.marionette-tests.ts b/types/backbone.marionette/backbone.marionette-tests.ts index c6400b2672..2b86849622 100644 --- a/types/backbone.marionette/backbone.marionette-tests.ts +++ b/types/backbone.marionette/backbone.marionette-tests.ts @@ -135,6 +135,15 @@ class MyView extends Marionette.View { } } +class MyOtherView extends MyView { + private readonly foo: string; + + constructor(model: MyModel) { + super(model); + this.foo = 'bar'; + } +} + class MainRegion extends Marionette.Region { constructor() { super(); @@ -185,10 +194,20 @@ class MyHtmlElRegion extends Marionette.Region { } } -class MyCollectionView extends Marionette.CollectionView { +class MyCollectionView extends Marionette.CollectionView { constructor() { super(); + + this.childView = (model: MyModel) => { + if (model.get('isFoo')) { + return MyView; + } + + return MyOtherView; + }; + this.childView = MyView; + this.childViewEvents = { render() { console.log('a childView has been rendered'); @@ -282,7 +301,7 @@ function CollectionViewTests() { cv.collection.add(new MyModel()); app.mainRegion.show(cv); cv.emptyView = MyView; - const view: Marionette.CollectionView = cv.destroy(); + const view: Marionette.CollectionView = cv.destroy(); } class MyController { diff --git a/types/backbone.marionette/index.d.ts b/types/backbone.marionette/index.d.ts index 0b717c9bb1..bacd045ba1 100644 --- a/types/backbone.marionette/index.d.ts +++ b/types/backbone.marionette/index.d.ts @@ -3,7 +3,8 @@ // Definitions by: Zeeshan Hamid , // Natan Vivo , // Sven Tschui , -// Volker Nauruhn +// Volker Nauruhn , +// Ard Timmerman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1157,7 +1158,7 @@ export interface CollectionViewOptions< /** * Specify a child view to use. */ - childView?: (() => typeof Backbone.View) | typeof Backbone.View; + childView?: ((model: TModel) => typeof Backbone.View) | typeof Backbone.View; /** * Define options to pass to the childView constructor. @@ -1219,7 +1220,7 @@ export class CollectionView { new(...args: any[]): TView }) | { new(...args: any[]): TView }; + childView: ((model: TModel) => { new(...args: any[]): TView }) | { new(...args: any[]): TView }; /** * Define options to pass to the childView constructor. From 8b490c354b69f4771f57f657ba4ba0142a829363 Mon Sep 17 00:00:00 2001 From: Roger Date: Mon, 30 Jul 2018 20:32:49 +0200 Subject: [PATCH 032/129] Less - add refresh, importManager, sheets, modifyVars callback. (#27443) * Add refresh method, importManager, sheets and modifyVars method callback. * Add a few less tests for their new methods. --- types/less/index.d.ts | 25 +++++++++++++++++++++---- types/less/less-tests.ts | 14 ++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/types/less/index.d.ts b/types/less/index.d.ts index bca5c21c33..7d69273a52 100644 --- a/types/less/index.d.ts +++ b/types/less/index.d.ts @@ -52,6 +52,11 @@ declare namespace Less { interface StaticOptions { async: boolean; fileAsync: boolean; + modifyVars: { [variable: string]: string }; + } + + interface ImportManager { + contents: { [fileName: string]: string }; } interface Options { @@ -76,21 +81,33 @@ declare namespace Less { map: string; imports: string[]; } + + interface RefreshOutput { + endTime: Date; + startTime: Date; + sheets: number; + totalMilliseconds: number; + } } interface LessStatic { options: Less.StaticOptions; - - modifyVars(vars: { [name: string]: string }): void; - + + importManager?: Less.ImportManager; + sheets: HTMLLinkElement[]; + + modifyVars(vars: { [name: string]: string }): Promise; + refreshStyles(): void; - + render(input: string, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string, options: Less.Options, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string): Promise; render(input: string, options: Less.Options): Promise; + refresh(reload?: boolean, modifyVars?: { [variable: string]: string }, clearFileCache?: boolean): Promise; + version: number[]; watch(): void; diff --git a/types/less/less-tests.ts b/types/less/less-tests.ts index 5d0029475a..20a1f587a9 100644 --- a/types/less/less-tests.ts +++ b/types/less/less-tests.ts @@ -39,8 +39,22 @@ less.render("h1 { background: red; }", options); less.modifyVars({ '@buttonFace': '#5B83AD', '@buttonText': '#D9EEF2' +}).then((output) => { + console.log('Successfully modified vars.'); }); less.refreshStyles(); less.watch(); + +less.refresh(true, { + '@buttonFace': '#5B83AD' +}, true).then((output) => { + console.log('successfully refreshed less files'); +}); + +if (less.importManager) { + for (let fileName in less.importManager.contents) { + let fileContents = less.importManager.contents[fileName]; + } +} \ No newline at end of file From 7d909e1f5650a74f6902e55d87d9f89ab8369d88 Mon Sep 17 00:00:00 2001 From: Tim Hwang Date: Mon, 30 Jul 2018 14:37:38 -0400 Subject: [PATCH 033/129] redux-form: Remove `label` from Field interface (#27502) This was added to DefinitelyTyped in PRs #21204 and #24041. However, both reasons given are incorrect: this prop is indeed featured in the examples, but only used for a sample component also defined for demo purposes. `props.label` is not a part of the `redux-form` `` API, and as such shouldn't be included. One reason is because `props.label` should be up to users to implement. If a user wants `props.label` to support React nodes instead of just strings, they can no longer just extend DefinitelyTyped interfaces because this causes an incompatibility with the set string type. I realize this change might cause backwards compatibility issues for users who are already using a `label` prop, as it's a ubiquitous pattern. Looking for input on how to properly proceed with this. Thanks! ------ Please fill in this template. - [x] Use a meaningful title for the pull request. Include the name of the package modified. - [x] Test the change in your own code. (Compile and run.) - [x] Add or edit tests to reflect the change. (Run with `npm test`.) *NOTE: I am getting `File name must be camelCase` both before and after my change* - [x] Follow the advice from the [readme](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#make-a-pull-request). - [x] Avoid [common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md#common-mistakes). - [x] Run `npm run lint package-name` (or `tsc` if no `tslint.json` is present). Select one of these and delete the others: If changing an existing definition: - [x] Provide a URL to documentation or source code which provides context for the suggested changes: https://github.com/erikras/redux-form/blob/master/src/createField.js ctrl-F label; no result - [ ] Increase the version number in the header if appropriate. - [x] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`. --- types/redux-form/lib/Field.d.ts | 2 -- types/redux-form/redux-form-tests.tsx | 1 - 2 files changed, 3 deletions(-) diff --git a/types/redux-form/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index d27a10ce47..c303f0d5c3 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -37,7 +37,6 @@ export interface CommonFieldProps extends CommonFieldInputProps { export interface BaseFieldProps

extends Partial { name: string; - label?: string; component?: ComponentType | "input" | "select" | "textarea"; format?: Formatter | null; normalize?: Normalizer; @@ -73,7 +72,6 @@ export class Field

extends Comp export interface WrappedFieldProps { input: WrappedFieldInputProps; meta: WrappedFieldMetaProps; - label?: string; } export interface WrappedFieldInputProps extends CommonFieldInputProps { diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 06344b54c5..ea13a9618f 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -110,7 +110,6 @@ interface MyFieldCustomProps { type MyFieldProps = MyFieldCustomProps & WrappedFieldProps; const MyField: React.StatelessComponent = ({ children, - label, input, meta, foo From 039caf4113d624977763d32e1f0d15153991149b Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 30 Jul 2018 11:48:14 -0700 Subject: [PATCH 034/129] QUnit assert.step and assert.verifySteps (#27558) --- types/qunit/index.d.ts | 27 +++++++++++++++++++++++++++ types/qunit/qunit-tests.ts | 8 ++++++++ 2 files changed, 35 insertions(+) diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index 2b7eb586ff..973a3b00a0 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for QUnit v2.5.0 // Project: http://qunitjs.com/ // Definitions by: James Bracy +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Assert { @@ -234,6 +235,32 @@ interface Assert { */ throws(block: () => void, expected?: any, message?: any): void; raises(block: () => void, expected?: any, message?: any): void; + + /** + * A marker for progress in a given test. + * + * The `step()` assertion registers a passing assertion with a provided message. This makes + * it easy to check that specific portions of code are being executed, especially in + * asynchronous test cases and when used with `verifySteps()`. + * + * Together with the `verifySteps()` method, `step()` assertions give you an easy way + * to verify both the count and order of code execution. + * + * @param message Message to display for the step + */ + step(message: string): void; + + /** + * A helper assertion to verify the order and number of steps in a test. + * + * The assert.verifySteps() assertion compares a given array of string values (representing steps) + * with the order and values of previous step() calls. This assertion is helpful for verifying + * the order and count of portions of code paths, especially asynchronous ones. + * + * @param steps Array of strings representing steps to verify + * @param message A short description of the assertion + */ + verifySteps(steps: string[], message?: string): void; } diff --git a/types/qunit/qunit-tests.ts b/types/qunit/qunit-tests.ts index e726113604..d475805cb0 100644 --- a/types/qunit/qunit-tests.ts +++ b/types/qunit/qunit-tests.ts @@ -562,3 +562,11 @@ equivResult = QUnit.equiv({}, {}); equivResult = QUnit.equiv(1, 2); equivResult = QUnit.equiv('foo', 'bar'); equivResult = QUnit.equiv(['foo'], ['bar']); + + +QUnit.test('steps', assert => { + assert.step('one'); + assert.step('two'); + assert.step('three'); + assert.verifySteps(['one', 'two', 'three'], 'Counting to three correctly'); +}); From d4b5c5d41199e87f882ab4207948dffbd17662f0 Mon Sep 17 00:00:00 2001 From: S McDowall Date: Mon, 30 Jul 2018 14:59:05 -0400 Subject: [PATCH 035/129] Fix problem in definition when passing a function in the origin: option field. (#27576) * Fixed type for function passing to cors() origin If you look at the actual code within @koa/cors and where it invokes any passed function within the origin: option, it invokes it with ctx, the standard Koa context, NOT the Request. Here is the code fragment.. https://github.com/koajs/cors/blob/b5a937fc24666761c61b1ac633f49f54612d1315/index.js#L58 Thus changed the signature of the origin option to reflect this. * Revert back to single quotes -- stupid prettier Fixed type for function passing to cors() origin If you look at the actual code within @koa/cors and where it invokes any passed function within the origin: option, it invokes it with ctx, the standard Koa context, NOT the Request. Here is the code fragment.. https://github.com/koajs/cors/blob/b5a937fc24666761c61b1ac633f49f54612d1315/index.js#L58 Thus changed the signature of the origin option to reflect this. --- types/koa__cors/index.d.ts | 9 ++++++--- types/koa__cors/koa__cors-tests.ts | 8 ++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/types/koa__cors/index.d.ts b/types/koa__cors/index.d.ts index 25d337716e..da58136652 100644 --- a/types/koa__cors/index.d.ts +++ b/types/koa__cors/index.d.ts @@ -1,10 +1,13 @@ // Type definitions for @koa/cors 2.2 // Project: https://github.com/koajs/cors -// Definitions by: Xavier Stouder , Izayoi Ko , Steve Hipwell +// Definitions by: Xavier Stouder +// Izayoi Ko +// Steve Hipwell +// Steven McDowall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Koa from "koa"; +import * as Koa from 'koa'; export = cors; @@ -12,7 +15,7 @@ declare function cors(options?: cors.Options): Koa.Middleware; declare namespace cors { interface Options { - origin?: ((req: Koa.Request) => string) | string; + origin?: ((ctx: Koa.Context) => string) | string; allowMethods?: string[] | string; exposeHeaders?: string[] | string; allowHeaders?: string[] | string; diff --git a/types/koa__cors/koa__cors-tests.ts b/types/koa__cors/koa__cors-tests.ts index 135845f205..25f068eb13 100644 --- a/types/koa__cors/koa__cors-tests.ts +++ b/types/koa__cors/koa__cors-tests.ts @@ -3,3 +3,11 @@ import cors = require('@koa/cors'); const app = new Koa(); app.use(cors()); + +// Trying using cors() passing in a function .. +function testCorsFunction(ctx: Koa.Context) { + const requestOrigin = ctx.request.origin; + return requestOrigin; +} + +app.use(cors({ origin: testCorsFunction })); From d738494b0898da6e5092660b7951ea969013ce4b Mon Sep 17 00:00:00 2001 From: Resi Respati Date: Tue, 31 Jul 2018 02:00:41 +0700 Subject: [PATCH 036/129] [next] recover old router events APIs (#27695) --- types/next/router.d.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 74aafd4a33..fe3563d473 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -62,7 +62,16 @@ export interface RouterProps { options?: EventChangeOptions, ): Promise; - // events + // events (deprecated soonish) + onAppUpdated?(nextRoute: string): void; + onBeforeHistoryChange?(as: string): void; + onHashChangeStart?(url: string): void; + onHashChangeComplete?(url: string): void; + onRouteChangeComplete?(url: string): void; + onRouteChangeError?(error: RouteChangeError, url: string): void; + onRouteChangeStart?(url: string): void; + + // events API (6.1.1+) readonly events: { on: (eventName: EventName, handler: EventHandler | ErrorEventHandler) => void; off: (eventName: EventName, handler: (url: string) => any) => void; From f8485f63111d3fc453fa367c6aa961cdfe4b8e1f Mon Sep 17 00:00:00 2001 From: Jurand Niemczycki <32194442+createdbyjurand@users.noreply.github.com> Date: Mon, 30 Jul 2018 21:00:47 +0200 Subject: [PATCH 037/129] espruino: added boolean to digitalwrite (#27577) * espruino added type for wifi module for access point * espruino added myself to definitions * changed tabsize to 4 * espruino: added boolean to digitalwrite --- types/espruino/espruino-tests.ts | 3 +++ types/espruino/index.d.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/types/espruino/espruino-tests.ts b/types/espruino/espruino-tests.ts index 32f044796d..c1bafc9048 100644 --- a/types/espruino/espruino-tests.ts +++ b/types/espruino/espruino-tests.ts @@ -10,5 +10,8 @@ wifi.startAP('ssid', { password: 'pass', authMode: 'wpa_wpa2' }, err => { console.log("created"); }); +digitalWrite(D2, false); +digitalWrite(D2, true); + I2C1.setup({ scl: D4, sda: D0 }); Serial2.setup(9600, { rx: D16, tx: D17 }); diff --git a/types/espruino/index.d.ts b/types/espruino/index.d.ts index 61cf72f173..cb6151e85a 100644 --- a/types/espruino/index.d.ts +++ b/types/espruino/index.d.ts @@ -3600,7 +3600,7 @@ declare function digitalPulse(pin: Pin, value: boolean, time: any): void; * @param value * @url http://www.espruino.com/Reference#l__global_digitalWrite */ -declare function digitalWrite(pin: Pin, value: number): void; +declare function digitalWrite(pin: Pin, value: number | boolean): void; /** *

Get the digital value of the given pin.

From bee839cc6d9f2b0b382ff68708a584049e901a6e Mon Sep 17 00:00:00 2001 From: Tomas Brambora Date: Tue, 31 Jul 2018 05:08:10 +1000 Subject: [PATCH 038/129] Remove unused template type (#27589) --- types/react-measure/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-measure/index.d.ts b/types/react-measure/index.d.ts index c61b22b187..241d482a53 100644 --- a/types/react-measure/index.d.ts +++ b/types/react-measure/index.d.ts @@ -46,7 +46,7 @@ export interface MeasuredComponentProps { type MeasuredComponent = React.ComponentType; -export interface MeasureProps { +export interface MeasureProps { client?: boolean; offset?: boolean; scroll?: boolean; @@ -60,5 +60,5 @@ export interface MeasureProps { export declare function withContentRect(types: ReadonlyArray | MeasurementType): (fn: MeasuredComponent) => React.ComponentType; -declare class Measure extends React.Component> {} +declare class Measure extends React.Component {} export default Measure; From 37ee427df7c9efb12fa8885a37e8a710ffcd7f50 Mon Sep 17 00:00:00 2001 From: Melvin Groenhoff Date: Mon, 30 Jul 2018 21:10:18 +0200 Subject: [PATCH 039/129] Depend on @babel/parser instead of babylon (#27596) --- types/babel__core/index.d.ts | 6 +++--- types/babel__core/tsconfig.json | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 84f49c20fc..277228341b 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -10,10 +10,10 @@ import { GeneratorOptions } from "@babel/generator"; import traverse, { Visitor, NodePath } from "@babel/traverse"; import template from "@babel/template"; import * as t from "@babel/types"; -import { BabylonOptions } from "babylon"; +import { ParseOptions } from "@babel/parser"; export { - BabylonOptions, + ParseOptions, GeneratorOptions, t as types, template, @@ -217,7 +217,7 @@ export interface TransformOptions { * * Default: `{}` */ - parserOpts?: BabylonOptions | null; + parserOpts?: ParseOptions | null; /** * List of plugins to load and use diff --git a/types/babel__core/tsconfig.json b/types/babel__core/tsconfig.json index 22eb208383..2f96e019cb 100644 --- a/types/babel__core/tsconfig.json +++ b/types/babel__core/tsconfig.json @@ -22,6 +22,9 @@ "@babel/generator": [ "babel__generator" ], + "@babel/parser": [ + "babel__parser" + ], "@babel/template": [ "babel__template" ], From 7f59e2096edb77eb00281f6b75a52fa7da0a0301 Mon Sep 17 00:00:00 2001 From: Max Loeb Date: Mon, 30 Jul 2018 12:13:46 -0700 Subject: [PATCH 040/129] [jquery.fileupload] fix add signature (#27653) * fix add args * simplify * ws * ws * update version number --- types/jquery.fileupload/index.d.ts | 50 +++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/types/jquery.fileupload/index.d.ts b/types/jquery.fileupload/index.d.ts index 6ca998d41a..28bbf3c969 100644 --- a/types/jquery.fileupload/index.d.ts +++ b/types/jquery.fileupload/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery File Upload Plugin 5.40.1 +// Type definitions for jQuery File Upload Plugin 9.22.0 // Project: https://github.com/blueimp/jQuery-File-Upload // Definitions by: Rob Alarcon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ /// -// Interface options for the plugin +// Interface options for the plugin interface JQueryFileInputOptions { /** @@ -106,8 +106,8 @@ interface JQueryFileInputOptions { */ redirectParamName?: string; - // The HTTP request method must be "POST" or "PUT" - type?: string, + // The HTTP request method must be "POST" or "PUT" + type?: string, /** * Set the following option to the location of a postMessage window, @@ -199,7 +199,7 @@ interface JQueryFileInputOptions { * handlers using jQuery's Deferred callbacks: * data.submit().done(func).fail(func).always(func); */ - add?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; + add?: (e: JQueryEventObject, data: JqueryFileUploadAddObject) => void; // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: @@ -209,7 +209,7 @@ interface JQueryFileInputOptions { cache?: boolean; timeout?: number; - + active?: Function; progress?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; send?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; @@ -217,13 +217,13 @@ interface JQueryFileInputOptions { // Validation /** - * The maximum allowed file size in bytes. - * Type: integer - * Default: undefined - * Example: 10000000 // 10 MB - * Note: This option has only an effect for browsers supporting the File API. - * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize - */ + * The maximum allowed file size in bytes. + * Type: integer + * Default: undefined + * Example: 10000000 // 10 MB + * Note: This option has only an effect for browsers supporting the File API. + * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize + */ maxFileSize?: number; // Other callbacks: @@ -243,7 +243,7 @@ interface JQueryFileInputOptions { chunkfail?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; chunkalways?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; - // Others + // Others url?: string; files?: any; @@ -263,6 +263,12 @@ interface JQuery { fileupload(action: string, message:string, settings: JQueryFileInputOptions | string): JQueryFileUpload; } +interface JqueryFileUploadEnhancedPromise extends JQueryPromise{ + success: JQueryPromise['done'], + error: JQueryPromise['fail'], + complete: JQueryPromise['always'], +} + interface JQuerySupport { fileInput?: boolean; } @@ -275,6 +281,20 @@ interface JQueryFileUploadChangeObject { originalFiles: File[]; } +interface JqueryFileUploadConvenienceObject { + abort: () => JqueryFileUploadEnhancedPromise; + process: (resolveFunc?: Function, rejectFunc?: Function) => JqueryFileUploadEnhancedPromise; + processing: () => JqueryFileUploadEnhancedPromise; + progress: () => JqueryFileUploadEnhancedPromise; + response: () => JqueryFileUploadEnhancedPromise; + submit(): JqueryFileUploadEnhancedPromise; + state: () => JqueryFileUploadEnhancedPromise; +} + +interface JqueryFileUploadAddObject extends JQueryFileUploadChangeObject, JqueryFileUploadConvenienceObject { + paramName?: string | string[]; +} + interface JQueryFileUploadProgressAllObject { loaded?: number; total?: number; @@ -304,4 +324,4 @@ interface JQueryFileUploadProgressObject extends JQueryFileInputOptions, JQueryF } interface JQueryFileUploadDone extends JQueryFileInputOptions, JQueryFileUploadXhr { -} +} \ No newline at end of file From 56325613eef6f5e27155d314432c2b53440418d0 Mon Sep 17 00:00:00 2001 From: Tyler Zhang Date: Mon, 30 Jul 2018 12:15:15 -0700 Subject: [PATCH 041/129] Add react-native-calendars typings (#27654) * initial type definitions * space out comments more * match pros to be closer to documented proptypes * indent tetss using 4 spaces * fix specs --- types/react-native-calendars/index.d.ts | 418 ++++++++++++++++++ .../react-native-calendars-tests.tsx | 374 ++++++++++++++++ types/react-native-calendars/tsconfig.json | 24 + types/react-native-calendars/tslint.json | 1 + 4 files changed, 817 insertions(+) create mode 100644 types/react-native-calendars/index.d.ts create mode 100644 types/react-native-calendars/react-native-calendars-tests.tsx create mode 100644 types/react-native-calendars/tsconfig.json create mode 100644 types/react-native-calendars/tslint.json diff --git a/types/react-native-calendars/index.d.ts b/types/react-native-calendars/index.d.ts new file mode 100644 index 0000000000..6294af4682 --- /dev/null +++ b/types/react-native-calendars/index.d.ts @@ -0,0 +1,418 @@ +// Type definitions for react-native-calendars 1.20 +// Project: https://github.com/wix/react-native-calendars#readme +// Definitions by: Tyler Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; +import { ViewProps, StyleProp } from 'react-native'; + +export interface DateObject { + year: number; + month: number; + day: number; + timestamp: number; + dateString: string; +} + +export interface CalendarTheme { + backgroundColor?: string; + calendarBackground?: string; + textSectionTitleColor?: string; + selectedDayBackgroundColor?: string; + selectedDayTextColor?: string; + todayTextColor?: string; + dayTextColor?: string; + textDisabledColor?: string; + dotColor?: string; + selectedDotColor?: string; + arrowColor?: string; + monthTextColor?: string; + textDayFontFamily?: string; + textMonthFontFamily?: string; + textDayHeaderFontFamily?: string; + textMonthFontWeight?: string; + textDayFontSize?: number; + textMonthFontSize?: number; + textDayHeaderFontSize?: number; +} + +export interface DayComponentProps { + state: '' | 'selected' | 'disabled' | 'today'; + theme: CalendarTheme; + onPress: () => any; + onLongPress: () => any; + date: DateObject; + marking: false | Marking[]; +} + +export interface CalendarBaseProps { + /** + * Styles for the view + */ + style?: StyleProp; + + /** + * Specify theme properties to override specific styles for calendar parts. Default = {} + */ + theme?: CalendarTheme; + + /** + * Initially visible month. Default = Date() + */ + current?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Handler which gets executed on day press. Default = undefined + */ + onDayPress?: (day: number) => void; + + /** + * Handler which gets executed on day long press. Default = undefined + */ + onDayLongPress?: (day: number) => void; + + /** + * Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + */ + monthFormat?: string; + + /** + * Handler which gets executed when visible month changes in calendar. Default = undefined + */ + onMonthChange?: (month: number) => void; + + /** + * Hide month navigation arrows. Default = false + */ + hideArrows?: boolean; + + /** + * Replace default arrows with custom ones (direction can be 'left' or 'right') + */ + renderArrow?: (direction: 'left' | 'right') => React.ReactNode; + + /** + * Do not show days of other months in month page. Default = false + */ + hideExtraDays?: boolean; + + /** + * If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + * day from another month that is visible in calendar page. Default = false + */ + disableMonthChange?: boolean; + + /** + * If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + */ + firstDay?: number; + + /** + * Hide day names. Default = false + */ + hideDayNames?: boolean; + + /** + * Show week numbers to the left. Default = false + */ + showWeekNumbers?: boolean; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go back month + */ + onPressArrowLeft?: (month: number) => void; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go next month + */ + onPressArrowRight?: (month: number) => void; + + /** + * Custom day renderer + */ + dayComponent?: React.Component | React.SFC; +} + +export interface DotForMultiDot { + key: string; + color: string; + selectedDotColor?: string; +} + +export interface MultiDotMarking { + dots: DotForMultiDot[]; + selected?: boolean; + selectedColor?: string; + disabled?: boolean; +} + +export interface DotMarking { + selected?: boolean; + marked?: boolean; + selectedColor?: string; + dotColor?: string; + activeOpacity?: number; + disabled?: boolean; + disableTouchEvent?: boolean; +} + +export interface PeriodMarking { + textColor?: string; + startingDay?: boolean; + color?: string; + selected?: boolean; + endingDay?: boolean; + disabled?: boolean; +} + +export interface MultiPeriodMarking { + periods: Array<{ + startingDay?: boolean; + endingDay?: boolean; + color?: string; + }>; +} + +export interface CustomMarking { + customStyles: any; +} + +export type Marking = + MultiDotMarking | + DotMarking | + PeriodMarking | + MultiPeriodMarking | + CustomMarking; + +export interface MultiDotMarkingProps { + markingType: 'multi-dot'; + markedDates: { + [date: string]: MultiDotMarking; + }; +} + +export interface DotMarkingProps { + markingType?: 'simple'; + markedDates: { + [date: string]: DotMarking; + }; +} + +export interface PeriodMarkingProps { + markingType: 'period'; + markedDates: { + [date: string]: PeriodMarking; + }; +} + +export interface CustomMarkingProps { + markingType: 'custom'; + markedDates: { + [date: string]: CustomMarking; + }; +} + +/** + * This type of marking is only fully supported by as it will expand the height + * of the component + */ +export interface MultiPeriodMarkingProps { + markingType: 'multi-period'; + markedDates: { + [date: string]: MultiPeriodMarking + }; +} + +export type CalendarMarkingProps = + MultiDotMarkingProps | + DotMarkingProps | + PeriodMarkingProps | + MultiPeriodMarkingProps | + CustomMarkingProps | + {}; + +export class Calendar extends React.Component {} + +export interface CalendarListBaseProps extends CalendarBaseProps { + /** + * Callback which gets executed when visible months change in scroll view. Default = undefined + */ + onVisibleMonthsChange?: (months: number) => void; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * Enable or disable scrolling of calendar list + */ + scrollEnabled?: boolean; + + /** + * Enable or disable vertical scroll indicator. Default = false + */ + showScrollIndicator?: boolean; + + /** + * Enable horizontal scrolling, default = false + */ + horizontal?: boolean; + + /** + * Enable paging on horizontal, default = false + */ + pagingEnabled?: boolean; + + /** + * Set custom calendarWidth. + */ + calendarWidth?: boolean; +} + +export class CalendarList extends React.Component {} + +export interface AgendaProps { + /** + * the list of items that have to be displayed in agenda. If you want to render item as empty date + * the value of date key kas to be an empty array []. If there exists no value for date key it is + * considered that the date in question is not yet loaded + */ + items: { + [key: string]: T[]; + }; + + /** + * callback that gets called when items for a certain month should be loaded (month became visible) + */ + loadItemsForMonth?: (date: DateObject) => void; + + /** + * callback that fires when the calendar is opened or closed + */ + onCalendarToggled?: (calendarOpened: boolean) => void; + + /** + * callback that gets called on day press + */ + onDayPress?: (day: number) => void; + + /** + * callback that gets called when day changes while scrolling agenda list + */ + onDayChange?: (day: number) => void; + + /** + * initially selected day + */ + selected?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * specify how each item should be rendered in agenda + */ + renderItem: (item: T, firstItemInDay?: T) => React.ReactNode; + + /** + * specify how each date should be rendered. day can be undefined if the item is not first in that day. + */ + renderDay?: (day: DateObject | undefined, item: T) => React.ReactNode; + + /** + * specify how empty date content with no items should be rendered + */ + renderEmptyDate?: () => React.ReactNode; + + /** + * specify how agenda knob should look like + */ + renderKnob?: () => React.ReactNode; + + /** + * specify what should be rendered instead of ActivityIndicator + */ + renderEmptyData?: () => React.ReactNode; + + /** + * specify your item comparison function for increased performance + */ + rowHasChanged?: (r1: any, r2: any) => boolean; + + /** + * Hide knob button. Default = false + */ + hideKnob?: boolean; + + /** + * A RefreshControl component, used to provide pull-to-refresh funtionality for the ScrollView + */ + refreshControl?: React.ReactNode; + + /** + * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. + * Make sure to also set the refreshing prop correctly. + */ + onRefresh?: () => any; + + /** + * Set this true while waiting for new data from a refresh + */ + refreshing?: boolean; + + /** + * Display loading indicator. Default = false + */ + displayLoadingIndicator?: boolean; + + /** + * agenda theme + */ + theme?: { + agendaDayTextColor?: string; + agendaDayNumColor?: string; + agendaTodayColor?: string; + agendaKnobColor?: string; + } & CalendarTheme; + + /** + * agenda container style + */ + style?: StyleProp; +} + +export class Agenda extends React.Component & CalendarMarkingProps> {} diff --git a/types/react-native-calendars/react-native-calendars-tests.tsx b/types/react-native-calendars/react-native-calendars-tests.tsx new file mode 100644 index 0000000000..5b438937e1 --- /dev/null +++ b/types/react-native-calendars/react-native-calendars-tests.tsx @@ -0,0 +1,374 @@ +import * as React from "react"; +import { Text, View } from "react-native"; +import { Calendar, CalendarList, Agenda } from "react-native-calendars"; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} + markedDates={{ + "2012-05-16": { selected: true, marked: true, selectedColor: "blue" }, + "2012-05-17": { marked: true }, + "2012-05-18": { marked: true, dotColor: "red", activeOpacity: 0 }, + "2012-05-19": { disabled: true, disableTouchEvent: true } + }} +/>; + +const vacation = { key: "vacation", color: "red", selectedDotColor: "blue" }; +const massage = { key: "massage", color: "blue", selectedDotColor: "blue" }; +const workout = { key: "workout", color: "green" }; + +; + +; + +; + +; + +; + + { + return ( + + + {date.day} + + + ); + }} +/>; + + { + console.log("now these months are visible", months); + }} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Horizontal + horizontal={true} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // Enable or disable scrolling of calendar list + scrollEnabled={true} + // Enable or disable vertical scroll indicator. Default = false + showScrollIndicator={true} + // Initially visible month. Default = Date() + current={"2012-03-01"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Handler which gets executed on day press. Default = undefined + onDayPress={day => { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("trigger items loading"); + }} + // callback that fires when the calendar is opened or closed + onCalendarToggled={calendarOpened => { + console.log(calendarOpened); + }} + // callback that gets called on day press + onDayPress={day => { + console.log("day pressed"); + }} + // callback that gets called when day changes while scrolling agenda list + onDayChange={day => { + console.log("day changed"); + }} + // initially selected day + selected={"2012-05-16"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // specify how each item should be rendered in agenda + renderItem={(item, firstItemInDay) => { + return ; + }} + // specify how each date should be rendered. day can be undefined if the item is not first in that day. + renderDay={(day, item) => { + return ; + }} + // specify how empty date content with no items should be rendered + renderEmptyDate={() => { + return ; + }} + // specify how agenda knob should look like + renderKnob={() => { + return ; + }} + // specify what should be rendered instead of ActivityIndicator + renderEmptyData={() => { + return ; + }} + // specify your item comparison function for increased performance + rowHasChanged={(r1, r2) => { + return r1.text !== r2.text; + }} + // Hide knob button. Default = false + hideKnob={true} + // By default, agenda dates are marked if they have at least one item, but you can override this if needed + markedDates={{ + "2012-05-16": { selected: true, marked: true }, + "2012-05-17": { marked: true }, + "2012-05-18": { disabled: true } + }} + // If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the refreshing prop correctly. + onRefresh={() => console.log("refreshing...")} + // Set this true while waiting for new data from a refresh + refreshing={false} + // Add a custom RefreshControl component, used to provide pull-to-refresh functionality for the ScrollView. + refreshControl={null} + // agenda theme + theme={{ + agendaDayTextColor: "yellow", + agendaDayNumColor: "green", + agendaTodayColor: "red", + agendaKnobColor: "blue" + }} + // agenda container style + style={{}} +/>; diff --git a/types/react-native-calendars/tsconfig.json b/types/react-native-calendars/tsconfig.json new file mode 100644 index 0000000000..e13f60597a --- /dev/null +++ b/types/react-native-calendars/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "react-native-calendars-tests.tsx" + ] +} diff --git a/types/react-native-calendars/tslint.json b/types/react-native-calendars/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-calendars/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 7f227d28c934dc33bb91d750271c61293e9ce0bc Mon Sep 17 00:00:00 2001 From: Johannes Henninger Date: Mon, 30 Jul 2018 21:15:37 +0200 Subject: [PATCH 042/129] Add type definitions for the WebAssembly Web API (#27663) --- types/webassembly-web-api/index.d.ts | 17 +++++++++++++ types/webassembly-web-api/tsconfig.json | 24 +++++++++++++++++++ types/webassembly-web-api/tslint.json | 6 +++++ .../webassembly-web-api-tests.ts | 18 ++++++++++++++ 4 files changed, 65 insertions(+) create mode 100644 types/webassembly-web-api/index.d.ts create mode 100644 types/webassembly-web-api/tsconfig.json create mode 100644 types/webassembly-web-api/tslint.json create mode 100644 types/webassembly-web-api/webassembly-web-api-tests.ts diff --git a/types/webassembly-web-api/index.d.ts b/types/webassembly-web-api/index.d.ts new file mode 100644 index 0000000000..fd53e094b2 --- /dev/null +++ b/types/webassembly-web-api/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for the WebAssembly Web API v1 +// Project: https://webassembly.org/ +// Definitions by: Johannes Henninger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +/** + * The WebAssembly Web API defines extensions to the JavaScript API made + * available specifically in web browsers. See [WebAssembly Web + * API](https://www.w3.org/TR/wasm-web-api-1/) for more information. + */ +declare namespace WebAssembly { + function compileStreaming(source: Response | Promise): Promise; + function instantiateStreaming(source: Response | Promise, importObject?: any): Promise; +} diff --git a/types/webassembly-web-api/tsconfig.json b/types/webassembly-web-api/tsconfig.json new file mode 100644 index 0000000000..eb9891f0e0 --- /dev/null +++ b/types/webassembly-web-api/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "webassembly-web-api-tests.ts" + ] +} diff --git a/types/webassembly-web-api/tslint.json b/types/webassembly-web-api/tslint.json new file mode 100644 index 0000000000..65c83fb1e3 --- /dev/null +++ b/types/webassembly-web-api/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": false + } +} diff --git a/types/webassembly-web-api/webassembly-web-api-tests.ts b/types/webassembly-web-api/webassembly-web-api-tests.ts new file mode 100644 index 0000000000..5c35d1362b --- /dev/null +++ b/types/webassembly-web-api/webassembly-web-api-tests.ts @@ -0,0 +1,18 @@ +const response: Response = new Response(); +const promise: Promise = Promise.resolve(response); + +// CompileStreaming - taking Response +// $ExpectType Promise +WebAssembly.compileStreaming(response); + +// CompileStreaming - taking Promise +// $ExpectType Promise +WebAssembly.compileStreaming(promise); + +// InstantiateStreaming - taking Response +// $ExpectType Promise +WebAssembly.instantiateStreaming(response); + +// InstantiateStreaming - taking Promise +// $ExpectType Promise +WebAssembly.instantiateStreaming(promise); From 9a8bb65edb5c07917626b4b011641033a8b2bd1e Mon Sep 17 00:00:00 2001 From: Michael Zlatkovsky Date: Mon, 30 Jul 2018 12:17:18 -0700 Subject: [PATCH 043/129] Fix erroneous typings for "charts.add" and "chart.setData" (#27694) * Add empty placeholder for host-specific powerpoint APIs (for use with our d.ts publishing toolchain) * Add extra separator * Fix erroneous typings for "charts.add" and chart.setData It erroneously said "Range | string", but it can only be a Range. --- types/office-js/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 36c659a7b2..7521381cbf 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -18430,7 +18430,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: Excel.ChartType, sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; + add(type: Excel.ChartType, sourceData: Range, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; /** * * Creates a new chart. @@ -18441,7 +18441,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; + add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; /** * * Returns the number of charts in the worksheet. @@ -18663,7 +18663,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): void; + setData(sourceData: Range, seriesBy?: Excel.ChartSeriesBy): void; /** * * Resets the source data for the chart. @@ -18673,7 +18673,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): void; + setData(sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): void; /** * * Positions the chart relative to cells on the worksheet. From 7d44adf2119f49c0536f574e2bde6cf94052bc12 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 30 Jul 2018 12:18:16 -0700 Subject: [PATCH 044/129] bull: make backoffStrategies optional (#27697) --- types/bull/bull-tests.tsx | 5 ++++- types/bull/index.d.ts | 2 +- types/bull/tsconfig.json | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index c2e0d3161f..a8c7f403a7 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -6,7 +6,10 @@ import Redis = require("ioredis"); import Queue = require("bull"); const videoQueue = new Queue('video transcoding', 'redis://127.0.0.1:6379'); -const audioQueue = new Queue('audio transcoding', {redis: {port: 6379, host: '127.0.0.1'}}); // Specify Redis connection using object +const audioQueue = new Queue('audio transcoding', { + redis: {port: 6379, host: '127.0.0.1'}, // Specify Redis connection using object + settings: {}, +}); const imageQueue: Queue.Queue<{ image: string }> = new Queue('image transcoding'); videoQueue.process((job, done) => { diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 6ed6fa88e7..a11ae0257a 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -88,7 +88,7 @@ declare namespace Bull { /** * Define a custom backoff strategy */ - backoffStrategies: { + backoffStrategies?: { [key: string]: (attemptsMade: number, err: typeof Error) => number; }; } diff --git a/types/bull/tsconfig.json b/types/bull/tsconfig.json index 3ce6f08792..7dbd4e7b61 100644 --- a/types/bull/tsconfig.json +++ b/types/bull/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ From 31c4ba6176f65cd23dfd25e94990a663687a9e17 Mon Sep 17 00:00:00 2001 From: Bond Date: Mon, 30 Jul 2018 20:36:23 +0100 Subject: [PATCH 045/129] Make custom backoff strategies optional (#27698) From 84b265e5b91ee54c23314fa7c1dc50c1a844bd3b Mon Sep 17 00:00:00 2001 From: JounQin Date: Tue, 31 Jul 2018 03:36:31 +0800 Subject: [PATCH 046/129] feat: add declarations for hoist-non-react-statics (#27673) --- .../hoist-non-react-statics-tests.ts | 31 +++++++++++++++++++ types/hoist-non-react-statics/index.d.ts | 28 +++++++++++++++++ types/hoist-non-react-statics/tsconfig.json | 23 ++++++++++++++ types/hoist-non-react-statics/tslint.json | 1 + 4 files changed, 83 insertions(+) create mode 100644 types/hoist-non-react-statics/hoist-non-react-statics-tests.ts create mode 100644 types/hoist-non-react-statics/index.d.ts create mode 100644 types/hoist-non-react-statics/tsconfig.json create mode 100644 types/hoist-non-react-statics/tslint.json diff --git a/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts b/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts new file mode 100644 index 0000000000..7065c47410 --- /dev/null +++ b/types/hoist-non-react-statics/hoist-non-react-statics-tests.ts @@ -0,0 +1,31 @@ +import * as React from 'react'; + +import hoistNonReactStatics = require('hoist-non-react-statics'); + +class A extends React.Component { + static a = 'a'; + + getA() { + return A.a; + } +} + +class B extends React.Component { + static b = 'b'; + + getB() { + return B.b; + } +} + +const C = hoistNonReactStatics(A, B); + +C.a !== C.b; + +C.prototype.getA(); // should work +// C.prototype.getB(); // should emit an error + +const D = hoistNonReactStatics(A, B, { b: true }); + +D.a; +// D.b; // should emit an error diff --git a/types/hoist-non-react-statics/index.d.ts b/types/hoist-non-react-statics/index.d.ts new file mode 100644 index 0000000000..f55fb92b6d --- /dev/null +++ b/types/hoist-non-react-statics/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for hoist-non-react-statics 3.0 +// Project: https://github.com/mridgway/hoist-non-react-statics#readme +// Definitions by: JounQin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +declare function hoistNonReactStatics< + T extends React.ComponentType, + S extends React.ComponentType, + C extends { + [key: string]: true + } = {} +>( + TargetComponent: T, + SourceComponent: S, + customStatic?: C, +): T & + { + [key in Exclude< + keyof S, + // only extends static properties, exclude instance properties + 'prototype' | keyof C + >]: S[key] + }; + +export = hoistNonReactStatics; diff --git a/types/hoist-non-react-statics/tsconfig.json b/types/hoist-non-react-statics/tsconfig.json new file mode 100644 index 0000000000..61c70382e5 --- /dev/null +++ b/types/hoist-non-react-statics/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hoist-non-react-statics-tests.ts" + ] +} diff --git a/types/hoist-non-react-statics/tslint.json b/types/hoist-non-react-statics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hoist-non-react-statics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From cca37a570aecfd6af85c4586f3c0e993a1e537dc Mon Sep 17 00:00:00 2001 From: Garrett McCullough Date: Mon, 30 Jul 2018 12:38:55 -0700 Subject: [PATCH 047/129] Add location state as an optional parameter for Location types in History and React Router (#27699) * Add optional location state parameter to Location types * Revert styling changes * Revert styling changes * Missing quote mark * Revert some other changes * update TS version on qhistory --- types/history/index.d.ts | 15 ++++++++------- types/qhistory/index.d.ts | 2 +- types/react-router/index.d.ts | 4 ++-- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/types/history/index.d.ts b/types/history/index.d.ts index eb15aaa0fc..1c7b35b8f2 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for history 4.6.2 +// Type definitions for history 4.7.2 // Project: https://github.com/mjackson/history // Definitions by: Sergey Buturlakin , Nathan Brown , Young Rok Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace History; export type Action = 'PUSH' | 'POP' | 'REPLACE'; @@ -23,24 +24,24 @@ export interface History { createHref(location: LocationDescriptorObject): Href; } -export interface Location { +export interface Location { pathname: Pathname; search: Search; - state: LocationState; + state: S; hash: Hash; key?: LocationKey; } -export interface LocationDescriptorObject { +export interface LocationDescriptorObject { pathname?: Pathname; search?: Search; - state?: LocationState; + state?: S; hash?: Hash; key?: LocationKey; } export namespace History { - export type LocationDescriptor = Path | LocationDescriptorObject; + export type LocationDescriptor = Path | LocationDescriptorObject; export type LocationKey = string; export type LocationListener = (location: Location, action: Action) => void; export type LocationState = any; @@ -53,7 +54,7 @@ export namespace History { export type Href = string; } -export type LocationDescriptor = History.LocationDescriptor; +export type LocationDescriptor = History.LocationDescriptor; export type LocationKey = History.LocationKey; export type LocationListener = History.LocationListener; export type LocationState = History.LocationState; diff --git a/types/qhistory/index.d.ts b/types/qhistory/index.d.ts index 301f6b4391..84bd4e6d83 100644 --- a/types/qhistory/index.d.ts +++ b/types/qhistory/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pshrmn/qhistory#readme // Definitions by: Diogo Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 export as namespace qhistory; diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 05d5fe30bb..6814ecf19f 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -64,9 +64,9 @@ export interface StaticContext { statusCode?: number; } -export interface RouteComponentProps { +export interface RouteComponentProps { history: H.History; - location: H.Location; + location: H.Location; match: match

; staticContext?: C; } From 5ecc5c6e55fdb345d9c94d0fc346e3db81b55cb1 Mon Sep 17 00:00:00 2001 From: dkorolev1 <40392622+dkorolev1@users.noreply.github.com> Date: Mon, 30 Jul 2018 22:49:39 +0300 Subject: [PATCH 048/129] react-adal (#27675) * Definitions for react-adal * empty line remove * ts version --- types/react-adal/index.d.ts | 411 ++++++++++++++++++++++++++ types/react-adal/react-adal-tests.tsx | 75 +++++ types/react-adal/tsconfig.json | 24 ++ types/react-adal/tslint.json | 1 + 4 files changed, 511 insertions(+) create mode 100644 types/react-adal/index.d.ts create mode 100644 types/react-adal/react-adal-tests.tsx create mode 100644 types/react-adal/tsconfig.json create mode 100644 types/react-adal/tslint.json diff --git a/types/react-adal/index.d.ts b/types/react-adal/index.d.ts new file mode 100644 index 0000000000..9f3cd9bef2 --- /dev/null +++ b/types/react-adal/index.d.ts @@ -0,0 +1,411 @@ +// Type definitions for react-adal 0.4 +// Project: https://github.com/salvoravida/react-adal#readme +// Definitions by: Dmitry Korolev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export type TokenCallback = ( + errorDesc: string | null, + token: string | null, + error: any +) => void; + +export type UserCallback = ( + errorDesc: string | null, + user: UserInfo | null +) => void; + +export interface AdalConfig { + /** + * Client ID assigned to your app by Azure Active Directory. + */ + clientId: string; + /** + * Endpoint at which you expect to receive tokens.Defaults to `window.location.href`. + */ + redirectUri?: string; + /** + * Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`. + */ + instance?: string; + /** + * Your target tenant. Defaults to `common`. + */ + tenant?: string; + /** + * Query parameters to add to the authentication request. + */ + extraQueryParameter?: string; + /** + * Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits). + */ + correlationId?: string; + /** + * User defined function of handling the navigation to Azure AD authorization endpoint in case of login. + */ + displayCall?: (url: string) => void; + /** + * Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`. + */ + popUp?: boolean; + /** + * Set this to the resource to request on login. Defaults to `clientId`. + */ + loginResource?: string; + /** + * Set this to redirect the user to a custom login page. + */ + localLoginUrl?: string; + /** + * Redirects to start page after login. Defaults to `true`. + */ + navigateToLoginRequestUrl?: boolean; + /** + * Set this to redirect the user to a custom logout page. + */ + logOutUri?: string; + /** + * Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`. + */ + postLogoutRedirectUri?: string; + /** + * Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`. + */ + cacheLocation?: "localStorage" | "sessionStorage"; + /** + * Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs. + */ + endpoints?: { [resource: string]: string }; + /** + * Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs. + */ + anonymousEndpoints?: string[]; + /** + * If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds. + */ + expireOffsetSeconds?: number; + /** + * The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds. + */ + loadFrameTimeout?: number; + /** + * Callback to be invoked when a token is acquired. + */ + callback?: TokenCallback; +} + +export type LoggingLevel = 0 | 1 | 2 | 3; + +export interface RequestInfo { + /** + * Object comprising of fields such as id_token/error, session_state, state, e.t.c. + */ + parameters: any; + /** + * Request type. + */ + requestType: RequestType; + /** + * Whether state is valid. + */ + stateMatch: boolean; + /** + * Unique guid used to match the response with the request. + */ + stateResponse: string; + /** + * Whether `requestType` contains `id_token`, `access_token` or error. + */ + valid: boolean; +} + +export type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN"; + +export type ResponseType = "id_token token" | "token"; + +export interface UserInfo { + /** + * Username assigned from UPN or email. + */ + userName: string; + /** + * Properties parsed from `id_token`. + */ + profile: any; +} + +export interface Constants { + ACCESS_TOKEN: 'access_token'; + EXPIRES_IN: 'expires_in'; + ID_TOKEN: 'id_token'; + ERROR_DESCRIPTION: 'error_description'; + SESSION_STATE: 'session_state'; + STORAGE: { + TOKEN_KEYS: 'adal.token.keys'; + ACCESS_TOKEN_KEY: 'adal.access.token.key'; + EXPIRATION_KEY: 'adal.expiration.key'; + STATE_LOGIN: 'adal.state.login'; + STATE_RENEW: 'adal.state.renew'; + NONCE_IDTOKEN: 'adal.nonce.idtoken'; + SESSION_STATE: 'adal.session.state'; + USERNAME: 'adal.username'; + IDTOKEN: 'adal.idtoken'; + ERROR: 'adal.error'; + ERROR_DESCRIPTION: 'adal.error.description'; + LOGIN_REQUEST: 'adal.login.request'; + LOGIN_ERROR: 'adal.login.error'; + RENEW_STATUS: 'adal.token.renew.status'; + }; + RESOURCE_DELIMETER: '|'; + LOADFRAME_TIMEOUT: '6000'; + TOKEN_RENEW_STATUS_CANCELED: 'Canceled'; + TOKEN_RENEW_STATUS_COMPLETED: 'Completed'; + TOKEN_RENEW_STATUS_IN_PROGRESS: 'In Progress'; + LOGGING_LEVEL: { + ERROR: 0; + WARN: 1; + INFO: 2; + VERBOSE: 3; + }; + LEVEL_STRING_MAP: { + 0: 'ERROR:'; + 1: 'WARNING:'; + 2: 'INFO:'; + 3: 'VERBOSE:'; + }; + POPUP_WIDTH: 483; + POPUP_HEIGHT: 600; +} + +export class AuthenticationContext { + instance: string; + config: AdalConfig; + callback: TokenCallback; + popUp: boolean; + isAngular: boolean; + + /** + * Enum for request type + */ + REQUEST_TYPE: RequestType; + RESPONSE_TYPE: ResponseType; + CONSTANTS: Constants; + + constructor(options: AdalConfig); + /** + * Initiates the login process by redirecting the user to Azure AD authorization endpoint. + */ + login(): void; + /** + * Returns whether a login is in progress. + */ + loginInProgress(): boolean; + /** + * Gets token for the specified resource from the cache. + * @param resource A URI that identifies the resource for which the token is requested. + */ + getCachedToken(resource: string): string; + /** + * If user object exists, returns it. Else creates a new user object by decoding `id_token` from the cache. + */ + getCachedUser(): UserInfo; + /** + * Adds the passed callback to the array of callbacks for the specified resource. + * @param resource A URI that identifies the resource for which the token is requested. + * @param expectedState A unique identifier (guid). + * @param callback The callback provided by the caller. It will be called with token or error. + */ + registerCallback( + expectedState: string, + resource: string, + callback: TokenCallback + ): void; + /** + * Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireToken(resource: string, callback: TokenCallback): void; + /** + * Acquires token (interactive flow using a popup window) by sending request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireTokenPopup( + resource: string, + extraQueryParameters: string | null | undefined, + claims: string | null | undefined, + callback: TokenCallback + ): void; + /** + * Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the authentication request constructor will be called. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + */ + acquireTokenRedirect( + resource: string, + extraQueryParameters?: string | null, + claims?: string | null + ): void; + /** + * Redirects the browser to Azure AD authorization endpoint. + * @param urlNavigate URL of the authorization endpoint. + */ + promptUser(urlNavigate: string): void; + /** + * Clears cache items. + */ + clearCache(): void; + /** + * Clears cache items for a given resource. + * @param resource Resource URI identifying the target resource. + */ + clearCacheForResource(resource: string): void; + /** + * Redirects user to logout endpoint. After logout, it will redirect to `postLogoutRedirectUri` if added as a property on the config object. + */ + logOut(): void; + /** + * Calls the passed in callback with the user object or error message related to the user. + * @param callback The callback provided by the caller. It will be called with user or error. + */ + getUser(callback: UserCallback): void; + /** + * Checks if the URL fragment contains access token, id token or error description. + * @param hash Hash passed from redirect page. + */ + isCallback(hash: string): boolean; + /** + * Gets login error. + */ + getLoginError(): string; + /** + * Creates a request info object from the URL fragment and returns it. + */ + getRequestInfo(hash: string): RequestInfo; + /** + * Saves token or error received in the response from AAD in the cache. In case of `id_token`, it also creates the user object. + */ + saveTokenFromHash(requestInfo: RequestInfo): void; + /** + * Gets resource for given endpoint if mapping is provided with config. + * @param endpoint Resource URI identifying the target resource. + */ + getResourceForEndpoint(resource: string): string; + /** + * This method must be called for processing the response received from AAD. It extracts the hash, processes the token or error, saves it in the cache and calls the callbacks with the result. + * @param hash Hash fragment of URL. Defaults to `window.location.hash`. + */ + handleWindowCallback(hash?: string): void; + + /** + * Checks the logging Level, constructs the log message and logs it. Users need to implement/override this method to turn on logging. + * @param level Level can be set 0, 1, 2 and 3 which turns on 'error', 'warning', 'info' or 'verbose' level logging respectively. + * @param message Message to log. + * @param error Error to log. + */ + log(level: LoggingLevel, message: string, error: any): void; + /** + * Logs messages when logging level is set to 0. + * @param message Message to log. + * @param error Error to log. + */ + error(message: string, error: any): void; + /** + * Logs messages when logging level is set to 1. + * @param message Message to log. + */ + warn(message: string): void; + /** + * Logs messages when logging level is set to 2. + * @param message Message to log. + */ + info(message: string): void; + /** + * Logs messages when logging level is set to 3. + * @param message Message to log. + */ + verbose(message: string): void; + + /** + * Logs Pii messages when Logging Level is set to 0 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + * @param error Error to log. + */ + errorPii(message: string, error: any): void; + + /** + * Logs Pii messages when Logging Level is set to 1 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + warnPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 2 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + infoPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 3 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + verbosePii(message: string): void; +} + +/** + * Return user token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function adalGetToken( + authContext: AuthenticationContext, + resourceUrl: string +): Promise; + +/** + * Allows to make requests with adal token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + * @param fetch Fetch client + * @param url Request url + * @param options Fetch options + */ +export function adalFetch( + authContext: AuthenticationContext, + resource: string, + fetch: (input: string, init: any) => Promise, + url: string, + options: any +): Promise; + +/** + * Wrap for the app + * @param authContext Authentication context + * @param app Render app callback + * @param doNotLogin Don`t need to login? + */ +export function runWithAdal( + authContext: AuthenticationContext, + app: () => void, + doNotLogin: boolean +): void; + +/** + * Creates a HOC that can be used to manage authentication for the certain components + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function withAdalLogin( + authContext: AuthenticationContext, + resource: string +): ( + wrappedComponent: React.ComponentClass | React.StatelessComponent, + renderLoading: () => JSX.Element | null, + renderError: (error: any) => JSX.Element | null +) => React.ComponentClass; diff --git a/types/react-adal/react-adal-tests.tsx b/types/react-adal/react-adal-tests.tsx new file mode 100644 index 0000000000..961246560f --- /dev/null +++ b/types/react-adal/react-adal-tests.tsx @@ -0,0 +1,75 @@ +import * as React from 'react'; +import { AuthenticationContext, adalFetch, adalGetToken, runWithAdal, withAdalLogin, AdalConfig } from 'react-adal'; + +const resourceUrl = 'https://graph.microsoft.net'; + +const adalConfig: AdalConfig = { + cacheLocation: "localStorage", + clientId: '9ha8cqc6-4668-459a-9272-f48c80a053y5', + endpoints: { + api: resourceUrl + }, + postLogoutRedirectUri: 'https://localhost:3000', + tenant: 'tenantname.onmicrosoft.com' + }; + +const authContext = new AuthenticationContext(adalConfig); + +const adalApiFetch = (fetch: any, url: string, options: any) => { + return adalFetch(authContext, resourceUrl, fetch, url, options); +}; + +const getToken = () => adalGetToken(authContext, resourceUrl); + +class App extends React.Component { + render() { + return null; + } +} + +// user must login to use the app +runWithAdal(authContext, () => { + // ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, false); + +const withAdalLoginApi = withAdalLogin(authContext, resourceUrl); + +const Loading: React.SFC = (props) => { + return null; +}; + +const ErrorPage: React.SFC = (props) => { + return null; +}; + +class SignInPage extends React.Component { + render() { + return null; + } +} + +class ProtectedPage1 extends React.Component { + render() { + return null; + } +} + +const ProtectedPage2: React.SFC = (props) => { + return null; +}; + +const AdalProtectedPage1 = withAdalLoginApi(ProtectedPage1, () => , () => ); +const AdalProtectedPage2 = withAdalLoginApi(ProtectedPage2, () =>

loading...

, () =>

It seems something went wrong...

); + +// user must login to use only specific pages +runWithAdal(authContext, () => { + const routes =
+ // $ExpectError + // $ExpectError + // $ExpectError +
; + // $ExpectError + const App = ; + // $ExpectError + ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, true); diff --git a/types/react-adal/tsconfig.json b/types/react-adal/tsconfig.json new file mode 100644 index 0000000000..b77e4dffc1 --- /dev/null +++ b/types/react-adal/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-adal-tests.tsx" + ] +} diff --git a/types/react-adal/tslint.json b/types/react-adal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-adal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9dd304c111ab32256ad44f8d7ac0a0ddb0c245e5 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Mon, 30 Jul 2018 21:53:09 +0200 Subject: [PATCH 049/129] Add types for detect-node (#27684) --- types/detect-node/detect-node-tests.ts | 3 +++ types/detect-node/index.d.ts | 8 ++++++++ types/detect-node/tsconfig.json | 16 ++++++++++++++++ types/detect-node/tslint.json | 1 + 4 files changed, 28 insertions(+) create mode 100644 types/detect-node/detect-node-tests.ts create mode 100644 types/detect-node/index.d.ts create mode 100644 types/detect-node/tsconfig.json create mode 100644 types/detect-node/tslint.json diff --git a/types/detect-node/detect-node-tests.ts b/types/detect-node/detect-node-tests.ts new file mode 100644 index 0000000000..01a81a356b --- /dev/null +++ b/types/detect-node/detect-node-tests.ts @@ -0,0 +1,3 @@ +import isNode = require("detect-node"); + +isNode; diff --git a/types/detect-node/index.d.ts b/types/detect-node/index.d.ts new file mode 100644 index 0000000000..38fd280f1e --- /dev/null +++ b/types/detect-node/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for detect-node 2.0 +// Project: https://github.com/iliakan/detect-node +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare const isNode: boolean; +export = isNode; diff --git a/types/detect-node/tsconfig.json b/types/detect-node/tsconfig.json new file mode 100644 index 0000000000..e853bcf92c --- /dev/null +++ b/types/detect-node/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "detect-node-tests.ts"] +} diff --git a/types/detect-node/tslint.json b/types/detect-node/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-node/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f20b7f5323c7193e5a391eab22890a85cf5483e3 Mon Sep 17 00:00:00 2001 From: Art Date: Mon, 30 Jul 2018 21:05:46 +0100 Subject: [PATCH 050/129] Add: req-cwd types (#27674) * add req-cwd types * Set typescript version to 2.3 * Fix lint issues --- types/req-cwd/index.d.ts | 15 +++++++++++++++ types/req-cwd/req-cwd-tests.ts | 9 +++++++++ types/req-cwd/tsconfig.json | 23 +++++++++++++++++++++++ types/req-cwd/tslint.json | 1 + 4 files changed, 48 insertions(+) create mode 100644 types/req-cwd/index.d.ts create mode 100644 types/req-cwd/req-cwd-tests.ts create mode 100644 types/req-cwd/tsconfig.json create mode 100644 types/req-cwd/tslint.json diff --git a/types/req-cwd/index.d.ts b/types/req-cwd/index.d.ts new file mode 100644 index 0000000000..56ca4f0786 --- /dev/null +++ b/types/req-cwd/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for req-cwd 2.0 +// Project: https://github.com/sindresorhus/req-cwd +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/** Like require(), throws when the module can't be found. */ +declare function reqCwd(moduleId: string): any; + +declare namespace reqCwd { + /** Returns null instead of throwing when the module can't be found. */ + function silent(moduleId: string): any; +} + +export = reqCwd; diff --git a/types/req-cwd/req-cwd-tests.ts b/types/req-cwd/req-cwd-tests.ts new file mode 100644 index 0000000000..df95f8161f --- /dev/null +++ b/types/req-cwd/req-cwd-tests.ts @@ -0,0 +1,9 @@ +import * as reqCwd from 'req-cwd'; + +const r1: string = reqCwd('./foo'); +const r2: number = reqCwd('./foo'); +const r3: {foo: string} = reqCwd('./foo'); + +const s1: string | null = reqCwd.silent('./foo'); +const s2: number | null = reqCwd.silent('./foo'); +const s3: {foo: string} | null = reqCwd.silent('./foo'); diff --git a/types/req-cwd/tsconfig.json b/types/req-cwd/tsconfig.json new file mode 100644 index 0000000000..648ca4cf75 --- /dev/null +++ b/types/req-cwd/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "req-cwd-tests.ts" + ] +} diff --git a/types/req-cwd/tslint.json b/types/req-cwd/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/req-cwd/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bb6b63a59b2741f1a05b206aa974125272dbdcd1 Mon Sep 17 00:00:00 2001 From: Romain Faust <11320210+romain-faust@users.noreply.github.com> Date: Mon, 30 Jul 2018 22:08:58 +0200 Subject: [PATCH 051/129] [@types/koa-html-minifier] Add type definitions (#27691) * Add koa-router's Router to koa's Context * [@types/koa-html-minifier] Add type definitions * Fix incorrect TypeScript version --- types/koa-html-minifier/index.d.ts | 14 +++++++++++ .../koa-html-minifier-tests.ts | 8 +++++++ types/koa-html-minifier/tsconfig.json | 23 +++++++++++++++++++ types/koa-html-minifier/tslint.json | 1 + 4 files changed, 46 insertions(+) create mode 100644 types/koa-html-minifier/index.d.ts create mode 100644 types/koa-html-minifier/koa-html-minifier-tests.ts create mode 100644 types/koa-html-minifier/tsconfig.json create mode 100644 types/koa-html-minifier/tslint.json diff --git a/types/koa-html-minifier/index.d.ts b/types/koa-html-minifier/index.d.ts new file mode 100644 index 0000000000..5343257116 --- /dev/null +++ b/types/koa-html-minifier/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for koa-html-minifier 1.0 +// Project: https://github.com/koajs/html-minifier +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Middleware } from 'koa'; +import { Options } from 'html-minifier'; + +declare function minifier(options?: Options): Middleware; + +declare namespace minifier {} + +export = minifier; diff --git a/types/koa-html-minifier/koa-html-minifier-tests.ts b/types/koa-html-minifier/koa-html-minifier-tests.ts new file mode 100644 index 0000000000..c068d303af --- /dev/null +++ b/types/koa-html-minifier/koa-html-minifier-tests.ts @@ -0,0 +1,8 @@ +import * as Koa from 'koa'; +import * as KoaHtmlMinifier from 'koa-html-minifier'; + +const app = new Koa() + .use(KoaHtmlMinifier()) + .use(KoaHtmlMinifier({ + collapseWhitespace: true + })); diff --git a/types/koa-html-minifier/tsconfig.json b/types/koa-html-minifier/tsconfig.json new file mode 100644 index 0000000000..9a46770f6f --- /dev/null +++ b/types/koa-html-minifier/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-html-minifier-tests.ts" + ] +} diff --git a/types/koa-html-minifier/tslint.json b/types/koa-html-minifier/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-html-minifier/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From b80b4b5e943c2189a13b9dcd4810192e67bd97ea Mon Sep 17 00:00:00 2001 From: Mike North Date: Mon, 30 Jul 2018 14:29:18 -0700 Subject: [PATCH 052/129] [@types/qunit] extract callback argument types to interfaces (#27616) * fix: extract QUnit callback argument types to interfaces * move event callback interfaces into QUnit namespace * Combine function argument type assertions into function declarations --- types/qunit/index.d.ts | 59 ++++++++++++++++++++++++-------------- types/qunit/qunit-tests.ts | 26 +++++++++++++++-- 2 files changed, 61 insertions(+), 24 deletions(-) diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index 973a3b00a0..c5e677d187 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -340,6 +340,38 @@ interface NestedHooks { } +declare namespace QUnit { + interface BeginDetails { totalTests: number } + interface DoneDetails { failed: number, passed: number, total: number, runtime: number } + interface LogDetails { + result: boolean, + actual: any; + expected: any; + message: string; + source: string; + module: string; + name: string; + runtime: number; + } + interface ModuleDoneDetails { + name: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface ModuleStartDetails { name: string } + interface TestDoneDetails { + name: string; + module: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface TestStartDetails { name: string; module: string; } +} + interface QUnit { /** @@ -360,7 +392,7 @@ interface QUnit { * * @callback callback Callback to execute. */ - begin(callback: (details: { totalTests: number }) => void): void; + begin(callback: (details: QUnit.BeginDetails) => void): void; /** * Configuration for QUnit @@ -375,7 +407,7 @@ interface QUnit { * * @param callback Callback to execute */ - done(callback: (details: { failed: number, passed: number, total: number, runtime: number }) => void): void; + done(callback: (details: QUnit.DoneDetails) => void): void; /** * Advanced and extensible data dumping for JavaScript. @@ -419,16 +451,7 @@ interface QUnit { * * @param callback Callback to execute */ - log(callback: (details: { - result: boolean, - actual: any; - expected: any; - message: string; - source: string; - module: string; - name: string; - runtime: number; - }) => void): void; + log(callback: (details: QUnit.LogDetails) => void): void; /** * Group related tests under a single label. @@ -476,20 +499,14 @@ interface QUnit { * * @param callback Callback to execute */ - moduleDone(callback: (details: { - name: string; - failed: number; - passed: number; - total: number; - runtime: number; - }) => void): void; + moduleDone(callback: (details: QUnit.ModuleDoneDetails) => void): void; /** * Register a callback to fire whenever a module begins. * * @param callback Callback to execute */ - moduleStart(callback: (details: { name: string }) => void): void; + moduleStart(callback: (details: QUnit.ModuleStartDetails) => void): void; /** * Adds a test to exclusively run, preventing all other tests from running. @@ -605,7 +622,7 @@ interface QUnit { * * @param callback Callback to execute */ - testStart(callback: (details: { name: string; module: string;}) => void): void; + testStart(callback: (details: QUnit.TestStartDetails) => void): void; /** * Adds a test which expects at least one failing assertion during its run. diff --git a/types/qunit/qunit-tests.ts b/types/qunit/qunit-tests.ts index d475805cb0..ae519cd0bc 100644 --- a/types/qunit/qunit-tests.ts +++ b/types/qunit/qunit-tests.ts @@ -214,13 +214,33 @@ QUnit.log(function( details ) { console.log( output ); }); -QUnit.moduleDone(function( details ) { - console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total ); +QUnit.log(function( details: QUnit.LogDetails ) { + let x: { actual: number; expected: number; message: string; module: string; name: string; result: boolean; runtime: number; source: string } = details; + x = details; }); -QUnit.moduleStart(function( details ) { +QUnit.begin(function( details: QUnit.BeginDetails ) { + console.log( "Total tests running: ", details.totalTests); +}); + +QUnit.done(function( details: QUnit.DoneDetails ) { + console.log( "Finished. Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleDone(function( details: QUnit.ModuleDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleStart(function( details: QUnit.ModuleStartDetails ) { console.log( "Now running: ", details.name ); }); +QUnit.testDone(function( details: QUnit.TestDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime); +}); + +QUnit.testStart(function( details: QUnit.TestStartDetails ) { + console.log( "Now running: ", details.name, ' from module ', details.module ); +}); let Robot: any = () => {}; From d621d5c0fcb8af0040b83bdb29979f55ec4f5063 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Mon, 30 Jul 2018 23:33:35 +0200 Subject: [PATCH 053/129] Add types for web3-provider-engine (#27707) --- types/web3-provider-engine/index.d.ts | 38 +++++++++++++++++++ types/web3-provider-engine/tsconfig.json | 16 ++++++++ types/web3-provider-engine/tslint.json | 1 + .../web3-provider-engine-tests.ts | 3 ++ 4 files changed, 58 insertions(+) create mode 100644 types/web3-provider-engine/index.d.ts create mode 100644 types/web3-provider-engine/tsconfig.json create mode 100644 types/web3-provider-engine/tslint.json create mode 100644 types/web3-provider-engine/web3-provider-engine-tests.ts diff --git a/types/web3-provider-engine/index.d.ts b/types/web3-provider-engine/index.d.ts new file mode 100644 index 0000000000..d5ba233b18 --- /dev/null +++ b/types/web3-provider-engine/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for web3-provider-engine 14.0 +// Project: https://github.com/MetaMask/provider-engine#readme +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { + Provider, + JSONRPCRequestPayload, + JSONRPCResponsePayload +} from "ethereum-protocol"; +interface Web3ProviderEngineOptions { + pollingInterval?: number; + blockTracker?: any; + blockTrackerProvider?: any; +} +declare class Web3ProviderEngine implements Provider { + constructor(options?: Web3ProviderEngineOptions); + on(event: string, handler: () => void): void; + send(payload: JSONRPCRequestPayload): void; + sendAsync( + payload: JSONRPCRequestPayload, + callback: ( + error: null | Error, + response: JSONRPCResponsePayload + ) => void + ): void; + addProvider(provider: any): void; + // start block polling + start(callback?: () => void): void; + // stop block polling + stop(): void; +} +export = Web3ProviderEngine; + +// declare module "web3-provider-engine/subproviders/nonce-tracker"; +// declare module "web3-provider-engine/subproviders/hooked-wallet"; +// declare module "web3-provider-engine/subproviders/filters"; diff --git a/types/web3-provider-engine/tsconfig.json b/types/web3-provider-engine/tsconfig.json new file mode 100644 index 0000000000..2caa7bbf7b --- /dev/null +++ b/types/web3-provider-engine/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "web3-provider-engine-tests.ts"] +} diff --git a/types/web3-provider-engine/tslint.json b/types/web3-provider-engine/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/web3-provider-engine/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/web3-provider-engine/web3-provider-engine-tests.ts b/types/web3-provider-engine/web3-provider-engine-tests.ts new file mode 100644 index 0000000000..d783728a1b --- /dev/null +++ b/types/web3-provider-engine/web3-provider-engine-tests.ts @@ -0,0 +1,3 @@ +import ProviderEngine = require("web3-provider-engine"); + +new ProviderEngine(); From 593d4f04314a5f41a03b7722c53a9d168be1876b Mon Sep 17 00:00:00 2001 From: Jack Sorrell Date: Mon, 30 Jul 2018 18:55:48 -0400 Subject: [PATCH 054/129] Add typings for thepiratebay (#27709) --- types/thepiratebay/index.d.ts | 69 +++++++++++++++ types/thepiratebay/thepiratebay-tests.ts | 104 +++++++++++++++++++++++ types/thepiratebay/tsconfig.json | 23 +++++ types/thepiratebay/tslint.json | 1 + 4 files changed, 197 insertions(+) create mode 100644 types/thepiratebay/index.d.ts create mode 100644 types/thepiratebay/thepiratebay-tests.ts create mode 100644 types/thepiratebay/tsconfig.json create mode 100644 types/thepiratebay/tslint.json diff --git a/types/thepiratebay/index.d.ts b/types/thepiratebay/index.d.ts new file mode 100644 index 0000000000..20a1cc8945 --- /dev/null +++ b/types/thepiratebay/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for thepiratebay 1.4 +// Project: http://github.com/t3chnoboy/thepiratebay +// Definitions by: Jack Sorrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function search(query?: string, options?: SearchOptions): Promise; +export function getTorrent(id: string | number | { link: string; [propName: string]: any; }): Promise; +export function getComments(id: string | number): Promise; +export function topTorrents(category?: number): Promise; +export function recentTorrents(): Promise; +export function userTorrents(user: string, options?: SearchOptions): Promise; +export function getTvShow(id: string | number): Promise; +export function getCategories(): Promise; + +export interface SearchOptions { + category?: string | number; + filter?: { verified?: boolean }; + page?: number; + orderBy?: string; + sortBy?: string; +} + +export interface Category { + id: string; + name: string; +} + +export interface CategoryGroup extends Category { + subcategories: Category[]; +} + +export interface Torrent { + id: string; + name: string; + size: string; + link: string; + seeders: string; + leechers: string; + uploadDate: string; + magnetLink: string; + uploader: string; + uploaderLink: string; +} + +export interface TorrentDetails extends Torrent { + description: string; +} + +export interface TorrentSearchResult extends Torrent { + category: Category; + subcategory: Category; + verified: boolean; +} + +export interface Comment { + user: string; + comment: string; +} + +export interface TVTorrent { + id: string; + title: string; + link: string; +} + +export interface TVSeason { + title: string; + torrents: TVTorrent[]; +} diff --git a/types/thepiratebay/thepiratebay-tests.ts b/types/thepiratebay/thepiratebay-tests.ts new file mode 100644 index 0000000000..76c56eb269 --- /dev/null +++ b/types/thepiratebay/thepiratebay-tests.ts @@ -0,0 +1,104 @@ +import * as PirateBay from 'thepiratebay'; + +// $ExpectType Promise +const searchResultPromise = PirateBay.search('Game of Thrones', { + category: 'all', + filter: { + verified: false + }, + page: 0, + orderBy: 'leeches', + sortBy: 'desc' +}); +searchResultPromise.then((res: PirateBay.TorrentSearchResult[]) => { + res[0].id; // $ExpectType string + res[0].name; // $ExpectType string + res[0].size; // $ExpectType string + res[0].link; // $ExpectType string + res[0].seeders; // $ExpectType string + res[0].leechers; // $ExpectType string + res[0].uploadDate; // $ExpectType string + res[0].magnetLink; // $ExpectType string + res[0].uploader; // $ExpectType string + res[0].uploaderLink; // $ExpectType string + + const category = res[0].category; // $ExpectType Category + category.id; // $ExpectType string + category.name; // $ExpectType string + + res[0].subcategory; // $ExpectType Category + res[0].verified; // $ExpectType boolean +}); +// $ExpectError +PirateBay.search(15); + +// $ExpectType Promise +const torrentPromise = PirateBay.getTorrent('15496322'); +torrentPromise.then((torrent: PirateBay.TorrentDetails) => { + torrent.id; // $ExpectType string + torrent.name; // $ExpectType string + torrent.size; // $ExpectType string + torrent.link; // $ExpectType string + torrent.seeders; // $ExpectType string + torrent.leechers; // $ExpectType string + torrent.uploadDate; // $ExpectType string + torrent.magnetLink; // $ExpectType string + torrent.uploader; // $ExpectType string + torrent.uploaderLink; // $ExpectType string + torrent.description; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTorrent(15496322); +// $ExpectError +PirateBay.getTorrent(false); +// $ExpectType Promise +PirateBay.getTorrent('https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit'); +// $ExpectType Promise +PirateBay.getTorrent({ name: "ubuntu", link: 'https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit' }); + +// $ExpectType Promise +PirateBay.topTorrents(); +// $ExpectError +PirateBay.topTorrents(true); +// $ExpectType Promise +PirateBay.topTorrents(400); + +// $ExpectType Promise +PirateBay.recentTorrents(); +// $ExpectError +PirateBay.recentTorrents(10); + +// $ExpectError +PirateBay.userTorrents(); +// $ExpectType Promise +PirateBay.userTorrents('alice', { + page: 3, + orderBy: 'name', + sortBy: 'asc' +}); +// $ExpectType Promise +PirateBay.userTorrents('bob'); + +// $ExpectType Promise +const categoryGroup = PirateBay.getCategories(); +categoryGroup.then((groups: PirateBay.CategoryGroup[]) => { + groups[0].id; // $ExpectType string + groups[0].name; // $ExpectType string + groups[0].subcategories; // $ExpectType Category[] +}); +// $ExpectError +PirateBay.getCategories(154); + +// $ExpectError +PirateBay.getTvShow(); +// $ExpectType Promise +const tvShow = PirateBay.getTvShow(15); +tvShow.then((seasons: PirateBay.TVSeason[]) => { + seasons[0].title; // $ExpectType string + const torrents = seasons[0].torrents; // $ExpectType TVTorrent[] + torrents[0].id; // $ExpectType string + torrents[0].title; // $ExpectType string + torrents[0].link; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTvShow('15'); diff --git a/types/thepiratebay/tsconfig.json b/types/thepiratebay/tsconfig.json new file mode 100644 index 0000000000..1d491e4d75 --- /dev/null +++ b/types/thepiratebay/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "thepiratebay-tests.ts" + ] +} diff --git a/types/thepiratebay/tslint.json b/types/thepiratebay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/thepiratebay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From eba49a93214286fdb652ccebf017b1e3753a6893 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Mon, 30 Jul 2018 15:56:47 -0700 Subject: [PATCH 055/129] office-js: tweak info about getEntities and getEntitiesByType (#27710) --- types/office-js/index.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 7521381cbf..d883822f37 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -8708,7 +8708,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8722,7 +8722,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8731,7 +8731,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * @@ -9989,7 +9989,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -10003,7 +10003,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -10012,7 +10012,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
@@ -11523,7 +11523,7 @@ declare namespace Office { */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11537,7 +11537,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11546,7 +11546,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * From f11a3342486e62b9f62a0fe54263a744bb5a34a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Freitas?= Date: Tue, 31 Jul 2018 00:02:02 +0100 Subject: [PATCH 056/129] video.js - complete definitions for video.js api (#27515) * Update index.d.ts Added definitions for almost every class * Update tslint.json Added rules to have module declaration support * Update index.d.ts Removed empty jsdoc comments * Update video.js-tests.ts Removed non existing size method call * Update tslint.json Disable no-redundant-jsdoc and void-return rules * Update index.d.ts Moved components option types one level up from the component specific namespace * Update video.js-tests.ts Removed default import signature * Update index.d.ts Fixed videojs.dom.getPointerPosition function return type from Coordinates to Dom.Coordinates * Update index.d.ts Removed redundant declare module change default export to = * Update tslint.json removed no-single-declare-module and no-declare-current-package disabling rules * Update tslint.json ups... * Update tslint.json ups again... * Update index.d.ts Changed Tech.SourceObject type option to be optional * Update tslint.json disabled 'no-redundant-jsdoc-2' rule * Update index.d.ts Removed types from @param and @return JSDoc tags set it compliant with no-redudant-jsdoc-2 * Update tslint.json Enabled no-redundant-jsdoc-2 rule --- types/video.js/index.d.ts | 6872 ++++++++++++++++++++++++++++-- types/video.js/video.js-tests.ts | 4 +- 2 files changed, 6609 insertions(+), 267 deletions(-) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index f18ff8890e..6e5863500d 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Video.js 6.2 +// Type definitions for Video.js 7.0 // Project: https://github.com/videojs/video.js // Definitions by: Vincent Bortone // Simon Clériot @@ -15,285 +15,6629 @@ // Javascript, whether the browser is playing the video through HTML5 // video, Flash, or any other supported playback technologies. -declare function videojs( - id: any, - options?: videojs.PlayerOptions, - ready?: () => void -): videojs.Player; -export default videojs; +/** + * Doubles as the main function for users to create a inplayer instance and also + * the main library object. + * The `videojs` function can be used to initialize or retrieve a player. + * + * @param id + * Video element or video element ID + * + * @param [options] + * Optional options object for config/settings + * + * @param [ready] + * Optional ready callback + * + * @return A player instance + */ +declare function videojs(id: any, options?: videojs.PlayerOptions, ready?: () => void): videojs.Player; +export = videojs; export as namespace videojs; declare namespace videojs { - const getComponent: typeof Component.getComponent; - const registerComponent: typeof Component.registerComponent; - const getPlugin: typeof Plugin.getPlugin; - function registerPlugin( - pluginName: string, - pluginFn: (this: Player, ...parameters: any[]) => void - ): void; - function addLanguage(lang: string, data: { [key: string]: string }): void; - function mergeOptions( - option: A, - option2?: B, - option3?: C, - option4?: D, - option5?: E, - option6?: F - ): A & B & C & D & E & F; + /** + * Adding languages so that they're available to all players. + * Example: `addLanguage('es', { 'Hello': 'Hola' });` + * + * @param code + * The language code or dictionary property + * + * @param data + * The data values to be translated + * + * @return The resulting language dictionary object + */ + function addLanguage(code: string, data: LanguageTranslations): LanguageTranslations; - interface PlayerOptions { - aspectRatio?: string; - autoplay?: boolean; - autoSetup?: boolean; - children?: string[]; - controlBar?: { - volumePanel?: { - inline?: boolean; - vertical?: boolean; - }; - }; - controls?: boolean; - defaultVolume?: number; - fluid?: boolean; - height?: number; - html5?: any; - inactivityTimeout?: number; - language?: string; - languages?: { [key: string]: string }; - loop?: boolean; - muted?: boolean; - nativeControlsForTouch?: boolean; - notSupportedMessage?: string; - playbackRates?: number[]; - plugins?: any; - poster?: string; - preload?: string; - sourceOrder?: boolean; - sources?: Source[]; - src?: string; - techCanOverridePoster?: boolean; - techOrder?: string[]; - width?: number; - } + /** + * Bind (a.k.a proxy or Context). A simple method for changing the context of a function + * It also stores a unique id on the function so it can be easily removed from events. + * + * @param context + * The object to bind as scope. + * + * @param fn + * The function to be bound to a scope. + * + * @param [uid] + * An optional unique ID for the function to be set + * + * @return The new function that will be bound into the context given + */ + function bind any)>(context: any, fn: F, uid?: number): F; - interface Source { - type: string; - src: string; - } + /** + * Should create a fake `TimeRange` object which mimics an HTML5 time range instance. + * + * @param start + * The start of a single range or an array of ranges + * + * @param end + * The end of a single range. + */ + function createTimeRanges(start?: number | TimeRange[], end?: number): TimeRange; - interface Dimensions { - width: number; - height: number; - } + /** + * A suite of browser and device tests from {@link browser}. + * + */ + const browser: Browser; - class EventTarget { - addEventListener( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - dispatchEvent(event: string | Event | { [key: string]: any }): void; - off( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - on( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - one( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - removeEventListener( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - trigger(event: string | Event | { [key: string]: any }): void; - } + const dom: Dom; - class Component extends EventTarget { - constructor(player: Player, options: any); + /** + * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds) + * will force a number of leading zeros to cover the length of the guide. + * + * @param seconds + * Number of seconds to be turned into a string + * + * @param guide + * Number (in seconds) to model the string after + * + * @return Time formatted as H:MM:SS or M:SS + */ + function formatTime(seconds: number, guide: number): string; - static getComponent(name: "Player" | "player"): typeof Player; - static getComponent(name: "Button" | "button"): typeof Button; - static getComponent( - name: "ClickableComponent" | "clickablecomponent" - ): typeof ClickableComponent; - static getComponent( - name: "ModalDialog" | "modaldialog" - ): typeof ModalDialog; - static getComponent( - name: "ControlBar" | "controlbar" - ): typeof ControlBar; - static getComponent( - name: "Component" | "component" | string - ): typeof Component; - static registerComponent( - name: string, - ComponentToRegister: typeof Component - ): typeof Component; + /** + * Returns an array of all current players. + * + * @return An array of all players. The array will be in the order that + * `Object.keys` provides, which could potentially vary between + * JavaScript engines. + * + */ + function getAllPlayers(): Player[]; - $(selector: string, context?: string | Element): Element; - $$(selector: string, context?: string | Element): NodeList; - addChild( - component: string, - optionsopt?: any, - indexopt?: number - ): Component; - addChild( - component: Element, - optionsopt?: any, - indexopt?: number - ): Element; - addChild( - component: T, - optionsopt?: any, - indexopt?: number - ): T; - addClass(classToAdd: string): void; - blur(): void; - buildCSSClass(): string; - cancelAnimationFrame(id: number): number; - children(): Component[]; - controlText(key: string): string; - clearInterval(intervalId: number): number; - clearTimeout(timeoutId: number): number; - contentEl(): Element; - createEl( - tagNameopt?: string, - properties?: any, - attributes?: any - ): Element; - currentDimension(widthOrHeight: "width" | "height"): number; - currentDimensions(): Dimensions; - currentHeight(): number; - currentWidth(): number; - dimension(widthOrHeight: "width" | "height"): number; - dimension( - widthOrHeight: "width" | "height", - num: string | number, - skipListenersopt?: boolean - ): void; - dimensions(width: string | number, height: string | number): void; - dispose(): void; - el(): Element; - enableTouchActivity(): void; - focus(): void; - getAttribute(attribute: string): string | null; - getChild(name: string): Component | undefined; - getChildById(id: string): Component | undefined; - hasClass(classToCheck: string): boolean; - height(): number | string; - height(num: number | string, skipListeners?: boolean): void; - hide(): void; - id(): string; - initChildren(): void; - localize(key: string, tokens?: string[], defaultValue?: string): string; - name(): string; - options(obj: any): any; - played(): TimeRanges; - player(): Player; - ready(callback: (this: this) => void): this; - removeAttribute(attribute: string): void; - removeChild(component: Component): void; - removeClass(classToRemove: string): void; - requestAnimationFrame(fn: () => void): number; - setAttribute(attribute: string, value: string): void; - setInterval(fn: () => void, interval: number): number; - setTimeout(fn: () => void, timeout: number): number; - show(): void; - toggleClass( - classToToggle: string, - predicate?: - | boolean - | ((element: Element, classToToggle: string) => boolean) - ): void; - trigger(eventName: string, ...parameters: any[]): void; - triggerReady(): void; - width(): string | number; - width(num: number, skipListeners?: number): void; - } + /** + * Get a component class object by name + * + * @borrows Component.getComponent as getComponent + */ + const getComponent: typeof Component.getComponent; - class ControlBar extends Component {} + /** + * Get a single player based on an ID or DOM element. + * + * This is useful if you want to check if an element or ID has an associated + * Video.js player, but not create one if it doesn't. + * + * @param id + * An HTML element - `
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
* * Returned by the status property of the AsyncResult object. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ enum AsyncResultStatus { /** @@ -297,7 +313,20 @@ declare namespace Office { * Specifies whether the add-in was just inserted or was already contained in the document. * * @remarks - *
HostsExcel, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum InitializationReason { /** @@ -313,7 +342,23 @@ declare namespace Office { * Specifies the host Office application in which the add-in is running. * * @remarks - *
HostsExcel, Word, PowerPoint, Outlook, OneNote, Project, Access
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum HostType { /** @@ -349,7 +394,23 @@ declare namespace Office { * Specifies the OS or other platform on which the Office host application is running. * * @remarks - *
HostsExcel, Word, PowerPoint, Outlook, OneNote, Project, Access
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum PlatformType { /** @@ -1157,7 +1218,18 @@ declare namespace Office { /** * Specifies the state of the active view of the document, for example, whether the user can edit the document. * @remarks - *
HostsPowerPoint
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
*/ enum ActiveView { /** @@ -1172,7 +1244,20 @@ declare namespace Office { /** * Specifies the type of the binding object that should be returned. * @remarks - *
HostsAccess, Excel, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ enum BindingType { /** @@ -1192,9 +1277,24 @@ declare namespace Office { * Specifies how to coerce data returned or set by the invoked method. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
- * * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. Project supports only `Office.CoercionType.Text`. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum CoercionType { /** @@ -1242,9 +1342,23 @@ declare namespace Office { * Specifies whether the document in the associated application is read-only or read-write. * * @remarks - *
HostsExcel, PowerPoint, Project, Word
- * + * * Returned by the mode property of the Document object. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ enum DocumentMode { /** @@ -1260,9 +1374,19 @@ declare namespace Office { * Specifies the type of the XML node. * * @remarks - * + *
HostsWord
Requirement SetsCustomXmlParts
* - * Requirement SetsCustomXmlParts + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
*/ enum CustomXMLNodeType { /** @@ -1296,13 +1420,27 @@ declare namespace Office { } /** * Specifies the kind of event that was raised. Returned by the `type` property of an *EventArgs object. - * - * @remarks - * - *
HostsAccess, Excel, PowerPoint, Project, Word
Hosts (BindingDataChanged and BindingSelectionChanged)Access, Excel, Word
- * * * Add-ins for Project support the `Office.EventType.ResourceSelectionChanged`, `Office.EventType.TaskSelectionChanged`, and `Office.EventType.ViewSelectionChanged` event types. + * + * BindingDataChanged and BindingSelectionChanged hosts
Access, Excel, Word
+ * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y
Project Y
Word Y Y
*/ enum EventType { /** @@ -1374,7 +1512,21 @@ declare namespace Office { * Specifies the format in which to return the document. * * @remarks - *
HostsPowerPoint, Word
+ * FileType.Text is only supported in Word, FileType.Pdf is only supported in Word for Windows, Word for Mac, Word Online, and PowerPoint. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
*/ enum FileType { /** @@ -1382,7 +1534,7 @@ declare namespace Office { */ Text, /** - * Returns the entire document (.pptx, .docx, or .xslx) in Office Open XML (OOXML) format as a byte array. + * Returns the entire document (.pptx, .docx, or .xlsx) in Office Open XML (OOXML) format as a byte array. */ Compressed, /** @@ -1394,7 +1546,20 @@ declare namespace Office { * Specifies whether filtering from the host application is applied when the data is retrieved. * * @remarks - *
HostsExcel, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum FilterType { /** @@ -1410,7 +1575,20 @@ declare namespace Office { * Specifies the type of place or object to navigate to. * * @remarks - *
HostsExcel, PowerPoint, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
*/ enum GoToType { /** @@ -1435,7 +1613,20 @@ declare namespace Office { * Specifies whether to select (highlight) the location to navigate to (when using the Document.goToByIdAsync method). * * @remarks - *
HostsExcel, PowerPoint, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad /th>
Excel Y Y Y
PowerPoint Y
Word Y Y
*/ enum SelectionMode { Default, @@ -1452,10 +1643,22 @@ declare namespace Office { * Specifies whether values, such as numbers and dates, returned by the invoked method are returned with their formatting applied. * * @remarks - *
HostsExcel, Project, Word
- * * For example, if the valueFormat parameter is specified as "formatted", a number formatted as currency, or a date formatted as mm/dd/yy in the host application will have its formatting preserved. * If the valueFormat parameter is specified as "unformatted", a date will be returned in its underlying sequential serial number form. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum ValueFormat { /** @@ -3419,7 +3622,18 @@ declare namespace Office { * Specifies enumerated values for the cells: property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. * * @remarks - *
HostsExcel
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
*/ enum Table { /** @@ -3450,9 +3664,20 @@ declare namespace Office { * Specifies the project fields that are available as a parameter for the getProjectFieldAsync method. * * @remarks - *
HostsProject
* * A ProjectProjectFields constant can be used as a parameter of the getProjectFieldAsync method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectProjectFields { /** @@ -3512,6 +3737,18 @@ declare namespace Office { * A ProjectResourceFields constant can be used as a parameter of the getResourceFieldAsync method. * * For more information about working with fields in Project, see {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectResourceFields { /** @@ -4322,8 +4559,18 @@ declare namespace Office { * A ProjectTaskFields constant can be used as a parameter of the getTaskFieldAsync method. * * For more information about working with fields in Project, see the {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. - * - *
HostsProject
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectTaskFields { /** @@ -5457,9 +5704,19 @@ declare namespace Office { * Specifies the types of views that the getSelectedViewAsync method can recognize. * * @remarks - *
HostsProject
- * * The getSelectedViewAsync method returns the ProjectViewTypes constant value and name that corresponds to the active view. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectViewTypes { /** From 3a9ec5cad2985894be9b275841c82d54bb3ce643 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel Date: Thu, 2 Aug 2018 16:40:51 -0700 Subject: [PATCH 128/129] office-js: initial set of SharedAPI scrub (#27826) * merge from master * office-js-first-set --- types/office-js/index.d.ts | 135 ++++++++++++++++++++++++++----------- 1 file changed, 95 insertions(+), 40 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 09cb848330..a731343bc6 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -280,7 +280,7 @@ declare namespace Office { * * @remarks * - * Returned by the status property of the AsyncResult object. + * Returned by the {@link Office.AsyncResult.status | status} property of the {@link Office.AsyncResult | AsyncResult} object. * * **Support details** * @@ -354,6 +354,7 @@ declare namespace Office { * Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac * Access Y * Excel Y Y Y + * OneNote Y Y * Outlook Y Y Y Y * PowerPoint Y Y Y * Project Y @@ -406,6 +407,7 @@ declare namespace Office { * Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac * Access Y * Excel Y Y Y + * OneNote Y Y * Outlook Y Y Y Y * PowerPoint Y Y Y * Project Y @@ -449,7 +451,7 @@ declare namespace Office { */ interface AsyncResult { /** - * Gets the user-defined item passed to the optional `asyncContext` parameter of the invoked method in the same state as it was passed in. This the user-defined item (which can be of any JavaScript type: String, Number, Boolean, Object, Array, Null, or Undefined) passed to the optional `asyncContext` parameter of the invoked method. Returns Undefined, if you didn't pass anything to the asyncContext parameter. + * Gets the user-defined item passed to the optional `asyncContext` parameter of the invoked method in the same state as it was passed in. This returns the user-defined item (which can be of any JavaScript type: String, Number, Boolean, Object, Array, Null, or Undefined) passed to the optional `asyncContext` parameter of the invoked method. Returns Undefined, if you didn't pass anything to the asyncContext parameter. * * @remarks *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
@@ -475,9 +477,9 @@ declare namespace Office { * @remarks *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
* - * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the `getSelectedDataAsync` and `setSelectedDataAsync` methods of the Document object. + * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the {@link Office.Document.getSelectedDataAsync | getSelectedDataAsync} and {@link Office.Document.setSelectedDataAsync | setSelectedDataAsync} methods of the Document object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. For a complete listing of the "Async" methods, see the Remarks section of the AsyncResult object topic. + * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. For a complete listing of the "Async" methods, see the Remarks section of the {@link Office.AsyncResult | AsyncResult} object topic. */ value: any; } @@ -509,6 +511,7 @@ declare namespace Office { diagnostics: ContextInformation; /** * Gets the locale (language) specified by the user for the UI of the Office host application. + * * @remarks * When using in Outlook, the applicable modes are Compose or read. */ @@ -821,7 +824,8 @@ declare namespace Office { * @remarks * * - *
HostsExcel, OneNote, Outlook, PowerPoint, Word
Requirement setsIdentityAPI
+ * Requirement sets{@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements +| IdentityAPI} * * This API requires a single sign-on configuration that bridges the add-in to an Azure application. Office users sign-in with Organizational Accounts and Microsoft Accounts. Microsoft Azure returns tokens intended for both user account types to access resources in the Microsoft Graph. * @@ -1269,7 +1273,7 @@ declare namespace Office { */ Matrix, /** - * Tabular data with a header row. Data is returned as a TableData object. + * Tabular data with a header row. Data is returned as a {@link Office.TableData | TableData} object. */ Table } @@ -1277,7 +1281,9 @@ declare namespace Office { * Specifies how to coerce data returned or set by the invoked method. * * @remarks - * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. Project supports only `Office.CoercionType.Text`. + * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. + * + * Project supports only `Office.CoercionType.Text`. * * **Support details** * @@ -1298,43 +1304,42 @@ declare namespace Office { */ enum CoercionType { /** - * Return or set data as text (string).Data is returned or set as a one-dimensional run of characters. + * Return or set data as text (string). Data is returned or set as a one-dimensional run of characters. */ Text, /** * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. - * @remarks - * Only applies to data in Excel and Word. + * + * Note: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. - * @remarks - * Only applies to data in Access, Excel and Word. + * + * Note: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. - * @remarks - * Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * + * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. - * @remarks - * Only applies to data in Word. + * + * Note: Only applies to data in Word. */ Ooxml, /** - * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides.For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. - * @remarks - * Only applies to data in PowerPoint when calling the Document.getSelectedData method to get the current slide or selected range of slides. + * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. + * + * Note: Only applies to data in PowerPoint when calling the {@link Office.Document.getSelectedData | Document.getSelectedData} method to get the current slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * @remarks - * Only applies to data in Excel, Word and PowerPoint. + * Note: Only applies to data in Excel, Word and PowerPoint. */ Image } @@ -1343,7 +1348,7 @@ declare namespace Office { * * @remarks * - * Returned by the mode property of the Document object. + * Returned by the mode property of the {@link Office.Document | Document} object. * * **Support details** * @@ -1437,6 +1442,7 @@ declare namespace Office { * * * + * * * * @@ -1468,27 +1474,33 @@ declare namespace Office { */ DialogEventReceived, /** - * Triggers when a document level selection happens + * Triggers when a document level selection happens. */ DocumentSelectionChanged, /** - * A Document.SelectionChanged event was raised. + * Triggers when the selected Outlook item was changed. + * + * [Api set: Mailbox 1.1] */ ItemChanged, /** - * Triggers when a customXmlPart node was deleted + * Triggers when a customXmlPart node was deleted. */ NodeDeleted, /** - * Triggers when a customXmlPart node was inserted + * Triggers when a customXmlPart node was inserted. */ NodeInserted, /** - * Triggers when a customXmlPart node was replaced + * Triggers when a customXmlPart node was replaced. */ NodeReplaced, /** - * The recurrence pattern of the selected series has changed. + * Triggers when the recurrence pattern of the selected series was changed in Outlook. + * + * [Api set: Mailbox Preview] + * + * @beta */ RecurrencePatternChanged, /** @@ -1593,24 +1605,67 @@ declare namespace Office { enum GoToType { /** * Goes to a binding object using the specified binding id. + * + * Supported hosts: Excel, Word */ Binding, /** * Goes to a named item using that item's name. * In Excel, you can use any structured reference for a named range or table: "Worksheet2!Table1" + * + * Supported hosts: Excel */ NamedItem, /** * Goes to a slide using the specified id. + * + * Supported hosts: PowerPoint */ Slide, /** - * Goes to the specified index by slide number or Office.Index + * Goes to the specified index by slide number or {@link Office.Index}. + * + * Supported hosts: PowerPoint */ Index } /** - * Specifies whether to select (highlight) the location to navigate to (when using the Document.goToByIdAsync method). + * Specifies the relative PowerPoint slide + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Outlook Y Y Y
PowerPoint Y Y
Project Y
Word Y Y
+ * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad /th>
PowerPoint Y Y Y
+ */ + enum Index { + /** + * Represents the first PowerPoint slide + */ + First, + /** + * Represents the last PowerPoint slide + */ + Last, + /** + * Represents the next PowerPoint slide + */ + Next, + /** + * Represents the previous PowerPoint slide + */ + Previous + } + /** + * Specifies whether to select (highlight) the location to navigate to (when using the {@link Office.Document.goToByIdAsync | Document.goToByIdAsync} method). * * @remarks * @@ -1635,7 +1690,7 @@ declare namespace Office { */ Selected, /** - * The cursor is moved the beginning of the location. + * The cursor is moved to the beginning of the location. */ None } @@ -3619,7 +3674,7 @@ declare namespace Office { rows: any[][]; } /** - * Specifies enumerated values for the cells: property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. + * Specifies enumerated values for the `cells` property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. * * @remarks * @@ -3661,11 +3716,11 @@ declare namespace Office { */ interface TextBinding extends Binding { } /** - * Specifies the project fields that are available as a parameter for the getProjectFieldAsync method. + * Specifies the project fields that are available as a parameter for the {@link Office.Document.getProjectFieldAsync | getProjectFieldAsync} method. * * @remarks * - * A ProjectProjectFields constant can be used as a parameter of the getProjectFieldAsync method. + * A ProjectProjectFields constant can be used as a parameter of the {@link Office.Document.getProjectFieldAsync | getProjectFieldAsync} method. * * **Support details** * @@ -3731,10 +3786,10 @@ declare namespace Office { WSSList } /** - * Specifies the resource fields that are available as a parameter for the getResourceFieldAsync method. + * Specifies the resource fields that are available as a parameter for the {@link Office.Document.getResourceFieldAsync | getResourceFieldAsync} method. * * @remarks - * A ProjectResourceFields constant can be used as a parameter of the getResourceFieldAsync method. + * A ProjectResourceFields constant can be used as a parameter of the {@link Office.Document.getResourceFieldAsync | getResourceFieldAsync} method. * * For more information about working with fields in Project, see {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. * @@ -4553,10 +4608,10 @@ declare namespace Office { Text9 } /** - * Specifies the task fields that are available as a parameter for the getTaskFieldAsync method. + * Specifies the task fields that are available as a parameter for the {@link Office.Document.getTaskFieldAsync | getTaskFieldAsync} method. * * @remarks - * A ProjectTaskFields constant can be used as a parameter of the getTaskFieldAsync method. + * A ProjectTaskFields constant can be used as a parameter of the {@link Office.Document.getTaskFieldAsync | getTaskFieldAsync} method. * * For more information about working with fields in Project, see the {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. * @@ -5701,10 +5756,10 @@ declare namespace Office { WSSID } /** - * Specifies the types of views that the getSelectedViewAsync method can recognize. + * Specifies the types of views that the {@link Office.Document.getSelectedViewAsync | getSelectedViewAsync} method can recognize. * * @remarks - * The getSelectedViewAsync method returns the ProjectViewTypes constant value and name that corresponds to the active view. + * The {@link Office.Document.getSelectedViewAsync | getSelectedViewAsync} method returns the ProjectViewTypes constant value and name that corresponds to the active view. * * **Support details** * From 7c33a958277e53aa335dcddec28ebfe6502638ca Mon Sep 17 00:00:00 2001 From: Claas Ahlrichs Date: Fri, 3 Aug 2018 01:41:18 +0200 Subject: [PATCH 129/129] added definitions for react select (v2) (#27737) * moved existing "react-select" definitions into "v1" directory * updated references to V1 of "react-select" * dts-gen --dt --name react-select --template module * added placeholders for react-select definitions and tests * fixed imports of react and react-select * updated config. files * drafted definitions for react-select * updated definitions for react-select * made Props in stateManager.d.ts and Select.d.ts optional * handle grouped options in Select.d.ts * updated definitions for react-select * resolved merge conflicts * fixed issues identified by "npm test" * updated type of "menuPortalTarget" * remove OptionType type and introduce throughout as a generic parameter * add an extra type * re-enable interface-over-type-literal lint rule * parameterize GroupedOptionsType after some consideration this should be parameterized, typically with a union type, see Grouped example which is a select of `ColourOption | FlavourOption` --- types/react-select/index.d.ts | 667 +----------------- types/react-select/lib/Async.d.ts | 47 ++ types/react-select/lib/AsyncCreatable.d.ts | 25 + types/react-select/lib/Creatable.d.ts | 49 ++ types/react-select/lib/Select.d.ts | 419 +++++++++++ .../react-select/lib/accessibility/index.d.ts | 10 + types/react-select/lib/animated/Input.d.ts | 10 + .../react-select/lib/animated/MultiValue.d.ts | 12 + .../lib/animated/Placeholder.d.ts | 9 + .../lib/animated/SingleValue.d.ts | 9 + .../lib/animated/ValueContainer.d.ts | 9 + types/react-select/lib/animated/index.d.ts | 17 + .../lib/animated/transitions.d.ts | 50 ++ types/react-select/lib/builtins.d.ts | 10 + .../react-select/lib/components/Control.d.ts | 29 + types/react-select/lib/components/Group.d.ts | 24 + types/react-select/lib/components/Input.d.ts | 23 + types/react-select/lib/components/Menu.d.ts | 158 +++++ .../lib/components/MultiValue.d.ts | 57 ++ types/react-select/lib/components/Option.d.ts | 41 ++ .../lib/components/Placeholder.d.ts | 17 + .../lib/components/SingleValue.d.ts | 23 + .../lib/components/containers.d.ts | 57 ++ types/react-select/lib/components/index.d.ts | 142 ++++ .../lib/components/indicators.d.ts | 67 ++ types/react-select/lib/diacritics.d.ts | 1 + types/react-select/lib/filters.d.ts | 16 + types/react-select/lib/stateManager.d.ts | 36 + types/react-select/lib/styles.d.ts | 99 +++ types/react-select/lib/theme.d.ts | 53 ++ types/react-select/lib/types.d.ts | 100 +++ types/react-select/lib/utils.d.ts | 121 ++++ types/react-select/test/AtlaskitDummy.ts | 11 + types/react-select/test/ChronoNodeDummy.ts | 1 + types/react-select/test/data.ts | 132 ++++ .../test/examples/AccessingInternals.tsx | 114 +++ .../test/examples/AnimatedMulti.tsx | 17 + .../test/examples/AsyncCallbacks.tsx | 42 ++ .../test/examples/AsyncCreatable.tsx | 28 + .../react-select/test/examples/AsyncMulti.tsx | 39 + .../test/examples/AsyncPromises.tsx | 34 + .../test/examples/BasicGrouped.tsx | 37 + .../react-select/test/examples/BasicMulti.tsx | 15 + .../test/examples/BasicSingle.tsx | 101 +++ .../test/examples/ControlledMenu.tsx | 42 ++ .../test/examples/CreatableAdvanced.tsx | 70 ++ .../test/examples/CreatableInputOnly.tsx | 72 ++ .../test/examples/CreatableMulti.tsx | 22 + .../test/examples/CreatableSingle.tsx | 29 + .../test/examples/CreateFilter.tsx | 85 +++ .../test/examples/CustomClearIndicator.tsx | 35 + .../test/examples/CustomControl.tsx | 32 + .../test/examples/CustomDropdownIndicator.tsx | 24 + .../test/examples/CustomFilterOptions.tsx | 34 + .../test/examples/CustomGetOptionLabel.tsx | 23 + .../test/examples/CustomGroup.tsx | 24 + .../test/examples/CustomGroupHeading.tsx | 31 + .../examples/CustomIndicatorSeparator.tsx | 27 + .../examples/CustomIndicatorsContainer.tsx | 21 + .../test/examples/CustomInput.tsx | 27 + .../test/examples/CustomIsOptionDisabled.tsx | 21 + .../test/examples/CustomLoadingIndicator.tsx | 47 ++ .../test/examples/CustomLoadingMessage.tsx | 50 ++ .../react-select/test/examples/CustomMenu.tsx | 37 + .../test/examples/CustomMenuList.tsx | 29 + .../examples/CustomMultiValueContainer.tsx | 23 + .../test/examples/CustomMultiValueLabel.tsx | 23 + .../test/examples/CustomMultiValueRemove.tsx | 25 + .../test/examples/CustomNoOptionsMessage.tsx | 31 + .../test/examples/CustomOption.tsx | 22 + .../test/examples/CustomPlaceholder.tsx | 19 + .../test/examples/CustomSelectContainer.tsx | 24 + .../test/examples/CustomSingleValue.tsx | 25 + .../test/examples/CustomValueContainer.tsx | 28 + .../test/examples/Experimental.tsx | 211 ++++++ .../react-select/test/examples/MenuPortal.tsx | 91 +++ .../test/examples/OnSelectResetsInput.tsx | 47 ++ types/react-select/test/examples/Popout.tsx | 128 ++++ .../test/examples/StyledMulti.tsx | 53 ++ .../test/examples/StyledSingle.tsx | 51 ++ types/react-select/test/styled-components.tsx | 17 + types/react-select/tsconfig.json | 97 ++- types/react-select/tslint.json | 4 +- types/react-select/v1/index.d.ts | 654 +++++++++++++++++ .../{ => v1}/lib/Option/index.d.ts | 0 .../lib/utils/defaultMenuRenderer/index.d.ts | 0 .../{ => v1}/react-select-tests.tsx | 0 types/react-select/v1/tsconfig.json | 35 + types/react-select/v1/tslint.json | 1 + types/react-virtualized-select/tsconfig.json | 9 +- 90 files changed, 4716 insertions(+), 662 deletions(-) create mode 100644 types/react-select/lib/Async.d.ts create mode 100644 types/react-select/lib/AsyncCreatable.d.ts create mode 100644 types/react-select/lib/Creatable.d.ts create mode 100644 types/react-select/lib/Select.d.ts create mode 100644 types/react-select/lib/accessibility/index.d.ts create mode 100644 types/react-select/lib/animated/Input.d.ts create mode 100644 types/react-select/lib/animated/MultiValue.d.ts create mode 100644 types/react-select/lib/animated/Placeholder.d.ts create mode 100644 types/react-select/lib/animated/SingleValue.d.ts create mode 100644 types/react-select/lib/animated/ValueContainer.d.ts create mode 100644 types/react-select/lib/animated/index.d.ts create mode 100644 types/react-select/lib/animated/transitions.d.ts create mode 100644 types/react-select/lib/builtins.d.ts create mode 100644 types/react-select/lib/components/Control.d.ts create mode 100644 types/react-select/lib/components/Group.d.ts create mode 100644 types/react-select/lib/components/Input.d.ts create mode 100644 types/react-select/lib/components/Menu.d.ts create mode 100644 types/react-select/lib/components/MultiValue.d.ts create mode 100644 types/react-select/lib/components/Option.d.ts create mode 100644 types/react-select/lib/components/Placeholder.d.ts create mode 100644 types/react-select/lib/components/SingleValue.d.ts create mode 100644 types/react-select/lib/components/containers.d.ts create mode 100644 types/react-select/lib/components/index.d.ts create mode 100644 types/react-select/lib/components/indicators.d.ts create mode 100644 types/react-select/lib/diacritics.d.ts create mode 100644 types/react-select/lib/filters.d.ts create mode 100644 types/react-select/lib/stateManager.d.ts create mode 100644 types/react-select/lib/styles.d.ts create mode 100644 types/react-select/lib/theme.d.ts create mode 100644 types/react-select/lib/types.d.ts create mode 100644 types/react-select/lib/utils.d.ts create mode 100644 types/react-select/test/AtlaskitDummy.ts create mode 100644 types/react-select/test/ChronoNodeDummy.ts create mode 100644 types/react-select/test/data.ts create mode 100644 types/react-select/test/examples/AccessingInternals.tsx create mode 100644 types/react-select/test/examples/AnimatedMulti.tsx create mode 100644 types/react-select/test/examples/AsyncCallbacks.tsx create mode 100644 types/react-select/test/examples/AsyncCreatable.tsx create mode 100644 types/react-select/test/examples/AsyncMulti.tsx create mode 100644 types/react-select/test/examples/AsyncPromises.tsx create mode 100644 types/react-select/test/examples/BasicGrouped.tsx create mode 100644 types/react-select/test/examples/BasicMulti.tsx create mode 100644 types/react-select/test/examples/BasicSingle.tsx create mode 100644 types/react-select/test/examples/ControlledMenu.tsx create mode 100644 types/react-select/test/examples/CreatableAdvanced.tsx create mode 100644 types/react-select/test/examples/CreatableInputOnly.tsx create mode 100644 types/react-select/test/examples/CreatableMulti.tsx create mode 100644 types/react-select/test/examples/CreatableSingle.tsx create mode 100644 types/react-select/test/examples/CreateFilter.tsx create mode 100644 types/react-select/test/examples/CustomClearIndicator.tsx create mode 100644 types/react-select/test/examples/CustomControl.tsx create mode 100644 types/react-select/test/examples/CustomDropdownIndicator.tsx create mode 100644 types/react-select/test/examples/CustomFilterOptions.tsx create mode 100644 types/react-select/test/examples/CustomGetOptionLabel.tsx create mode 100644 types/react-select/test/examples/CustomGroup.tsx create mode 100644 types/react-select/test/examples/CustomGroupHeading.tsx create mode 100644 types/react-select/test/examples/CustomIndicatorSeparator.tsx create mode 100644 types/react-select/test/examples/CustomIndicatorsContainer.tsx create mode 100644 types/react-select/test/examples/CustomInput.tsx create mode 100644 types/react-select/test/examples/CustomIsOptionDisabled.tsx create mode 100644 types/react-select/test/examples/CustomLoadingIndicator.tsx create mode 100644 types/react-select/test/examples/CustomLoadingMessage.tsx create mode 100644 types/react-select/test/examples/CustomMenu.tsx create mode 100644 types/react-select/test/examples/CustomMenuList.tsx create mode 100644 types/react-select/test/examples/CustomMultiValueContainer.tsx create mode 100644 types/react-select/test/examples/CustomMultiValueLabel.tsx create mode 100644 types/react-select/test/examples/CustomMultiValueRemove.tsx create mode 100644 types/react-select/test/examples/CustomNoOptionsMessage.tsx create mode 100644 types/react-select/test/examples/CustomOption.tsx create mode 100644 types/react-select/test/examples/CustomPlaceholder.tsx create mode 100644 types/react-select/test/examples/CustomSelectContainer.tsx create mode 100644 types/react-select/test/examples/CustomSingleValue.tsx create mode 100644 types/react-select/test/examples/CustomValueContainer.tsx create mode 100644 types/react-select/test/examples/Experimental.tsx create mode 100644 types/react-select/test/examples/MenuPortal.tsx create mode 100644 types/react-select/test/examples/OnSelectResetsInput.tsx create mode 100644 types/react-select/test/examples/Popout.tsx create mode 100644 types/react-select/test/examples/StyledMulti.tsx create mode 100644 types/react-select/test/examples/StyledSingle.tsx create mode 100644 types/react-select/test/styled-components.tsx create mode 100644 types/react-select/v1/index.d.ts rename types/react-select/{ => v1}/lib/Option/index.d.ts (100%) rename types/react-select/{ => v1}/lib/utils/defaultMenuRenderer/index.d.ts (100%) rename types/react-select/{ => v1}/react-select-tests.tsx (100%) create mode 100644 types/react-select/v1/tsconfig.json create mode 100644 types/react-select/v1/tslint.json diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index 31ff0db561..9c4728254c 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -1,654 +1,21 @@ -// Type definitions for react-select 1.3 -// Project: https://github.com/JedWatson/react-select -// Definitions by: ESQUIBET Hugo -// Gilad Gray -// Izaak Baker -// Tadas Dailyda -// Mark Vujevits -// Mike Deverell -// MartynasZilinskas -// Onat Yigit Mercan -// Ian Johnson -// Anton Novik -// David Schkalee -// Arthur Udalov -// Sebastian Silbermann -// Endurance Idehen -// Guillaume Chartier +// Type definitions for react-select 2.0 +// Project: https://github.com/JedWatson/react-select#readme +// Definitions by: Claas Ahlrichs +// Jon Freedman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.9 -import * as React from 'react'; +import SelectBase from './lib/Select'; +import { StateManager } from './lib/stateManager'; -export default class ReactSelectClass extends React.Component> { - focus(): void; - setValue(value: Option): void; -} -// Other components -export class Creatable extends React.Component> { } -export class Async extends React.Component> { } -export class AsyncCreatable extends React.Component> { } +export default SelectBase; +// export default StateManager; -export type OptionComponentType = React.ComponentType>; -export type ValueComponentType = React.ComponentType>; - -export type HandlerRendererResult = JSX.Element | null | false; - -// Handlers -export type FocusOptionHandler = (option: Option) => void; -export type SelectValueHandler = (option: Option) => void; -export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; -export type ClearRendererHandler = () => HandlerRendererResult; -export type FilterOptionHandler = (option: Option, filter: string) => boolean; -export type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; -export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; -export type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; -export type OnCloseHandler = () => void; -export type OnInputChangeHandler = (inputValue: string) => string; -export type OnInputKeyDownHandler = React.KeyboardEventHandler; -export type OnMenuScrollToBottomHandler = () => void; -export type OnOpenHandler = () => void; -export type OnFocusHandler = React.FocusEventHandler; -export type OnBlurHandler = React.FocusEventHandler; -export type OptionRendererHandler = (option: Option) => HandlerRendererResult; -export type ValueRendererHandler = (option: Option, index?: number) => HandlerRendererResult; -export type OnValueClickHandler = (option: Option, event: React.MouseEvent) => void; -export type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; -export type IsValidNewOptionHandler = (arg: { label: string }) => boolean; -export type NewOptionCreatorHandler = (arg: { label: string, labelKey: string, valueKey: string }) => Option; -export type PromptTextCreatorHandler = (filterText: string) => string; -export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean; - -export type OnChangeSingleHandler = OnChangeHandler>; -export type OnChangeMultipleHandler = OnChangeHandler>; -export type OnChangeHandler | Options> = (newValue: TOption | null) => void; -export type OnNewOptionClickHandler = (option: Option) => void; - -export type LoadOptionsHandler = LoadOptionsAsyncHandler | LoadOptionsLegacyHandler; -export type LoadOptionsAsyncHandler = (input: string) => Promise>; -export type LoadOptionsLegacyHandler = (input: string, callback: (err: any, result: AutocompleteResult) => void) => void; - -export interface AutocompleteResult { - /** The search-results to be displayed */ - options: Options; - /** - * Should be set to true, if and only if a longer query with the same prefix - * would return a subset of the results - * If set to true, more specific queries will not be sent to the server. - */ - complete: boolean; -} - -export type Options = Array>; - -export interface Option { - /** Text for rendering */ - label?: string; - /** Value for searching */ - value?: TValue; - /** - * Allow this option to be cleared - * @default true - */ - clearableValue?: boolean; - /** - * Do not allow this option to be selected - * @default false - */ - disabled?: boolean; - /** - * In the event that a custom menuRenderer is provided, Option should be able - * to accept arbitrary key-value pairs. See react-virtualized-select. - */ - [property: string]: any; -} - -export type OptionValues = string | number | boolean; - -export interface MenuRendererProps { - /** - * The currently focused option; should be visible in the menu by default. - * default {} - */ - focusedOption: Option; - - /** - * Callback to focus a new option; receives the option as a parameter. - */ - focusOption: FocusOptionHandler; - - /** - * Option labels are accessible with this string key. - */ - labelKey: string; - - /** - * Ordered array of options to render. - */ - options: Options; - - /** - * Callback to select a new option; receives the option as a parameter. - */ - selectValue: SelectValueHandler; - - /** - * Array of currently selected options. - */ - valueArray: Options; - - /** - * Callback to remove selection from option; receives the option as a parameter. - */ - removeValue: SelectValueHandler; - - /** - * function which returns a custom way to render the options in the menu - */ - optionRenderer: OptionRendererHandler; -} - -export interface OptionComponentProps { - /** - * Classname(s) to apply to the option component. - */ - className?: string; - - /** - * Currently focused option. - */ - focusOption?: Option; - - inputValue?: string; - instancePrefix?: string; - - /** - * True if this option is disabled. - */ - isDisabled?: boolean; - - /** - * True if this option is focused. - */ - isFocused?: boolean; - - /** - * True if this option is selected. - */ - isSelected?: boolean; - - /** - * Callback to be invoked when this option is focused. - */ - onFocus?: (option: Option, event: any) => void; - - /** - * Callback to be invoked when this option is selected. - */ - onSelect?: (option: Option, event: any) => void; - - /** - * Option to be rendered by this component. - */ - option: Option; - - /** - * Index of the option being rendered in the list - */ - optionIndex?: number; - - /** - * Callback to invoke when removing an option from a multi-selection. (Not necessarily the one - * being rendered) - */ - removeValue?: (value: TValue | TValue[]) => void; - - /** - * Callback to invoke to select an option. (Not necessarily the one being rendered) - */ - selectValue?: (value: TValue | TValue[]) => void; -} - -export interface ArrowRendererProps { - /** - * Arrow mouse down event handler. - */ - onMouseDown: React.MouseEventHandler; - - /** - * whether the Select is open or not. - */ - isOpen: boolean; -} - -export interface ValueComponentProps { - disabled: ReactSelectProps['disabled']; - id: string; - instancePrefix: string; - onClick: OnValueClickHandler | null; - onRemove?: SelectValueHandler; - placeholder: ReactSelectProps['placeholder']; - value: Option; - values?: Array>; -} - -export interface ReactSelectProps extends React.Props> { - /** - * text to display when `allowCreate` is true. - * @default 'Add "{label}"?' - */ - addLabelText?: string; - /** - * renders a custom drop-down arrow to be shown in the right-hand side of the select. - * @default undefined - */ - arrowRenderer?: ArrowRendererHandler | null; - /** - * blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices. - * @default false - */ - autoBlur?: boolean; - /** - * autofocus the component on mount - * @deprecated. Use autoFocus instead - * @default false - */ - autofocus?: boolean; - /** - * autofocus the component on mount - * @default false - */ - autoFocus?: boolean; - /** - * If enabled, the input will expand as the length of its value increases - */ - autosize?: boolean; - /** - * whether pressing backspace removes the last item when there is no input value - * @default true - */ - backspaceRemoves?: boolean; - /** - * Message to use for screenreaders to press backspace to remove the current item - * {label} is replaced with the item label - * @default "Press backspace to remove..." - */ - backspaceToRemoveMessage?: string; - /** - * CSS className for the outer element - */ - className?: string; - /** - * Prefix prepended to element default className if no className is defined - */ - classNamePrefix?: string; - /** - * title for the "clear" control when `multi` is true - * @default "Clear all" - */ - clearAllText?: string; - /** - * Renders a custom clear to be shown in the right-hand side of the select when clearable true - * @default undefined - */ - clearRenderer?: ClearRendererHandler; - /** - * title for the "clear" control - * @default "Clear value" - */ - clearValueText?: string; - /** - * whether to close the menu when a value is selected - * @default true - */ - closeOnSelect?: boolean; - /** - * whether it is possible to reset value. if enabled, an X button will appear at the right side. - * @default true - */ - clearable?: boolean; - /** - * whether backspace removes an item if there is no text input - * @default true - */ - deleteRemoves?: boolean; - /** - * delimiter to use to join multiple values - * @default "," - */ - delimiter?: string; - /** - * whether the Select is disabled or not - * @default false - */ - disabled?: boolean; - /** - * whether escape clears the value when the menu is closed - * @default true - */ - escapeClearsValue?: boolean; - /** - * method to filter a single option - */ - filterOption?: FilterOptionHandler; - /** - * method to filter the options array - */ - filterOptions?: FilterOptionsHandler; - /** - * id for the underlying HTML input element - * @default undefined - */ - id?: string; - /** - * whether to strip diacritics when filtering - * @default true - */ - ignoreAccents?: boolean; - /** - * whether to perform case-insensitive filtering - * @default true - */ - ignoreCase?: boolean; - /** - * custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} - * @default {} - */ - inputProps?: { [key: string]: any }; - /** - * renders a custom input - */ - inputRenderer?: InputRendererHandler; - /** - * allows for synchronization of component id's on server and client. - * @see https://github.com/JedWatson/react-select/pull/1105 - */ - instanceId?: string; - /** - * whether the Select is loading externally or not (such as options being loaded). - * if true, a loading spinner will be shown at the right side. - * @default false - */ - isLoading?: boolean; - /** - * (legacy mode) joins multiple values into a single form field with the delimiter - * @default false - */ - joinValues?: boolean; - /** - * the option property to use for the label - * @default "label" - */ - labelKey?: string; - /** - * (any, start) match the start or entire string when filtering - * @default "any" - */ - matchPos?: string; - /** - * (any, label, value) which option property to filter on - * @default "any" - */ - matchProp?: string; - /** - * buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport - * @default 0 - */ - menuBuffer?: number; - /** - * optional style to apply to the menu container - */ - menuContainerStyle?: React.CSSProperties; - /** - * renders a custom menu with options - */ - menuRenderer?: MenuRendererHandler; - /** - * optional style to apply to the menu - */ - menuStyle?: React.CSSProperties; - /** - * multi-value input - * @default false - */ - multi?: boolean; - /** - * field name, for hidden `` tag - */ - name?: string; - /** - * placeholder displayed when there are no matching search results or a falsy value to hide it - * @default "No results found" - */ - noResultsText?: string | JSX.Element; - /** - * onBlur handler: function (event) {} - */ - onBlur?: OnBlurHandler; - /** - * whether to clear input on blur or not - * @default true - */ - onBlurResetsInput?: boolean; - /** - * whether the input value should be reset when options are selected. - * Also input value will be set to empty if 'onSelectResetsInput=true' and - * Select will get new value that not equal previous value. - * @default true - */ - onSelectResetsInput?: boolean; - /** - * whether to clear input when closing the menu through the arrow - * @default true - */ - onCloseResetsInput?: boolean; - /** - * onChange handler: function (newValue) {} - */ - onChange?: OnChangeHandler; - /** - * fires when the menu is closed - */ - onClose?: OnCloseHandler; - /** - * onFocus handler: function (event) {} - */ - onFocus?: OnFocusHandler; - /** - * onInputChange handler: function (inputValue) {} - */ - onInputChange?: OnInputChangeHandler; - /** - * onInputKeyDown handler: function (keyboardEvent) {} - */ - onInputKeyDown?: OnInputKeyDownHandler; - /** - * fires when the menu is scrolled to the bottom; can be used to paginate options - */ - onMenuScrollToBottom?: OnMenuScrollToBottomHandler; - /** - * fires when the menu is opened - */ - onOpen?: OnOpenHandler; - /** - * boolean to enable opening dropdown when focused - * @default false - */ - openOnClick?: boolean; - /** - * open the options menu when the input gets focus (requires searchable = true) - * @default true - */ - openOnFocus?: boolean; - /** - * className to add to each option component - */ - optionClassName?: string; - /** - * option component to render in dropdown - */ - optionComponent?: OptionComponentType; - /** - * function which returns a custom way to render the options in the menu - */ - optionRenderer?: OptionRendererHandler; - /** - * array of Select options - * @default false - */ - options?: Options; - /** - * number of options to jump when using page up/down keys - * @default 5 - */ - pageSize?: number; - /** - * field placeholder, displayed when there's no value - * @default "Select..." - */ - placeholder?: string | JSX.Element; - /** - * whether the selected option is removed from the dropdown on multi selects - * @default true - */ - removeSelected?: boolean; - /** - * applies HTML5 required attribute when needed - * @default false - */ - required?: boolean; - /** - * value to use when you clear the control - */ - resetValue?: any; - /** - * use react-select in right-to-left direction - * @default false - */ - rtl?: boolean; - /** - * whether the viewport will shift to display the entire menu when engaged - * @default true - */ - scrollMenuIntoView?: boolean; - /** - * whether to enable searching feature or not - * @default true; - */ - searchable?: boolean; - /** - * whether to select the currently focused value when the [tab] key is pressed - */ - tabSelectsValue?: boolean; - /** - * initial field value - */ - value?: Option | Options | string | string[] | number | number[] | boolean; - /** - * the option property to use for the value - * @default "value" - */ - valueKey?: string; - /** - * function which returns a custom way to render the value selected - * @default false - */ - valueRenderer?: ValueRendererHandler; - /** - * optional style to apply to the control - */ - style?: React.CSSProperties; - - /** - * optional tab index of the control - */ - tabIndex?: string | number; - - /** - * value component to render - */ - valueComponent?: ValueComponentType; - - /** - * optional style to apply to the component wrapper - */ - wrapperStyle?: React.CSSProperties; - - /** - * onClick handler for value labels: function (value, event) {} - */ - onValueClick?: OnValueClickHandler; - - /** - * pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false - */ - simpleValue?: boolean; -} - -export interface ReactCreatableSelectProps extends ReactSelectProps { - /** - * Searches for any matching option within the set of options. This function prevents - * duplicate options from being created. - */ - isOptionUnique?: IsOptionUniqueHandler; - - /** - * Determines if the current input text represents a valid option. - */ - isValidNewOption?: IsValidNewOptionHandler; - - /** - * factory to create new options - */ - newOptionCreator?: NewOptionCreatorHandler; - - /** - * Creates prompt/placeholder for option text. - */ - promptTextCreator?: PromptTextCreatorHandler; - - /** - * Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option. - */ - shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler; - - /** - * new option click handler: function (option) {} - */ - onNewOptionClick?: OnNewOptionClickHandler; - - /** - * true: Show new option at top of list - * false: Show new option at bottom of list - * @default true - */ - showNewOptionAtTop?: boolean; -} - -export interface ReactAsyncSelectProps extends ReactSelectProps { - /** - * Whether to auto-load the default async options set. - */ - autoload?: boolean; - - /** - * object to use to cache results; can be null to disable cache - */ - cache?: { [key: string]: any } | boolean; - - /** - * function to call to load options asynchronously - */ - loadOptions: LoadOptionsHandler; - - /** - * replaces the placeholder while options are loading - */ - loadingPlaceholder?: string | JSX.Element; - /** - * displayed in the drop down list when the user did not type anything yet - */ - searchPromptText?: string; -} - -export type ReactAsyncCreatableSelectProps = ReactAsyncSelectProps & ReactCreatableSelectProps; +export { SelectBase }; +export { default as Async } from './lib/Async'; +export { default as AsyncCreatable } from './lib/AsyncCreatable'; +export { default as Creatable } from './lib/Creatable'; +export { createFilter } from './lib/filters'; +export { default as makeAnimated } from './lib/animated/index'; +export { components } from './lib/components/index'; +export { mergeStyles } from './lib/styles'; diff --git a/types/react-select/lib/Async.d.ts b/types/react-select/lib/Async.d.ts new file mode 100644 index 0000000000..8acc5532b7 --- /dev/null +++ b/types/react-select/lib/Async.d.ts @@ -0,0 +1,47 @@ +import * as React from 'react'; +import Select, { Props as SelectProps } from './Select'; +import { handleInputChange } from './utils'; +import manageState from './stateManager'; +import { OptionsType, InputActionMeta } from './types'; + +export interface AsyncProps { + /* The default set of options to show before the user starts searching. When + set to `true`, the results for loadOptions('') will be autoloaded. */ + defaultOptions: OptionsType | boolean; + /* Function that returns a promise, which is the set of options to be used + once the promise resolves. */ + loadOptions: (inputValue: string, callback: ((options: OptionsType) => void)) => Promise | void; + /* If cacheOptions is truthy, then the loaded data will be cached. The cache + will remain until `cacheOptions` changes value. */ + cacheOptions: any; +} + +export type Props = SelectProps & AsyncProps; + +export const defaultProps: Props; + +export interface State { + defaultOptions?: OptionsType; + inputValue: string; + isLoading: boolean; + loadedInputValue?: string; + loadedOptions: OptionsType; + passEmptyOptions: boolean; +} + +export class Async extends React.Component, State> { + static defaultProps: Props; + select: React.Ref; + lastRequest: {}; + mounted: boolean; + optionsCache: { [key: string]: OptionsType }; + + focus(): void; + blur(): void; + loadOptions(inputValue: string, callback: (options: OptionsType) => void): void; + handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; +} + +export function makeAsyncSelect(SelectComponent: React.ComponentType): Async; + +export default Async; diff --git a/types/react-select/lib/AsyncCreatable.d.ts b/types/react-select/lib/AsyncCreatable.d.ts new file mode 100644 index 0000000000..5fbdd8e52c --- /dev/null +++ b/types/react-select/lib/AsyncCreatable.d.ts @@ -0,0 +1,25 @@ +import { Component, Ref as ElementRef } from 'react'; +import { Props as AsyncProps, State as AsyncState } from './Async'; +import { Props as CreatableProps, State as CreatableState } from './Creatable'; +import { OptionsType, ValueType, ActionMeta, InputActionMeta } from './types'; +import { cleanValue } from './utils'; + +type Props = AsyncProps & CreatableProps; + +type State = AsyncState & CreatableState; + +export class AsyncCreatable extends Component, State> { + static defaultProps: Props; + select: ElementRef; + lastRequest: {}; + mounted: boolean; + optionsCache: { [key: string]: OptionsType }; + + focus(): void; + blur(): void; + loadOptions(inputValue: string, callback: (options: OptionsType) => void): void; + handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; + onChange: (newValue: ValueType, actionMeta: ActionMeta) => void; +} + +export default AsyncCreatable; diff --git a/types/react-select/lib/Creatable.d.ts b/types/react-select/lib/Creatable.d.ts new file mode 100644 index 0000000000..c194441a8b --- /dev/null +++ b/types/react-select/lib/Creatable.d.ts @@ -0,0 +1,49 @@ +import * as React from 'react'; +import Select, { Props as SelectProps } from './Select'; +import { OptionsType, ValueType, ActionMeta } from './types'; +import { cleanValue } from './utils'; +import manageState from './stateManager'; + +export interface CreatableProps { + /* Allow options to be created while the `isLoading` prop is true. Useful to + prevent the "create new ..." option being displayed while async results are + still being loaded. */ + allowCreateWhileLoading?: boolean; + /* Gets the label for the "create new ..." option in the menu. Is given the + current input value. */ + formatCreateLabel?: (inputValue: string) => Node; + /* Determines whether the "create new ..." option should be displayed based on + the current input value, select value and options array. */ + isValidNewOption?: (a: string, b: ValueType, c: OptionsType) => boolean; + /* Returns the data for the new option when it is created. Used to display the + value, and is passed to `onChange`. */ + getNewOptionData?: (a: string, b: Node) => OptionType; + /* If provided, this will be called with the input value when a new option is + created, and `onChange` will **not** be called. Use this when you need more + control over what happens when new options are created. */ + onCreateOption?: (inputValue: string) => void; + /* Sets the position of the createOption element in your options list. Defaults to 'last' */ + createOptionPosition?: 'first' | 'last'; +} + +export type Props = SelectProps & CreatableProps; + +export const defaultProps: Props; + +export interface State { + newOption: OptionType | undefined; + options: OptionsType; +} + +export class Creatable extends React.Component, State> { + static defaultProps: Props; + select: React.Ref; + + onChange: (newValue: ValueType, actionMeta: ActionMeta) => void; + focus(): void; + blur(): void; +} + +export function makeCreatableSelect(SelectComponent: React.ComponentType): Creatable; + +export default Creatable; diff --git a/types/react-select/lib/Select.d.ts b/types/react-select/lib/Select.d.ts new file mode 100644 index 0000000000..0298ea0288 --- /dev/null +++ b/types/react-select/lib/Select.d.ts @@ -0,0 +1,419 @@ +import * as React from 'react'; + +import { Option } from './filters'; +import { + InstructionsContext, + ValueEventContext, +} from './accessibility/index'; + +import { + classNames, + noop, + scrollIntoView, +} from './utils'; + +import { + formatGroupLabel, + getOptionLabel, + getOptionValue, + isOptionDisabled, +} from './builtins'; + +import { + PlaceholderOrValue, + SelectComponents, + SelectComponentsConfig, +} from './components/index'; +import { StylesConfig } from './styles'; + +import { + ActionMeta, + ActionTypes, + FocusDirection, + FocusEventHandler, + GroupType, + InputActionMeta, + KeyboardEventHandler, + MenuPlacement, + MenuPosition, + OptionsType, + ValueType, + GroupedOptionsType, +} from './types'; + +export type MouseOrTouchEvent = + | React.MouseEvent + | React.TouchEvent; +export type FormatOptionLabelContext = 'menu' | 'value'; +export interface FormatOptionLabelMeta { + context: FormatOptionLabelContext; + inputValue: string; + selectValue: ValueType; +} + +export interface Props { + /* Aria label (for assistive tech) */ + 'aria-label'?: string; + /* HTML ID of an element that should be used as the label (for assistive tech) */ + 'aria-labelledby'?: string; + /* Focus the control when it is mounted */ + autoFocus?: boolean; + /* Remove the currently focused option when the user presses backspace */ + backspaceRemovesValue?: boolean; + /* Remove focus from the input when the user selects an option (handy for dismissing the keyboard on touch devices) */ + blurInputOnSelect?: boolean; + /* When the user reaches the top/bottom of the menu, prevent scroll on the scroll-parent */ + captureMenuScroll?: boolean; + /* className attribute applied to the outer component */ + className?: string; + /* classNamePrefix attribute used as a base for inner component classNames */ + classNamePrefix?: string | null; + /* Close the select menu when the user selects an option */ + closeMenuOnSelect?: boolean; + /* + If `true`, close the select menu when the user scrolls the document/body. + + If a function, takes a standard javascript `ScrollEvent` you return a boolean: + + `true` => The menu closes + + `false` => The menu stays open + + This is useful when you have a scrollable modal and want to portal the menu out, + but want to avoid graphical issues. + */ + closeMenuOnScroll?: boolean | EventListener; + /* + This complex object includes all the compositional components that are used + in `react-select`. If you wish to overwrite a component, pass in an object + with the appropriate namespace. + + If you only wish to restyle a component, we recommend using the `styles` prop + instead. For a list of the components that can be passed in, and the shape + that will be passed to them, see [the components docs](/api#components) + */ + components?: SelectComponentsConfig; + /* Whether the value of the select, e.g. SingleValue, should be displayed in the control. */ + controlShouldRenderValue?: boolean; + /* Delimiter used to join multiple values into a single HTML Input value */ + delimiter?: string; + /* Clear all values when the user presses escape AND the menu is closed */ + escapeClearsValue?: boolean; + /* Custom method to filter whether an option should be displayed in the menu */ + filterOption?: (( + option: Option, + rawInput: string + ) => boolean) | null; + /* Formats group labels in the menu as React components */ + formatGroupLabel?: typeof formatGroupLabel; + /* Formats option labels in the menu and control as React components */ + formatOptionLabel?: (a: OptionType, b: FormatOptionLabelMeta) => Node; + /* Resolves option data to a string to be displayed as the label by components */ + getOptionLabel?: typeof getOptionLabel; + /* Resolves option data to a string to compare options and specify value attributes */ + getOptionValue?: typeof getOptionValue; + /* Hide the selected option from the menu */ + hideSelectedOptions?: boolean; + /* The id to set on the SelectContainer component. */ + id?: string; + /* The value of the search input */ + inputValue?: string; + /* The id of the search input */ + inputId?: string; + /* Define an id prefix for the select components e.g. {your-id}-value */ + instanceId?: number | string; + /* Is the select value clearable */ + isClearable?: boolean; + /* Is the select disabled */ + isDisabled?: boolean; + /* Is the select in a state of loading (async) */ + isLoading?: boolean; + /* Override the built-in logic to detect whether an option is disabled */ + isOptionDisabled?: (a: OptionType, b: OptionsType) => boolean | false; + /* Override the built-in logic to detect whether an option is selected */ + isOptionSelected?: (a: OptionType, b: OptionsType) => boolean; + /* Support multiple selected options */ + isMulti?: boolean; + /* Is the select direction right-to-left */ + isRtl?: boolean; + /* Whether to enable search functionality */ + isSearchable?: boolean; + /* Async: Text to display when loading options */ + loadingMessage?: (obj: { inputValue: string }) => string | null; + /* Minimum height of the menu before flipping */ + minMenuHeight?: number; + /* Maximum height of the menu before scrolling */ + maxMenuHeight?: number; + /* Whether the menu is open */ + menuIsOpen?: boolean; + /* Default placement of the menu in relation to the control. 'auto' will flip + when there isn't enough space below the control. */ + menuPlacement?: MenuPlacement; + /* The CSS position value of the menu, when "fixed" extra layout management is required */ + menuPosition?: MenuPosition; + /* Whether the menu should use a portal, and where it should attach */ + menuPortalTarget?: HTMLElement | null; + /* Whether to block scroll events when the menu is open */ + menuShouldBlockScroll?: boolean; + /* Whether the menu should be scrolled into view when it opens */ + menuShouldScrollIntoView?: boolean; + /* Name of the HTML Input (optional - without this, no input will be rendered) */ + name?: string; + /* Text to display when there are no options */ + noOptionsMessage?: (obj: { inputValue: string }) => string | null; + /* Handle blur events on the control */ + onBlur?: FocusEventHandler; + /* Handle change events on the select */ + onChange?: (value: ValueType, action: ActionMeta) => void; + /* Handle focus events on the control */ + onFocus?: FocusEventHandler; + /* Handle change events on the input */ + onInputChange?: (newValue: string, actionMeta: InputActionMeta) => void; + /* Handle key down events on the select */ + onKeyDown?: KeyboardEventHandler; + /* Handle the menu opening */ + onMenuOpen?: () => void; + /* Handle the menu closing */ + onMenuClose?: () => void; + /* Fired when the user scrolls to the top of the menu */ + onMenuScrollToTop?: (event: React.SyntheticEvent) => void; + /* Fired when the user scrolls to the bottom of the menu */ + onMenuScrollToBottom?: (event: React.SyntheticEvent) => void; + /* Allows control of whether the menu is opened when the Select is focused */ + openMenuOnFocus?: boolean; + /* Allows control of whether the menu is opened when the Select is clicked */ + openMenuOnClick?: boolean; + /* Array of options that populate the select menu */ + options?: GroupedOptionsType | OptionsType; + /* Number of options to jump in menu when page{up|down} keys are used */ + pageSize?: number; + /* Placeholder text for the select value */ + placeholder?: string; + /* Status to relay to screen readers */ + screenReaderStatus?: (obj: { count: number }) => string; + /* Style modifier methods */ + styles?: StylesConfig; + /* Sets the tabIndex attribute on the input */ + tabIndex?: string; + /* Select the currently focused option when the user presses tab */ + tabSelectsValue?: boolean; + /* The value of the select; reflected by the selected option */ + value?: ValueType; + + defaultInputValue?: string; + defaultMenuIsOpen?: boolean; + defaultValue?: ValueType; +} + +export const defaultProps: Props; + +export interface MenuOptions { + render: OptionType[]; + focusable: OptionType[]; +} + +export interface State { + ariaLiveSelection: string; + ariaLiveContext: string; + inputIsHidden: boolean; + isFocused: boolean; + isComposing: boolean; + focusedOption: OptionType | null; + focusedValue: OptionType | null; + menuOptions: MenuOptions; + selectValue: OptionsType; +} + +export type ElRef = React.Ref; + +export default class Select extends React.Component, State> { + static defaultProps: Props; + + // Misc. Instance Properties + // ------------------------------ + + blockOptionHover: boolean; + clearFocusValueOnUpdate: boolean; + commonProps: any; // TODO + components: SelectComponents; + hasGroups: boolean; + initialTouchX: number; + initialTouchY: number; + inputIsHiddenAfterUpdate: boolean | null; + instancePrefix: string; + openAfterFocus: boolean; + scrollToFocusedOptionOnUpdate: boolean; + userIsDragging: boolean | null; + + // Refs + // ------------------------------ + + controlRef: ElRef; + getControlRef: (ref: HTMLElement) => void; + focusedOptionRef: ElRef; + getFocusedOptionRef: (ref: HTMLElement) => void; + menuListRef: ElRef; + getMenuListRef: (ref: HTMLElement) => void; + inputRef: ElRef; + getInputRef: (ref: HTMLElement) => void; + + // Lifecycle + // ------------------------------ + + cacheComponents: (components: SelectComponents) => void; + + // ============================== + // Consumer Handlers + // ============================== + + onMenuOpen(): void; + onMenuClose(): void; + onInputChange(newValue: string, actionMeta: InputActionMeta): void; + + // ============================== + // Methods + // ============================== + + focusInput(): void; + blurInput(): void; + + // aliased for consumers + focus(): void; + blur(): void; + + openMenu(focusOption: 'first' | 'last'): void; + focusValue(direction: 'previous' | 'next'): void; + + focusOption(direction: FocusDirection): void; + setValue: ( + newValue: ValueType, + action: ActionTypes, + option?: OptionType + ) => void; + selectOption: (newValue: OptionType) => void; + removeValue: (removedValue: OptionType) => void; + clearValue: () => void; + popValue: () => void; + + // ============================== + // Getters + // ============================== + + getCommonProps(): { + cx: any; + clearValue: () => void; + getStyles: (key: string, props: {}) => {}; + getValue: () => OptionType[]; + hasValue: boolean; + isMulti: boolean; + isRtl: boolean; + options: OptionsType; + selectOption: (newValue: OptionType) => void; + setValue: (newValue: ValueType, action: ActionTypes, option?: OptionType) => void; + selectProps: Readonly<{ + children?: Node; + }> & Readonly>; +}; + + getNextFocusedValue(nextSelectValue: OptionsType): OptionType; + + getNextFocusedOption(options: OptionsType): OptionType; + getOptionLabel: (data: OptionType) => string; + getOptionValue: (data: OptionType) => string; + getStyles: (key: string, props: {}) => {}; + getElementId: (element: 'group' | 'input' | 'listbox' | 'option') => string; + getActiveDescendentId: () => any; + + // ============================== + // Helpers + // ============================== + announceAriaLiveSelection: (props: { + event: string, + context: ValueEventContext, + }) => void; + announceAriaLiveContext: (props: { + event: string, + context?: InstructionsContext, + }) => void; + + hasValue(): boolean; + hasOptions(): boolean; + countOptions(): number; + isClearable(): boolean; + isOptionDisabled(option: OptionType, selectValue: OptionsType): boolean; + isOptionSelected(option: OptionType, selectValue: OptionsType): boolean; + filterOption(option: {}, inputValue: string): boolean; + formatOptionLabel(data: OptionType, context: FormatOptionLabelContext): Node; + formatGroupLabel(data: GroupType): Node; + + // ============================== + // Mouse Handlers + // ============================== + + onMenuMouseDown: (event: React.MouseEvent) => void; + onMenuMouseMove: (event: React.MouseEvent) => void; + onControlMouseDown: (event: MouseOrTouchEvent) => void; + onDropdownIndicatorMouseDown: (event: MouseOrTouchEvent) => void; + onClearIndicatorMouseDown: (event: MouseOrTouchEvent) => void; + onScroll: (event: Event) => void; + + // ============================== + // Composition Handlers + // ============================== + + startListeningComposition(): void; + stopListeningComposition(): void; + onCompositionStart: () => void; + onCompositionEnd: () => void; + + // ============================== + // Touch Handlers + // ============================== + + startListeningToTouch(): void; + stopListeningToTouch(): void; + onTouchStart: (event: TouchEvent) => void; + onTouchMove: (event: TouchEvent) => void; + onTouchEnd: (event: TouchEvent) => void; + onControlTouchEnd: (event: React.TouchEvent) => void; + onClearIndicatorTouchEnd: (event: React.TouchEvent) => void; + onDropdownIndicatorTouchEnd: (event: React.TouchEvent) => void; + + // ============================== + // Focus Handlers + // ============================== + + handleInputChange: (event: React.KeyboardEvent) => void; + onInputFocus: (event: React.FocusEvent) => void; + onInputBlur: (event: React.FocusEvent) => void; + onOptionHover: (focusedOption: OptionType) => void; + shouldHideSelectedOptions: () => boolean; + + // ============================== + // Keyboard Handlers + // ============================== + + onKeyDown: (event: React.KeyboardEvent) => void; + + // ============================== + // Menu Options + // ============================== + + buildMenuOptions(props: Props, selectValue: OptionsType): MenuOptions; + + // ============================== + // Renderers + // ============================== + constructAriaLiveMessage(): string; + + renderInput(): Node; + renderPlaceholderOrValue(): PlaceholderOrValue | null; + renderClearIndicator(): Node; + renderLoadingIndicator(): Node; + renderIndicatorSeparator(): Node; + renderDropdownIndicator(): Node; + renderMenu(): Node; + renderFormField(): Node; + + renderLiveRegion(): Node; +} diff --git a/types/react-select/lib/accessibility/index.d.ts b/types/react-select/lib/accessibility/index.d.ts new file mode 100644 index 0000000000..633aaeda72 --- /dev/null +++ b/types/react-select/lib/accessibility/index.d.ts @@ -0,0 +1,10 @@ +export interface InstructionsContext { isSearchable?: boolean; isMulti?: boolean; label?: string; } +export interface ValueEventContext { value: string; } + +export function instructionsAriaMessage(event: any, context?: InstructionsContext): string; + +export function valueEventAriaMessage(event: any, context: ValueEventContext): string; + +export function valueFocusAriaMessage({ focusedValue, getOptionLabel, selectValue }: any): string; +export function optionFocusAriaMessage({ focusedOption, getOptionLabel, options }: any): string; +export function resultsAriaMessage({ inputValue, screenReaderMessage }: any): string; diff --git a/types/react-select/lib/animated/Input.d.ts b/types/react-select/lib/animated/Input.d.ts new file mode 100644 index 0000000000..ad752a96c5 --- /dev/null +++ b/types/react-select/lib/animated/Input.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { InputProps } from '../components/Input'; +import { BaseTransition } from './transitions'; +import { PropsWithInnerRef } from '../types'; + +export type AnimatedInputProps = BaseTransition & PropsWithInnerRef & InputProps; + +export function AnimatedInput(WrappedComponent: React.ComponentType): React.ComponentType; + +export default AnimatedInput; diff --git a/types/react-select/lib/animated/MultiValue.d.ts b/types/react-select/lib/animated/MultiValue.d.ts new file mode 100644 index 0000000000..8a8f37ad16 --- /dev/null +++ b/types/react-select/lib/animated/MultiValue.d.ts @@ -0,0 +1,12 @@ +import { ComponentType } from 'react'; +import { MultiValueProps } from '../components/MultiValue'; +import { Collapse, fn } from './transitions'; + +export type AnimatedMultiValueProps = { + in: boolean, + onExited: fn, +} & MultiValueProps; + +export function AnimatedMultiValue(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedMultiValue; diff --git a/types/react-select/lib/animated/Placeholder.d.ts b/types/react-select/lib/animated/Placeholder.d.ts new file mode 100644 index 0000000000..1dbd3ba203 --- /dev/null +++ b/types/react-select/lib/animated/Placeholder.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { PlaceholderProps } from '../components/Placeholder'; +import { Fade, collapseDuration } from './transitions'; + +export type AnimatedPlaceholderProps = PlaceholderProps; + +export function AnimatedPlaceholder(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedPlaceholder; diff --git a/types/react-select/lib/animated/SingleValue.d.ts b/types/react-select/lib/animated/SingleValue.d.ts new file mode 100644 index 0000000000..6cd1bea908 --- /dev/null +++ b/types/react-select/lib/animated/SingleValue.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { SingleValueProps } from '../components/SingleValue'; +import { Fade } from './transitions'; + +export type AnimatedSingleValueProps = SingleValueProps; + +export function AnimatedSingleValue(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedSingleValue; diff --git a/types/react-select/lib/animated/ValueContainer.d.ts b/types/react-select/lib/animated/ValueContainer.d.ts new file mode 100644 index 0000000000..6bd15c0c19 --- /dev/null +++ b/types/react-select/lib/animated/ValueContainer.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { TransitionGroup } from 'react-transition-group'; +import { ValueContainerProps } from '../components/containers'; + +export type AnimatedValueContainerProps = ValueContainerProps; + +export function AnimatedValueContainer(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedValueContainer; diff --git a/types/react-select/lib/animated/index.d.ts b/types/react-select/lib/animated/index.d.ts new file mode 100644 index 0000000000..6760d55e81 --- /dev/null +++ b/types/react-select/lib/animated/index.d.ts @@ -0,0 +1,17 @@ +import { ComponentType } from 'react'; +import { SelectComponents, defaultComponents } from '../components/index'; +import { default as AnimatedInput, AnimatedInputProps } from './Input'; +import { default as AnimatedMultiValue, AnimatedMultiValueProps } from './MultiValue'; +import { default as AnimatedPlaceholder, AnimatedPlaceholderProps } from './Placeholder'; +import { default as AnimatedSingleValue, AnimatedSingleValueProps } from './SingleValue'; +import { default as AnimatedValueContainer, AnimatedValueContainerProps } from './ValueContainer'; + +export function makeAnimated(externalComponents?: SelectComponents): SelectComponents; + +export const Input: ComponentType; +export const MultiValue: ComponentType>; +export const Placeholder: ComponentType>; +export const SingleValue: ComponentType>; +export const ValueContainer: ComponentType>; + +export default makeAnimated; diff --git a/types/react-select/lib/animated/transitions.d.ts b/types/react-select/lib/animated/transitions.d.ts new file mode 100644 index 0000000000..ee2bd3c83b --- /dev/null +++ b/types/react-select/lib/animated/transitions.d.ts @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { Transition } from 'react-transition-group'; + +export type fn = () => void; +export interface BaseTransition { + /** Whether we are in a transition. */ + in: boolean; + /** Function to be called once transition finishes. */ + onExited: fn; +} + +// ============================== +// Fade Transition +// ============================== + +export type FadeProps = BaseTransition & { + component: React.ComponentType, + duration: number, +}; +export const Fade: React.ComponentType; + +// ============================== +// Collapse Transition +// ============================== + +export const collapseDuration: number; + +export type TransitionState = 'exiting' | 'exited'; +export type Width = number | 'auto'; +export interface CollapseProps { children: any; in: boolean; } +export interface CollapseState { width: Width; } + +// wrap each MultiValue with a collapse transition; decreases width until +// finally removing from DOM +export class Collapse extends React.Component { + duration: number; + transition: { + exiting: any, + exited: any, + }; + + // width must be calculated; cannot transition from `undefined` to `number` + getWidth: (ref: React.Ref) => void; + + // get base styles + getStyle: (width: Width) => any; + + // get transition styles + getTransition: (state: TransitionState) => any; +} diff --git a/types/react-select/lib/builtins.d.ts b/types/react-select/lib/builtins.d.ts new file mode 100644 index 0000000000..b1e1c37cc8 --- /dev/null +++ b/types/react-select/lib/builtins.d.ts @@ -0,0 +1,10 @@ +import { ReactNode as Node } from 'react'; +import { GroupType } from './types'; + +export function formatGroupLabel(group: GroupType): Node; + +export function getOptionLabel(option: any): string; + +export function getOptionValue(option: any): string; + +export function isOptionDisabled(option: any): boolean; diff --git a/types/react-select/lib/components/Control.d.ts b/types/react-select/lib/components/Control.d.ts new file mode 100644 index 0000000000..019f75bee9 --- /dev/null +++ b/types/react-select/lib/components/Control.d.ts @@ -0,0 +1,29 @@ +import { ComponentType, ReactNode as Node, Ref as ElementRef } from 'react'; + +import { borderRadius, colors, spacing } from '../theme'; +import { CommonProps, PropsWithStyles } from '../types'; + +interface State { + /** Whether the select is disabled. */ + isDisabled: boolean; + /** Whether the select is focused. */ + isFocused: boolean; +} + +export type ControlProps = CommonProps & + PropsWithStyles & + State & { + /** Children to render. */ + children: Node, + innerRef: ElementRef, + /** The mouse down event and the innerRef to pass down to the controller element. */ + innerProps: { + onMouseDown: (event: React.MouseEvent) => void, + }, + }; + +export function css(state: State): any; // TODO css type + +declare const Control: ComponentType>; + +export default Control; diff --git a/types/react-select/lib/components/Group.d.ts b/types/react-select/lib/components/Group.d.ts new file mode 100644 index 0000000000..d37964c0b4 --- /dev/null +++ b/types/react-select/lib/components/Group.d.ts @@ -0,0 +1,24 @@ +import { ReactNode as Node, ComponentType } from 'react'; + +import { spacing } from '../theme'; +import { CommonProps } from '../types'; + +interface ComponentProps { + /** The children to be rendered. */ + children: Node; + /** Component to wrap the label, recieves headingProps. */ + Heading: ComponentType; + /** Label to be displayed in the heading component. */ + label: Node; +} +export type GroupProps = CommonProps & ComponentProps; + +export function groupCSS(): any; // TODO css type + +export const Group: ComponentType>; + +export function groupHeadingCSS(): any; // TODO css type + +export const GroupHeading: ComponentType; + +export default Group; diff --git a/types/react-select/lib/components/Input.d.ts b/types/react-select/lib/components/Input.d.ts new file mode 100644 index 0000000000..16f07491d2 --- /dev/null +++ b/types/react-select/lib/components/Input.d.ts @@ -0,0 +1,23 @@ +import { ComponentType, Ref as ElementRef } from 'react'; + +import { colors, spacing } from '../theme'; + +import { PropsWithStyles, ClassNamesState } from '../types'; + +export type InputProps = PropsWithStyles & { + cx: (a: string | null, b: ClassNamesState, c: string) => string | void, + /** Reference to the internal element */ + innerRef: (element: ElementRef) => void, + /** Set whether the input should be visible. Does not affect input size. */ + isHidden: boolean, + /** Whether the input is disabled */ + isDisabled?: boolean, + className?: string, +}; + +export function inputCSS(props: InputProps): any; // TODO css type; +export function inputStyle(isHidden: boolean): any; // TODO css type + +export const Input: ComponentType; + +export default Input; diff --git a/types/react-select/lib/components/Menu.d.ts b/types/react-select/lib/components/Menu.d.ts new file mode 100644 index 0000000000..85b5ef0fae --- /dev/null +++ b/types/react-select/lib/components/Menu.d.ts @@ -0,0 +1,158 @@ +import { + Component, + ReactElement, + Ref as ElementRef, + ReactNode as Node, + ComponentType +} from 'react'; +import { createPortal } from 'react-dom'; + +import { + animatedScrollTo, + getBoundingClientObj, + RectType, + getScrollParent, + getScrollTop, + scrollTo, +} from '../utils'; +import { borderRadius, colors, spacing } from '../theme'; +import { + InnerRef, + MenuPlacement, + MenuPosition, + CommonProps, +} from '../types'; + +// ============================== +// Menu +// ============================== + +// Get Menu Placement +// ------------------------------ + +interface MenuState { placement: 'bottom' | 'top' | null; maxHeight: number; } +interface PlacementArgs { + maxHeight: number; + menuEl: ElementRef; + minHeight: number; + placement: 'bottom' | 'top' | 'auto'; + shouldScroll: boolean; + isFixedPosition: boolean; +} + +export function getMenuPlacement(args: PlacementArgs): MenuState; + +// Menu Component +// ------------------------------ + +export type MenuProps = CommonProps & { + /** The children to be rendered. */ + children: ReactElement, + /** Callback to update the portal after possible flip. */ + getPortalPlacement: (state: MenuState) => void, + /** Props to be passed to the menu wrapper. */ + innerProps: object, + /** Set the maximum height of the menu. */ + maxMenuHeight: number, + /** Set whether the menu should be at the top, at the bottom. The auto options sets it to bottom. */ + menuPlacement: MenuPlacement, + /* The CSS position value of the menu, when "fixed" extra layout management is required */ + menuPosition: MenuPosition, + /** Set the minimum height of the menu. */ + minMenuHeight: number, + /** Set whether the page should scroll to show the menu. */ + menuShouldScrollIntoView: boolean, +}; + +export function menuCSS(state: MenuState): any; // TODO css type + +export class Menu extends Component, MenuState> { + static contextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; + getPlacement: (ref: ElementRef) => void; + getState: () => MenuProps & MenuState; +} + +export default Menu; + +// ============================== +// Menu List +// ============================== + +interface MenuListState { + /** Set classname for isMulti */ + isMulti: boolean; + /* Set the max height of the Menu component */ + maxHeight: number; +} + +export interface MenuListProps { + /** The children to be rendered. */ + children: Node; + /** Inner ref to DOM Node */ + innerRef: InnerRef; +} +export type MenuListComponentProps = CommonProps & + MenuListProps & + MenuListState; +export function menuListCSS(state: MenuState): any; // TODO css type +export const MenuList: ComponentType>; + +// ============================== +// Menu Notices +// ============================== + +export function noOptionsMessageCSS(): any; // TODO css type +export function loadingMessageCSS(): any; // TODO css type + +export type NoticeProps = CommonProps & { + /** The children to be rendered. */ + children: Node, + /** Props to be passed on to the wrapper. */ + innerProps: { [key: string]: any }, +}; + +export const NoOptionsMessage: ComponentType>; +// NoOptionsMessage.defaultProps = { +// children: 'No options', +// }; + +export const LoadingMessage: ComponentType>; +// LoadingMessage.defaultProps = { +// children: 'Loading...', +// }; + +// ============================== +// Menu Portal +// ============================== + +export type MenuPortalProps = CommonProps & { + appendTo: HTMLElement, + children: Node, // ideally Menu + controlElement: HTMLElement, + menuPlacement: MenuPlacement, + menuPosition: MenuPosition, +}; +interface MenuPortalState { + placement: 'bottom' | 'top' | null; +} +interface PortalStyleArgs { + offset: number; + position: MenuPosition; + rect: RectType; +} + +export function menuPortalCSS(args: PortalStyleArgs): any; // TODO css type + +export class MenuPortal extends Component, MenuPortalState> { + static childContextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; + getChildContext(): { + getPortalPlacement: (state: MenuState) => void; + }; + + // callback for occassions where the menu must "flip" + getPortalPlacement: (state: MenuState) => void; +} diff --git a/types/react-select/lib/components/MultiValue.d.ts b/types/react-select/lib/components/MultiValue.d.ts new file mode 100644 index 0000000000..495b4fc96f --- /dev/null +++ b/types/react-select/lib/components/MultiValue.d.ts @@ -0,0 +1,57 @@ +import { ComponentType, Component, ReactNode as Node } from 'react'; + +import { borderRadius, colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +export type MultiValueProps = CommonProps &{ + children: Node, + components: any, + cropWithEllipsis: boolean, + data: OptionType, + innerProps: any, + isFocused: boolean, + isDisabled: boolean, + removeProps: { + onTouchEnd: (event: any) => void, + onClick: (event: any) => void, + onMouseDown: (event: any) => void, + }, +}; + +export function multiValueCSS(): any; // TODO css type +export function multiValueLabelCSS(props: MultiValueProps): any; // TODO css type +export function multiValueRemoveCSS(props: MultiValueProps): any; // TODO css type + +export interface MultiValueGenericProps { + children: Node; + data: OptionType; + innerProps: { className?: string }; + selectProps: any; +} +export const MultiValueGeneric: ComponentType>; + +export const MultiValueContainer: typeof MultiValueGeneric; +export const MultiValueLabel: typeof MultiValueGeneric; +export type MultiValueRemoveProps = CommonProps & { + children: Node, + innerProps: { + className: string, + onTouchEnd: (event: any) => void, + onClick: (event: any) => void, + onMouseDown: (event: any) => void, + }, + selectProps: any, +}; +export class MultiValueRemove extends Component> { + static defaultProps: { + children: Node, + }; +} + +export class MultiValue extends Component> { + static defaultProps: { + cropWithEllipsis: boolean, + }; +} + +export default MultiValue; diff --git a/types/react-select/lib/components/Option.d.ts b/types/react-select/lib/components/Option.d.ts new file mode 100644 index 0000000000..743083fff8 --- /dev/null +++ b/types/react-select/lib/components/Option.d.ts @@ -0,0 +1,41 @@ +import { ComponentType, ReactNode as Node, MouseEventHandler } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps, PropsWithStyles, InnerRef } from '../types'; + +interface State { + /** Wether the option is disabled. */ + isDisabled: boolean; + /** Wether the option is focused. */ + isFocused: boolean; + /** Whether the option is selected. */ + isSelected: boolean; +} +interface InnerProps { + id: string; + key: string; + onClick: MouseEventHandler; + onMouseOver: MouseEventHandler; + tabIndex: number; +} +export type OptionProps = PropsWithStyles & + CommonProps & + State & { + /** The children to be rendered. */ + children: Node, + /** Inner ref to DOM Node */ + innerRef: InnerRef, + /** props passed to the wrapping element for the group. */ + innerProps: InnerProps, + /* Text to be displayed representing the option. */ + label: string, + /* Type is used by the menu to determine whether this is an option or a group. + In the case of option this is always `option`. */ + type: 'option', + }; + +export function optionCSS(state: State): any; // TODO css type + +export const Option: ComponentType>; + +export default Option; diff --git a/types/react-select/lib/components/Placeholder.d.ts b/types/react-select/lib/components/Placeholder.d.ts new file mode 100644 index 0000000000..f674f74cc2 --- /dev/null +++ b/types/react-select/lib/components/Placeholder.d.ts @@ -0,0 +1,17 @@ +import { ComponentType, ReactNode as Node } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +export type PlaceholderProps = CommonProps & { + /** The children to be rendered. */ + children: Node, + /** props passed to the wrapping element for the group. */ + innerProps: { [key: string]: any }, +}; + +export function placeholderCSS(): any; // TODO css type + +export const Placeholder: ComponentType>; + +export default Placeholder; diff --git a/types/react-select/lib/components/SingleValue.d.ts b/types/react-select/lib/components/SingleValue.d.ts new file mode 100644 index 0000000000..c5f922d84c --- /dev/null +++ b/types/react-select/lib/components/SingleValue.d.ts @@ -0,0 +1,23 @@ +import { ComponentType } from 'react'; +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +interface State { + /** Whether this is disabled */ + isDisabled: boolean; +} +interface ValueProps { + /** The children to be rendered. */ + children: string; + /* The data of the selected option rendered in the Single Value componentn */ + data: OptionType; + /** Props passed to the wrapping element for the group. */ + innerProps: any; +} +export type SingleValueProps = CommonProps & ValueProps & State; + +export function css(props: SingleValueProps): any; // TODO css type + +export const SingleValue: ComponentType>; + +export default SingleValue; diff --git a/types/react-select/lib/components/containers.d.ts b/types/react-select/lib/components/containers.d.ts new file mode 100644 index 0000000000..373a552062 --- /dev/null +++ b/types/react-select/lib/components/containers.d.ts @@ -0,0 +1,57 @@ +import { Component, ReactNode as Node, ComponentType } from 'react'; +import { spacing } from '../theme'; +import { CommonProps, KeyboardEventHandler } from '../types'; + +// ============================== +// Root Container +// ============================== + +export interface ContainerState { + /** Whether the select is disabled. */ + isDisabled: boolean; + /** Whether the text in the select is indented from right to left. */ + isRtl: boolean; +} + +export type ContainerProps = CommonProps & + ContainerState & { + /** The children to be rendered. */ + children: Node, + /** Inner props to be passed down to the container. */ + innerProps: { onKeyDown: KeyboardEventHandler }, + }; +export function containerCSS(state: ContainerState): any; // TODO css type; +export const SelectContainer: ComponentType>; + +// ============================== +// Value Container +// ============================== + +export type ValueContainerProps = CommonProps & { + /** Set when the value container should hold multiple values */ + isMulti: boolean, + /** Whether the value container currently holds a value. */ + hasValue: boolean, + /** The children to be rendered. */ + children: Node, +}; +export function valueContainerCSS(): any; // TODO css type; +export class ValueContainer extends Component> {} + +// ============================== +// Indicator Container +// ============================== + +export interface IndicatorsState { + /** Whether the text should be rendered right to left. */ + isRtl: boolean; +} + +export type IndicatorContainerProps = CommonProps & + IndicatorsState & { + /** The children to be rendered. */ + children: Node, + }; + +export function indicatorsContainerCSS(): any; // TODO css type; +export const IndicatorsContainer: ComponentType>; diff --git a/types/react-select/lib/components/index.d.ts b/types/react-select/lib/components/index.d.ts new file mode 100644 index 0000000000..7d493a562a --- /dev/null +++ b/types/react-select/lib/components/index.d.ts @@ -0,0 +1,142 @@ +import { + ComponentType, + ReactElement as Element, +} from 'react'; +import { + IndicatorContainerProps, + ContainerProps, + ValueContainerProps, + IndicatorsContainer, + SelectContainer, + ValueContainer, +} from './containers'; +import { + IndicatorProps, + LoadingIconProps, + ClearIndicator, + DropdownIndicator, + LoadingIndicator, + IndicatorSeparator, + DownChevron, + CrossIcon, +} from './indicators'; + +import Control, { ControlProps } from './Control'; +import Group, { GroupProps, GroupHeading } from './Group'; +import Input, { InputProps } from './Input'; +import Menu, { + MenuProps, + MenuList, + MenuListComponentProps, + MenuPortal, + MenuPortalProps, + NoticeProps, + NoOptionsMessage, + LoadingMessage, +} from './Menu'; +import MultiValue, { + MultiValueProps, + MultiValueContainer, + MultiValueLabel, + MultiValueRemove, +} from './MultiValue'; +import Option, { OptionProps } from './Option'; +import Placeholder, { PlaceholderProps } from './Placeholder'; +import SingleValue, { SingleValueProps } from './SingleValue'; + +export type PlaceholderOrValue = + | Element>> + | Element>> + | Array>>>; + +export type IndicatorComponentType = ComponentType>; + +export interface SelectComponents { + ClearIndicator: IndicatorComponentType | null; + Control: ComponentType>; + DropdownIndicator: IndicatorComponentType | null; + DownChevron: ComponentType; + CrossIcon: ComponentType; + Group: ComponentType>; + GroupHeading: ComponentType; + IndicatorsContainer: ComponentType>; + IndicatorSeparator: IndicatorComponentType | null; + Input: ComponentType; + LoadingIndicator: ComponentType> | null; + Menu: ComponentType>; + MenuList: ComponentType>; + MenuPortal: ComponentType>; + LoadingMessage: ComponentType>; + NoOptionsMessage: ComponentType>; + MultiValue: ComponentType>; + MultiValueContainer: ComponentType; + MultiValueLabel: ComponentType; + MultiValueRemove: ComponentType; + Option: ComponentType>; + Placeholder: ComponentType>; + SelectContainer: ComponentType>; + SingleValue: ComponentType>; + ValueContainer: ComponentType>; +} + +export interface SelectComponentsConfig { + ClearIndicator?: IndicatorComponentType | null; + Control?: ComponentType>; + DropdownIndicator?: IndicatorComponentType | null; + DownChevron?: ComponentType; + CrossIcon?: ComponentType; + Group?: ComponentType>; + GroupHeading?: ComponentType; + IndicatorsContainer?: ComponentType>; + IndicatorSeparator?: IndicatorComponentType | null; + Input?: ComponentType; + LoadingIndicator?: ComponentType> | null; + Menu?: ComponentType>; + MenuList?: ComponentType>; + MenuPortal?: ComponentType>; + LoadingMessage?: ComponentType>; + NoOptionsMessage?: ComponentType>; + MultiValue?: ComponentType>; + MultiValueContainer?: ComponentType; + MultiValueLabel?: ComponentType; + MultiValueRemove?: ComponentType; + Option?: ComponentType>; + Placeholder?: ComponentType>; + SelectContainer?: ComponentType>; + SingleValue?: ComponentType>; + ValueContainer?: ComponentType>; +} + +export namespace components { + const ClearIndicator: IndicatorComponentType | null; + const Control: ComponentType>; + const DropdownIndicator: IndicatorComponentType | null; + const DownChevron: ComponentType; + const CrossIcon: ComponentType; + const Group: ComponentType>; + const GroupHeading: ComponentType; + const IndicatorsContainer: ComponentType>; + const IndicatorSeparator: IndicatorComponentType | null; + const Input: ComponentType; + const LoadingIndicator: ComponentType> | null; + const Menu: ComponentType>; + const MenuList: ComponentType>; + const MenuPortal: ComponentType>; + const LoadingMessage: ComponentType>; + const NoOptionsMessage: ComponentType>; + const MultiValue: ComponentType>; + const MultiValueContainer: ComponentType; + const MultiValueLabel: ComponentType; + const MultiValueRemove: ComponentType; + const Option: ComponentType>; + const Placeholder: ComponentType>; + const SelectContainer: ComponentType>; + const SingleValue: ComponentType>; + const ValueContainer: ComponentType>; +} + +export interface Props { + components: SelectComponentsConfig; +} + +export function defaultComponents(props: Props): SelectComponentsConfig; diff --git a/types/react-select/lib/components/indicators.d.ts b/types/react-select/lib/components/indicators.d.ts new file mode 100644 index 0000000000..d27cc518da --- /dev/null +++ b/types/react-select/lib/components/indicators.d.ts @@ -0,0 +1,67 @@ +import { ComponentType, ReactElement as ElementType } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +// ============================== +// Dropdown & Clear Icons +// ============================== + +export function CrossIcon(props: any): any; // TODO svg type +export function DownChevron(props: any): any; // TODO svg type + +// ============================== +// Dropdown & Clear Buttons +// ============================== + +export type IndicatorProps = CommonProps & { + /** The children to be rendered inside the indicator. */ + children: ElementType, + /** Props that will be passed on to the children. */ + innerProps: any, + /** The focused state of the select. */ + isFocused: boolean, + /** Whether the text is right to left */ + isRtl: boolean, +}; + +export type baseCSS = (props: IndicatorProps) => any; // TODO css type + +export const dropdownIndicatorCSS: baseCSS; +export const DropdownIndicator: ComponentType>; + +export const clearIndicatorCSS: baseCSS; +export const ClearIndicator: ComponentType>; + +// ============================== +// Separator +// ============================== + +export interface SeparatorState { isDisabled: boolean; } + +export function indicatorSeparatorCSS(state: SeparatorState): any; // TODO css type + +export const IndicatorSeparator: ComponentType>; + +// ============================== +// Loading +// ============================== + +export function loadingIndicatorCSS(state: { + isFocused: boolean, + size: number, +}): any; // TODO css type + +export type LoadingIconProps = { + /** Props that will be passed on to the children. */ + innerProps: any, + /** The focused state of the select. */ + isFocused: boolean, + /** Whether the text is right to left */ + isRtl: boolean, +} & CommonProps & { + /** Set size of the container. */ + size: number, +}; +export const LoadingIndicator: ComponentType>; +// TODO LoadingIndicator.defaultProps: { size: number }; diff --git a/types/react-select/lib/diacritics.d.ts b/types/react-select/lib/diacritics.d.ts new file mode 100644 index 0000000000..855a0e152a --- /dev/null +++ b/types/react-select/lib/diacritics.d.ts @@ -0,0 +1 @@ +export function stripDiacritics(str: string): string; diff --git a/types/react-select/lib/filters.d.ts b/types/react-select/lib/filters.d.ts new file mode 100644 index 0000000000..33d1a7fddf --- /dev/null +++ b/types/react-select/lib/filters.d.ts @@ -0,0 +1,16 @@ +export interface Config { + ignoreCase?: boolean; + ignoreAccents?: boolean; + stringify?: (obj: any) => string; + trim?: boolean; + matchFrom?: 'any' | 'start'; +} + +import { stripDiacritics } from './diacritics'; + +export interface Option { label: string; value: string; data: any; } + +export function createFilter(config: Config | null): ( + option: Option, + rawInput: string +) => boolean; diff --git a/types/react-select/lib/stateManager.d.ts b/types/react-select/lib/stateManager.d.ts new file mode 100644 index 0000000000..07a17f52f7 --- /dev/null +++ b/types/react-select/lib/stateManager.d.ts @@ -0,0 +1,36 @@ +import { Component, ComponentType, Ref as ElementRef } from 'react'; + +import { ActionMeta, InputActionMeta, ValueType } from './types'; + +export interface Props { + defaultInputValue?: string; + defaultMenuIsOpen?: boolean; + defaultValue?: ValueType; + inputValue?: string; + menuIsOpen?: boolean; + value?: ValueType; +} +interface State { + inputValue: string; + menuIsOpen: boolean; + value: ValueType; +} + +export class StateManager extends Component, State> { + static defaultProps: Props; + + select: ElementRef; + + focus(): void; + blur(): void; + getProp(key: string): any; + callProp(name: string, ...args: any[]): any; + onChange: (value: any, actionMeta: ActionMeta) => void; + onInputChange: (value: any, actionMeta: InputActionMeta) => void; + onMenuOpen: () => void; + onMenuClose: () => void; +} + +export function manageState(SelectComponent: ComponentType): StateManager; + +export default manageState; diff --git a/types/react-select/lib/styles.d.ts b/types/react-select/lib/styles.d.ts new file mode 100644 index 0000000000..9c5178fed1 --- /dev/null +++ b/types/react-select/lib/styles.d.ts @@ -0,0 +1,99 @@ +import { + containerCSS, + indicatorsContainerCSS, + valueContainerCSS, +} from './components/containers'; +import { css as controlCSS } from './components/Control'; +import { groupCSS, groupHeadingCSS } from './components/Group'; +import { + clearIndicatorCSS, + dropdownIndicatorCSS, + loadingIndicatorCSS, + indicatorSeparatorCSS, +} from './components/indicators'; +import { inputCSS } from './components/Input'; +import { placeholderCSS } from './components/Placeholder'; +import { optionCSS } from './components/Option'; +import { + menuCSS, + menuListCSS, + menuPortalCSS, + noOptionsMessageCSS, + loadingMessageCSS, +} from './components/Menu'; +import { css as singleValueCSS } from './components/SingleValue'; +import { + multiValueCSS, + multiValueLabelCSS, + multiValueRemoveCSS, +} from './components/MultiValue'; + +export interface Props { [key: string]: any; } + +/** + * @param base -- the component's default style + * @param state -- the component's current state e.g. `isFocused` + * @returns + */ +export type styleFn = (base: any, state: any) => any; + +export interface Styles { + clearIndicator?: styleFn; + container?: styleFn; + control?: styleFn; + dropdownIndicator?: styleFn; + group?: styleFn; + groupHeading?: styleFn; + indicatorsContainer?: styleFn; + indicatorSeparator?: styleFn; + input?: styleFn; + loadingIndicator?: styleFn; + // TODO loadingMessageCSS?: styleFn; + loadingMessage?: styleFn; + menu?: styleFn; + menuList?: styleFn; + menuPortal?: styleFn; + multiValue?: styleFn; + multiValueLabel?: styleFn; + multiValueRemove?: styleFn; + // TODO noOptionsMessageCSS?: styleFn; + noOptionsMessage?: styleFn; + option?: styleFn; + placeholder?: styleFn; + singleValue?: styleFn; + valueContainer: styleFn; +} +export interface StylesConfig { + clearIndicator?: styleFn; + container?: styleFn; + control?: styleFn; + dropdownIndicator?: styleFn; + group?: styleFn; + groupHeading?: styleFn; + indicatorsContainer?: styleFn; + indicatorSeparator?: styleFn; + input?: styleFn; + loadingIndicator?: styleFn; + // TODO loadingMessageCSS?: styleFn; + loadingMessage?: styleFn; + menu?: styleFn; + menuList?: styleFn; + menuPortal?: styleFn; + multiValue?: styleFn; + multiValueLabel?: styleFn; + multiValueRemove?: styleFn; + // TODO noOptionsMessageCSS?: styleFn; + noOptionsMessage?: styleFn; + option?: styleFn; + placeholder?: styleFn; + singleValue?: styleFn; + valueContainer?: styleFn; +} +export type GetStyles = (a: string, b: Props) => any; + +export const defaultStyles: Styles; + +// Merge Utility +// Allows consumers to extend a base Select with additional styles + +export function mergeStyles(source: any, target: any): any; diff --git a/types/react-select/lib/theme.d.ts b/types/react-select/lib/theme.d.ts new file mode 100644 index 0000000000..7282dd20ad --- /dev/null +++ b/types/react-select/lib/theme.d.ts @@ -0,0 +1,53 @@ +export const borderRadius: number; + +export const colors: { + text: string; + textLight: string; + primary: string; + primary75: string; + primary50: string; + primary25: string; + danger: string; + dangerLight: string; + + neutral0: string; + neutral1: string; + neutral2: string; + neutral3: string; + neutral4: string; + neutral5: string; + neutral10: string; + neutral20: string; + neutral30: string; + neutral40: string; + neutral50: string; + neutral60: string; + neutral70: string; + neutral80: string; + neutral90: string; + neutral100: string; + + neutral1a: string; + neutral2a: string; + neutral3a: string; + neutral4a: string; + neutral5a: string; + neutral10a: string; + neutral20a: string; + neutral30a: string; + neutral40a: string; + neutral50a: string; + neutral60a: string; + neutral70a: string; + neutral80a: string; + neutral90a: string; +}; + +export const spacing: { + /* Used to calculate consistent margin/padding on elements */ + baseUnit: number, + /* The minimum height of the control */ + controlHeight: number, + /* The amount of space between the control and menu */ + menuGutter: number, +}; diff --git a/types/react-select/lib/types.d.ts b/types/react-select/lib/types.d.ts new file mode 100644 index 0000000000..08ebfae965 --- /dev/null +++ b/types/react-select/lib/types.d.ts @@ -0,0 +1,100 @@ +import * as React from 'react'; + +export type OptionsType = OptionType[]; + +export interface GroupType { + options: OptionsType; + [key: string]: any; +} + +export type GroupedOptionsType = Array>; + +export type ValueType = OptionType | OptionsType | null | undefined; + +export type FocusEventHandler = (event: React.FocusEvent) => void; +export type MouseEventHandler = (event: React.MouseEvent) => void; +export type KeyboardEventHandler = (event: React.KeyboardEvent) => void; + +export type InnerRef = React.Ref; +export interface PropsWithInnerRef { + /** The inner reference. */ + innerRef: React.Ref; +} + +export interface PropsWithStyles { + /* + Get the styles of a particular part of the select. Pass in the name of the + property as the first argument, and the current props as the second argument. + See the `styles` object for the properties available. + */ + getStyles: (name: string, props: any) => {}; +} + +export type ClassNameList = string[]; +export type ClassNamesState = { [key: string]: boolean } | undefined; + +export interface CommonProps { + clearValue: () => void; + className?: string; + cx: (a: string | null, b: ClassNamesState | undefined, c: string | undefined) => string | void; + /* + Get the styles of a particular part of the select. Pass in the name of the + property as the first argument, and the current props as the second argument. + See the `styles` object for the properties available. + */ + getStyles: (name: string, props: any) => {}; + getValue: () => ValueType; + hasValue: boolean; + isMulti: boolean; + options: OptionsType; + selectOption: (option: OptionType) => void; + selectProps: any; + setValue: (value: ValueType, action: ActionTypes) => void; +} + +export type ActionTypes = + | 'select-option' + | 'deselect-option' + | 'remove-value' + | 'pop-value' + | 'set-value' + | 'clear' + | 'create-option'; + +export interface ActionMeta { + action: ActionTypes; +} + +export type InputActionTypes = + | 'set-value' + | 'input-change' + | 'input-blur' + | 'menu-close'; + +export interface InputActionMeta { + action: InputActionTypes; +} + +export type MenuPlacement = 'auto' | 'bottom' | 'top'; +export type MenuPosition = 'absolute' | 'fixed'; + +export type FocusDirection = + | 'up' + | 'down' + | 'pageup' + | 'pagedown' + | 'first' + | 'last'; + +export type OptionProps = PropsWithInnerRef & { + data: any, + id: number, + index: number, + isDisabled: boolean, + isFocused: boolean, + isSelected: boolean, + label: string, + onClick: MouseEventHandler, + onMouseOver: MouseEventHandler, + value: any, +}; diff --git a/types/react-select/lib/utils.d.ts b/types/react-select/lib/utils.d.ts new file mode 100644 index 0000000000..c907d59c2a --- /dev/null +++ b/types/react-select/lib/utils.d.ts @@ -0,0 +1,121 @@ +import * as React from 'react'; +import { + ClassNamesState, + InputActionMeta, + OptionsType, + ValueType, +} from './types'; + +// ============================== +// NO OP +// ============================== + +export function noop(): void; +export function emptyString(): string; + +// ============================== +// Class Name Prefixer +// ============================== + +export function classNames( + prefix?: string | null, + cssKey?: string | null, + state?: ClassNamesState, + className?: string, +): string; + +// ============================== +// Clean Value +// ============================== + +export function cleanValue(value: ValueType): OptionsType; + +// ============================== +// Handle Input Change +// ============================== + +export function handleInputChange( + inputValue: string, + actionMeta: InputActionMeta, + onInputChange?: (inputValue: string, actionMeta: InputActionMeta) => string | void +): string; + +// ============================== +// Scroll Helpers +// ============================== + +export function isDocumentElement(el: Element): boolean; + +// Normalized Scroll Top +// ------------------------------ + +export function normalizedHeight(el: Element): number; + +// Normalized scrollTo & scrollTop +// ------------------------------ + +export function getScrollTop(el: Element): number; + +export function scrollTo(el: Element, top: number): void; + +// Get Scroll Parent +// ------------------------------ + +export function getScrollParent(element: React.Ref): Element; + +// Animated Scroll To +// ------------------------------ + +export function animatedScrollTo( + element: Element, + to: number, + duration: number, + callback: (element: Element) => void +): void; + +// Scroll Into View +// ------------------------------ + +export function scrollIntoView( + menuEl: HTMLElement, + focusedEl: HTMLElement +): void; + +// ============================== +// Get bounding client object +// ============================== + +// cannot get keys using array notation with DOMRect +export function getBoundingClientObj(element: HTMLElement): { + bottom: number; + height: number; + left: number; + right: number; + top: number; + width: number; +}; +export interface RectType { + left: number; + right: number; + bottom: number; + height: number; + width: number; +} + +// ============================== +// String to Key (kebabify) +// ============================== + +export function toKey(str: string): string; + +// ============================== +// Touch Capability Detector +// ============================== + +export function isTouchCapable(): boolean; + +// ============================== +// Mobile Device Detector +// ============================== + +export function isMobileDevice(): boolean; diff --git a/types/react-select/test/AtlaskitDummy.ts b/types/react-select/test/AtlaskitDummy.ts new file mode 100644 index 0000000000..e6e75e9e32 --- /dev/null +++ b/types/react-select/test/AtlaskitDummy.ts @@ -0,0 +1,11 @@ +export const Tooltip = (props: any) => null; + +export const EmojiIcon = (props: any) => null; + +export const EditorPanelIcon = (props: any) => null; + +export const Spinner = (props: any) => null; + +export const Button = (props: any) => null; + +export const Modal = (props: any) => null; diff --git a/types/react-select/test/ChronoNodeDummy.ts b/types/react-select/test/ChronoNodeDummy.ts new file mode 100644 index 0000000000..1e4aed01b0 --- /dev/null +++ b/types/react-select/test/ChronoNodeDummy.ts @@ -0,0 +1 @@ +export function parseDate(a: any): any {} diff --git a/types/react-select/test/data.ts b/types/react-select/test/data.ts new file mode 100644 index 0000000000..a4bff0225d --- /dev/null +++ b/types/react-select/test/data.ts @@ -0,0 +1,132 @@ +import { GroupedOptionsType, GroupType } from "react-select/lib/types"; + +export interface ColourOption { + value: string; + label: string; + color: string; + disabled?: boolean; +} + +export const colourOptions: ColourOption[] = [ + { value: 'ocean', label: 'Ocean', color: '#00B8D9' }, + { value: 'blue', label: 'Blue', color: '#0052CC', disabled: true }, + { value: 'purple', label: 'Purple', color: '#5243AA' }, + { value: 'red', label: 'Red', color: '#FF5630' }, + { value: 'orange', label: 'Orange', color: '#FF8B00' }, + { value: 'yellow', label: 'Yellow', color: '#FFC400' }, + { value: 'green', label: 'Green', color: '#36B37E' }, + { value: 'forest', label: 'Forest', color: '#00875A' }, + { value: 'slate', label: 'Slate', color: '#253858' }, + { value: 'silver', label: 'Silver', color: '#666666' }, +]; + +export interface FlavourOption { + value: string; + label: string; + rating: 'safe' | 'good' | 'wild' | 'crazy'; +} + +export const flavourOptions: FlavourOption[] = [ + { value: 'vanilla', label: 'Vanilla', rating: 'safe' }, + { value: 'chocolate', label: 'Chocolate', rating: 'good' }, + { value: 'strawberry', label: 'Strawberry', rating: 'wild' }, + { value: 'salted-caramel', label: 'Salted Caramel', rating: 'crazy' }, +]; + +export interface StateOption { + value: string; + label: string; +} + +export const stateOptions: StateOption[] = [ + { value: 'AL', label: 'Alabama' }, + { value: 'AK', label: 'Alaska' }, + { value: 'AS', label: 'American Samoa' }, + { value: 'AZ', label: 'Arizona' }, + { value: 'AR', label: 'Arkansas' }, + { value: 'CA', label: 'California' }, + { value: 'CO', label: 'Colorado' }, + { value: 'CT', label: 'Connecticut' }, + { value: 'DE', label: 'Delaware' }, + { value: 'DC', label: 'District Of Columbia' }, + { value: 'FM', label: 'Federated States Of Micronesia' }, + { value: 'FL', label: 'Florida' }, + { value: 'GA', label: 'Georgia' }, + { value: 'GU', label: 'Guam' }, + { value: 'HI', label: 'Hawaii' }, + { value: 'ID', label: 'Idaho' }, + { value: 'IL', label: 'Illinois' }, + { value: 'IN', label: 'Indiana' }, + { value: 'IA', label: 'Iowa' }, + { value: 'KS', label: 'Kansas' }, + { value: 'KY', label: 'Kentucky' }, + { value: 'LA', label: 'Louisiana' }, + { value: 'ME', label: 'Maine' }, + { value: 'MH', label: 'Marshall Islands' }, + { value: 'MD', label: 'Maryland' }, + { value: 'MA', label: 'Massachusetts' }, + { value: 'MI', label: 'Michigan' }, + { value: 'MN', label: 'Minnesota' }, + { value: 'MS', label: 'Mississippi' }, + { value: 'MO', label: 'Missouri' }, + { value: 'MT', label: 'Montana' }, + { value: 'NE', label: 'Nebraska' }, + { value: 'NV', label: 'Nevada' }, + { value: 'NH', label: 'New Hampshire' }, + { value: 'NJ', label: 'New Jersey' }, + { value: 'NM', label: 'New Mexico' }, + { value: 'NY', label: 'New York' }, + { value: 'NC', label: 'North Carolina' }, + { value: 'ND', label: 'North Dakota' }, + { value: 'MP', label: 'Northern Mariana Islands' }, + { value: 'OH', label: 'Ohio' }, + { value: 'OK', label: 'Oklahoma' }, + { value: 'OR', label: 'Oregon' }, + { value: 'PW', label: 'Palau' }, + { value: 'PA', label: 'Pennsylvania' }, + { value: 'PR', label: 'Puerto Rico' }, + { value: 'RI', label: 'Rhode Island' }, + { value: 'SC', label: 'South Carolina' }, + { value: 'SD', label: 'South Dakota' }, + { value: 'TN', label: 'Tennessee' }, + { value: 'TX', label: 'Texas' }, + { value: 'UT', label: 'Utah' }, + { value: 'VT', label: 'Vermont' }, + { value: 'VI', label: 'Virgin Islands' }, + { value: 'VA', label: 'Virginia' }, + { value: 'WA', label: 'Washington' }, + { value: 'WV', label: 'West Virginia' }, + { value: 'WI', label: 'Wisconsin' }, + { value: 'WY', label: 'Wyoming' }, +]; + +export const optionLength = [ + { value: 1, label: 'general' }, + { + value: 2, + label: + 'Evil is the moment when I lack the strength to be true to the Good that compels me.', + }, + { + value: 3, + label: + // tslint:disable-next-line:max-line-length + "It is now an easy matter to spell out the ethic of a truth: 'Do all that you can to persevere in that which exceeds your perseverance. Persevere in the interruption. Seize in your being that which has seized and broken you.", + }, +]; + +// let bigOptions = []; +// for (let i = 0; i < 10000; i++) { +// bigOptions = bigOptions.concat(colourOptions); +// } + +const colourGroup: GroupType = { + label: 'Colours', + options: colourOptions +}; +const flavourGroup: GroupType = { + label: 'Flavours', + options: flavourOptions, +}; + +export const groupedOptions: GroupedOptionsType = [ colourGroup, flavourGroup ]; diff --git a/types/react-select/test/examples/AccessingInternals.tsx b/types/react-select/test/examples/AccessingInternals.tsx new file mode 100644 index 0000000000..8948bc19e7 --- /dev/null +++ b/types/react-select/test/examples/AccessingInternals.tsx @@ -0,0 +1,114 @@ +import * as React from 'react'; + +import Select from 'react-select'; +import AsyncSelect from 'react-select/lib/Async'; +import CreatableSelect from 'react-select/lib/Creatable'; +import { Note } from '../styled-components'; +import { ColourOption, colourOptions } from '../data'; + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class AccessingInterals extends React.Component { + selectRef: Select; + asyncRef: AsyncSelect; + creatableRef: CreatableSelect; + focus = () => { + console.log(this.selectRef); + this.selectRef.focus(); + } + focusCreatable = () => { + console.log(this.creatableRef); + this.creatableRef.focus(); + } + focusAsync = () => { + console.log(this.asyncRef); + this.asyncRef.focus(); + } + blurAsync = () => { + this.asyncRef.blur(); + } + blurCreatable = () => { + this.creatableRef.blur(); + } + blur = () => this.selectRef.blur(); + onSelectRef = (ref: any) => { + console.log(ref); + this.selectRef = ref; + } + render() { + return ( + +

+ Creatable Select +

+ { this.creatableRef = ref; }} + isClearable + options={colourOptions} + /> + + + + + + +

+ Async Select +

+ { this.asyncRef = ref; }} + cacheOptions + defaultOptions + loadOptions={promiseOptions} + /> + + + + + + +

Select

+ +); diff --git a/types/react-select/test/examples/BasicSingle.tsx b/types/react-select/test/examples/BasicSingle.tsx new file mode 100644 index 0000000000..69697566c2 --- /dev/null +++ b/types/react-select/test/examples/BasicSingle.tsx @@ -0,0 +1,101 @@ +import * as React from 'react'; + +import Select from 'react-select'; +import { colourOptions } from '../data'; +import { Note } from '../styled-components'; + +const Checkbox = (props: any) => ; + +interface State { + isClearable: boolean; + isDisabled: boolean; + isLoading: boolean; + isRtl: boolean; + isSearchable: boolean; +} + +export default class SingleSelect extends React.Component { + state = { + isClearable: true, + isDisabled: false, + isLoading: false, + isRtl: false, + isSearchable: true, + }; + + toggleClearable = () => + this.setState(state => ({ isClearable: !state.isClearable })) + toggleDisabled = () => + this.setState(state => ({ isDisabled: !state.isDisabled })) + toggleLoading = () => + this.setState(state => ({ isLoading: !state.isLoading })) + toggleRtl = () => this.setState(state => ({ isRtl: !state.isRtl })); + toggleSearchable = () => + this.setState(state => ({ isSearchable: !state.isSearchable })) + render() { + const { + isClearable, + isSearchable, + isDisabled, + isLoading, + isRtl, + } = this.state; + return ( + + ; + +interface State { + menuIsOpen: boolean; +} + +export default class controlledMenu extends React.Component { + state = { + menuIsOpen: false, + }; + toggleMenuIsOpen = () => + this.setState(state => ({ menuIsOpen: !state.menuIsOpen })) + render() { + const { menuIsOpen } = this.state; + return ( + + ; + +interface State { + ignoreCase: boolean; + ignoreAccents: boolean; + trim: boolean; + matchFromStart: boolean; +} + +export default class SelectCreateFilter extends React.Component { + state: State = { + ignoreCase: false, + ignoreAccents: false, + trim: false, + matchFromStart: false, + }; + toggleOption = (key: string) => () => { + this.setState((state: any) => ({ ...state, [key]: !state[key] })); + } + render() { + const { + ignoreCase, + ignoreAccents, + trim, + matchFromStart, + } = this.state; + + const filterConfig = { + ignoreCase, + ignoreAccents, + trim, + matchFrom: this.state.matchFromStart ? ('start' as 'start') : ('any' as 'any'), + }; + + return ( + + + ); +} diff --git a/types/react-select/test/examples/CustomControl.tsx b/types/react-select/test/examples/CustomControl.tsx new file mode 100644 index 0000000000..3ed018e05e --- /dev/null +++ b/types/react-select/test/examples/CustomControl.tsx @@ -0,0 +1,32 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; +const controlStyles = { + borderRadius: '1px solid black', + padding: '5px', + background: colourOptions[2].color, + color: 'white' +}; + +const ControlComponent = (props: any) => ( +
+ {

Custom Control

} + +
+); + +export default class CustomControl extends React.Component { + render() { + return ( + +); diff --git a/types/react-select/test/examples/CustomFilterOptions.tsx b/types/react-select/test/examples/CustomFilterOptions.tsx new file mode 100644 index 0000000000..62a13f2a89 --- /dev/null +++ b/types/react-select/test/examples/CustomFilterOptions.tsx @@ -0,0 +1,34 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; + +interface State { + ignoreCase: boolean; + ignoreAccents: boolean; + trim: boolean; + matchFrom: boolean; +} + +const filterOptions = (candidate: any, input: string) => { + if (input) { + return candidate.value === customOptions[0].value; + } + return true; +}; + +const customOptions = [{ value: 'custom', label: 'Using a custom filter to always display this option on search' }, ...colourOptions]; + +export default class SelectCreateFilter extends React.Component { + render() { + return ( + +
+ ); + } +} diff --git a/types/react-select/test/examples/CustomGroup.tsx b/types/react-select/test/examples/CustomGroup.tsx new file mode 100644 index 0000000000..7085e2901c --- /dev/null +++ b/types/react-select/test/examples/CustomGroup.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +const groupStyles = { + border: `2px dotted ${colourOptions[2].color}`, + borderRadius: '5px', + background: '#f2fcff' +}; + +const Group = (props: any) => ( +
+ +
+); + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ Group }} + /> +); diff --git a/types/react-select/test/examples/CustomGroupHeading.tsx b/types/react-select/test/examples/CustomGroupHeading.tsx new file mode 100644 index 0000000000..abf09de9ef --- /dev/null +++ b/types/react-select/test/examples/CustomGroupHeading.tsx @@ -0,0 +1,31 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; +import { EditorPanelIcon, Tooltip } from '../AtlaskitDummy'; + +const groupStyles = { + border: `2px dotted ${colourOptions[2].color}`, + color: 'white', + background: colourOptions[2].color, + padding: '5px 0px', + display: 'flex', +}; + +const GroupHeading = (props: any) => ( +
+ + + + +
+); + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ GroupHeading }} + styles={{ groupHeading: (base: any) => ({ ...base, flex: '1 1', color: 'white', margin: 0 }) }} + /> +); diff --git a/types/react-select/test/examples/CustomIndicatorSeparator.tsx b/types/react-select/test/examples/CustomIndicatorSeparator.tsx new file mode 100644 index 0000000000..c63d4a0f0e --- /dev/null +++ b/types/react-select/test/examples/CustomIndicatorSeparator.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; + +const indicatorSeparatorStyle = { + alignSelf: 'stretch', + backgroundColor: colourOptions[2].color, + marginBottom: 8, + marginTop: 8, + width: 1, +}; + +const IndicatorSeparator = ({ innerProps }: any) => { + return ( + + ); +}; + +export default () => ( + +); diff --git a/types/react-select/test/examples/CustomInput.tsx b/types/react-select/test/examples/CustomInput.tsx new file mode 100644 index 0000000000..e2bd0eb7d6 --- /dev/null +++ b/types/react-select/test/examples/CustomInput.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const Input = (props: any) => { + if (props.isHidden) { + return ; + } + return ( +
+ + + +
+ ); +}; + +export default () => ( + option.rating !== 'safe'} + /> +
+ ); + } +} diff --git a/types/react-select/test/examples/CustomLoadingIndicator.tsx b/types/react-select/test/examples/CustomLoadingIndicator.tsx new file mode 100644 index 0000000000..627599d52a --- /dev/null +++ b/types/react-select/test/examples/CustomLoadingIndicator.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import { Spinner, Tooltip } from '../AtlaskitDummy'; +import AsyncSelect from 'react-select/lib/Async'; +import { colourOptions } from '../data'; + +const LoadingIndicator = (props: any) => { + return ( + + + + ); +}; + +interface State { + inputValue: string; +} + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class CustomLoadingIndicator extends React.Component { + state = { inputValue: '' }; + handleInputChange = (newValue: string) => { + const inputValue = newValue.replace(/\W/g, ''); + this.setState({ inputValue }); + return inputValue; + } + render() { + return ( + + ); + } +} diff --git a/types/react-select/test/examples/CustomLoadingMessage.tsx b/types/react-select/test/examples/CustomLoadingMessage.tsx new file mode 100644 index 0000000000..04776ebfd6 --- /dev/null +++ b/types/react-select/test/examples/CustomLoadingMessage.tsx @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import AsyncSelect from 'react-select/lib/Async'; +import { colourOptions } from '../data'; + +const LoadingMessage = (props: any) => { + return ( + +
+ {props.children} +
+
+ ); +}; + +interface State { + inputValue: string; +} + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class CustomLoadingIndicator extends React.Component { + state = { inputValue: '' }; + handleInputChange = (newValue: string) => { + const inputValue = newValue.replace(/\W/g, ''); + this.setState({ inputValue }); + return inputValue; + } + render() { + return ( + ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }} + components={{ LoadingMessage }} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomMenu.tsx b/types/react-select/test/examples/CustomMenu.tsx new file mode 100644 index 0000000000..b774a7fa1e --- /dev/null +++ b/types/react-select/test/examples/CustomMenu.tsx @@ -0,0 +1,37 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +function getLength(options: any) { + return options.reduce((acc: any, curr: any) => { + if (curr.options) return acc + getLength(curr.options); + return acc + 1; + }, 0); +} + +const menuHeaderStyle = { + padding: '8px 12px', +}; + +const Menu = (props: any) => { + const optionsLength = getLength(props.options); + return ( + +
+ Custom Menu with {optionsLength} options +
+ + {props.children} + +
+ ); +}; + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ Menu }} + /> +); diff --git a/types/react-select/test/examples/CustomMenuList.tsx b/types/react-select/test/examples/CustomMenuList.tsx new file mode 100644 index 0000000000..48a3cf62f7 --- /dev/null +++ b/types/react-select/test/examples/CustomMenuList.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +const menuHeaderStyle = { + padding: '8px 12px', + background: colourOptions[2].color, + color: 'white', +}; + +const MenuList = (props: any) => { + return ( + +
+ Custom Menu List +
+ {props.children} +
+ ); +}; + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ MenuList }} + /> +); diff --git a/types/react-select/test/examples/CustomMultiValueContainer.tsx b/types/react-select/test/examples/CustomMultiValueContainer.tsx new file mode 100644 index 0000000000..1b556751e1 --- /dev/null +++ b/types/react-select/test/examples/CustomMultiValueContainer.tsx @@ -0,0 +1,23 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const MultiValueContainer = (props: any) => { + return ( + + + + ); +}; + +export default () => ( + ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }} + defaultValue={[colourOptions[4], colourOptions[5]]} + isMulti + options={colourOptions} + /> +); diff --git a/types/react-select/test/examples/CustomMultiValueRemove.tsx b/types/react-select/test/examples/CustomMultiValueRemove.tsx new file mode 100644 index 0000000000..81dfaf35e9 --- /dev/null +++ b/types/react-select/test/examples/CustomMultiValueRemove.tsx @@ -0,0 +1,25 @@ +import * as React from 'react'; +import { EmojiIcon, Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const MultiValueRemove = (props: any) => { + return ( + + + + + + ); +}; + +export default () => ( + ({ ...base, ...msgStyles }) }} + isSearchable + name="color" + options={[]} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomOption.tsx b/types/react-select/test/examples/CustomOption.tsx new file mode 100644 index 0000000000..aa115e78bf --- /dev/null +++ b/types/react-select/test/examples/CustomOption.tsx @@ -0,0 +1,22 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const Option = (props: any) => { + return ( + + + + ); +}; + +export default () => ( + ({ ...base, fontSize: '1em', color: colourOptions[2].color, fontWeight: 400 }) }} + options={colourOptions} + /> +); diff --git a/types/react-select/test/examples/CustomSelectContainer.tsx b/types/react-select/test/examples/CustomSelectContainer.tsx new file mode 100644 index 0000000000..393b8d1dd8 --- /dev/null +++ b/types/react-select/test/examples/CustomSelectContainer.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; +import Select, { components } from 'react-select'; +import { Tooltip } from '../AtlaskitDummy'; +import { colourOptions } from '../data'; + +const SelectContainer = ({ children, ...props }: any) => { + return ( + + + {children} + + + ); +}; + +export default () => ( + ({ ...base, padding: 5, borderRadius: 5, background: colourOptions[2].color, color: 'white', display: 'flex' }) }} + components={{ SingleValue }} + isSearchable + name="color" + options={colourOptions} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomValueContainer.tsx b/types/react-select/test/examples/CustomValueContainer.tsx new file mode 100644 index 0000000000..31d18ef50b --- /dev/null +++ b/types/react-select/test/examples/CustomValueContainer.tsx @@ -0,0 +1,28 @@ +import * as React from 'react'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const ValueContainer = ({ children, ...props }: any) => ( + + {children} + +); + +export default class CustomControl extends React.Component { + render() { + return ( + v.some(i => i.date.isSame(o.date, 'day'))} + maxMenuHeight={380} + onChange={this.props.onChange} + onInputChange={this.handleInputChange} + options={options} + value={value} + /> + ); + } +} + +export default class Experimental extends React.Component { + state = { + value: defaultOptions[0], + }; + handleChange = (value: any) => { + this.setState({ value }); + } + render() { + const { value } = this.state; + const displayValue = value && value.value ? value.value.toString() : 'null'; + return ( +
+
Value: {displayValue}
+ +
+ ); + } +} diff --git a/types/react-select/test/examples/MenuPortal.tsx b/types/react-select/test/examples/MenuPortal.tsx new file mode 100644 index 0000000000..32590acfb1 --- /dev/null +++ b/types/react-select/test/examples/MenuPortal.tsx @@ -0,0 +1,91 @@ +import * as React from 'react'; +import { Modal, Button } from '../AtlaskitDummy'; +import Select from 'react-select'; +import { H1, Note } from '../styled-components'; + +import { colourOptions } from '../data'; + +interface State { + isOpen: boolean; + isFixed: boolean; + portalPlacement: 'auto' | 'bottom' | 'top'; +} + +export default class MenuPortal extends React.Component { + state: State = { + isOpen: false, + isFixed: false, + portalPlacement: 'bottom', + }; + open = () => { + console.log('menuPortal is Open'); + this.setState({ isOpen: true }); + } + close = () => { this.setState({ isOpen: false }); }; + setPlacement = ({ currentTarget }: any) => { + const portalPlacement = currentTarget && currentTarget.value; + this.setState({ portalPlacement }); + } + toggleMode = () => { + this.setState(state => ({ isFixed: !state.isFixed })); + } + render() { + const { close, open } = this; + const { isOpen, isFixed, portalPlacement } = this.state; + return ( + + + { + isOpen ? + +

Portaled Menu Element

+ + + + + + + + + Fixed + + + + Portal + +
+ : null + } +
+ ); + } +} diff --git a/types/react-select/test/examples/OnSelectResetsInput.tsx b/types/react-select/test/examples/OnSelectResetsInput.tsx new file mode 100644 index 0000000000..af1327b1bb --- /dev/null +++ b/types/react-select/test/examples/OnSelectResetsInput.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; +import { InputActionMeta } from 'react-select/lib/types'; + +export default class OnSelectResetsInput extends React.Component { + state = { + inputValue: '', + menuIsOpen: undefined + }; + onInputChange = (inputValue: string, { action }: InputActionMeta) => { + console.log(inputValue, action); + switch (action) { + case 'input-change': + this.setState({ inputValue }); + return; + case 'menu-close': + console.log(this.state.inputValue); + let menuIsOpen; + if (this.state.inputValue) { + menuIsOpen = true; + } + this.setState({ + menuIsOpen + }); + return; + default: + return; + } + } + render() { + const { inputValue, menuIsOpen } = this.state; + return ( + + + ); + } +} + +// styled components + +const Menu = (props: any) => { + const shadow = colors.neutral10a; + return ( +
+ ); +}; +const Blanket = (props: any) => ( +
+); +const Dropdown = ({ children, isOpen, target, onClose }: any) => ( +
// TODO css type + {target} + {isOpen ? {children} : null} + {isOpen ? : null} +
+); +const Svg = (p: any) => ( + +); +const DropdownIndicator = () => ( +
// TODO css type + + + +
+); +const ChevronDown = () => ( + + + +); diff --git a/types/react-select/test/examples/StyledMulti.tsx b/types/react-select/test/examples/StyledMulti.tsx new file mode 100644 index 0000000000..a4dedb4156 --- /dev/null +++ b/types/react-select/test/examples/StyledMulti.tsx @@ -0,0 +1,53 @@ +import * as React from 'react'; +import * as chroma from 'chroma-js'; + +import { colourOptions } from '../data'; +import Select from 'react-select'; + +const colourStyles = { + control: (styles: any) => ({ ...styles, backgroundColor: 'white' }), + option: (styles: any, { data, isDisabled, isFocused, isSelected }: any) => { + const color = chroma(data.color); + return { + ...styles, + backgroundColor: isDisabled + ? null + : isSelected ? data.color : isFocused ? color.alpha(0.1).css() : null, + color: isDisabled + ? '#ccc' + : isSelected + ? chroma.contrast(color, 'white') > 2 ? 'white' : 'black' + : data.color, + cursor: isDisabled ? 'not-allowed' : 'default', + }; + }, + multiValue: (styles: any, { data }: any) => { + const color = chroma(data.color); + return { + ...styles, + backgroundColor: color.alpha(0.1).css(), + }; + }, + multiValueLabel: (styles: any, { data }: any) => ({ + ...styles, + color: data.color, + }), + multiValueRemove: (styles: any, { data }: any) => ({ + ...styles, + color: data.color, + ':hover': { + backgroundColor: data.color, + color: 'white', + }, + }), +}; + +export default () => ( + +); diff --git a/types/react-select/test/styled-components.tsx b/types/react-select/test/styled-components.tsx new file mode 100644 index 0000000000..fa18465cd8 --- /dev/null +++ b/types/react-select/test/styled-components.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; + +export const Note = ({ Tag = 'div', ...props }: any) => ( + +); + +export const H1 = (props: any) =>

; +export const H2 = (props: any) =>

; diff --git a/types/react-select/tsconfig.json b/types/react-select/tsconfig.json index 7855eceaf1..8c7a1921bd 100644 --- a/types/react-select/tsconfig.json +++ b/types/react-select/tsconfig.json @@ -1,10 +1,4 @@ { - "files": [ - "index.d.ts", - "lib/Option/index.d.ts", - "lib/utils/defaultMenuRenderer/index.d.ts", - "react-select-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -12,16 +6,99 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "jsx": "react", "typeRoots": [ "../" ], + "jsx": "react", "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "lib/animated/Input.d.ts", + "lib/animated/MultiValue.d.ts", + "lib/animated/Placeholder.d.ts", + "lib/animated/SingleValue.d.ts", + "lib/animated/ValueContainer.d.ts", + "lib/animated/transitions.d.ts", + "lib/animated/index.d.ts", + "lib/components/containers.d.ts", + "lib/components/Control.d.ts", + "lib/components/Group.d.ts", + "lib/components/Input.d.ts", + "lib/components/Menu.d.ts", + "lib/components/MultiValue.d.ts", + "lib/components/Option.d.ts", + "lib/components/Placeholder.d.ts", + "lib/components/SingleValue.d.ts", + "lib/components/indicators.d.ts", + "lib/components/index.d.ts", + "lib/accessibility/index.d.ts", + "lib/theme.d.ts", + "lib/Creatable.d.ts", + "lib/Async.d.ts", + "lib/AsyncCreatable.d.ts", + "lib/filters.d.ts", + "lib/styles.d.ts", + "lib/stateManager.d.ts", + "lib/builtins.d.ts", + "lib/utils.d.ts", + "lib/diacritics.d.ts", + "lib/types.d.ts", + "lib/Select.d.ts", + "test/data.ts", + "test/styled-components.tsx", + "test/AtlaskitDummy.ts", + "test/ChronoNodeDummy.ts", + "test/examples/AccessingInternals.tsx", + "test/examples/AnimatedMulti.tsx", + "test/examples/AsyncCallbacks.tsx", + "test/examples/AsyncCreatable.tsx", + "test/examples/AsyncMulti.tsx", + "test/examples/AsyncPromises.tsx", + "test/examples/BasicGrouped.tsx", + "test/examples/BasicMulti.tsx", + "test/examples/BasicSingle.tsx", + "test/examples/ControlledMenu.tsx", + "test/examples/CreatableAdvanced.tsx", + "test/examples/CreatableInputOnly.tsx", + "test/examples/CreatableMulti.tsx", + "test/examples/CreatableSingle.tsx", + "test/examples/CreateFilter.tsx", + "test/examples/CustomClearIndicator.tsx", + "test/examples/CustomControl.tsx", + "test/examples/CustomDropdownIndicator.tsx", + "test/examples/CustomFilterOptions.tsx", + "test/examples/CustomGetOptionLabel.tsx", + "test/examples/CustomGroup.tsx", + "test/examples/CustomGroupHeading.tsx", + "test/examples/CustomIndicatorsContainer.tsx", + "test/examples/CustomIndicatorSeparator.tsx", + "test/examples/CustomInput.tsx", + "test/examples/CustomIsOptionDisabled.tsx", + "test/examples/CustomLoadingIndicator.tsx", + "test/examples/CustomLoadingMessage.tsx", + "test/examples/CustomMenu.tsx", + "test/examples/CustomMenuList.tsx", + "test/examples/CustomMultiValueContainer.tsx", + "test/examples/CustomMultiValueLabel.tsx", + "test/examples/CustomMultiValueRemove.tsx", + "test/examples/CustomNoOptionsMessage.tsx", + "test/examples/CustomOption.tsx", + "test/examples/CustomPlaceholder.tsx", + "test/examples/CustomSelectContainer.tsx", + "test/examples/CustomSingleValue.tsx", + "test/examples/CustomValueContainer.tsx", + "test/examples/Experimental.tsx", + "test/examples/MenuPortal.tsx", + "test/examples/OnSelectResetsInput.tsx", + "test/examples/Popout.tsx", + "test/examples/StyledMulti.tsx", + "test/examples/StyledSingle.tsx" + ] } diff --git a/types/react-select/tslint.json b/types/react-select/tslint.json index 3db14f85ea..f93cf8562a 100644 --- a/types/react-select/tslint.json +++ b/types/react-select/tslint.json @@ -1 +1,3 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-select/v1/index.d.ts b/types/react-select/v1/index.d.ts new file mode 100644 index 0000000000..31ff0db561 --- /dev/null +++ b/types/react-select/v1/index.d.ts @@ -0,0 +1,654 @@ +// Type definitions for react-select 1.3 +// Project: https://github.com/JedWatson/react-select +// Definitions by: ESQUIBET Hugo +// Gilad Gray +// Izaak Baker +// Tadas Dailyda +// Mark Vujevits +// Mike Deverell +// MartynasZilinskas +// Onat Yigit Mercan +// Ian Johnson +// Anton Novik +// David Schkalee +// Arthur Udalov +// Sebastian Silbermann +// Endurance Idehen +// Guillaume Chartier +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import * as React from 'react'; + +export default class ReactSelectClass extends React.Component> { + focus(): void; + setValue(value: Option): void; +} +// Other components +export class Creatable extends React.Component> { } +export class Async extends React.Component> { } +export class AsyncCreatable extends React.Component> { } + +export type OptionComponentType = React.ComponentType>; +export type ValueComponentType = React.ComponentType>; + +export type HandlerRendererResult = JSX.Element | null | false; + +// Handlers +export type FocusOptionHandler = (option: Option) => void; +export type SelectValueHandler = (option: Option) => void; +export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; +export type ClearRendererHandler = () => HandlerRendererResult; +export type FilterOptionHandler = (option: Option, filter: string) => boolean; +export type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; +export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; +export type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; +export type OnCloseHandler = () => void; +export type OnInputChangeHandler = (inputValue: string) => string; +export type OnInputKeyDownHandler = React.KeyboardEventHandler; +export type OnMenuScrollToBottomHandler = () => void; +export type OnOpenHandler = () => void; +export type OnFocusHandler = React.FocusEventHandler; +export type OnBlurHandler = React.FocusEventHandler; +export type OptionRendererHandler = (option: Option) => HandlerRendererResult; +export type ValueRendererHandler = (option: Option, index?: number) => HandlerRendererResult; +export type OnValueClickHandler = (option: Option, event: React.MouseEvent) => void; +export type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; +export type IsValidNewOptionHandler = (arg: { label: string }) => boolean; +export type NewOptionCreatorHandler = (arg: { label: string, labelKey: string, valueKey: string }) => Option; +export type PromptTextCreatorHandler = (filterText: string) => string; +export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean; + +export type OnChangeSingleHandler = OnChangeHandler>; +export type OnChangeMultipleHandler = OnChangeHandler>; +export type OnChangeHandler | Options> = (newValue: TOption | null) => void; +export type OnNewOptionClickHandler = (option: Option) => void; + +export type LoadOptionsHandler = LoadOptionsAsyncHandler | LoadOptionsLegacyHandler; +export type LoadOptionsAsyncHandler = (input: string) => Promise>; +export type LoadOptionsLegacyHandler = (input: string, callback: (err: any, result: AutocompleteResult) => void) => void; + +export interface AutocompleteResult { + /** The search-results to be displayed */ + options: Options; + /** + * Should be set to true, if and only if a longer query with the same prefix + * would return a subset of the results + * If set to true, more specific queries will not be sent to the server. + */ + complete: boolean; +} + +export type Options = Array>; + +export interface Option { + /** Text for rendering */ + label?: string; + /** Value for searching */ + value?: TValue; + /** + * Allow this option to be cleared + * @default true + */ + clearableValue?: boolean; + /** + * Do not allow this option to be selected + * @default false + */ + disabled?: boolean; + /** + * In the event that a custom menuRenderer is provided, Option should be able + * to accept arbitrary key-value pairs. See react-virtualized-select. + */ + [property: string]: any; +} + +export type OptionValues = string | number | boolean; + +export interface MenuRendererProps { + /** + * The currently focused option; should be visible in the menu by default. + * default {} + */ + focusedOption: Option; + + /** + * Callback to focus a new option; receives the option as a parameter. + */ + focusOption: FocusOptionHandler; + + /** + * Option labels are accessible with this string key. + */ + labelKey: string; + + /** + * Ordered array of options to render. + */ + options: Options; + + /** + * Callback to select a new option; receives the option as a parameter. + */ + selectValue: SelectValueHandler; + + /** + * Array of currently selected options. + */ + valueArray: Options; + + /** + * Callback to remove selection from option; receives the option as a parameter. + */ + removeValue: SelectValueHandler; + + /** + * function which returns a custom way to render the options in the menu + */ + optionRenderer: OptionRendererHandler; +} + +export interface OptionComponentProps { + /** + * Classname(s) to apply to the option component. + */ + className?: string; + + /** + * Currently focused option. + */ + focusOption?: Option; + + inputValue?: string; + instancePrefix?: string; + + /** + * True if this option is disabled. + */ + isDisabled?: boolean; + + /** + * True if this option is focused. + */ + isFocused?: boolean; + + /** + * True if this option is selected. + */ + isSelected?: boolean; + + /** + * Callback to be invoked when this option is focused. + */ + onFocus?: (option: Option, event: any) => void; + + /** + * Callback to be invoked when this option is selected. + */ + onSelect?: (option: Option, event: any) => void; + + /** + * Option to be rendered by this component. + */ + option: Option; + + /** + * Index of the option being rendered in the list + */ + optionIndex?: number; + + /** + * Callback to invoke when removing an option from a multi-selection. (Not necessarily the one + * being rendered) + */ + removeValue?: (value: TValue | TValue[]) => void; + + /** + * Callback to invoke to select an option. (Not necessarily the one being rendered) + */ + selectValue?: (value: TValue | TValue[]) => void; +} + +export interface ArrowRendererProps { + /** + * Arrow mouse down event handler. + */ + onMouseDown: React.MouseEventHandler; + + /** + * whether the Select is open or not. + */ + isOpen: boolean; +} + +export interface ValueComponentProps { + disabled: ReactSelectProps['disabled']; + id: string; + instancePrefix: string; + onClick: OnValueClickHandler | null; + onRemove?: SelectValueHandler; + placeholder: ReactSelectProps['placeholder']; + value: Option; + values?: Array>; +} + +export interface ReactSelectProps extends React.Props> { + /** + * text to display when `allowCreate` is true. + * @default 'Add "{label}"?' + */ + addLabelText?: string; + /** + * renders a custom drop-down arrow to be shown in the right-hand side of the select. + * @default undefined + */ + arrowRenderer?: ArrowRendererHandler | null; + /** + * blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices. + * @default false + */ + autoBlur?: boolean; + /** + * autofocus the component on mount + * @deprecated. Use autoFocus instead + * @default false + */ + autofocus?: boolean; + /** + * autofocus the component on mount + * @default false + */ + autoFocus?: boolean; + /** + * If enabled, the input will expand as the length of its value increases + */ + autosize?: boolean; + /** + * whether pressing backspace removes the last item when there is no input value + * @default true + */ + backspaceRemoves?: boolean; + /** + * Message to use for screenreaders to press backspace to remove the current item + * {label} is replaced with the item label + * @default "Press backspace to remove..." + */ + backspaceToRemoveMessage?: string; + /** + * CSS className for the outer element + */ + className?: string; + /** + * Prefix prepended to element default className if no className is defined + */ + classNamePrefix?: string; + /** + * title for the "clear" control when `multi` is true + * @default "Clear all" + */ + clearAllText?: string; + /** + * Renders a custom clear to be shown in the right-hand side of the select when clearable true + * @default undefined + */ + clearRenderer?: ClearRendererHandler; + /** + * title for the "clear" control + * @default "Clear value" + */ + clearValueText?: string; + /** + * whether to close the menu when a value is selected + * @default true + */ + closeOnSelect?: boolean; + /** + * whether it is possible to reset value. if enabled, an X button will appear at the right side. + * @default true + */ + clearable?: boolean; + /** + * whether backspace removes an item if there is no text input + * @default true + */ + deleteRemoves?: boolean; + /** + * delimiter to use to join multiple values + * @default "," + */ + delimiter?: string; + /** + * whether the Select is disabled or not + * @default false + */ + disabled?: boolean; + /** + * whether escape clears the value when the menu is closed + * @default true + */ + escapeClearsValue?: boolean; + /** + * method to filter a single option + */ + filterOption?: FilterOptionHandler; + /** + * method to filter the options array + */ + filterOptions?: FilterOptionsHandler; + /** + * id for the underlying HTML input element + * @default undefined + */ + id?: string; + /** + * whether to strip diacritics when filtering + * @default true + */ + ignoreAccents?: boolean; + /** + * whether to perform case-insensitive filtering + * @default true + */ + ignoreCase?: boolean; + /** + * custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} + * @default {} + */ + inputProps?: { [key: string]: any }; + /** + * renders a custom input + */ + inputRenderer?: InputRendererHandler; + /** + * allows for synchronization of component id's on server and client. + * @see https://github.com/JedWatson/react-select/pull/1105 + */ + instanceId?: string; + /** + * whether the Select is loading externally or not (such as options being loaded). + * if true, a loading spinner will be shown at the right side. + * @default false + */ + isLoading?: boolean; + /** + * (legacy mode) joins multiple values into a single form field with the delimiter + * @default false + */ + joinValues?: boolean; + /** + * the option property to use for the label + * @default "label" + */ + labelKey?: string; + /** + * (any, start) match the start or entire string when filtering + * @default "any" + */ + matchPos?: string; + /** + * (any, label, value) which option property to filter on + * @default "any" + */ + matchProp?: string; + /** + * buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport + * @default 0 + */ + menuBuffer?: number; + /** + * optional style to apply to the menu container + */ + menuContainerStyle?: React.CSSProperties; + /** + * renders a custom menu with options + */ + menuRenderer?: MenuRendererHandler; + /** + * optional style to apply to the menu + */ + menuStyle?: React.CSSProperties; + /** + * multi-value input + * @default false + */ + multi?: boolean; + /** + * field name, for hidden `` tag + */ + name?: string; + /** + * placeholder displayed when there are no matching search results or a falsy value to hide it + * @default "No results found" + */ + noResultsText?: string | JSX.Element; + /** + * onBlur handler: function (event) {} + */ + onBlur?: OnBlurHandler; + /** + * whether to clear input on blur or not + * @default true + */ + onBlurResetsInput?: boolean; + /** + * whether the input value should be reset when options are selected. + * Also input value will be set to empty if 'onSelectResetsInput=true' and + * Select will get new value that not equal previous value. + * @default true + */ + onSelectResetsInput?: boolean; + /** + * whether to clear input when closing the menu through the arrow + * @default true + */ + onCloseResetsInput?: boolean; + /** + * onChange handler: function (newValue) {} + */ + onChange?: OnChangeHandler; + /** + * fires when the menu is closed + */ + onClose?: OnCloseHandler; + /** + * onFocus handler: function (event) {} + */ + onFocus?: OnFocusHandler; + /** + * onInputChange handler: function (inputValue) {} + */ + onInputChange?: OnInputChangeHandler; + /** + * onInputKeyDown handler: function (keyboardEvent) {} + */ + onInputKeyDown?: OnInputKeyDownHandler; + /** + * fires when the menu is scrolled to the bottom; can be used to paginate options + */ + onMenuScrollToBottom?: OnMenuScrollToBottomHandler; + /** + * fires when the menu is opened + */ + onOpen?: OnOpenHandler; + /** + * boolean to enable opening dropdown when focused + * @default false + */ + openOnClick?: boolean; + /** + * open the options menu when the input gets focus (requires searchable = true) + * @default true + */ + openOnFocus?: boolean; + /** + * className to add to each option component + */ + optionClassName?: string; + /** + * option component to render in dropdown + */ + optionComponent?: OptionComponentType; + /** + * function which returns a custom way to render the options in the menu + */ + optionRenderer?: OptionRendererHandler; + /** + * array of Select options + * @default false + */ + options?: Options; + /** + * number of options to jump when using page up/down keys + * @default 5 + */ + pageSize?: number; + /** + * field placeholder, displayed when there's no value + * @default "Select..." + */ + placeholder?: string | JSX.Element; + /** + * whether the selected option is removed from the dropdown on multi selects + * @default true + */ + removeSelected?: boolean; + /** + * applies HTML5 required attribute when needed + * @default false + */ + required?: boolean; + /** + * value to use when you clear the control + */ + resetValue?: any; + /** + * use react-select in right-to-left direction + * @default false + */ + rtl?: boolean; + /** + * whether the viewport will shift to display the entire menu when engaged + * @default true + */ + scrollMenuIntoView?: boolean; + /** + * whether to enable searching feature or not + * @default true; + */ + searchable?: boolean; + /** + * whether to select the currently focused value when the [tab] key is pressed + */ + tabSelectsValue?: boolean; + /** + * initial field value + */ + value?: Option | Options | string | string[] | number | number[] | boolean; + /** + * the option property to use for the value + * @default "value" + */ + valueKey?: string; + /** + * function which returns a custom way to render the value selected + * @default false + */ + valueRenderer?: ValueRendererHandler; + /** + * optional style to apply to the control + */ + style?: React.CSSProperties; + + /** + * optional tab index of the control + */ + tabIndex?: string | number; + + /** + * value component to render + */ + valueComponent?: ValueComponentType; + + /** + * optional style to apply to the component wrapper + */ + wrapperStyle?: React.CSSProperties; + + /** + * onClick handler for value labels: function (value, event) {} + */ + onValueClick?: OnValueClickHandler; + + /** + * pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false + */ + simpleValue?: boolean; +} + +export interface ReactCreatableSelectProps extends ReactSelectProps { + /** + * Searches for any matching option within the set of options. This function prevents + * duplicate options from being created. + */ + isOptionUnique?: IsOptionUniqueHandler; + + /** + * Determines if the current input text represents a valid option. + */ + isValidNewOption?: IsValidNewOptionHandler; + + /** + * factory to create new options + */ + newOptionCreator?: NewOptionCreatorHandler; + + /** + * Creates prompt/placeholder for option text. + */ + promptTextCreator?: PromptTextCreatorHandler; + + /** + * Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option. + */ + shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler; + + /** + * new option click handler: function (option) {} + */ + onNewOptionClick?: OnNewOptionClickHandler; + + /** + * true: Show new option at top of list + * false: Show new option at bottom of list + * @default true + */ + showNewOptionAtTop?: boolean; +} + +export interface ReactAsyncSelectProps extends ReactSelectProps { + /** + * Whether to auto-load the default async options set. + */ + autoload?: boolean; + + /** + * object to use to cache results; can be null to disable cache + */ + cache?: { [key: string]: any } | boolean; + + /** + * function to call to load options asynchronously + */ + loadOptions: LoadOptionsHandler; + + /** + * replaces the placeholder while options are loading + */ + loadingPlaceholder?: string | JSX.Element; + /** + * displayed in the drop down list when the user did not type anything yet + */ + searchPromptText?: string; +} + +export type ReactAsyncCreatableSelectProps = ReactAsyncSelectProps & ReactCreatableSelectProps; diff --git a/types/react-select/lib/Option/index.d.ts b/types/react-select/v1/lib/Option/index.d.ts similarity index 100% rename from types/react-select/lib/Option/index.d.ts rename to types/react-select/v1/lib/Option/index.d.ts diff --git a/types/react-select/lib/utils/defaultMenuRenderer/index.d.ts b/types/react-select/v1/lib/utils/defaultMenuRenderer/index.d.ts similarity index 100% rename from types/react-select/lib/utils/defaultMenuRenderer/index.d.ts rename to types/react-select/v1/lib/utils/defaultMenuRenderer/index.d.ts diff --git a/types/react-select/react-select-tests.tsx b/types/react-select/v1/react-select-tests.tsx similarity index 100% rename from types/react-select/react-select-tests.tsx rename to types/react-select/v1/react-select-tests.tsx diff --git a/types/react-select/v1/tsconfig.json b/types/react-select/v1/tsconfig.json new file mode 100644 index 0000000000..e01d55ae8a --- /dev/null +++ b/types/react-select/v1/tsconfig.json @@ -0,0 +1,35 @@ +{ + "files": [ + "index.d.ts", + "lib/Option/index.d.ts", + "lib/utils/defaultMenuRenderer/index.d.ts", + "react-select-tests.tsx" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "jsx": "react", + "typeRoots": [ + "../../" + ], + "paths": { + "react-select": [ + "react-select/v1" + ], + "react-select/*": [ + "react-select/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/react-select/v1/tslint.json b/types/react-select/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-select/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-virtualized-select/tsconfig.json b/types/react-virtualized-select/tsconfig.json index b544360da3..42387bc3e0 100644 --- a/types/react-virtualized-select/tsconfig.json +++ b/types/react-virtualized-select/tsconfig.json @@ -10,11 +10,18 @@ "noImplicitThis": true, "strictFunctionTypes": true, "strictNullChecks": true, - "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], + "paths": { + "react-select": [ + "react-select/v1" + ], + "react-select/*": [ + "react-select/v1/*" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true