diff --git a/react-table-filter/index.d.ts b/react-table-filter/index.d.ts new file mode 100644 index 0000000000..8f9c50a26f --- /dev/null +++ b/react-table-filter/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for react-table-filter 1.0.0 +// Project: https://github.com/cheekujha/react-table-filter +// Definitions by: Gnanavel N +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export interface TabfilterProps { + rows: string | Array | { [name: string]: boolean; }; + onFilterUpdate: (filteredArray: Array, currentFilters: any[]) => any[] | void; + rowClass?: string; + initialFilters?: string | Array | { [name: string]: boolean; }; +} + +export declare class TableFilter extends React.Component {} \ No newline at end of file diff --git a/react-table-filter/react-table-filter-tests.ts b/react-table-filter/react-table-filter-tests.ts new file mode 100644 index 0000000000..051f694f75 --- /dev/null +++ b/react-table-filter/react-table-filter-tests.ts @@ -0,0 +1,18 @@ +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import { TableFilter } from "react-table-filter"; + +interface TestTableFilterProps extends TableFilter {} + +class TestApp extends React.Component { + onFilterUpdate = (filteredArray: Array, currentFilters: any[]) => { + console.log("Filtered Array: " + filteredArray); + console.log("Current Filters: " + currentFilters); + } + + render() { + return React.createElement(TableFilter, {onFilterUpdate: this.onFilterUpdate}); + } +} + +ReactDOM.render(React.createElement(TestApp, {}), document.getElementById("test-app")); \ No newline at end of file diff --git a/react-table-filter/tsconfig.json b/react-table-filter/tsconfig.json new file mode 100644 index 0000000000..ca4a35b1cb --- /dev/null +++ b/react-table-filter/tsconfig.json @@ -0,0 +1,22 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/react-table-filter/tslint.json b/react-table-filter/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/react-table-filter/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/d3-request/d3-request-tests.ts b/types/d3-request/d3-request-tests.ts index 8b2130240a..e2208481d8 100644 --- a/types/d3-request/d3-request-tests.ts +++ b/types/d3-request/d3-request-tests.ts @@ -36,13 +36,13 @@ interface ResponseDatumPOST { success: boolean; } -let listenerXhr: (this: d3Request.Request, xhr: XMLHttpRequest) => void; +let listenerXhr: ((this: d3Request.Request, xhr: XMLHttpRequest) => void) | undefined; -let listenerProgress: (this: d3Request.Request, progEvent: ProgressEvent) => void; +let listenerProgress: ((this: d3Request.Request, progEvent: ProgressEvent) => void) | undefined; -let listenerError: (this: d3Request.Request, error: any) => void; +let listenerError: ((this: d3Request.Request, error: any) => void) | undefined; -let listenerResult: (this: d3Request.Request, result: ResponseDatumGET[]) => void; +let listenerResult: ((this: d3Request.Request, result: ResponseDatumGET[]) => void) | undefined; // ------------------------------------------------------------------------------- // Generic Request @@ -108,7 +108,7 @@ const r7: d3Request.Request = request.header('Accept-Encoding', null); // Mime Type ------------------------------------------------------------------- // get -let mimeType: string = request.mimeType(); +let mimeType: string | null = request.mimeType(); // set const r8: d3Request.Request = request.mimeType('application/json'); // remove @@ -162,11 +162,12 @@ r10 = r10.on('load', function(result: ResponseDatumGET[]) { // do something; }); -// r10 = r10.on('load', function(result: number) { // fails, wrong argument type for callback -// const that: d3Request.Request = this; -// const res: number = result; -// // do something; -// }); +// $ExpectError +r10 = r10.on('load', function(result: number) { // fails, wrong argument type for callback + const that: d3Request.Request = this; + const res: number = result; + // do something; +}); listenerResult = r10.on('load'); @@ -191,9 +192,10 @@ listenerError = r10.on('error.foo'); // Password --------------------------------------------------------------------- // get -const password: string = request.password(); +const password: string | null = request.password(); // set const r11: d3Request.Request = request.password('MyPassword'); +const r25: d3Request.Request = request.password(null); // Post ------------------------------------------------------------------------- @@ -238,11 +240,11 @@ const r16: d3Request.Request = d3Request.request(url) // ResponseType ----------------------------------------------------------------- // get -const responseType: string = d3Request.request(url) +const responseType: XMLHttpRequestResponseType | undefined = d3Request.request(url) .responseType(); // set const r17: d3Request.Request = d3Request.request(url) - .responseType('application/json'); + .responseType('json'); // Send ------------------------------------------------------------------------ @@ -259,7 +261,7 @@ const r20: d3Request.Request = d3Request.request(url) .response(xhr2Listing) .send('GET', (error, response) => { if (!error) { - const r: ResponseDatumGET[] = response; + const r: ResponseDatumGET[] | null = response; console.log(r); } }); @@ -269,7 +271,7 @@ const r21: d3Request.Request = d3Request.request(url) .response(xhr2Listing) .send('GET', { kind: 'Listing' }, (error, response) => { if (!error) { - const r: ResponseDatumGET[] = response; + const r: ResponseDatumGET[] | null = response; console.log(r); } }); @@ -286,9 +288,10 @@ const r22: d3Request.Request = d3Request.request(url) // User---------------------------------------------------------------------------- // get -const user: string = request.user(); +const user: string | null = request.user(); // set const r23: d3Request.Request = request.user('User'); +const r24: d3Request.Request = request.user(null); // ------------------------------------------------------------------------------- // HTML Request @@ -360,8 +363,8 @@ const csvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.csv, Alex Ford , Boris Yankov , Tom Wanzek +// Definitions by: Hugues Stefanski +// Alex Ford +// Boris Yankov +// Tom Wanzek +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -// Last module patch version validated against: 1.0.2 +// Last module patch version validated against: 1.0.6 import { DSVParsedArray, DSVRowString, DSVRowAny } from 'd3-dsv'; export interface Request { + /** + * Aborts this request, if it is currently in-flight, and returns this request instance. + * See XMLHttpRequest’s abort. + */ abort(): this; + /** + * Equivalent to `request.send` with the GET method: `request.send("GET")`. + */ get(): this; + /** + * Equivalent to `request.send` with the GET method: `request.send("GET", data)`. + */ get(data: RequestData): this; + /** + * Equivalent to `request.send` with the GET method: `request.send("GET", callback)`. + */ get(callback: (error: any, d: ResponseData) => void): this; + /** + * Equivalent to `request.send` with the GET method: `request.send("GET", data, callback)`. + */ get(data: RequestData, callback: (error: any, d: ResponseData) => void): this; + /** + * Returns the current value of the request header with the specified name. + * Header names are case-insensitive. + */ header(name: string): string; + /** + * Sets the request header with the specified name to the specified value and returns this request instance. + * If value is null, removes the request header with the specified name instead. + * Header names are case-insensitive. + * + * Request headers can only be modified before the request is sent. + * Therefore, you cannot pass a callback to the request constructor if you wish to specify a header; + * use `request.get` or similar instead. + */ header(name: string, value: string | null): this; + /** + * Returns the current mime type, which defaults to null. + */ mimeType(): string | null; + /** + * Sets the request mime type to the specified value and returns this request instance. + * If type is null, clears the current mime type (if any) instead. + * + * The mime type is used to both set the "Accept" request header and for `overrideMimeType`, where supported. + * + * The request mime type can only be modified before the request is sent. + * Therefore, you cannot pass a callback to the request constructor if you wish to override the mime type; + * use `request.get` or similar instead. + */ mimeType(value: string | null): this; - on(type: 'beforesend'): (this: this, xhr: XMLHttpRequest) => void; - on(type: 'progress'): (this: this, progressEvent: ProgressEvent) => void; - on(type: 'error'): (this: this, error: any) => void; - on(type: 'load'): (this: this, data: ResponseData) => void; - on(type: string): (this: this, data: any) => void; + /** + * Returns the currently-assigned listener for the "beforesend" type, if any. + */ + on(type: 'beforesend'): ((this: this, xhr: XMLHttpRequest) => void) | undefined; + /** + * Returns the currently-assigned listener for the "progress" type, if any. + */ + on(type: 'progress'): ((this: this, progressEvent: ProgressEvent) => void) | undefined; + /** + * Returns the currently-assigned listener for the "error" type, if any. + */ + on(type: 'error'): ((this: this, error: any) => void) | undefined; + /** + * Returns the currently-assigned listener for the "load" type, if any. + */ + on(type: 'load'): ((this: this, data: ResponseData) => void) | undefined; + /** + * Returns the currently-assigned listener for the specified type, if any. + */ + on(type: string): ((this: this, data: any) => void) | undefined; + + /** + * Removes the current event listener for the specified type, if any. + */ on(type: string, listener: null): this; + + /** + * Sets the event listener for the "beforesend" type, + * to allow custom headers and the like to be set before the request is sent, + * and returns this request instance. + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `beforesend.foo`. See d3-dispatch for details. + */ on(type: 'beforesend', listener: (this: this, xhr: XMLHttpRequest) => void): this; + /** + * Sets the event listener for the "progress" type, + * to monitor the progress of the request, + * and returns this request instance. + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `progress.foo`. See d3-dispatch for details. + */ on(type: 'progress', listener: (this: this, progressEvent: ProgressEvent) => void): this; + /** + * Sets the event listener for the "error" type, + * when the request completes unsuccessfully; this includes 4xx and 5xx response codes, + * and returns this request instance. + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `error.foo`. See d3-dispatch for details. + */ on(type: 'error', listener: (this: this, error: any) => void): this; + /** + * Sets the event listener for the "load" type, + * when the request completes successfully, + * and returns this request instance. + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `load.foo`. See d3-dispatch for details. + */ on(type: 'load', listener: (this: this, data: ResponseData) => void): this; + /** + * Sets the event listener for the specified type, + * and returns this request instance. + * + * The type must be one of the following: "beforesend", "progress", "load", "error". + * + * If an event listener was already registered for the same type, the existing listener is removed before the new listener is added. + * To register multiple listeners for the same type, the type may be followed by an optional name, such as `load.foo`. See d3-dispatch for details. + */ on(type: string, listener: (this: this, data: any) => void): this; + /** + * Returns the current password, which defaults to null. + */ password(): string | null; - password(value: string): this; + /** + * Sets the password for authentication to the specified string and returns this request instance. + */ + password(value: string | null): this; + /** + * Equivalent to `request.send` with the POST method: `request.send("POST")`. + */ post(): this; + /** + * Equivalent to `request.send` with the POST method: `request.send("POST", data)`. + */ post(data: RequestData): this; + /** + * Equivalent to `request.send` with the POST method: `request.send("POST", callback)`. + */ post(callback: (this: this, error: any, d: ResponseData) => void): this; + /** + * Equivalent to `request.send` with the POST method: `request.send("POST", data, callback)`. + */ post(data: RequestData, callback: (this: this, error: any, d: ResponseData) => void): this; + /** + * Sets the response value function to the specified function and returns this request instance. + * The response value function is used to map the response XMLHttpRequest object to a useful data value. + * See the convenience methods `json` and `text` for examples. + */ response(callback: (this: this, response: XMLHttpRequest) => ResponseData): this; - responseType(): string | null; - responseType(value: string): this; + /** + * Returns the current response type, which defaults to `` (the empty string). + */ + responseType(): XMLHttpRequestResponseType | undefined; + /** + * Sets the response type attribute of the request and returns this request instance. Typical values are: `` (the empty string), `arraybuffer`, `blob`, `document`, and `text`. + */ + responseType(value: XMLHttpRequestResponseType): this; + /** + * Issues this request using the specified method (such as GET or POST). + * + * The listeners "load" and "error" should be registered via `request.on`. + */ send(method: string): this; + /** + * Issues this request using the specified method (such as GET or POST), posting the specified data in the request body, and returns this request instance. + * + * The listeners "load" and "error" should be registered via `request.on`. + */ send(method: string, data: RequestData): this; + /** + * Issues this request using the specified method (such as GET or POST) and returns this request instance. + * The callback will be invoked asynchronously when the request succeeds or fails. + * The callback is invoked with two arguments: the error, if any, and the response value. + * The response value is undefined if an error occurs. + */ send(method: string, callback: (this: this, error: any | null, d: ResponseData | null) => void): this; + /** + * Issues this request using the specified method (such as GET or POST), posting the specified data in the request body, and returns this request instance. + * The callback will be invoked asynchronously when the request succeeds or fails. + * The callback is invoked with two arguments: the error, if any, and the response value. + * The response value is undefined if an error occurs. + */ send(method: string, data: RequestData, callback: (this: this, error: any | null, d: ResponseData | null) => void): this; + /** + * Returns the current response timeout, which defaults to 0. + */ timeout(): number; + /** + * Sets the timeout attribute of the request to the specified number of milliseconds and returns this request instance. + */ timeout(value: number): this; + /** + * Returns the current user name, which defaults to null. + */ user(): string | null; - user(value: string): this; + /** + * Sets the user name for authentication to the specified string and returns this request instance. + */ + user(value: string | null): this; } export interface DsvRequest extends Request { row(value: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DsvRequest; } +/** + * Returns a new request for the CSV file at the specified url with the default mime type `text/csv`. + */ export function csv(url: string): DsvRequest; +/** + * Returns a new request for the CSV file at the specified url with the default mime type `text/csv`. + * And send a GET request. + */ export function csv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void): DsvRequest; +/** + * Returns a new request for the CSV file at the specified url with the default mime type `text/csv`. + * And send a GET request. + * Use a row conversion function to map and filter row objects to a more-specific representation; see `dsv.parse` for details. + */ export function csv( url: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void ): DsvRequest; +/** + * Returns a new request for the HTML file at the specified url with the default mime type `text/html`. The HTML file is returned as a document fragment. + */ export function html(url: string): Request; +/** + * Returns a new request for the HTML file at the specified url with the default mime type `text/html`. The HTML file is returned as a document fragment. + * And send a GET request. + */ export function html(url: string, callback: (this: Request, error: any, d: DocumentFragment) => void): Request; +/** + * Returns a new request to get the JSON file at the specified url with the default mime type `application/json`. + */ export function json(url: string): Request; +/** + * Returns a new request to get the JSON file at the specified url with the default mime type `application/json`. + * And send a GET request. + */ export function json(url: string, callback: (this: Request, error: any, d: ParsedObject) => void): Request; +/** + * Returns a new request for specified url. The returned request is not yet sent and can be further configured. + * + * See `d3.json`, `d3.csv`, `d3.tsv`, `d3.text`, `d3.html` and `d3.xml` for content-specific convenience constructors. + */ export function request(url: string): Request; +/** + * Returns a new request for specified url. It is equivalent to calling `request.get` immediately after construction: `d3.request(url).get(callback)`. + * And send a GET request. + * + * If you wish to specify a request header or a mime type, you must not specify a callback to the constructor. + * Use `request.header` or `request.mimeType` followed by `request.get` instead. + * + * See `d3.json`, `d3.csv`, `d3.tsv`, `d3.text`, `d3.html` and `d3.xml` for content-specific convenience constructors. + */ export function request(url: string, callback: (this: Request, error: any, d: XMLHttpRequest) => void): Request; +/** + * Returns a new request to get the text file at the specified url with the default mime type `text/plain`. + */ export function text(url: string): Request; +/** + * Returns a new request to get the text file at the specified url with the default mime type `text/plain`. + * And send a GET request. + */ export function text(url: string, callback: (this: Request, error: any, d: string) => void): Request; +/** + * Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`. + */ export function tsv(url: string): DsvRequest; +/** + * Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`. + * And send a GET request. + */ export function tsv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void): DsvRequest; +/** + * Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`. + * And send a GET request. + * Use a row conversion function to map and filter row objects to a more-specific representation; see `dsv.parse` for details. + */ export function tsv( url: string, row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void ): DsvRequest; +/** + * Returns a new request to get the XML file at the specified url with the default mime type `application/xml`. + */ export function xml(url: string): Request; +/** + * Returns a new request to get the XML file at the specified url with the default mime type `application/xml`. + * And send a GET request. + */ export function xml(url: string, callback: (this: Request, error: any, d: any) => void): Request; diff --git a/types/d3-request/tsconfig.json b/types/d3-request/tsconfig.json index a52d00ffaa..9ba2eb33f3 100644 --- a/types/d3-request/tsconfig.json +++ b/types/d3-request/tsconfig.json @@ -6,8 +6,8 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": false, "baseUrl": "../", "typeRoots": [ diff --git a/types/d3-request/tslint.json b/types/d3-request/tslint.json index a965459d61..1aeb60bae1 100644 --- a/types/d3-request/tslint.json +++ b/types/d3-request/tslint.json @@ -3,9 +3,7 @@ "rules": { // TODOs "no-any-union": false, - "no-this-assignment": false, "no-unnecessary-generics": false, - "unified-signatures": false, - "max-line-length": [false, 145] + "unified-signatures": false } } diff --git a/types/koa-bunyan-logger/index.d.ts b/types/koa-bunyan-logger/index.d.ts new file mode 100644 index 0000000000..1cf77fec92 --- /dev/null +++ b/types/koa-bunyan-logger/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for koa-bunyan-logger 2.0 +// Project: https://github.com/koajs/bunyan-logger +// Definitions by: Steven McDowall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Middleware } from 'koa'; + +import Logger = require('bunyan'); + +export = koaBunyanLogger; + +declare function koaBunyanLogger(logger?: Logger): Middleware; + +// Extend the Koa context to add the logger.. +declare module 'koa' { + // tslint:disable-next-line: interface-name + interface BaseContext { + log: Logger; + } +} diff --git a/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts b/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts new file mode 100644 index 0000000000..daaf26b7a3 --- /dev/null +++ b/types/koa-bunyan-logger/koa-bunyan-logger-tests.ts @@ -0,0 +1,12 @@ +import Koa = require('koa'); +import koaBunyanLogger = require('koa-bunyan-logger'); + +const app = new Koa(); +app.use(koaBunyanLogger()); + +app.use(async (ctx, next) => { + ctx.log.info('Got a request from %s for %s', ctx.request.ip, ctx.path); + await next(); +}); + +app.listen(8000); diff --git a/types/koa-bunyan-logger/tsconfig.json b/types/koa-bunyan-logger/tsconfig.json new file mode 100644 index 0000000000..67657f2ec2 --- /dev/null +++ b/types/koa-bunyan-logger/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-bunyan-logger-tests.ts" + ] +} diff --git a/types/koa-bunyan-logger/tslint.json b/types/koa-bunyan-logger/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-bunyan-logger/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 0822dea605..8402d8bc9b 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -11,10 +11,12 @@ export as namespace L; import * as geojson from 'geojson'; export class Class { - static extend(props: any): any/* how to return constructor of self extended type ? */; - static include(props: any): any /* how to return self extended type ? */; - static mergeOptions(props: any): any /* how to return self extended type ? */; - static addInitHook(initHookFn: () => void): any/* how to return self extended type ? */; + static extend(props: any): {new(...args: any[]): any} & typeof Class; + static include(props: any): any & typeof Class; + static mergeOptions(props: any): any & typeof Class; + + static addInitHook(initHookFn: () => void): any & typeof Class; + static addInitHook(methodName: string, ...args: any[]): any & typeof Class; } export class Transformation { @@ -1532,8 +1534,12 @@ export namespace Browser { } export namespace Util { - function extend(dest: any, src?: any): any; - function create(proto: any, properties?: any): any; + function extend(dest: D, src?: S1): D & S1; + function extend(dest: D, src1: S1, src2: S2): D & S1 & S2; + function extend(dest: D, src1: S1, src2: S2, src3: S3): D & S1 & S2 & S3; + function extend(dest: any, ...src: any[]): any; + + function create(proto: object | null, properties?: PropertyDescriptorMap): any; function bind(fn: () => void, ...obj: any[]): () => void; function stamp(obj: any): number; function throttle(fn: () => void, time: number, context: any): () => void; @@ -1547,7 +1553,7 @@ export namespace Util { function template(str: string, data: any): string; function isArray(obj: any): boolean; function indexOf(array: any[], el: any): number; - function requestAnimFrame(fn: () => void, context?: any, immediate?: boolean): number; + function requestAnimFrame(fn: (timestamp: number) => void, context?: any, immediate?: boolean): number; function cancelAnimFrame(id: number): void; let lastId: number; diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index 66f12fd0ed..d1375fa83f 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -444,10 +444,13 @@ defaultIcon = new L.Icon.Default({imagePath: 'apath'}); const myControlClass = L.Control.extend({}); const myControl = new myControlClass(); +const myOtherControlClass = myControlClass.extend({}); +const myOtherControl = new myOtherControlClass(); L.Control.include({}); L.Control.mergeOptions({}); L.Control.addInitHook(() => {}); +L.Control.addInitHook('method1', 'hello', 1); export class MyNewControl extends L.Control { constructor() { @@ -526,8 +529,35 @@ polyline = new L.Polyline(multiPolylineLatLngs); polyline.setLatLngs(multiPolylineLatLngs); const multiPolylineLatLngs2: L.LatLng[][] = polyline.getLatLngs() as L.LatLng[][]; -L.Util.extend({}); +const obj1 = { + prop1: 1, +}; + +const obj2 = { + prop2: '2', +}; + +const obj3 = { + prop3: 'three', +}; + +const obj4 = { + prop4: 'cuatro', +}; + +const obj5 = { + prop5: 'cinque', +}; + +const extended0: typeof obj1 = L.Util.extend(obj1); +const extended1: typeof obj1 & typeof obj2 = L.Util.extend(obj1, obj2); +const extended2: typeof obj1 & typeof obj2 & typeof obj3 = L.Util.extend(obj1, obj2, obj3); +const extended3: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 = L.Util.extend(obj1, obj2, obj3, obj4); +const extended4: typeof obj1 & typeof obj2 & typeof obj3 & typeof obj4 & typeof obj5 = L.Util.extend(obj1, obj2, obj3, obj4, obj5); + L.Util.create({}); +L.Util.create(null, {foo: {writable: true, value: 'bar'}}); + L.Util.bind(() => {}, {}); L.Util.stamp({}); L.Util.throttle(() => {}, 123, {}); @@ -546,7 +576,7 @@ L.Util.template('template', {}); L.Util.isArray({}); L.Util.indexOf([], {}); L.Util.requestAnimFrame(() => {}); -L.Util.requestAnimFrame(() => {}, {}); +L.Util.requestAnimFrame(timestamp => console.log(timestamp), {}); L.Util.requestAnimFrame(() => {}, {}, true); L.Util.cancelAnimFrame(1); L.Util.emptyImageUrl; diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 99d7ddac1b..73ca28ee82 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -11346,6 +11346,36 @@ declare namespace Office { * @beta */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; + + /** + * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. + * + * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * for Office 365. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee
+ * + * In addition to this signature, the method also has the following signature: + * + * `getInitializationContextAsync(callback?: (result: AsyncResult) => void): void;` + * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property + * set to 9020 and its name property set to GenericResponseError. + * + * @beta + */ + getInitializationContextAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Asynchronously loads custom properties for this add-in on the selected item. diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 5f62134c90..5d30bf798a 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1647,6 +1647,35 @@ export interface LaunchOptions { * Useful so that you can see what is going on. */ slowMo?: number; + /** + * Sets a consistent viewport for each page. Defaults to an 800x600 viewport. null disables the default viewport. + */ + defaultViewport?: { + /** + * page width in pixels. + */ + width?: number; + /** + * page height in pixels. + */ + height?: number; + /** + * Specify device scale factor (can be thought of as dpr). Defaults to 1. + */ + deviceScaleFactor?: number; + /** + * Whether the meta viewport tag is taken into account. Defaults to false. + */ + isMobile?: boolean; + /** + * Specifies if viewport supports touch events. Defaults to false. + */ + hasTouch?: boolean; + /** + * Specifies if viewport is in landscape mode. Defaults to false. + */ + isLandscape?: boolean; + }; /** * Additional arguments to pass to the Chromium instance. List of Chromium * flags can be found here. diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index e883157fec..2db92a9171 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -167,6 +167,7 @@ puppeteer.launch().then(async browser => { '--no-sandbox', '--disable-setuid-sandbox', ], + defaultViewport: { width: 800, height: 600 }, handleSIGINT: true, handleSIGHUP: true, handleSIGTERM: true, diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index c5e677d187..120c61d667 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -7,14 +7,14 @@ interface Assert { /** * Instruct QUnit to wait for an asynchronous operation. - * + * * The callback returned from `assert.async()` will throw an Error if it is * invoked more than once (or more often than the accepted call count, if * provided). * * This replaces functionality previously provided by `QUnit.stop()` and * `QUnit.start()`. - * + * * @param {number} [acceptCallCount=1] Number of expected callbacks before the test is done. */ async(acceptCallCount?: number): () => void; @@ -22,179 +22,179 @@ interface Assert { /** * A deep recursive comparison, working on primitive types, arrays, objects, * regular expressions, dates and functions. - * + * * The `deepEqual()` assertion can be used just like `equal()` when comparing * the value of objects, such that `{ key: value }` is equal to * `{ key: value }`. For non-scalar values, identity will be disregarded by * deepEqual. - * + * * `notDeepEqual()` can be used to explicitly test deep, strict inequality. - * + * * @param actual Object or Expression being tested * @param expected Known comparision value - * @param {string} [message] A short description of the assertion + * @param {string} [message] A short description of the assertion */ - deepEqual(actual: any, expected: any, message?: string): void; - + deepEqual(actual: T, expected: T, message?: string): void; + /** * A non-strict comparison, roughly equivalent to JUnit's assertEquals. - * + * * The `equal` assertion uses the simple comparison operator (`==`) to * compare the actual and expected arguments. When they are equal, the * assertion passes; otherwise, it fails. When it fails, both actual and * expected values are displayed in the test result, in addition to a given * message. - * + * * `notEqual()` can be used to explicitly test inequality. - * + * * `strictEqual()` can be used to test strict equality. - * + * * @param actual Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ equal(actual: any, expected: any, message?: string): void; - + /** * Specify how many assertions are expected to run within a test. - * + * * To ensure that an explicit number of assertions are run within any test, * use `assert.expect( number )` to register an expected count. If the * number of assertions run does not match the expected count, the test will * fail. - * + * * @param {number} amount Number of assertions in this test. */ expect(amount: number): void; - + /** * An inverted deep recursive comparison, working on primitive types, * arrays, objects, regular expressions, dates and functions. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ notDeepEqual(actual: any, expected: any, message?: string): void; - + /** * A non-strict comparison, checking for inequality. - * + * * The `notEqual` assertion uses the simple inverted comparison operator * (`!=`) to compare the actual and expected arguments. When they aren't * equal, the assertion passes; otherwise, it fails. When it fails, both * actual and expected values are displayed in the test result, in addition * to a given message. - * + * * `equal()` can be used to test equality. - * + * * `notStrictEqual()` can be used to test strict inequality. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ notEqual(actual: any, expected: any, message?: string): void; - + /** * A boolean check, inverse of `ok()` and CommonJS's `assert.ok()`, and * equivalent to JUnit's `assertFalse()`. Passes if the first argument is * falsy. - * + * * `notOk()` requires just one argument. If the argument evaluates to false, * the assertion passes; otherwise, it fails. If a second message argument * is provided, it will be displayed in place of the result. - * + * * @param state Expression being tested * @param {string} [message] A short description of the assertion */ notOk(state: any, message?: string): void; - + /** * A strict comparison of an object's own properties, checking for inequality. - * + * * The `notPropEqual` assertion uses the strict inverted comparison operator * (`!==`) to compare the actual and expected arguments as Objects regarding * only their properties but not their constructors. - * + * * When they aren't equal, the assertion passes; otherwise, it fails. When * it fails, both actual and expected values are displayed in the test * result, in addition to a given message. - * + * * `equal()` can be used to test equality. - * + * * `propEqual()` can be used to test strict equality of an Object properties. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ notPropEqual(actual: any, expected: any, message?: string): void; - + /** * A strict comparison, checking for inequality. - * + * * The `notStrictEqual` assertion uses the strict inverted comparison * operator (`!==`) to compare the actual and expected arguments. When they * aren't equal, the assertion passes; otherwise, it fails. When it fails, * both actual and expected values are displayed in the test result, in * addition to a given message. - * + * * `equal()` can be used to test equality. - * + * * `strictEqual()` can be used to test strict equality. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ notStrictEqual(actual: any, expected: any, message?: string): void; - + /** * A boolean check, equivalent to CommonJS's assert.ok() and JUnit's * assertTrue(). Passes if the first argument is truthy. - * + * * The most basic assertion in QUnit, ok() requires just one argument. If * the argument evaluates to true, the assertion passes; otherwise, it * fails. If a second message argument is provided, it will be displayed in * place of the result. - * + * * @param state Expression being tested * @param {string} message A short description of the assertion */ ok(state: any, message?: string): void; - + /** * A strict type and value comparison of an object's own properties. - * + * * The `propEqual()` assertion provides strictly (`===`) comparison of * Object properties. Unlike `deepEqual()`, this assertion can be used to * compare two objects made with different constructors and prototype. - * + * * `strictEqual()` can be used to test strict equality. - * + * * `notPropEqual()` can be used to explicitly test strict inequality of * Object properties. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ propEqual(actual: any, expected: any, message?: string): void; - + /** * Report the result of a custom assertion - * + * * Some test suites may need to express an expectation that is not defined * by any of QUnit's built-in assertions. This need may be met by * encapsulating the expectation in a JavaScript function which returns a * `Boolean` value representing the result; this value can then be passed * into QUnit's `ok` assertion. - * + * * A more readable solution would involve defining a custom assertion. If * the expectation function invokes `pushResult`, QUnit will be notified of * the result and report it accordingly. - * + * * @param assertionResult The assertion result */ pushResult(assertResult: { @@ -203,31 +203,31 @@ interface Assert { expected: any; message: string; }): void; - + /** * A strict type and value comparison. - * + * * The `strictEqual()` assertion provides the most rigid comparison of type * and value with the strict equality operator (`===`). - * + * * `equal()` can be used to test non-strict equality. - * + * * `notStrictEqual()` can be used to explicitly test strict inequality. - * + * * @param actual Object or Expression being tested * @param expected Known comparison value * @param {string} [message] A short description of the assertion */ - strictEqual(actual: any, expected: any, message?: string): void; - + strictEqual(actual: T, expected: T, message?: string): void; + /** * Test if a callback throws an exception, and optionally compare the thrown * error. - * + * * When testing code that is expected to throw an exception based on a * specific set of circumstances, use assert.throws() to catch the error * object for testing and comparison. - * + * * In very few environments, like Closure Compiler, throws is considered a * reserved word and will cause an error. For that case, an alias is bundled * called `raises`. It has the same signature and behaviour, just a @@ -238,30 +238,30 @@ interface Assert { /** * 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()`. - * + * + * 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; - + } interface Config { @@ -296,7 +296,7 @@ interface Hooks { /** * Runs after the last test. If additional tests are defined after the * module's queue has emptied, it will not run this hook again. - */ + */ after?: (assert: Assert) => void; /** @@ -320,7 +320,7 @@ interface NestedHooks { /** * Runs after the last test. If additional tests are defined after the * module's queue has emptied, it will not run this hook again. - */ + */ after: (fn: (assert: Assert) => void) => void; /** @@ -337,7 +337,7 @@ interface NestedHooks { * Runs before each test. */ beforeEach: (fn: (assert: Assert) => void) => void; - + } declare namespace QUnit { @@ -373,30 +373,30 @@ declare namespace QUnit { } interface QUnit { - + /** * Namespace for QUnit assertions - * + * * QUnit's built-in assertions are defined on the `QUnit.assert` object. An * instance of this object is passed as the only argument to the `QUnit.test` * function callback. - * + * * This object has properties for each of QUnit's built-in assertion methods. */ assert: Assert; /** * Register a callback to fire whenever the test suite begins. - * + * * `QUnit.begin()` is called once before running any tests. - * + * * @callback callback Callback to execute. */ begin(callback: (details: QUnit.BeginDetails) => void): void; /** * Configuration for QUnit - * + * * QUnit has a bunch of internal configuration defaults, some of which are * useful to override. Check the description for each option for details. */ @@ -404,23 +404,23 @@ interface QUnit { /** * Register a callback to fire whenever the test suite ends. - * + * * @param callback Callback to execute */ done(callback: (details: QUnit.DoneDetails) => void): void; /** * Advanced and extensible data dumping for JavaScript. - * + * * This method does string serialization by parsing data structures and * objects. It parses DOM elements to a string representation of their outer * HTML. By default, nested structures will be displayed up to five levels * deep. Anything beyond that is replaced by `[object Object]` and * `[object Array]` placeholders. - * + * * If you need more or less output, change the value of `QUnit.dump.maxDepth`, * representing how deep the elements should be parsed. - * + * * Note: This method used to be in QUnit.jsDump, which was changed to * QUnit.dump. The old property will be removed in QUnit 3.0. */ @@ -431,12 +431,12 @@ interface QUnit { /** * Copy the properties defined by the `mixin` object into the `target` object. - * + * * This method will modify the `target` object to contain the "own" properties * defined by the `mixin`. If the `mixin` object specifies the value of any * attribute as undefined, this property will instead be removed from the * `target` object. - * + * * @param target An object whose properties are to be modified * @param mixin An object describing which properties should be modified */ @@ -444,12 +444,12 @@ interface QUnit { /** * Register a callback to fire whenever an assertion completes. - * + * * This is one of several callbacks QUnit provides. Its intended for * integration scenarios like PhantomJS or Jenkins. The properties of the * details argument are listed below as options. - * - * @param callback Callback to execute + * + * @param callback Callback to execute */ log(callback: (details: QUnit.LogDetails) => void): void; @@ -457,36 +457,36 @@ interface QUnit { * Group related tests under a single label. * * You can use the module name to organize, select, and filter tests to run. - * + * * All tests inside a module callback function will be grouped into that * module. The test names will all be preceded by the module name in the * test results. Other modules can be nested inside this callback function, * where their tests' names will be labeled by their names recursively * prefixed by their parent modules. - * + * * If `QUnit.module` is defined without a `nested` callback argument, all * subsequently defined tests will be grouped into the module until another * module is defined. - * + * * Modules with test group functions allow you to define nested modules, and * QUnit will run tests on the parent module before going deep on the nested * ones, even if they're declared first. Additionally, any hook callbacks on * a parent module will wrap the hooks on a nested module. In other words, * `before` and `beforeEach` callbacks will form a queue while the * `afterEach` and `after` callbacks will form a stack. - * + * * You can specify code to run before and after tests using the hooks * argument, and also to create properties that will be shared on the * testing context. Any additional properties on the `hooks` object will be * added to that context. The `hooks` argument is still optional if you call * `QUnit.module` with a callback argument. - * + * * The module's callback is invoked with the test environment as its `this` * context, with the environment's properties copied to the module's tests, * hooks, and nested modules. Note that changes on tests' `this` are not * preserved between sibling tests, where `this` will be reset to the initial * value for each test. - * + * * @param {string} name Label for this group of tests * @param hookds Callbacks to run during test execution * @param nested A callback with grouped tests and nested modules to run under the current module label @@ -496,31 +496,31 @@ interface QUnit { /** * Register a callback to fire whenever a module ends. - * + * * @param callback Callback to execute */ moduleDone(callback: (details: QUnit.ModuleDoneDetails) => void): void; /** * Register a callback to fire whenever a module begins. - * + * * @param callback Callback to execute */ moduleStart(callback: (details: QUnit.ModuleStartDetails) => void): void; /** * Adds a test to exclusively run, preventing all other tests from running. - * + * * Use this method to focus your test suite on a specific test. QUnit.only * will cause any other tests in your suite to be ignored. - * + * * Note, that if more than one QUnit.only is present only the first instance * will run. - * + * * This is an alternative to filtering tests to run in the HTML reporter. It * is especially useful when you use a console reporter or in a codebase * with a large set of long running tests. - * + * * @param {string} name Title of unit being tested * @param callback Function to close over assertions */ @@ -528,48 +528,48 @@ interface QUnit { /** * DEPRECATED: Report the result of a custom assertion. - * + * * This method is deprecated and it's recommended to use pushResult on its * direct reference in the assertion context. - * + * * QUnit.push reflects to the current running test, and it may leak * assertions in asynchronous mode. Checkout assert.pushResult() to set a * proper custom assertion. - * + * * Invoking QUnit.push allows to create a readable expectation that is not * defined by any of QUnit's built-in assertions. - * + * * @deprecated */ push(result: boolean, actual: any, expected: any, message: string): void; /** * Adds a test like object to be skipped. - * + * * Use this method to replace QUnit.test() instead of commenting out entire * tests. - * + * * This test's prototype will be listed on the suite as a skipped test, * ignoring the callback argument and the respective global and module's * hooks. - * + * * @param {string} Title of unit being tested */ skip(name: string, callback?: (assert: Assert) => void): void; /** * Returns a single line string representing the stacktrace (call stack). - * + * * This method returns a single line string representing the stacktrace from * where it was called. According to its offset argument, `QUnit.stack()` will * return the correspondent line from the call stack. - * + * * The default `offset` is `0` and will return the current location where it * was called. - * + * * Not all browsers support retrieving stracktraces. In those, `QUnit.stack()` * will return undefined. - * + * * @param {number} offset Set the stacktrace line offset. */ stack(offset?: number): string; @@ -577,10 +577,10 @@ interface QUnit { /** * `QUnit.start()` must be used to start a test run that has * `QUnit.config.autostart` set to `false`. - * + * * This method was previously used to control async tests on text contexts * along with QUnit.stop. For asynchronous tests, use assert.async instead. - * + * * When your async test has multiple exit points, call `QUnit.start()` for the * corresponding number of `QUnit.stop()` increments. */ @@ -588,16 +588,16 @@ interface QUnit { /** * Add a test to run. - * + * * Add a test to run using `QUnit.test()`. - * + * * The `assert` argument to the callback contains all of QUnit's assertion * methods. Use this argument to call your test assertions. * * `QUnit.test()` can automatically handle the asynchronous resolution of a * Promise on your behalf if you return a thenable Promise as the result of * your callback function. - * + * * @param {string} Title of unit being tested * @param callback Function to close over assertions */ @@ -605,7 +605,7 @@ interface QUnit { /** * Register a callback to fire whenever a test ends. - * + * * @param callback Callback to execute */ testDone(callback: (details: { @@ -619,7 +619,7 @@ interface QUnit { /** * Register a callback to fire whenever a test begins. - * + * * @param callback Callback to execute */ testStart(callback: (details: QUnit.TestStartDetails) => void): void; @@ -649,7 +649,7 @@ interface QUnit { /** * Are the test running from the server or not. - */ + */ isLocal: boolean; /** diff --git a/types/react-data-grid/index.d.ts b/types/react-data-grid/index.d.ts index bfa4ea979f..b41c2c2501 100644 --- a/types/react-data-grid/index.d.ts +++ b/types/react-data-grid/index.d.ts @@ -1,24 +1,43 @@ -// Type definitions for react-data-grid 2.0 +// Type definitions for react-data-grid 4.0 // Project: https://github.com/adazzle/react-data-grid.git -// Definitions by: Simon Gellis , Kieran Peat , Martin Novak +// Definitions by: Simon Gellis , Kieran Peat , Martin Novak , Sebastijan Grabar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// declare namespace AdazzleReactDataGrid { - - interface SelectionParams { - rowIdx: number, - row: any + interface ExcelColumn { + editable: boolean; + name: any; + key: string; + width: number; + resizeable: boolean; + filterable: boolean; } - interface GridProps { + interface EditorBaseProps { + value: any; + column: ExcelColumn; + height: number; + onBlur: () => void; + onCommit: () => void; + onCommitCancel: () => void; + rowData: any; + rowMetaData: any; + } + + interface SelectionParams { + rowIdx: number; + row: T; + } + + interface GridProps { /** * Gets the data to render in each row. Required. * Can be an array or a function that takes an index and returns an object. */ - rowGetter: Array | ((rowIdx: number) => object) + rowGetter: Array | ((rowIdx: number) => T) /** * The total number of rows to render. Required. */ @@ -26,14 +45,14 @@ declare namespace AdazzleReactDataGrid { /** * The columns to render. */ - columns?: Array + columns?: Array> /** * Invoked when the user changes the value of a single cell. * Should update that cell's value. * @param e Information about the event */ - onRowUpdated?: (e: RowUpdateEvent) => void + onRowUpdated?: (e: RowUpdateEvent) => void /** * Invoked when the user pulls down the drag handle of an editable cell. * Should update the values of the selected cells. @@ -45,7 +64,7 @@ declare namespace AdazzleReactDataGrid { * Should update the values of the cells beneath the selected cell. * @param e Information about the event */ - onDragHandleDoubleClick?: (e: DragHandleDoubleClickEvent) => void + onDragHandleDoubleClick?: (e: DragHandleDoubleClickEvent) => void /** * Invoked when the user copies a value from one cell and pastes it into another (in the same column). * Should update the value of the cell in row e.toRow. @@ -56,7 +75,7 @@ declare namespace AdazzleReactDataGrid { * Invoked after the user updates the grid rows in any way. * @param e Information about the event */ - onGridRowsUpdated?: (e: GridRowsUpdatedEvent) => void + onGridRowsUpdated?: (e: GridRowsUpdatedEvent) => void /** * A toolbar to display above the grid. @@ -164,7 +183,7 @@ declare namespace AdazzleReactDataGrid { * Called when a row is selected. * @param rows The (complete) current selection of rows. */ - onRowSelect?: (rows: Array) => void + onRowSelect?: (rows: Array) => void /** * A property that's unique to every row. * This property is required to enable row selection. @@ -206,8 +225,8 @@ declare namespace AdazzleReactDataGrid { rowSelection?: { showCheckbox?: boolean enableShiftSelect?: boolean - onRowsSelected?: (rows: Array) => void, - onRowsDeselected?: (rows: Array) => void, + onRowsSelected?: (rows: Array>) => void, + onRowsDeselected?: (rows: Array>) => void, selectBy?: { indexes?: Array; keys?: { rowKey: string, values: Array }; @@ -230,7 +249,7 @@ declare namespace AdazzleReactDataGrid { * @param rowIdx zero index number of row clicked * @param row object behind the row */ - onRowClick?: (rowIdx : number, row : object) => void + onRowClick?: (rowIdx: number, row: T) => void /** * An event function called when a row is expanded with the toggle @@ -246,12 +265,12 @@ declare namespace AdazzleReactDataGrid { */ getValidFilterValues?: (columnKey: string) => Array - getCellActions?: (column: Column, row: object) => (ActionButton | ActionMenu)[] + getCellActions?: (column: Column, row: T) => (ActionButton | ActionMenu)[] } type ActionButton = { icon: string; - callback: () => void; + callback: () => void; } type ActionMenu = { @@ -266,7 +285,7 @@ declare namespace AdazzleReactDataGrid { /** * Information about a specific column to be rendered. */ - interface Column { + interface Column { /** * A unique key for this column. Required. * Each row should have a property with this name, which contains this column's value. @@ -314,7 +333,10 @@ declare namespace AdazzleReactDataGrid { * The editor for this column. Several editors are available in "react-data-grid/addons". * @default A simple text editor */ - editor?: React.ReactElement | React.ComponentClass | React.StatelessComponent + editor?: + | React.ReactElement + | React.ComponentClass + | React.StatelessComponent; /** * A custom read-only formatter for this column. An image formatter is available in "react-data-grid/addons". */ @@ -331,11 +353,11 @@ declare namespace AdazzleReactDataGrid { */ events?: { [name: string]: ColumnEventCallback - } + }; /** * Retrieve meta data about the row, optionally provide column as a second argument */ - getRowMetaData?: (rowdata: any, column?: Column) => any; + getRowMetaData?: (rowdata: T, column?: Column) => any; /** * A class name to be applied to the cells in the column */ @@ -357,9 +379,10 @@ declare namespace AdazzleReactDataGrid { } /** - * Information about a row update + * Information about a row update. Generic event type returns untyped row, use parameterized type with the row type as the parameter + * @default T = any */ - interface RowUpdateEvent { + interface RowUpdateEvent { /** * The index of the updated row. */ @@ -367,7 +390,7 @@ declare namespace AdazzleReactDataGrid { /** * The columns that were updated and their values. */ - updated: object + updated: T /** * The name of the column that was updated. */ @@ -401,9 +424,10 @@ declare namespace AdazzleReactDataGrid { } /** - * Information about a drag handle double click + * Information about a drag handle double click. Generic event type returns untyped row, use parameterized type with the row type as the parameter + * @default T = any */ - interface DragHandleDoubleClickEvent { + interface DragHandleDoubleClickEvent { /** * The row where the double click occurred. */ @@ -415,7 +439,7 @@ declare namespace AdazzleReactDataGrid { /** * The values of the row. */ - rowData: object + rowData: T /** * The double click event. */ @@ -449,9 +473,10 @@ declare namespace AdazzleReactDataGrid { } /** - * Information about some update to the grid's contents + * Information about some update to the grid's contents. Generic event type returns untyped row, use parameterized type with the row type as the parameter + * @default T = any */ - interface GridRowsUpdatedEvent { + interface GridRowsUpdatedEvent { /** * The key of the column where the event occurred. */ @@ -467,7 +492,7 @@ declare namespace AdazzleReactDataGrid { /** * The columns that were updated and their values. */ - updated: object + updated: T /** * The action that occurred to trigger this event. * One of 'cellUpdate', 'cellDrag', 'columnFill', or 'copyPaste'. @@ -511,7 +536,7 @@ declare namespace AdazzleReactDataGrid { * Excel-like grid component built with React, with editors, keyboard navigation, copy & paste, and the like * http://adazzle.github.io/react-data-grid/ */ - export class ReactDataGrid extends React.Component { + export class ReactDataGrid extends React.Component> { /** * Opens the editor for the cell (idx) in the given row (rowIdx). If the column is not editable then nothing will happen. */ @@ -531,6 +556,18 @@ declare namespace AdazzleReactDataGrid { export import GridRowsUpdatedEvent = AdazzleReactDataGrid.GridRowsUpdatedEvent; export import OnRowExpandToggle = AdazzleReactDataGrid.OnRowExpandToggle; + export namespace editors { + class EditorBase

extends React.Component

{ + getStyle(): { width: string }; + + getValue(): any; + + getInputNode(): Element | null | Text; + + inheritContainerStyles(): boolean; + } + } + // Actual classes exposed on module.exports /** * A react component that renders a row of the grid @@ -541,15 +578,48 @@ declare namespace AdazzleReactDataGrid { */ export class Cell extends React.Component { } } -} + } + + declare namespace AdazzleReactDataGridPlugins { + interface AutoCompleteEditorProps { + onCommit?: () => void; + options?: Array<{ id: number; title: string }>; + label?: any; + value?: any; + height?: number; + valueParams?: string[]; + column?: AdazzleReactDataGrid.ExcelColumn; + resultIdentifier?: string; + search?: string; + onKeyDown?: () => void; + onFocus?: () => void; + editorDisplayValue?: (column: AdazzleReactDataGrid.ExcelColumn, value: any) => string; + } + + interface AutoCompleteTokensEditorProps { + options: Array; + column?: AdazzleReactDataGrid.ExcelColumn; + value?: any[]; + } + + interface DropDownEditorProps { + options: + Array; + } -declare namespace AdazzleReactDataGridPlugins { - // TODO: refine types for these addons export namespace Editors { - export class AutoComplete extends React.Component { } - export class DropDownEditor extends React.Component { } - export class SimpleTextEditor extends React.Component { } - export class CheckboxEditor extends React.Component { } + export class AutoComplete extends React.Component {} + export class AutoCompleteTokensEditor extends React.Component {} + export class DropDownEditor extends React.Component {} + + // TODO: refine types for these addons + export class SimpleTextEditor extends React.Component {} + export class CheckboxEditor extends React.Component {} } export namespace Filters { export class NumericFilter extends React.Component { } @@ -589,16 +659,16 @@ declare namespace AdazzleReactDataGridPlugins { configure?: (props: any) => any ): (Component: any) => any } -} + } -declare module "react-data-grid" { + declare module "react-data-grid" { import ReactDataGrid = AdazzleReactDataGrid.ReactDataGrid; // commonjs export export = ReactDataGrid; -} + } -declare module "react-data-grid-addons" { + declare module "react-data-grid-addons" { import Plugins = AdazzleReactDataGridPlugins; import Editors = Plugins.Editors; import Filters = Plugins.Filters; @@ -633,4 +703,4 @@ declare module "react-data-grid-addons" { } } } -} + } diff --git a/types/react-data-grid/react-data-grid-tests.tsx b/types/react-data-grid/react-data-grid-tests.tsx index aa09041846..201e53a3ca 100644 --- a/types/react-data-grid/react-data-grid-tests.tsx +++ b/types/react-data-grid/react-data-grid-tests.tsx @@ -131,7 +131,7 @@ var counties = [ var titles = ['Dr.', 'Mr.', 'Mrs.', 'Miss', 'Ms.']; -var columns:ReactDataGrid.Column[] = [ +var columns:ReactDataGrid.Column[] = [ { key: 'id', name: 'ID', @@ -152,7 +152,7 @@ var columns:ReactDataGrid.Column[] = [ editor: , width: 200, resizable: true, - getRowMetaData: (rowdata: any, column: ReactDataGrid.Column) => { + getRowMetaData: (rowdata: any, column: ReactDataGrid.Column) => { return {}; } }, @@ -262,7 +262,7 @@ class Example extends React.Component { return clonedColumns; } - handleGridRowsUpdated(updatedRowData:ReactDataGrid.GridRowsUpdatedEvent) { + handleGridRowsUpdated(updatedRowData:ReactDataGrid.GridRowsUpdatedEvent) { var rows = this.state.rows; for (var i = updatedRowData.fromRow; i <= updatedRowData.toRow; i++) { @@ -315,12 +315,12 @@ class Example extends React.Component { return this.state.rows.length; } - onRowsSelected(rows: Array) { + onRowsSelected(rows: Array>) { var selectedIndexes = this.state.selectedIndexes as Array; this.setState({selectedIndexes: selectedIndexes.concat(rows.map(r => r.rowIdx))}); } - onRowsDeselected(rows: Array) { + onRowsDeselected(rows: Array>) { var rowIndexes = rows.map(r => r.rowIdx); var selectedIndexes = this.state.selectedIndexes as Array; this.setState({selectedIndexes: selectedIndexes.filter(i => rowIndexes.indexOf(i) === -1 )}); diff --git a/types/react-data-grid/v1/tsconfig.json b/types/react-data-grid/v1/tsconfig.json index c2602fd049..6919c8eb55 100644 --- a/types/react-data-grid/v1/tsconfig.json +++ b/types/react-data-grid/v1/tsconfig.json @@ -20,11 +20,14 @@ "paths": { "react-data-grid": [ "react-data-grid/v1" - ] + ], + "react-data-grid/*": [ + "react-data-grid/v1/*" + ] } }, "files": [ "index.d.ts", "react-data-grid-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-data-grid/v2/index.d.ts b/types/react-data-grid/v2/index.d.ts new file mode 100644 index 0000000000..bfa4ea979f --- /dev/null +++ b/types/react-data-grid/v2/index.d.ts @@ -0,0 +1,636 @@ +// Type definitions for react-data-grid 2.0 +// Project: https://github.com/adazzle/react-data-grid.git +// Definitions by: Simon Gellis , Kieran Peat , Martin Novak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +declare namespace AdazzleReactDataGrid { + + interface SelectionParams { + rowIdx: number, + row: any + } + + interface GridProps { + /** + * Gets the data to render in each row. Required. + * Can be an array or a function that takes an index and returns an object. + */ + rowGetter: Array | ((rowIdx: number) => object) + /** + * The total number of rows to render. Required. + */ + rowsCount: number + /** + * The columns to render. + */ + columns?: Array + + /** + * Invoked when the user changes the value of a single cell. + * Should update that cell's value. + * @param e Information about the event + */ + onRowUpdated?: (e: RowUpdateEvent) => void + /** + * Invoked when the user pulls down the drag handle of an editable cell. + * Should update the values of the selected cells. + * @param e Information about the event + */ + onCellsDragged?: (e: CellDragEvent) => void + /** + * Invoked when the user double clicks on the drag handle of an editable cell. + * Should update the values of the cells beneath the selected cell. + * @param e Information about the event + */ + onDragHandleDoubleClick?: (e: DragHandleDoubleClickEvent) => void + /** + * Invoked when the user copies a value from one cell and pastes it into another (in the same column). + * Should update the value of the cell in row e.toRow. + * @param e Information about the event + */ + onCellCopyPaste?: (e: CellCopyPasteEvent) => void + /** + * Invoked after the user updates the grid rows in any way. + * @param e Information about the event + */ + onGridRowsUpdated?: (e: GridRowsUpdatedEvent) => void + + /** + * A toolbar to display above the grid. + * Consider using the toolbar included in "react-data-grid/addons". + */ + toolbar?: React.ReactElement + /** + * A context menu to disiplay when the user right-clicks a cell. + * Consider using "react-contextmenu", included in "react-data-grid/addons". + */ + contextMenu?: React.ReactElement + /** + * A react component to customize how rows are rendered. + * If you want to define your own, consider extending ReactDataGrid.Row. + */ + rowRenderer?: React.ReactElement | React.ComponentClass | React.StatelessComponent + /** + * A component to display when there are no rows to render. + */ + emptyRowsView?: React.ComponentClass | React.StatelessComponent + + /** + * The minimum width of the entire grid in pixels. + */ + minWidth?: number + /** + * The minimum height of the entire grid in pixels. + * @default 350 + */ + minHeight?: number + /** + * The height of each individual row in pixels. + * @default 35 + */ + rowHeight?: number + /** + * The height of the header row in pixels. + * @default rowHeight + */ + headerRowHeight?: number + /** + * The height of the header filter row in pixels. + * @default 45 + */ + headerFiltersHeight?: number + /** + * The minimum width of each column in pixels. + * @default 80 + */ + minColumnWidth?: number + /** + * Invoked when a column has been resized. + * @param index The index of the column + * @param width The new width of the column + */ + onColumnResize?: (index: number, width: number) => void + + /** + * Controls what happens when the user navigates beyond the first or last cells. + * 'loopOverRow' will navigate to the beginning/end of the current row. + * 'changeRow' will navigate to the beginning of the next row or the end of the last. + * 'none' will do nothing. + * @default none + */ + cellNavigationMode?: 'none' | 'loopOverRow' | 'changeRow' + + /** + * Called when the user sorts the grid by some column. + * Should update the order of the rows returned by rowGetter. + * @param sortColumn The name of the column being sorted by + * @param sortDirection The direction to sort ('ASC'/'DESC'/'NONE') + */ + onGridSort?: (sortColumn: string, sortDirection: 'ASC' | 'DESC' | 'NONE') => void + + /** + * Initial sorting direction + */ + sortDirection?: 'ASC' | 'DESC' | 'NONE' + + /** + * key of the initial sorted column + */ + sortColumn?: string + + /** + * Called when the user filters a column by some value. + * Should restrict the rows in rowGetter to only things that match the filter. + * @param filter The filter being added + */ + onAddFilter?: (filter: Filter) => void + /** + * Called when the user clears all filters. + * Should restore the rows in rowGetter to their original state. + */ + onClearFilters?: () => void + + /** + * When set to true or 'multi', enables multiple row select. + * When set to 'single', enables single row select. + * When set to false or not set, disables row select. + * @default false + */ + enableRowSelect?: boolean | 'single' | 'multi' + /** + * Called when a row is selected. + * @param rows The (complete) current selection of rows. + */ + onRowSelect?: (rows: Array) => void + /** + * A property that's unique to every row. + * This property is required to enable row selection. + * @default 'id' + */ + rowKey?: string + + /** + * Enables cells to be selected when clicked. + * @default false + */ + enableCellSelect?: boolean + + /** + * Enables cells to be dragged and dropped + * @default false + */ + enableDragAndDrop?: boolean + + /** + * Called when a cell is selected. + * @param coordinates The row and column indices of the selected cell. + */ + onCellSelected?: (coordinates: {rowIdx: number, idx: number}) => void + /** + * Called when a cell is deselected. + * @param coordinates The row and column indices of the deselected cell. + */ + onCellDeSelected?: (coordinates: {rowIdx: number, idx: number}) => void + + /** + * How long to wait before rendering a new row while scrolling in milliseconds. + * @default 0 + */ + rowScrollTimeout?: number + /** + * Options object for selecting rows + */ + rowSelection?: { + showCheckbox?: boolean + enableShiftSelect?: boolean + onRowsSelected?: (rows: Array) => void, + onRowsDeselected?: (rows: Array) => void, + selectBy?: { + indexes?: Array; + keys?: { rowKey: string, values: Array }; + isSelectedKey?: string; + } + } + /** + * A custom formatter for the select all checkbox cell + * @default react-data-grid/src/formatters/SelectAll.js + */ + selectAllRenderer?: React.ComponentClass | React.StatelessComponent; + /** + * A custom formatter for select row column + * @default AdazzleReactDataGridPlugins.Editors.CheckboxEditor + */ + rowActionsCell?: React.ComponentClass | React.StatelessComponent; + /** + * An event function called when a row is clicked. + * Clicking the header row will trigger a call with -1 for the rowIdx. + * @param rowIdx zero index number of row clicked + * @param row object behind the row + */ + onRowClick?: (rowIdx : number, row : object) => void + + /** + * An event function called when a row is expanded with the toggle + * @param props OnRowExpandToggle object + */ + onRowExpandToggle?: (props: OnRowExpandToggle ) => void + + /** + * Responsible for returning an Array of values that can be used for filtering + * a column that is column.filterable and using a column.filterRenderer that + * displays a list of options. + * @param columnKey the column key that we are looking to pull values from + */ + getValidFilterValues?: (columnKey: string) => Array + + getCellActions?: (column: Column, row: object) => (ActionButton | ActionMenu)[] + } + + type ActionButton = { + icon: string; + callback: () => void; + } + + type ActionMenu = { + icon: string; + actions: { + icon: string; + text: string; + callback: () => void; + }[]; + } + + /** + * Information about a specific column to be rendered. + */ + interface Column { + /** + * A unique key for this column. Required. + * Each row should have a property with this name, which contains this column's value. + */ + key: string + /** + * This column's display name. Required. + */ + name: string + /** + * A custom width for this specific column. + * @default minColumnWidth from the ReactDataGrid + */ + width?: number + /** + * Whether this column can be resized by the user. + * @default false + */ + resizable?: boolean + /** + * Whether this column should stay fixed on the left as the user scrolls horizontally. + * @default false + */ + locked?: boolean + /** + * Whether this column can be edited. + * @default false + */ + editable?: boolean + /** + * Whether the rows in the grid can be sorted by this column. + * @default false + */ + sortable?: boolean + /** + * Whether the rows in the grid can be filtered by this column. + * @default false + */ + filterable?: boolean; + /** + * A custom formatter for this column's filter. + */ + filterRenderer?: React.ReactElement | React.ComponentClass | React.StatelessComponent; + /** + * The editor for this column. Several editors are available in "react-data-grid/addons". + * @default A simple text editor + */ + editor?: React.ReactElement | React.ComponentClass | React.StatelessComponent + /** + * A custom read-only formatter for this column. An image formatter is available in "react-data-grid/addons". + */ + formatter?: React.ReactElement | React.ComponentClass | React.StatelessComponent + /** + * A custom formatter for this column's header. + */ + headerRenderer?: React.ReactElement | React.ComponentClass | React.StatelessComponent + /** + * Events to be bound to the cells in this specific column. + * Each event must respect this standard in order to work correctly: + * @example + * function onXxx(ev :SyntheticEvent, (rowIdx, idx, name): args) + */ + events?: { + [name: string]: ColumnEventCallback + } + /** + * Retrieve meta data about the row, optionally provide column as a second argument + */ + getRowMetaData?: (rowdata: any, column?: Column) => any; + /** + * A class name to be applied to the cells in the column + */ + cellClass?: string; + /** + * Whether this column can be dragged (re-arranged). + * @default false + */ + draggable?: boolean; + } + + interface ColumnEventCallback { + /** + * A callback for a native react event on a specific cell. + * @param ev The react event + * @param args The row and column coordinates of the cell, and the name of the event. + */ + (ev: React.SyntheticEvent, args: {rowIdx: number, idx: number, name: string}): void + } + + /** + * Information about a row update + */ + interface RowUpdateEvent { + /** + * The index of the updated row. + */ + rowIdx: number + /** + * The columns that were updated and their values. + */ + updated: object + /** + * The name of the column that was updated. + */ + cellKey: string + /** + * The name of the key pressed to trigger the event ('Tab', 'Enter', etc.). + */ + key: string + } + + /** + * Information about a cell drag + */ + interface CellDragEvent { + /** + * The name of the column that was dragged. + */ + cellKey: string + /** + * The row where the drag began. + */ + fromRow: number + /** + * The row where the drag ended. + */ + toRow: number + /** + * The value of the cell that was dragged. + */ + value: any + } + + /** + * Information about a drag handle double click + */ + interface DragHandleDoubleClickEvent { + /** + * The row where the double click occurred. + */ + rowIdx: number + /** + * The column where the double click occurred. + */ + idx: number + /** + * The values of the row. + */ + rowData: object + /** + * The double click event. + */ + e: React.SyntheticEvent + } + + /** + * Information about a copy paste + */ + interface CellCopyPasteEvent { + /** + * The row that was pasted to. + */ + rowIdx: number + /** + * The value that was pasted. + */ + value: any + /** + * The row that was copied from. + */ + fromRow: number + /** + * The row that was pasted to. + */ + toRow: number + /** + * The key of the column where the copy paste occurred. + */ + cellKey: string + } + + /** + * Information about some update to the grid's contents + */ + interface GridRowsUpdatedEvent { + /** + * The key of the column where the event occurred. + */ + cellKey: string + /** + * The top row affected by the event. + */ + fromRow: number + /** + * The bottom row affected by the event. + */ + toRow: number + /** + * The columns that were updated and their values. + */ + updated: object + /** + * The action that occurred to trigger this event. + * One of 'cellUpdate', 'cellDrag', 'columnFill', or 'copyPaste'. + */ + action: 'cellUpdate' | 'cellDrag' | 'columnFill' | 'copyPaste' + } + + /** + * Information about the row toggler + */ + interface OnRowExpandToggle { + /** + * The name of the column group the row is in + */ + columnGroupName: string + /** + * The name of the expanded row + */ + name: string + /** + * If it should expand or not + */ + shouldExpand: boolean + } + + /** + * Some filter to be applied to the grid's contents + */ + interface Filter { + /** + * The key of the column being filtered. + */ + columnKey: string + /** + * The term to filter by. + */ + filterTerm: string + } + + /** + * Excel-like grid component built with React, with editors, keyboard navigation, copy & paste, and the like + * http://adazzle.github.io/react-data-grid/ + */ + export class ReactDataGrid extends React.Component { + /** + * Opens the editor for the cell (idx) in the given row (rowIdx). If the column is not editable then nothing will happen. + */ + openCellEditor(rowIdx: number, idx: number): void; + } + export namespace ReactDataGrid { + // Useful types + export import Column = AdazzleReactDataGrid.Column; + export import Filter = AdazzleReactDataGrid.Filter; + + // Various events + export import RowUpdateEvent = AdazzleReactDataGrid.RowUpdateEvent; + export import SelectionParams = AdazzleReactDataGrid.SelectionParams; + export import CellDragEvent = AdazzleReactDataGrid.CellDragEvent; + export import DragHandleDoubleClickEvent = AdazzleReactDataGrid.DragHandleDoubleClickEvent; + export import CellCopyPasteEvent = AdazzleReactDataGrid.CellCopyPasteEvent; + export import GridRowsUpdatedEvent = AdazzleReactDataGrid.GridRowsUpdatedEvent; + export import OnRowExpandToggle = AdazzleReactDataGrid.OnRowExpandToggle; + + // Actual classes exposed on module.exports + /** + * A react component that renders a row of the grid + */ + export class Row extends React.Component { } + /** + * A react coponent that renders a cell of the grid + */ + export class Cell extends React.Component { } + } +} + +declare namespace AdazzleReactDataGridPlugins { + // TODO: refine types for these addons + export namespace Editors { + export class AutoComplete extends React.Component { } + export class DropDownEditor extends React.Component { } + export class SimpleTextEditor extends React.Component { } + export class CheckboxEditor extends React.Component { } + } + export namespace Filters { + export class NumericFilter extends React.Component { } + export class AutoCompleteFilter extends React.Component { } + export class MultiSelectFilter extends React.Component { } + export class SingleSelectFilter extends React.Component { } + } + export namespace Formatters { + export class ImageFormatter extends React.Component { } + export class DropDownFormatter extends React.Component { } + } + export class Toolbar extends React.Component {} + export namespace DraggableHeader { + export class DraggableContainer extends React.Component{ } + } + export namespace Data { + export const Selectors: { + getRows: (state: object) => object[]; + getSelectedRowsByKey: (state: object) => object[]; + } + } + // TODO: re-export the react-contextmenu typings once those exist + // https://github.com/vkbansal/react-contextmenu/issues/10 + export namespace Menu { + export class ContextMenu extends React.Component { } + export class MenuHeader extends React.Component { } + export class MenuItem extends React.Component { } + export class SubMenu extends React.Component { } + export const monitor: { + getItem(): any + getPosition(): any + hideMenu(): void + }; + export function connect(Menu: any): any; + export function ContextMenuLayer( + identifier: any, + configure?: (props: any) => any + ): (Component: any) => any + } +} + +declare module "react-data-grid" { + import ReactDataGrid = AdazzleReactDataGrid.ReactDataGrid; + + // commonjs export + export = ReactDataGrid; +} + +declare module "react-data-grid-addons" { + import Plugins = AdazzleReactDataGridPlugins; + import Editors = Plugins.Editors; + import Filters = Plugins.Filters; + import Formatters = Plugins.Formatters; + import Toolbar = Plugins.Toolbar; + import Menu = Plugins.Menu; + import Data = Plugins.Data; + import DraggableHeader = Plugins.DraggableHeader; + + // ES6 named exports + export { + Editors, + Filters, + Formatters, + Toolbar, + Menu, + Data, + DraggableHeader + } + + // attach to window + global { + interface Window { + ReactDataGridPlugins: { + Editors: typeof Editors, + Filters: typeof Filters, + Formatters: typeof Formatters, + Toolbar: typeof Toolbar, + Menu: typeof Menu, + Data: typeof Data, + DraggableHeader: typeof DraggableHeader + } + } + } +} diff --git a/types/react-data-grid/v2/react-data-grid-tests.tsx b/types/react-data-grid/v2/react-data-grid-tests.tsx new file mode 100644 index 0000000000..aa09041846 --- /dev/null +++ b/types/react-data-grid/v2/react-data-grid-tests.tsx @@ -0,0 +1,362 @@ +import * as React from 'react'; +import ReactDataGrid = require('react-data-grid'); +import * as ReactDataGridPlugins from 'react-data-grid-addons'; +import faker = require('faker'); + +var Editors = ReactDataGridPlugins.Editors; +var Toolbar = ReactDataGridPlugins.Toolbar; +var AutoCompleteEditor = Editors.AutoComplete; +var DropDownEditor = Editors.DropDownEditor; +var { Selectors } = ReactDataGridPlugins.Data; + +class CustomFilterHeaderCell extends React.Component { + state = { + filterTerm: "" + }; + handleChange(e: any) { + let val = e.target.value; + this.setState({filterTerm: val}); + this.props.onChange({filterTerm: val, column: this.props.column}); + } + render() { + return ( +
+ this.handleChange(e)} /> +
+ ); + } +} + +class CustomRowSelectorCell extends ReactDataGridPlugins.Editors.CheckboxEditor { + render(){ + return super.render(); + } +} + +export interface ICustomSelectAllProps { + onChange: any; + inputRef: any; +} + +class CustomSelectAll extends React.Component { + render() { + return ( +
+ + +
+ ); + } +} + +faker.locale = 'en_GB'; + +function createFakeRowObjectData(index:number):Object { + return { + id: 'id_' + index, + avartar: faker.image.avatar(), + county: faker.address.county(), + email: faker.internet.email(), + title: faker.name.prefix(), + firstName: faker.name.firstName(), + lastName: faker.name.lastName(), + street: faker.address.streetName(), + zipCode: faker.address.zipCode(), + date: faker.date.past().toLocaleDateString(), + bs: faker.company.bs(), + catchPhrase: faker.company.catchPhrase(), + companyName: faker.company.companyName(), + words: faker.lorem.words(), + sentence: faker.lorem.sentence() + }; +} + +function createRows(numberOfRows:number) { + var rows:Object[] = []; + for (var i = 0; i < numberOfRows; i++) { + rows[i] = createFakeRowObjectData(i); + } + return rows; +} + +var counties = [ + {id: 0, title: 'Bedfordshire'}, + {id: 1, title: 'Berkshire'}, + {id: 2, title: 'Buckinghamshire'}, + {id: 3, title: 'Cambridgeshire'}, + {id: 4, title: 'Cheshire'}, + {id: 5, title: 'Cornwall'}, + {id: 6, title: 'Cumbria, (Cumberland)'}, + {id: 7, title: 'Derbyshire'}, + {id: 8, title: 'Devon'}, + {id: 9, title: 'Dorset'}, + {id: 10, title: 'Durham'}, + {id: 11, title: 'Essex'}, + {id: 12, title: 'Gloucestershire'}, + {id: 13, title: 'Hampshire'}, + {id: 14, title: 'Hertfordshire'}, + {id: 15, title: 'Huntingdonshire'}, + {id: 16, title: 'Kent'}, + {id: 17, title: 'Lancashire'}, + {id: 18, title: 'Leicestershire'}, + {id: 19, title: 'Lincolnshire'}, + {id: 20, title: 'Middlesex'}, + {id: 21, title: 'Norfolk'}, + {id: 22, title: 'Northamptonshire'}, + {id: 23, title: 'Northumberland'}, + {id: 24, title: 'Nottinghamshire'}, + {id: 25, title: 'Northamptonshire'}, + {id: 26, title: 'Oxfordshire'}, + {id: 27, title: 'Northamptonshire'}, + {id: 28, title: 'Rutland'}, + {id: 29, title: 'Shropshire'}, + {id: 30, title: 'Somerset'}, + {id: 31, title: 'Staffordshire'}, + {id: 32, title: 'Suffolk'}, + {id: 33, title: 'Surrey'}, + {id: 34, title: 'Sussex'}, + {id: 35, title: 'Warwickshire'}, + {id: 36, title: 'Westmoreland'}, + {id: 37, title: 'Wiltshire'}, + {id: 38, title: 'Worcestershire'}, + {id: 39, title: 'Yorkshire'} +]; + +var titles = ['Dr.', 'Mr.', 'Mrs.', 'Miss', 'Ms.']; + +var columns:ReactDataGrid.Column[] = [ + { + key: 'id', + name: 'ID', + width: 80, + resizable: true + }, + { + key: 'avartar', + name: 'Avartar', + width: 60, + formatter: ReactDataGridPlugins.Formatters.ImageFormatter, + resizable: true, + headerRenderer: + }, + { + key: 'county', + name: 'County', + editor: , + width: 200, + resizable: true, + getRowMetaData: (rowdata: any, column: ReactDataGrid.Column) => { + return {}; + } + }, + { + key: 'title', + name: 'Title', + editor: , + width: 200, + resizable: true, + events: { + onDoubleClick: function () { + console.log("The user double clicked on title column"); + } + } + }, + { + key: 'firstName', + name: 'First Name', + editable: true, + width: 200, + resizable: true + }, + { + key: 'lastName', + name: 'Last Name', + editable: true, + width: 200, + resizable: true + }, + { + key: 'email', + name: 'Email', + editable: true, + width: 200, + resizable: true + }, + { + key: 'street', + name: 'Street', + editable: true, + width: 200, + resizable: true + }, + { + key: 'zipCode', + name: 'ZipCode', + editable: true, + width: 200, + resizable: true + }, + { + key: 'date', + name: 'Date', + editable: true, + width: 200, + resizable: true + }, + { + key: 'bs', + name: 'bs', + editable: true, + width: 200, + resizable: true + }, + { + key: 'catchPhrase', + name: 'Catch Phrase', + editable: true, + width: 200, + resizable: true + }, + { + key: 'companyName', + name: 'Company Name', + editable: true, + width: 200, + resizable: true, + filterable: true, + filterRenderer: CustomFilterHeaderCell + }, + { + key: 'sentence', + name: 'Sentence', + editable: true, + width: 200, + resizable: true, + cellClass: 'sentence-class' + } +]; + +class Example extends React.Component { + getInitialState() { + var fakeRows = createRows(2000); + return {rows: fakeRows}; + } + + getColumns() { + var clonedColumns = columns.slice(); + clonedColumns[2].events = { + onClick: function (ev:React.SyntheticEvent, args:{idx:number, rowIdx:number}) { + var idx = args.idx; + var rowIdx = args.rowIdx; + this.refs.grid.openCellEditor(rowIdx, idx); + }.bind(this) + }; + + return clonedColumns; + } + + handleGridRowsUpdated(updatedRowData:ReactDataGrid.GridRowsUpdatedEvent) { + var rows = this.state.rows; + + for (var i = updatedRowData.fromRow; i <= updatedRowData.toRow; i++) { + var rowToUpdate = rows[i]; + var updatedRow = Object.assign({}, rowToUpdate, updatedRowData.updated); + rows[i] = updatedRow; + } + + this.setState({rows: rows}); + } + + onRowExpandToggle = ({ columnGroupName, name, shouldExpand }:ReactDataGrid.OnRowExpandToggle ) => { + let expandedRows = Object.assign({}, this.state.expandedRows); + expandedRows[columnGroupName] = Object.assign({}, expandedRows[columnGroupName]); + expandedRows[columnGroupName][name] = {isExpanded: shouldExpand}; + this.setState({expandedRows: expandedRows}); + } + + onRowClick(rowIdx:number, row: Object) { + // Do nothing, just test that it accepts an event + } + + getRows() { + const rows = Selectors.getRows(this.state); + console.log(rows); + return rows; + } + + handleAddRow(e:any) { + var newRow = { + value: e.newRowIndex, + userStory: '', + developer: '', + epic: '' + }; + var rows = this.state.rows; + rows.push(newRow); + this.setState({rows: rows}); + } + + getRowAt(index:number) { + this.getRows(); + if (index < 0 || index > this.getSize()) { + return undefined; + } + return this.state.rows[index]; + } + + getSize() { + return this.state.rows.length; + } + + onRowsSelected(rows: Array) { + var selectedIndexes = this.state.selectedIndexes as Array; + + this.setState({selectedIndexes: selectedIndexes.concat(rows.map(r => r.rowIdx))}); + } + onRowsDeselected(rows: Array) { + var rowIndexes = rows.map(r => r.rowIdx); + var selectedIndexes = this.state.selectedIndexes as Array; + this.setState({selectedIndexes: selectedIndexes.filter(i => rowIndexes.indexOf(i) === -1 )}); + } + + render() { + let selectedRows = ['id1', 'id2']; + return ( + } + enableRowSelect={true} + rowHeight={50} + minHeight={600} + rowScrollTimeout={200} + rowSelection={{ + showCheckbox: true, + enableShiftSelect: true, + onRowsSelected: this.onRowsSelected, + onRowsDeselected: this.onRowsDeselected, + selectBy: { + keys: {rowKey: 'id', values: selectedRows} + } + }} + rowActionsCell={CustomRowSelectorCell} + selectAllRenderer={CustomSelectAll} + onRowClick={this.onRowClick} + /> + + ); + } +} diff --git a/types/react-data-grid/v2/tsconfig.json b/types/react-data-grid/v2/tsconfig.json new file mode 100644 index 0000000000..1f5bd63312 --- /dev/null +++ b/types/react-data-grid/v2/tsconfig.json @@ -0,0 +1,33 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "jsx": "react", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "react-data-grid": [ + "react-data-grid/v2" + ], + "react-data-grid/*": [ + "react-data-grid/v2/*" + ] + } + }, + "files": [ + "index.d.ts", + "react-data-grid-tests.tsx" + ] +} diff --git a/types/react-data-grid/v2/tslint.json b/types/react-data-grid/v2/tslint.json new file mode 100644 index 0000000000..637071b426 --- /dev/null +++ b/types/react-data-grid/v2/tslint.json @@ -0,0 +1,80 @@ +{ + "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-object-spread": 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 + } +} diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 6a54805118..f66e46cb1e 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -2179,7 +2179,7 @@ export interface WebViewIOSLoadRequestEvent { loading: boolean; title: string; canGoForward: boolean; - navigationType: "other" | "click"; + navigationType: "click" | "formsubmit" | "backforward" | "reload" | "formresubmit" | "other"; url: string; } @@ -2252,7 +2252,7 @@ export interface WebViewUriSource { * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ - method?: string; + method?: "GET" | "POST"; /* * Additional HTTP headers to send with the request. diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index b5a0a5c4cb..8bc6757c48 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -628,6 +628,7 @@ class WebViewTest extends React.Component { originWhitelist={['https://origin.test']} saveFormDataDisabled={false} nativeConfig={{ component: 'test', props: {}, viewManager: {} }} + onShouldStartLoadWithRequest={(event) => event.navigationType !== 'formresubmit'} /> ); } diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 852d6594c4..fe4e70eacb 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -24,11 +24,11 @@ declare namespace wx { /** 文件的临时路径 */ tempFilePath: string; } - interface BaseOptions { + interface BaseOptions { /** 接口调用成功的回调函数 */ - success?(res: any): void; + success?(res: R): void; /** 接口调用失败的回调函数 */ - fail?(res: any): void; + fail?(res: E): void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?(res: any): void; } @@ -41,7 +41,7 @@ declare namespace wx { interface RequestHeader { [key: string]: string; } - interface RequestOptions extends BaseOptions { + interface RequestOptions extends BaseOptions { /** 开发者服务器接口地址 */ url: string; /** 请求的参数 */ @@ -2997,8 +2997,10 @@ declare namespace wx { type CheckSessionOption = BaseOptions; /** * 检测当前用户登录态是否有效。 - * 通过wx.login获得的用户登录态拥有一定的时效性。用户越久未使用小程序,用户登录态越有可能失效。反之如果用户一直在使用小程序,则用户登录态一直保持有效。具体时效逻辑由微信维护,对开发者透明。开发者只需要调用wx.checkSession接口检测当前用户登录态是否有效。登录态过期后开发者可以再调用wx.login获取新的用户登录态。 - * + * 通过wx.login获得的用户登录态拥有一定的时效性。用户越久未使用小程序,用户登录态越有可能失效。 + * 反之如果用户一直在使用小程序,则用户登录态一直保持有效。具体时效逻辑由微信维护,对开发者透明。 + * 开发者只需要调用wx.checkSession接口检测当前用户登录态是否有效。 + * 登录态过期后开发者可以再调用wx.login获取新的用户登录态。 */ function checkSession(options: CheckSessionOption): void; /** @@ -3487,6 +3489,59 @@ declare namespace wx { } // #endregion // #region 接口 + interface Logger { + /** + * 写log日志,可以提供任意个参数,每个参数的类型为Object/Array/Number/String,参数p1到pN的内容会写入日志 + */ + log: (...args: any[]) => void; + /** + * 写warn日志,参数同log方法 + */ + warn: (...args: any[]) => void; + /** + * 写debug日志,参数同log方法 + */ + debug: (...args: any[]) => void; + /** + * 写info日志,参数同log方法 + */ + info: (...args: any[]) => void; + } + + // #region LogManager + /** + * 获取日志管理器 logManager 对象。logManager提供log、info、warn、debug四个方法写日志到文件, + * 这四个方法接受任意个类型为Object/Array/Number/String的参数, + * 每次调用的参数的总大小不超过100Kb。最多保存5M的日志内容,超过5M后,旧的日志内容会被删除。 + * 用户可以通过设置Button组件的open-type为feedback来上传打印的日志。 + * 用户上传的日志可以通过登录小程序管理后台后进入左侧菜单“客服反馈”页面获取到。 + */ + function getLogManager(): Logger; + + /** + * 自定义业务数据监控上报接口。使用前,需要在小程序管理后台-运维中心-性能监控-业务数据监控中新建监控事件, + * 配置监控描述与告警类型。每一个监控事件对应唯一的监控ID,开发者最多可以创建128个监控事件。 + * @param name 监控ID,在小程序管理后台新建数据指标后获得 + * @param value 上报数值,经处理后会在小程序管理后台上展示每分钟的上报总量 + */ + function reportMonitor(name: string, value: number): void; + + /** + * 用于延迟一部分操作到下一个时间片再执行(类似于 setTimeout)。 + * @param func + * @version 2.2.3 + */ + function nextTick(func: () => any): void; + + function setEnableDebug(options: EnableDebugOptions): void; + // #endregion + + // #endregion + + interface EnableDebugOptions extends BaseOptions { + enableDebug: boolean; + } + // #region App里的onLaunch、onShow回调参数 /** * App 实现的接口对象 * 开发者可以添加任意的函数或数据到 Object 参数中,用 this 可以访问 @@ -3532,6 +3587,7 @@ declare namespace wx { getCurrentPage(): Page; } // #endregion + // #region Compontent组件 type DefaultData = object | ((this: V) => object); diff --git a/types/weixin-app/weixin-app-tests.ts b/types/weixin-app/weixin-app-tests.ts index 6ae60ca85d..44ffb6254f 100644 --- a/types/weixin-app/weixin-app-tests.ts +++ b/types/weixin-app/weixin-app-tests.ts @@ -1,424 +1,436 @@ getCurrentPages(); interface MyOwnEvent - extends wx.CustomEvent< - "my-own", - { - hello: string; - } - > { } + extends wx.CustomEvent< + "my-own", + { + hello: string; + } + > { } let behavior = Behavior({ - behaviors: [], - properties: { - myBehaviorProperty: { - type: String - } - }, - data: { - myBehaviorData: "" - }, - attached() { }, - methods: { - myBehaviorMethod() { - const s: string = this.data.myBehaviorData; - } - } + behaviors: [], + properties: { + myBehaviorProperty: { + type: String + } + }, + data: { + myBehaviorData: "" + }, + attached() { }, + methods: { + myBehaviorMethod() { + const s: string = this.data.myBehaviorData; + } + } }); Component({ - behaviors: [behavior, "wx://form-field"], + behaviors: [behavior, "wx://form-field"], - options: { - multipleSlots: false, - addGlobalClass: false - }, + options: { + multipleSlots: false, + addGlobalClass: false + }, - properties: { - myProperty: { - // 属性名 - type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型) - value: "", // 属性初始值(可选),如果未指定则会根据类型选择一个 - observer(newVal: string, oldVal: string, changedPath: string) { - const anotherKey = newVal + changedPath; - this.setData({ - anotherKey - }); - } // 属性被改变时执行的函数(可选),也可以写成在methods段中定义的方法名字符串, 如:'_propertyChange' - }, - myProperty2: String // 简化的定义方式 - }, - data: { - key: "value", - anotherKey: "value" - }, // 私有数据,可用于模版渲染 + properties: { + myProperty: { + // 属性名 + type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型) + value: "", // 属性初始值(可选),如果未指定则会根据类型选择一个 + observer(newVal: string, oldVal: string, changedPath: string) { + const anotherKey = newVal + changedPath; + this.setData({ + anotherKey + }); + } // 属性被改变时执行的函数(可选),也可以写成在methods段中定义的方法名字符串, 如:'_propertyChange' + }, + myProperty2: String // 简化的定义方式 + }, + data: { + key: "value", + anotherKey: "value" + }, // 私有数据,可用于模版渲染 - lifetimes: { - attached() { }, + lifetimes: { + attached() { + wx.setEnableDebug({ + enableDebug: true, + success(res) { } + }); - detached() { - this.setData( - { - key: null - }, - () => { } - ); - } - }, + wx.reportMonitor("123", 123); - pageLifetimes: { - show() { }, - hide() { } - }, + wx.getLogManager().info("123"); + wx.getLogManager().log("123"); + wx.getLogManager().warn("123"); + wx.getLogManager().debug("123"); + }, - // 生命周期函数,可以为函数,或一个在methods段中定义的方法名 - attached() { - this.setData( - { - key: "123" - }, - () => { } - ); - }, + detached() { + this.setData( + { + key: null + }, + () => { } + ); + } + }, - moved() { }, + pageLifetimes: { + show() { }, + hide() { } + }, - detached() { }, + // 生命周期函数,可以为函数,或一个在methods段中定义的方法名 + attached() { + this.setData( + { + key: "123" + }, + () => { } + ); + }, - methods: { - readMyDataAndMyProps() { - const stringValue1: string = this.data.myProperty; - const stringValue2: string = this.data.myProperty2; - const stringValue3: string = this.data.key; - this.data.anotherKey; - this.properties.myProperty; - this.properties.myProperty2; - this.properties.key; - this.properties.anotherKey; - this.setData({ - key: stringValue1 + stringValue2 + stringValue3 - }); - }, - onMyButtonTap() { - // 更新属性和数据的方法与更新页面数据的方法类似 - this.setData({ - key: 123 // note this is edge case where it cannot detect wrong types... - }); - }, - _myPrivateMethod() { - // 内部方法建议以下划线开头 - // this.replaceDataOnPath(['A', 0, 'B'], 'myPrivateData'); // 这里将 data.A[0].B 设为 'myPrivateData' - // this.applyDataUpdates(); - this.setData({ - anotherKey: 123 - }); - }, - _propertyChange(newVal: string, oldVal: string) { - // - } - }, - relations: { - "./custom-ul": { - type: "parent", // 关联的目标节点应为父节点 - linked(target: wx.Component<{ key: string }, {}>) { - // 每次被插入到custom-ul时执行,target是custom-ul节点实例对象,触发在attached生命周期之后 - target.data.key; - }, - linkChanged(target: wx.Component<{ key: string }, {}>) { - // 每次被移动后执行,target是custom-ul节点实例对象,触发在moved生命周期之后 - target.data.key; - }, - unlinked(target: wx.Component<{ key: string }, {}>) { - // 每次被移除时执行,target是custom-ul节点实例对象,触发在detached生命周期之后 - target.data.key; - } - } - } + moved() { }, + + detached() { }, + + methods: { + readMyDataAndMyProps() { + const stringValue1: string = this.data.myProperty; + const stringValue2: string = this.data.myProperty2; + const stringValue3: string = this.data.key; + this.data.anotherKey; + this.properties.myProperty; + this.properties.myProperty2; + this.properties.key; + this.properties.anotherKey; + this.setData({ + key: stringValue1 + stringValue2 + stringValue3 + }); + }, + onMyButtonTap() { + // 更新属性和数据的方法与更新页面数据的方法类似 + this.setData({ + key: 123 // note this is edge case where it cannot detect wrong types... + }); + }, + _myPrivateMethod() { + // 内部方法建议以下划线开头 + // this.replaceDataOnPath(['A', 0, 'B'], 'myPrivateData'); // 这里将 data.A[0].B 设为 'myPrivateData' + // this.applyDataUpdates(); + this.setData({ + anotherKey: 123 + }); + }, + _propertyChange(newVal: string, oldVal: string) { + // + } + }, + relations: { + "./custom-ul": { + type: "parent", // 关联的目标节点应为父节点 + linked(target: wx.Component<{ key: string }, {}>) { + // 每次被插入到custom-ul时执行,target是custom-ul节点实例对象,触发在attached生命周期之后 + target.data.key; + }, + linkChanged(target: wx.Component<{ key: string }, {}>) { + // 每次被移动后执行,target是custom-ul节点实例对象,触发在moved生命周期之后 + target.data.key; + }, + unlinked(target: wx.Component<{ key: string }, {}>) { + // 每次被移除时执行,target是custom-ul节点实例对象,触发在detached生命周期之后 + target.data.key; + } + } + } }); // index.js Page({ - data: { - text: "This is page data." - }, - onLoad() { - // Do some initialize when page load. - this.setData({}, () => { - // callback - }); - }, - onReady: () => { - // Do something when page ready. - }, - onShow: () => { - // Do something when page show. - }, - onHide: () => { - // Do something when page hide. - }, - onUnload: () => { - // Do something when page close. - }, - onPullDownRefresh: () => { - // Do something when pull down. - }, - onReachBottom: () => { - // Do something when page reach bottom. - }, - onShareAppMessage: res => { - if (res && res.from === "menu") { - // - } - // return custom share data when user share. - return { - success(res) { - console.log(res.shareTickets.length); - } - }; - }, - onPageScroll: () => { - // this. - // Do something when page scroll - }, - onTabItemTap(item: any) { - this.setData({ - 1: null, - _2: "undefined" - }); - console.log(item.index); - console.log(item.pagePath); - console.log(item.text); - }, - // Event handler. - viewTap() { - this.setData( - { - text: "Set some data for updating view." - }, - () => { - // this is setData callback - } - ); - }, - customData: { - hi: "MINA" - }, - onMyOwnEvent(e: MyOwnEvent) { - e.detail.hello; - }, - onTouchStart(e: wx.TouchStartEvent) { - e.touches; - e.detail.x; - e.detail.y; - }, - onTouchEnd(e: wx.TouchEndEvent) { - e.touches; - e.detail.x; - e.detail.y; - }, - onTouchCancel(e: wx.TouchCancelEvent) { - e.touches; - e.detail.x; - e.detail.y; - }, - onTouchMove(e: wx.TouchMoveEvent) { - e.touches; - e.detail.x; - e.detail.y; - } + data: { + text: "This is page data." + }, + onLoad() { + // Do some initialize when page load. + this.setData({}, () => { + // callback + }); + }, + onReady: () => { + // Do something when page ready. + }, + onShow: () => { + // Do something when page show. + }, + onHide: () => { + // Do something when page hide. + }, + onUnload: () => { + // Do something when page close. + }, + onPullDownRefresh: () => { + // Do something when pull down. + }, + onReachBottom: () => { + // Do something when page reach bottom. + }, + onShareAppMessage: res => { + if (res && res.from === "menu") { + // + } + // return custom share data when user share. + return { + success(res) { + console.log(res.shareTickets.length); + } + }; + }, + onPageScroll: () => { + // this. + // Do something when page scroll + }, + onTabItemTap(item: any) { + this.setData({ + 1: null, + _2: "undefined" + }); + console.log(item.index); + console.log(item.pagePath); + console.log(item.text); + }, + // Event handler. + viewTap() { + this.setData( + { + text: "Set some data for updating view." + }, + () => { + // this is setData callback + } + ); + }, + customData: { + hi: "MINA" + }, + onMyOwnEvent(e: MyOwnEvent) { + e.detail.hello; + }, + onTouchStart(e: wx.TouchStartEvent) { + e.touches; + e.detail.x; + e.detail.y; + }, + onTouchEnd(e: wx.TouchEndEvent) { + e.touches; + e.detail.x; + e.detail.y; + }, + onTouchCancel(e: wx.TouchCancelEvent) { + e.touches; + e.detail.x; + e.detail.y; + }, + onTouchMove(e: wx.TouchMoveEvent) { + e.touches; + e.detail.x; + e.detail.y; + } }); Page({ - getScrollOffset: () => { - wx.createSelectorQuery() - .selectViewport() - .scrollOffset(res => { - res.id; // 节点的ID - res.dataset; // 节点的dataset - res.scrollLeft; // 节点的水平滚动位置 - res.scrollTop; // 节点的竖直滚动位置 - }) - .exec(); - } + getScrollOffset: () => { + wx.createSelectorQuery() + .selectViewport() + .scrollOffset(res => { + res.id; // 节点的ID + res.dataset; // 节点的dataset + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + }) + .exec(); + } }); Page({ - getFields: () => { - wx.createSelectorQuery() - .select("#the-id") - .fields( - { - id: true, - dataset: true, - size: true, - scrollOffset: true, - properties: ["scrollX", "scrollY"] - }, - res => { - // res. - res.dataset; // 节点的dataset - res.width; // 节点的宽度 - res.height; // 节点的高度 - res.scrollLeft; // 节点的水平滚动位置 - res.scrollTop; // 节点的竖直滚动位置 - res.scrollX; // 节点 scroll-x 属性的当前值 - res.scrollY; // 节点 scroll-x 属性的当前值 - } - ) - .exec(); - } + getFields: () => { + wx.createSelectorQuery() + .select("#the-id") + .fields( + { + id: true, + dataset: true, + size: true, + scrollOffset: true, + properties: ["scrollX", "scrollY"] + }, + res => { + // res. + res.dataset; // 节点的dataset + res.width; // 节点的宽度 + res.height; // 节点的高度 + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + res.scrollX; // 节点 scroll-x 属性的当前值 + res.scrollY; // 节点 scroll-x 属性的当前值 + } + ) + .exec(); + } }); Page({ - getRect: () => { - wx.createSelectorQuery() - .select("#the-id") - .boundingClientRect((rect: wx.NodesRefRect) => { - rect.id; // 节点的ID - rect.dataset; // 节点的dataset - rect.left; // 节点的左边界坐标 - rect.right; // 节点的右边界坐标 - rect.top; // 节点的上边界坐标 - rect.bottom; // 节点的下边界坐标 - rect.width; // 节点的宽度 - rect.height; // 节点的高度 - }) - .exec(); - }, - getAllRects: () => { - wx.createSelectorQuery() - .selectAll(".a-class") - .boundingClientRect((rects: wx.NodesRefRect[]) => { - rects.forEach(rect => { - rect.id; // 节点的ID - rect.dataset; // 节点的dataset - rect.left; // 节点的左边界坐标 - rect.right; // 节点的右边界坐标 - rect.top; // 节点的上边界坐标 - rect.bottom; // 节点的下边界坐标 - rect.width; // 节点的宽度 - rect.height; // 节点的高度 - }); - }) - .exec(); - } + getRect: () => { + wx.createSelectorQuery() + .select("#the-id") + .boundingClientRect((rect: wx.NodesRefRect) => { + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }) + .exec(); + }, + getAllRects: () => { + wx.createSelectorQuery() + .selectAll(".a-class") + .boundingClientRect((rects: wx.NodesRefRect[]) => { + rects.forEach(rect => { + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }); + }) + .exec(); + } }); const recorderManager = wx.getRecorderManager(); recorderManager.onStart(() => { - console.log("recorder start"); + console.log("recorder start"); }); recorderManager.onResume(() => { - console.log("recorder resume"); + console.log("recorder resume"); }); recorderManager.onPause(() => { - console.log("recorder pause"); + console.log("recorder pause"); }); recorderManager.onStop(res => { - console.log("recorder stop", res); - const { tempFilePath } = res; + console.log("recorder stop", res); + const { tempFilePath } = res; }); recorderManager.onFrameRecorded(res => { - const { frameBuffer } = res; - console.log("frameBuffer.byteLength", frameBuffer.byteLength); + const { frameBuffer } = res; + console.log("frameBuffer.byteLength", frameBuffer.byteLength); }); const options = { - duration: 10000, - sampleRate: 44100, - numberOfChannels: 1, - encodeBitRate: 192000, - format: "aac", - frameSize: 50 + duration: 10000, + sampleRate: 44100, + numberOfChannels: 1, + encodeBitRate: 192000, + format: "aac", + frameSize: 50 }; recorderManager.start(options); wx.onGetWifiList(res => { - if (res.wifiList.length) { - wx.setWifiList({ - wifiList: [ - { - SSID: res.wifiList[0].SSID, - BSSID: res.wifiList[0].BSSID, - password: "123456" - } - ] - }); - } else { - wx.setWifiList({ - wifiList: [] - }); - } + if (res.wifiList.length) { + wx.setWifiList({ + wifiList: [ + { + SSID: res.wifiList[0].SSID, + BSSID: res.wifiList[0].BSSID, + password: "123456" + } + ] + }); + } else { + wx.setWifiList({ + wifiList: [] + }); + } }); wx.getWifiList(); wx.onWifiConnected(wifi => { - // wifi.BSSID + // wifi.BSSID }); wx.getConnectedWifi({ - success(result) { - result.signalStrength; - } + success(result) { + result.signalStrength; + } }); wx.getWeRunData({ - success(res) { - const encryptedData = res.encryptedData; - } + success(res) { + const encryptedData = res.encryptedData; + } }); const uploadTask = wx.uploadFile({ - url: "http://example.weixin.qq.com/upload", // 仅为示例,非真实的接口地址 - filePath: "/local/folder/file.ext", - name: "file", - formData: { - user: "test" - }, - success: res => { - const data = res.data; - // do something - } + url: "http://example.weixin.qq.com/upload", // 仅为示例,非真实的接口地址 + filePath: "/local/folder/file.ext", + name: "file", + formData: { + user: "test" + }, + success: res => { + const data = res.data; + // do something + } }); uploadTask.onProgressUpdate(res => { - console.log("上传进度", res.progress); - console.log("已经上传的数据长度", res.totalBytesSent); - console.log("预期需要上传的数据总长度", res.totalBytesExpectedToSend); + console.log("上传进度", res.progress); + console.log("已经上传的数据长度", res.totalBytesSent); + console.log("预期需要上传的数据总长度", res.totalBytesExpectedToSend); }); uploadTask.abort(); // 取消上传任务 const downloadTask = wx.downloadFile({ - url: "http://example.com/audio/123", // 仅为示例,并非真实的资源 - success: res => { - wx.playVoice({ - filePath: res.tempFilePath - }); - } + url: "http://example.com/audio/123", // 仅为示例,并非真实的资源 + success: res => { + wx.playVoice({ + filePath: res.tempFilePath + }); + } }); downloadTask.onProgressUpdate(res => { - console.log("下载进度", res.progress); - console.log("已经下载的数据长度", res.totalBytesWritten); - console.log("预期需要下载的数据总长度", res.totalBytesExpectedToWrite); + console.log("下载进度", res.progress); + console.log("已经下载的数据长度", res.totalBytesWritten); + console.log("预期需要下载的数据总长度", res.totalBytesExpectedToWrite); }); downloadTask.abort(); // 取消下载任务 wx.request({ - url: "https://www.baidu.com", - method: "GET", - success(res) { - if (res.statusCode < 300) { - console.log(res.data); - } else { - console.warn(res.statusCode, res.header); - } - }, - fail(e) { - console.error(e); - } + url: "https://www.baidu.com", + method: "GET", + success(res) { + if (res.statusCode < 300) { + console.log(res.data); + } else { + console.warn(res.statusCode, res.header); + } + }, + fail(e) { + console.error(e); + } }).abort();