From 920d2d7bdfc6cd50f06bd2020991f25f46d8c7a6 Mon Sep 17 00:00:00 2001 From: beary Date: Thu, 4 May 2017 18:13:19 +0800 Subject: [PATCH 01/98] Add default generic to Collection TypeScript support default generic since version 2.3, so add generic to Collection. --- types/mongodb/index.d.ts | 52 ++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 5fe6332350..6f5cf3df0e 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -181,20 +181,20 @@ export class Db extends EventEmitter { close(forceClose?: boolean): Promise; close(forceClose: boolean, callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#collection - collection(name: string): Collection; - collection(name: string, callback: MongoCallback): Collection; - collection(name: string, options: DbCollectionOptions, callback: MongoCallback): Collection; + collection(name: string): Collection; + collection(name: string, callback: MongoCallback>): Collection; + collection(name: string, options: DbCollectionOptions, callback: MongoCallback>): Collection; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#collections - collections(): Promise; - collections(callback: MongoCallback): void; + collections(): Promise[]>; + collections(callback: MongoCallback[]>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#command command(command: Object, callback: MongoCallback): void; command(command: Object, options?: { readPreference: ReadPreference | string }): Promise; command(command: Object, options: { readPreference: ReadPreference | string }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createCollection - createCollection(name: string, callback: MongoCallback): void; - createCollection(name: string, options?: CollectionCreateOptions): Promise; - createCollection(name: string, options: CollectionCreateOptions, callback: MongoCallback): void; + createCollection(name: string, callback: MongoCallback>): void; + createCollection(name: string, options?: CollectionCreateOptions): Promise>; + createCollection(name: string, options: CollectionCreateOptions, callback: MongoCallback>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#createIndex createIndex(name: string, fieldOrSpec: string | Object, callback: MongoCallback): void; createIndex(name: string, fieldOrSpec: string | Object, options?: IndexOptions): Promise; @@ -236,9 +236,9 @@ export class Db extends EventEmitter { removeUser(username: string, options?: { w?: number | string, wtimeout?: number, j?: boolean }): Promise; removeUser(username: string, options: { w?: number | string, wtimeout?: number, j?: boolean }, callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#renameCollection - renameCollection(fromCollection: string, toCollection: string, callback: MongoCallback): void; - renameCollection(fromCollection: string, toCollection: string, options?: { dropTarget?: boolean }): Promise; - renameCollection(fromCollection: string, toCollection: string, options: { dropTarget?: boolean }, callback: MongoCallback): void; + renameCollection(fromCollection: string, toCollection: string, callback: MongoCallback>): void; + renameCollection(fromCollection: string, toCollection: string, options?: { dropTarget?: boolean }): Promise>; + renameCollection(fromCollection: string, toCollection: string, options: { dropTarget?: boolean }, callback: MongoCallback>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#stats stats(callback: MongoCallback): void; stats(options?: { scale?: number }): Promise; @@ -409,7 +409,7 @@ export interface FSyncOptions { } // Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html -export interface Collection { +export interface Collection { // Get the collection name. collectionName: string; // Get the full collection namespace. @@ -421,10 +421,10 @@ export interface Collection { // Get current index hint for collection. hint: any; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate - aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; - aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; - aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; - aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; + // aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; + // aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; + aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; + aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite bulkWrite(operations: Object[], callback: MongoCallback): void; bulkWrite(operations: Object[], options?: CollectionBluckWriteOptions): Promise; @@ -463,14 +463,14 @@ export interface Collection { dropIndexes(): Promise; dropIndexes(callback?: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find - find(query?: Object): Cursor; - find(query?: Object): Cursor; + // find(query?: Object): Cursor; + find(query?: Object): Cursor; /** @deprecated */ - find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; + find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne - findOne(filter: Object, callback: MongoCallback): void; - findOne(filter: Object, options?: FindOneOptions): Promise; - findOne(filter: Object, options: FindOneOptions, callback: MongoCallback): void; + findOne(filter: Object, callback: MongoCallback): void; + findOne(filter: Object, options?: FindOneOptions): Promise; + findOne(filter: Object, options: FindOneOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndDelete findOneAndDelete(filter: Object, callback: MongoCallback): void; findOneAndDelete(filter: Object, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise; @@ -551,9 +551,9 @@ export interface Collection { /** @deprecated Use use deleteOne, deleteMany or bulkWrite */ remove(selector: Object, options?: CollectionOptions & { single?: boolean }, callback?: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#rename - rename(newName: string, callback: MongoCallback): void; - rename(newName: string, options?: { dropTarget?: boolean }): Promise; - rename(newName: string, options: { dropTarget?: boolean }, callback: MongoCallback): void; + rename(newName: string, callback: MongoCallback>): void; + rename(newName: string, options?: { dropTarget?: boolean }): Promise>; + rename(newName: string, options: { dropTarget?: boolean }, callback: MongoCallback>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#replaceOne replaceOne(filter: Object, doc: Object, callback: MongoCallback): void; replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise; @@ -1204,7 +1204,7 @@ export interface GridFSBucketOpenUploadStreamOptions { // https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucketReadStream.html export class GridFSBucketReadStream extends Readable { - constructor(chunks: Collection, files: Collection, readPreference: Object, filter: Object, options?: GridFSBucketReadStreamOptions); + constructor(chunks: Collection, files: Collection, readPreference: Object, filter: Object, options?: GridFSBucketReadStreamOptions); } // https://mongodb.github.io/node-mongodb-native/2.1/api/GridFSBucketReadStream.html From 22b3831e3141b51b0d2038b465d9f2a7fcafea6a Mon Sep 17 00:00:00 2001 From: beary Date: Thu, 4 May 2017 18:22:34 +0800 Subject: [PATCH 02/98] Add generic to collection --- types/mongodb/index.d.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 6f5cf3df0e..bd15f3bd07 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -421,8 +421,6 @@ export interface Collection { // Get current index hint for collection. hint: any; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#aggregate - // aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; - // aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; aggregate(pipeline: Object[], callback: MongoCallback): AggregationCursor; aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#bulkWrite @@ -463,7 +461,6 @@ export interface Collection { dropIndexes(): Promise; dropIndexes(callback?: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find - // find(query?: Object): Cursor; find(query?: Object): Cursor; /** @deprecated */ find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; From b0d31d86b194178eb882ca60fc37d53b16c7e12e Mon Sep 17 00:00:00 2001 From: beary Date: Thu, 4 May 2017 19:19:41 +0800 Subject: [PATCH 03/98] Add generic to findOneAnd*** functions --- types/mongodb/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index bd15f3bd07..02208e721b 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -461,25 +461,25 @@ export interface Collection { dropIndexes(): Promise; dropIndexes(callback?: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find - find(query?: Object): Cursor; + find(query?: Object): Cursor; /** @deprecated */ find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne - findOne(filter: Object, callback: MongoCallback): void; + findOne(filter: Object, callback: MongoCallback): void; findOne(filter: Object, options?: FindOneOptions): Promise; findOne(filter: Object, options: FindOneOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndDelete - findOneAndDelete(filter: Object, callback: MongoCallback): void; - findOneAndDelete(filter: Object, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise; - findOneAndDelete(filter: Object, options: { projection?: Object, sort?: Object, maxTimeMS?: number }, callback: MongoCallback): void; + findOneAndDelete(filter: Object, callback: MongoCallback>): void; + findOneAndDelete(filter: Object, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise>; + findOneAndDelete(filter: Object, options: { projection?: Object, sort?: Object, maxTimeMS?: number }, callback: MongoCallback>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndReplace - findOneAndReplace(filter: Object, replacement: Object, callback: MongoCallback): void; - findOneAndReplace(filter: Object, replacement: Object, options?: FindOneAndReplaceOption): Promise; - findOneAndReplace(filter: Object, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback): void; + findOneAndReplace(filter: Object, replacement: Object, callback: MongoCallback>): void; + findOneAndReplace(filter: Object, replacement: Object, options?: FindOneAndReplaceOption): Promise>; + findOneAndReplace(filter: Object, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndUpdate - findOneAndUpdate(filter: Object, update: Object, callback: MongoCallback): void; - findOneAndUpdate(filter: Object, update: Object, options?: FindOneAndReplaceOption): Promise; - findOneAndUpdate(filter: Object, update: Object, options: FindOneAndReplaceOption, callback: MongoCallback): void; + findOneAndUpdate(filter: Object, update: Object, callback: MongoCallback>): void; + findOneAndUpdate(filter: Object, update: Object, options?: FindOneAndReplaceOption): Promise>; + findOneAndUpdate(filter: Object, update: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#geoHaystackSearch geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; @@ -707,9 +707,9 @@ export interface DeleteWriteOpResultObject { } //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~findAndModifyWriteOpResult -export interface FindAndModifyWriteOpResultObject { +export interface FindAndModifyWriteOpResultObject { //Document returned from findAndModify command. - value?: any; + value?: TSchema; //The raw lastErrorObject returned from the command. lastErrorObject?: any; //Is 1 if the command executed correctly. From 5dcda0ca0b73e2eb3ee06ba20c56e4b507b687f4 Mon Sep 17 00:00:00 2001 From: Hugo Wood Date: Mon, 15 May 2017 14:13:32 +0200 Subject: [PATCH 04/98] highland: add support for mapping hints Also fixes the signature of _(source) for the Event Emitter case. The signature was missing the first parameter. Closes #13727. --- types/highland/highland-tests.ts | 8 ++++++- types/highland/index.d.ts | 36 +++++++++++++++++++++++++++----- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/types/highland/highland-tests.ts b/types/highland/highland-tests.ts index 7c813e1c1e..e4af44c0a0 100644 --- a/types/highland/highland-tests.ts +++ b/types/highland/highland-tests.ts @@ -134,7 +134,10 @@ fooStream = _((push, next) => { fooStream = _(fooStream); fooStream = _(readable); -fooStream = _(emitter); +fooStream = _(str, emitter); +fooStream = _(str, emitter, num); +fooStream = _(str, emitter, strArr); +fooStream = _(str, emitter, f); fooStream = _(fooStreamThen); fooStream = _(fooThen); @@ -210,6 +213,9 @@ _.log(str, num, foo); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - f = _.wrapCallback(func); +f = _.wrapCallback(func, num); +f = _.wrapCallback(func, strArr); +f = _.wrapCallback(func, fn); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/types/highland/index.d.ts b/types/highland/index.d.ts index b10f8e00bf..82806d6349 100644 --- a/types/highland/index.d.ts +++ b/types/highland/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Highland 1.14.0 +// Type definitions for Highland 2.10.5 // Project: http://highlandjs.org/ // Definitions by: Bart van der Schoor +// Hugo Wood // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -48,6 +49,17 @@ interface HighlandStatic { * event emitter as the two arguments to the constructor and the first * argument emitted to the event handler will be written to the new Stream. * + * You can pass a mapping hint as the third argument, which specifies how + * event arguments are pushed into the stream. If no mapping hint is + * provided, only the first value emitted with the event to the will be + * pushed onto the Stream. + * + * If mappingHint is a number, an array of that length will be pushed onto + * the stream, containing exactly that many parameters from the event. If + * it's an array, it's used as keys to map the arguments into an object which + * is pushed to the tream. If it is a function, it's called with the event + * arguments, and the returned value is pushed. + * * **Promise -** Accepts an ES6 / jQuery style promise and returns a * Highland Stream which will emit a single value (or an error). * @@ -63,7 +75,7 @@ interface HighlandStatic { (xs: Highland.Stream): Highland.Stream; (xs: NodeJS.ReadableStream): Highland.Stream; - (xs: NodeJS.EventEmitter): Highland.Stream; + (eventName: string, xs: NodeJS.EventEmitter, mappingHint?: Highland.MappingHint): Highland.Stream; // moar (promise for everything?) (xs: Highland.Thenable>): Highland.Stream; @@ -298,16 +310,28 @@ interface HighlandStatic { /** * Wraps a node-style async function which accepts a callback, transforming * it to a function which accepts the same arguments minus the callback and - * returns a Highland Stream instead. Only the first argument to the - * callback (or an error) will be pushed onto the Stream. + * returns a Highland Stream instead. The wrapped function keeps its context, + * so you can safely use it as a method without binding (see the second + * example below). + * + * wrapCallback also accepts an optional mappingHint, which specifies how + * callback arguments are pushed to the stream. This can be used to handle + * non-standard callback protocols that pass back more than one value. + * + * mappingHint can be a function, number, or array. See the documentation on + * EventEmitter Stream Objects for details on the mapping hint. If + * mappingHint is a function, it will be called with all but the first + * argument that is passed to the callback. The first is still assumed to be + * the error argument. * * @id wrapCallback * @section Utils * @name _.wrapCallback(f) * @param {Function} f - the node-style function to wrap + * @param {Array | Function | Number} [mappingHint] - how to pass the arguments to the callback * @api public */ - wrapCallback(f: Function): Function; + wrapCallback(f: Function, mappingHint?: Highland.MappingHint): (...args: any[]) => Highland.Stream; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -1009,6 +1033,8 @@ declare namespace Highland { */ latest(): Stream; } + + type MappingHint = number | string[] | Function; } declare var highland:HighlandStatic; From 485f913ab730e724f243885b2a039217a302562a Mon Sep 17 00:00:00 2001 From: Eliot Fallon Date: Mon, 22 May 2017 14:24:16 +0100 Subject: [PATCH 05/98] Updated to include 'playsinline' parameter --- types/youtube/index.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/types/youtube/index.d.ts b/types/youtube/index.d.ts index a45ec6a8c8..5a2dc3f19e 100644 --- a/types/youtube/index.d.ts +++ b/types/youtube/index.d.ts @@ -2,7 +2,8 @@ // Project: https://developers.google.com/youtube/ // Definitions by: Daz Wilkin , // Ian Obermiller , -// Josh Goldberg +// Josh Goldberg +// Eliot Fallon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -518,6 +519,11 @@ declare namespace YT * Comma separated list of video IDs to play after the URL path's video. */ playlist?: string; + + /** + * Whether videos play inline or fullscreen in an HTML5 player on iOS. Valid values are: 1 or 0. + */ + playsinline?: number; /** * Whether to show related videos after the video finishes (by default, Show). From c42655ba9dc3b7b59e693e99f7b4626b16f91111 Mon Sep 17 00:00:00 2001 From: james1293 Date: Tue, 23 May 2017 16:37:38 -0400 Subject: [PATCH 06/98] Add undefined as possible output of Map.get() --- types/es6-shim/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/es6-shim/index.d.ts b/types/es6-shim/index.d.ts index 483f4357e0..b1dd1d8fd4 100644 --- a/types/es6-shim/index.d.ts +++ b/types/es6-shim/index.d.ts @@ -556,7 +556,7 @@ interface Map { clear(): void; delete(key: K): boolean; forEach(callbackfn: (value: V, index: K, map: Map) => void, thisArg?: any): void; - get(key: K): V; + get(key: K): V | undefined; has(key: K): boolean; set(key: K, value?: V): Map; size: number; From 7c3baa4616a9c634f6242f9035030007390f512c Mon Sep 17 00:00:00 2001 From: Eliot Fallon Date: Wed, 24 May 2017 10:05:42 +0100 Subject: [PATCH 07/98] Added a new type to better restrict playsinline parameter to 1 or 0. --- types/youtube/index.d.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/types/youtube/index.d.ts b/types/youtube/index.d.ts index 5a2dc3f19e..11e2a4e30d 100644 --- a/types/youtube/index.d.ts +++ b/types/youtube/index.d.ts @@ -251,6 +251,22 @@ declare namespace YT */ Modest = 1 } + + /** + * Whether to playback video inline or full-screen in an HTML5 player on iOS + */ + export const enum PlaysInline + { + /** + * Playback in fullscreen. + */ + Fullscreen = 0, + + /** + * Playback inline + */ + Inline = 1 + } /** * Whether to show related videos after the video finishes. @@ -267,7 +283,7 @@ declare namespace YT */ Show = 1 } - + /** * Whether to show video information before playing. */ @@ -521,9 +537,9 @@ declare namespace YT playlist?: string; /** - * Whether videos play inline or fullscreen in an HTML5 player on iOS. Valid values are: 1 or 0. + * Whether videos play inline or fullscreen in an HTML5 player on iOS. (currently by default, Fullscreen). */ - playsinline?: number; + playsinline?: PlaysInline; /** * Whether to show related videos after the video finishes (by default, Show). From 9f2fc6d8382ea219fd63e6121d142ebf1e71927c Mon Sep 17 00:00:00 2001 From: Tim Brust Date: Fri, 2 Jun 2017 12:06:13 +0200 Subject: [PATCH 08/98] fix(webdriverio): $$ utility returns an array, fixes #16841 --- types/webdriverio/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/webdriverio/index.d.ts b/types/webdriverio/index.d.ts index 5c856575b2..666da7f5bf 100644 --- a/types/webdriverio/index.d.ts +++ b/types/webdriverio/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for WebdriverIO 4.7 // Project: http://www.webdriver.io/ -// Definitions by: Nick Malaguti , Tim Brust +// Definitions by: Nick Malaguti +// Tim Brust +// Fredrik Smedberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -1551,7 +1553,7 @@ declare namespace WebdriverIO { $(selector: string): Client> & RawResult; $

(selector: string): Client

; - $$(selector: string): Client> & RawResult; + $$(selector: string): Client>> & Array>; $$

(selector: string): Client

; addCommand( From 4d87daf40a39ab1954ea8dc1183b34a1d529455c Mon Sep 17 00:00:00 2001 From: Marco Gonzalez Date: Fri, 2 Jun 2017 09:45:41 -0600 Subject: [PATCH 09/98] Added typings for the http-aws-es package. --- types/http-aws-es/http-aws-es-tests.ts | 42 ++++++++++++++++++++++++++ types/http-aws-es/index.d.ts | 25 +++++++++++++++ types/http-aws-es/package.json | 5 +++ types/http-aws-es/tsconfig.json | 22 ++++++++++++++ types/http-aws-es/tslint.json | 1 + 5 files changed, 95 insertions(+) create mode 100644 types/http-aws-es/http-aws-es-tests.ts create mode 100644 types/http-aws-es/index.d.ts create mode 100644 types/http-aws-es/package.json create mode 100644 types/http-aws-es/tsconfig.json create mode 100644 types/http-aws-es/tslint.json diff --git a/types/http-aws-es/http-aws-es-tests.ts b/types/http-aws-es/http-aws-es-tests.ts new file mode 100644 index 0000000000..df432dbab4 --- /dev/null +++ b/types/http-aws-es/http-aws-es-tests.ts @@ -0,0 +1,42 @@ +import { EnvironmentCredentials } from "aws-sdk/lib/core"; +import { Client } from "elasticsearch"; +import HttpAmazonESConnector = require("http-aws-es"); + +new Client({ + amazonES: { + accessKey: "AKID", + region: "us-east-1", + secretKey: "secret", + }, + connectionClass: HttpAmazonESConnector, + host: "https://amazon-es-host.us-east-1.es.amazonaws.com", +}); + +new Client({ + amazonES: { + accessKey: "AKID", + region: "us-east-1", + secretKey: "secret", + }, + connectionClass: require("http-aws-es"), + host: "https://amazon-es-host.us-east-1.es.amazonaws.com", +}); + +const myCredentials = new EnvironmentCredentials("AWS"); +new Client({ + amazonES: { + credentials: myCredentials, + region: "us-east-1", + }, + connectionClass: HttpAmazonESConnector, + host: "https://amazon-es-host.us-east-1.es.amazonaws.com", +}); + +new Client({ + amazonES: { + credentials: myCredentials, + region: "us-east-1", + }, + connectionClass: require("http-aws-es"), + host: "https://amazon-es-host.us-east-1.es.amazonaws.com", +}); diff --git a/types/http-aws-es/index.d.ts b/types/http-aws-es/index.d.ts new file mode 100644 index 0000000000..c14547a58f --- /dev/null +++ b/types/http-aws-es/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for http-aws-es 1.1 +// Project: https://github.com/TheDeveloper/http-aws-es#readme +// Definitions by: Marco Gonzalez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as e from "elasticsearch"; +import { Credentials } from "aws-sdk/lib/core"; + +declare module "elasticsearch" { + interface AmazonESOptions { + accessKey?: string; + credentials?: Credentials; + region: string; + secretKey?: string; + } + + interface ConfigOptions { + amazonES?: AmazonESOptions; + } +} + +declare const HttpAmazonESConnector: any; +export = HttpAmazonESConnector; diff --git a/types/http-aws-es/package.json b/types/http-aws-es/package.json new file mode 100644 index 0000000000..e4fd5a5e97 --- /dev/null +++ b/types/http-aws-es/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "aws-sdk": "^2.7.0" + } +} diff --git a/types/http-aws-es/tsconfig.json b/types/http-aws-es/tsconfig.json new file mode 100644 index 0000000000..f1689d92e4 --- /dev/null +++ b/types/http-aws-es/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "http-aws-es-tests.ts" + ] +} diff --git a/types/http-aws-es/tslint.json b/types/http-aws-es/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-aws-es/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c27c678fa5d0ad5035390a5f574bc0b2415078ea Mon Sep 17 00:00:00 2001 From: Brandon Liles Date: Fri, 2 Jun 2017 16:25:09 -0400 Subject: [PATCH 10/98] Add support for Meteor 1.4 feature for specifying Mongo connection options --- types/meteor/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/meteor/index.d.ts b/types/meteor/index.d.ts index b33973f943..5f5963b164 100644 --- a/types/meteor/index.d.ts +++ b/types/meteor/index.d.ts @@ -1511,6 +1511,8 @@ declare module Mongo { new (hexString?: string): ObjectID; } interface ObjectID { } + + function setConnectionOptions(options: any): void; } declare module "meteor/mongo" { @@ -1620,6 +1622,8 @@ declare module "meteor/mongo" { new (hexString?: string): ObjectID; } interface ObjectID { } + + function setConnectionOptions(options: any): void; } } From c381369fde30ea9c1c60967d5ce08b8a94595909 Mon Sep 17 00:00:00 2001 From: Maxime Quandalle Date: Sat, 3 Jun 2017 18:06:02 +0200 Subject: [PATCH 11/98] [react-text-mask] Update to 2.1.0 --- types/react-css-transition-replace/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-css-transition-replace/index.d.ts b/types/react-css-transition-replace/index.d.ts index ce09917fbe..776ebcdd0a 100644 --- a/types/react-css-transition-replace/index.d.ts +++ b/types/react-css-transition-replace/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-css-transition-replace 2.0.1 +// Type definitions for react-css-transition-replace 2.1 // Project: http://marnusw.github.io/react-css-transition-replace/ // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,6 +9,7 @@ import * as CSSTransitionGroup from "react-addons-css-transition-group"; declare namespace CSSTransitionReplace { interface Props extends React.CSSTransitionGroupProps { + changeWidth?: boolean overflowHidden?: boolean } } From 0f40cdba7eb609897f5caf1c978178d954b9dd2a Mon Sep 17 00:00:00 2001 From: pilagod Date: Sun, 4 Jun 2017 01:54:34 +0800 Subject: [PATCH 12/98] [stacktrace-js] add getSync definition --- types/stacktrace-js/index.d.ts | 10 +++++++++- types/stacktrace-js/stacktrace-js-tests.ts | 1 + 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/types/stacktrace-js/index.d.ts b/types/stacktrace-js/index.d.ts index 9f3078b102..7f3c972508 100644 --- a/types/stacktrace-js/index.d.ts +++ b/types/stacktrace-js/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for stacktrace.js // Project: https://github.com/stacktracejs/stacktrace.js // Definitions by: Exceptionless +// Chun-Yan Ho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace StackTrace { @@ -34,7 +35,7 @@ declare namespace StackTrace { isNative: boolean; toString(): string; } - + export interface RequestOptions { headers: { [id: string]: string }; } @@ -46,6 +47,13 @@ declare namespace StackTrace { */ export function get(options?: StackTraceOptions): Promise; + /** + * Get a backtrace from invocation point synchronously. + * @param options Options Object + * @return Array[StackFrame] + */ + export function getSync(options?: { filter?: (stackFrame: StackFrame) => boolean }): StackFrame[] + /** * Given an error object, parse it. * @param error Error object diff --git a/types/stacktrace-js/stacktrace-js-tests.ts b/types/stacktrace-js/stacktrace-js-tests.ts index da263a6485..1de6abb185 100644 --- a/types/stacktrace-js/stacktrace-js-tests.ts +++ b/types/stacktrace-js/stacktrace-js-tests.ts @@ -29,6 +29,7 @@ const options: StackTrace.StackTraceOptions = { const error = new Error('BOOM!'); StackTrace.get(options).then(logger); +logger(StackTrace.getSync({ filter: options.filter })) StackTrace.fromError(error, options).then(logger); StackTrace.generateArtificially(options).then(logger); From 9db0ab843c9f8e4e12960d1438876b926d007c7e Mon Sep 17 00:00:00 2001 From: Christian Howe Date: Sun, 4 Jun 2017 00:01:24 -0400 Subject: [PATCH 13/98] [types/node] Add promisify to util A simple type definition that allows us to use the exciting util.promisify function. --- types/node/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 66f118d62c..12799c7686 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -3815,6 +3815,7 @@ declare module "util" { export function isSymbol(object: any): object is symbol; export function isUndefined(object: any): object is undefined; export function deprecate(fn: Function, message: string): Function; + export function promisify(fn: Function): Function; } declare module "assert" { From a85c080ce2639b33a65f2c48c3f4ec7fda46eb7f Mon Sep 17 00:00:00 2001 From: Konstantin Vasilev Date: Mon, 5 Jun 2017 11:40:42 +0300 Subject: [PATCH 14/98] Upgrade react-swipeable to v4.0 --- types/react-swipeable/index.d.ts | 44 ++++++--------- .../react-swipeable/react-swipeable-tests.tsx | 56 +++++++++++++------ types/react-swipeable/tslint.json | 3 + 3 files changed, 58 insertions(+), 45 deletions(-) create mode 100644 types/react-swipeable/tslint.json diff --git a/types/react-swipeable/index.d.ts b/types/react-swipeable/index.d.ts index fadf0f057f..da72f528e3 100644 --- a/types/react-swipeable/index.d.ts +++ b/types/react-swipeable/index.d.ts @@ -1,29 +1,19 @@ -// Type definitions for react-swipeable 3.3.1 +// Type definitions for react-swipeable 4.0 // Project: https://www.npmjs.com/package/react-swipeable // Definitions by: Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 -/// +declare module 'react-swipeable' { + import * as React from 'react'; -declare namespace ReactSwipeableModule { - interface onSwipingCallback { - (event: React.TouchEvent, deltaX: number, deltaY: number, absX: number, absY: number, velocity: number): void; - } + type onSwipingCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, absX: number, absY: number, velocity: number) => void; + type OnSwipedCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, isFlick: boolean, velocity: number) => void; + type OnSwipedDirectionCallback = (event: React.TouchEvent, delta: number, isFlick: boolean) => void; + type OnSwipingDirectionCallback = (event: React.TouchEvent, delta: number) => void; + type OnTapCallback = (event: React.TouchEvent) => void; - interface OnSwipedCallback { - (event: React.TouchEvent, deltaX: number, deltaY: number, isFlick: boolean, velocity: number): void; - } - - interface OnSwipedDirectionCallback { - (event: React.TouchEvent, delta: number, isFlick: boolean): void; - } - - interface OnSwipingDirectionCallback { - (event: React.TouchEvent, delta: number): void; - } - - interface Props { + interface Props extends React.ClassAttributes, React.HTMLAttributes { onSwiped?: OnSwipedCallback; onSwiping?: onSwipingCallback; onSwipingUp?: OnSwipingDirectionCallback; @@ -34,18 +24,18 @@ declare namespace ReactSwipeableModule { onSwipedRight?: OnSwipedDirectionCallback; onSwipedDown?: OnSwipedDirectionCallback; onSwipedLeft?: OnSwipedDirectionCallback; + onTap?: OnTapCallback; flickThreshold?: number; delta?: number; preventDefaultTouchmoveEvent?: boolean; + stopPropagation?: boolean; nodeName?: string; + trackMouse?: boolean; + children?: React.ReactNode; } - interface ReactSwipeable extends React.ComponentClass { } + class ReactSwipeable extends React.Component {} + namespace ReactSwipeable {} -} - - -declare module "react-swipeable" { - let module: ReactSwipeableModule.ReactSwipeable; - export = module; + export = ReactSwipeable; } diff --git a/types/react-swipeable/react-swipeable-tests.tsx b/types/react-swipeable/react-swipeable-tests.tsx index 7e8682ade7..05e057c11f 100644 --- a/types/react-swipeable/react-swipeable-tests.tsx +++ b/types/react-swipeable/react-swipeable-tests.tsx @@ -1,26 +1,46 @@ -import Swipeable = require('react-swipeable'); -import React = require('react'); +import * as React from 'react'; +import * as Swipeable from 'react-swipeable'; -var SampleComponent = React.createClass({ - render: function () { +class SampleComponent extends React.PureComponent { + private handleSwiped = () => {}; + private handleSwiping = () => {}; + private handleSwipingUp = () => {}; + private handleSwipingRight = () => {}; + private handleSwipingDown = () => {}; + private handleSwipingLeft = () => {}; + private handleSwipedUp = () => {}; + private handleSwipedRight = () => {}; + private handleSwipedDown = () => {}; + private handleSwipedLeft = () => {}; + private handleTap = () => {}; + private handleClick = () => {}; + + render() { return ( + onSwiped={this.handleSwiped} + onSwiping={this.handleSwiping} + onSwipingUp={this.handleSwipingUp} + onSwipingRight={this.handleSwipingRight} + onSwipingDown={this.handleSwipingDown} + onSwipingLeft={this.handleSwipingLeft} + onSwipedUp={this.handleSwipedUp} + onSwipedRight={this.handleSwipedRight} + onSwipedDown={this.handleSwipedDown} + onSwipedLeft={this.handleSwipedLeft} + onTap={this.handleTap} + flickThreshold={10} + delta={10} + preventDefaultTouchmoveEvent + stopPropagation + nodeName="swipe" + trackMouse + onClick={this.handleClick} + >

This element can be swiped
- ) + ); } -}) +} diff --git a/types/react-swipeable/tslint.json b/types/react-swipeable/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-swipeable/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 52fbfebcb6051948ac425ac5e2c797c3ed3bc04b Mon Sep 17 00:00:00 2001 From: Konstantin Vasilev Date: Mon, 5 Jun 2017 12:01:17 +0300 Subject: [PATCH 15/98] fix single module declaration --- types/react-swipeable/index.d.ts | 62 ++++++++++++++++---------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/types/react-swipeable/index.d.ts b/types/react-swipeable/index.d.ts index da72f528e3..489964ee0c 100644 --- a/types/react-swipeable/index.d.ts +++ b/types/react-swipeable/index.d.ts @@ -4,38 +4,36 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -declare module 'react-swipeable' { - import * as React from 'react'; +import * as React from 'react'; - type onSwipingCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, absX: number, absY: number, velocity: number) => void; - type OnSwipedCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, isFlick: boolean, velocity: number) => void; - type OnSwipedDirectionCallback = (event: React.TouchEvent, delta: number, isFlick: boolean) => void; - type OnSwipingDirectionCallback = (event: React.TouchEvent, delta: number) => void; - type OnTapCallback = (event: React.TouchEvent) => void; +type onSwipingCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, absX: number, absY: number, velocity: number) => void; +type OnSwipedCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, isFlick: boolean, velocity: number) => void; +type OnSwipedDirectionCallback = (event: React.TouchEvent, delta: number, isFlick: boolean) => void; +type OnSwipingDirectionCallback = (event: React.TouchEvent, delta: number) => void; +type OnTapCallback = (event: React.TouchEvent) => void; - interface Props extends React.ClassAttributes, React.HTMLAttributes { - onSwiped?: OnSwipedCallback; - onSwiping?: onSwipingCallback; - onSwipingUp?: OnSwipingDirectionCallback; - onSwipingRight?: OnSwipingDirectionCallback; - onSwipingDown?: OnSwipingDirectionCallback; - onSwipingLeft?: OnSwipingDirectionCallback; - onSwipedUp?: OnSwipedDirectionCallback; - onSwipedRight?: OnSwipedDirectionCallback; - onSwipedDown?: OnSwipedDirectionCallback; - onSwipedLeft?: OnSwipedDirectionCallback; - onTap?: OnTapCallback; - flickThreshold?: number; - delta?: number; - preventDefaultTouchmoveEvent?: boolean; - stopPropagation?: boolean; - nodeName?: string; - trackMouse?: boolean; - children?: React.ReactNode; - } - - class ReactSwipeable extends React.Component {} - namespace ReactSwipeable {} - - export = ReactSwipeable; +interface Props extends React.ClassAttributes, React.HTMLAttributes { + onSwiped?: OnSwipedCallback; + onSwiping?: onSwipingCallback; + onSwipingUp?: OnSwipingDirectionCallback; + onSwipingRight?: OnSwipingDirectionCallback; + onSwipingDown?: OnSwipingDirectionCallback; + onSwipingLeft?: OnSwipingDirectionCallback; + onSwipedUp?: OnSwipedDirectionCallback; + onSwipedRight?: OnSwipedDirectionCallback; + onSwipedDown?: OnSwipedDirectionCallback; + onSwipedLeft?: OnSwipedDirectionCallback; + onTap?: OnTapCallback; + flickThreshold?: number; + delta?: number; + preventDefaultTouchmoveEvent?: boolean; + stopPropagation?: boolean; + nodeName?: string; + trackMouse?: boolean; + children?: React.ReactNode; } + +declare class ReactSwipeable extends React.Component {} +declare namespace ReactSwipeable {} + +export = ReactSwipeable; From 45795eeb3e7cf609dcc3a3b5f3681aca7f21faf7 Mon Sep 17 00:00:00 2001 From: Eli Young Date: Mon, 5 Jun 2017 14:57:40 -0700 Subject: [PATCH 16/98] [bunyan] Add LogLevel type --- types/bunyan/index.d.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/types/bunyan/index.d.ts b/types/bunyan/index.d.ts index f3c739a992..281e0d5c3f 100644 --- a/types/bunyan/index.d.ts +++ b/types/bunyan/index.d.ts @@ -16,8 +16,8 @@ declare class Logger extends EventEmitter { reopenFileStreams(): void; level(): string | number; - level(value: number | string): void; - levels(name: number | string, value: number | string): void; + level(value: Logger.LogLevel): void; + levels(name: number | string, value: Logger.LogLevel): void; fields: any; src: boolean; @@ -217,17 +217,19 @@ declare namespace Logger { const ERROR: number; const FATAL: number; + type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | number; + const stdSerializers: StdSerializers; function createLogger(options: LoggerOptions): Logger; function safeCycles(): (key: string, value: any) => any; - function resolveLevel(value: number | string): number; + function resolveLevel(value: LogLevel): number; interface Stream { type?: string; - level?: number | string; + level?: LogLevel; path?: string; stream?: NodeJS.WritableStream | Stream; closeOnExit?: boolean; @@ -238,7 +240,7 @@ declare namespace Logger { interface LoggerOptions { name: string; streams?: Stream[]; - level?: string | number; + level?: LogLevel; stream?: NodeJS.WritableStream; serializers?: Serializers | StdSerializers; src?: boolean; From 33853d9ad97d4af4155675b4a6e41913bf072561 Mon Sep 17 00:00:00 2001 From: Chris Thompson Date: Mon, 5 Jun 2017 17:50:52 -0600 Subject: [PATCH 17/98] Add ConnectionError and RequestError --- types/tedious/index.d.ts | 20 ++++++++++++++++++++ types/tedious/tedious-tests.ts | 8 ++++++++ 2 files changed, 28 insertions(+) diff --git a/types/tedious/index.d.ts b/types/tedious/index.d.ts index b89ac58beb..b8cef4ad9c 100644 --- a/types/tedious/index.d.ts +++ b/types/tedious/index.d.ts @@ -548,3 +548,23 @@ export declare class Connection extends events.EventEmitter { close(): void; } + +/** + * Error emitted by Connection class 'error' event + */ +export declare class ConnectionError extends Error { + constructor(message?: string, code?: number); + + public message: string; + public code: number; +} + +/** + * Error emitted by Request class + */ +export declare class RequestError extends Error { + constructor(message?: string, code?: number); + + public message: string; + public code: number; +} diff --git a/types/tedious/tedious-tests.ts b/types/tedious/tedious-tests.ts index 297deb3e3d..726436c882 100644 --- a/types/tedious/tedious-tests.ts +++ b/types/tedious/tedious-tests.ts @@ -31,4 +31,12 @@ request.on("row", (row: tedious.ColumnValue[]): void => { }); connection.execSql(request); +var requestError = new tedious.RequestError(); +requestError.message = 'test'; +requestError.code = 1; +requestError = new tedious.RequestError('test', 50005); +var connectionError = new tedious.ConnectionError(); +connectionError.message = 'test'; +connectionError.code = 1; +connectionError = new tedious.ConnectionError('test', 50005); From b5521f8a97d2bf067dbe68ae091174bd4bc9c11f Mon Sep 17 00:00:00 2001 From: Eli Young Date: Mon, 5 Jun 2017 16:33:37 -0700 Subject: [PATCH 18/98] [bunyan] Clean things up --- types/bunyan/bunyan-tests.ts | 30 ++++----- types/bunyan/index.d.ts | 121 ++++++++++++++++------------------- types/bunyan/tslint.json | 7 ++ 3 files changed, 77 insertions(+), 81 deletions(-) create mode 100644 types/bunyan/tslint.json diff --git a/types/bunyan/bunyan-tests.ts b/types/bunyan/bunyan-tests.ts index acf382c7c2..e1d1e4571b 100644 --- a/types/bunyan/bunyan-tests.ts +++ b/types/bunyan/bunyan-tests.ts @@ -1,16 +1,15 @@ - import Logger = require('bunyan'); -var ringBufferOptions: Logger.RingBufferOptions = { +let ringBufferOptions: Logger.RingBufferOptions = { limit: 100 }; -var ringBuffer: Logger.RingBuffer = new Logger.RingBuffer(ringBufferOptions); +let ringBuffer: Logger.RingBuffer = new Logger.RingBuffer(ringBufferOptions); ringBuffer.write("hello"); ringBuffer.end(); ringBuffer.destroy(); ringBuffer.destroySoon(); -var level: number; +let level: number; level = Logger.resolveLevel("trace"); level = Logger.resolveLevel("debug"); level = Logger.resolveLevel("info"); @@ -24,7 +23,7 @@ level = Logger.resolveLevel(Logger.WARN); level = Logger.resolveLevel(Logger.ERROR); level = Logger.resolveLevel(Logger.FATAL); -var options: Logger.LoggerOptions = { +let options: Logger.LoggerOptions = { name: 'test-logger', serializers: Logger.stdSerializers, streams: [{ @@ -54,9 +53,9 @@ var options: Logger.LoggerOptions = { }] }; -var log = Logger.createLogger(options); +let log = Logger.createLogger(options); -var customSerializer = function(anything: any) { +let customSerializer = (anything: any) => { return { obj: anything}; }; @@ -70,7 +69,7 @@ log.addSerializers( } ); -var child = log.child({name: 'child'}); +let child = log.child({name: 'child'}); child.reopenFileStreams(); log.addStream({path: '/dev/null'}); child.level(Logger.DEBUG); @@ -80,9 +79,9 @@ child.levels(0, 'error'); child.levels('stream1', Logger.FATAL); child.levels('stream1', 'fatal'); -var buffer = new Buffer(0); -var error = new Error(''); -var object = { +let buffer = new Buffer(0); +let error = new Error(''); +let object = { test: 123 }; @@ -117,12 +116,11 @@ log.fatal(error); log.fatal(object); log.fatal('Hello, %s', 'world!'); -var recursive: any = { +let recursive: any = { hello: 'world', - whats: { - huh: recursive - } -} + whats: {} +}; +recursive.whats['huh'] = recursive; JSON.stringify(recursive, Logger.safeCycles()); diff --git a/types/bunyan/index.d.ts b/types/bunyan/index.d.ts index 281e0d5c3f..aad597de4e 100644 --- a/types/bunyan/index.d.ts +++ b/types/bunyan/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-bunyan +// Type definitions for node-bunyan 1.8 // Project: https://github.com/trentm/node-bunyan // Definitions by: Alex Mikhalev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,18 +10,21 @@ import { EventEmitter } from 'events'; declare class Logger extends EventEmitter { constructor(options: Logger.LoggerOptions); addStream(stream: Logger.Stream): void; - addSerializers(serializers: Logger.Serializers | Logger.StdSerializers): void; - child(options: Logger.LoggerOptions, simple?: boolean): Logger; - child(obj: Object, simple?: boolean): Logger; + addSerializers(serializers: Logger.Serializers): void; + child(options: Object, simple?: boolean): Logger; reopenFileStreams(): void; - level(): string | number; + level(): number; level(value: Logger.LogLevel): void; + levels(): number[]; + levels(name: number | string): number; levels(name: number | string, value: Logger.LogLevel): void; fields: any; src: boolean; + /* tslint:disable:unified-signatures */ + /** * Returns a boolean: is the `trace` level enabled? * @@ -35,14 +38,7 @@ declare class Logger extends EventEmitter { * (including the stack) and sets `msg` to the exception * message or you can specify the `msg`. */ - trace(error: Error, format?: any, ...params: any[]): void; - - trace(buffer: Buffer, format?: any, ...params: any[]): void; - - /** - * Uses `util.format` for msg formatting. - */ - trace(format: string | number, ...params: any[]): void; + trace(error: Error, ...params: any[]): void; /** * The first field can optionally be a "fields" object, which @@ -51,7 +47,12 @@ declare class Logger extends EventEmitter { * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ - trace(obj: Object, format?: any, ...params: any[]): void; + trace(obj: Object, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + trace(format: any, ...params: any[]): void; /** * Returns a boolean: is the `debug` level enabled? @@ -66,14 +67,7 @@ declare class Logger extends EventEmitter { * (including the stack) and sets `msg` to the exception * message or you can specify the `msg`. */ - debug(error: Error, format?: any, ...params: any[]): void; - - debug(buffer: Buffer, format?: any, ...params: any[]): void; - - /** - * Uses `util.format` for msg formatting. - */ - debug(format: string | number, ...params: any[]): void; + debug(error: Error, ...params: any[]): void; /** * The first field can optionally be a "fields" object, which @@ -82,7 +76,12 @@ declare class Logger extends EventEmitter { * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ - debug(obj: Object, format?: any, ...params: any[]): void; + debug(obj: Object, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + debug(format: any, ...params: any[]): void; /** * Returns a boolean: is the `info` level enabled? @@ -97,14 +96,7 @@ declare class Logger extends EventEmitter { * (including the stack) and sets `msg` to the exception * message or you can specify the `msg`. */ - info(error: Error, format?: any, ...params: any[]): void; - - info(buffer: Buffer, format?: any, ...params: any[]): void; - - /** - * Uses `util.format` for msg formatting. - */ - info(format: string | number, ...params: any[]): void; + info(error: Error, ...params: any[]): void; /** * The first field can optionally be a "fields" object, which @@ -113,7 +105,12 @@ declare class Logger extends EventEmitter { * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ - info(obj: Object, format?: any, ...params: any[]): void; + info(obj: Object, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + info(format: any, ...params: any[]): void; /** * Returns a boolean: is the `warn` level enabled? @@ -128,14 +125,7 @@ declare class Logger extends EventEmitter { * (including the stack) and sets `msg` to the exception * message or you can specify the `msg`. */ - warn(error: Error, format?: any, ...params: any[]): void; - - warn(buffer: Buffer, format?: any, ...params: any[]): void; - - /** - * Uses `util.format` for msg formatting. - */ - warn(format: string | number, ...params: any[]): void; + warn(error: Error, ...params: any[]): void; /** * The first field can optionally be a "fields" object, which @@ -144,7 +134,12 @@ declare class Logger extends EventEmitter { * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ - warn(obj: Object, format?: any, ...params: any[]): void; + warn(obj: Object, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + warn(format: any, ...params: any[]): void; /** * Returns a boolean: is the `error` level enabled? @@ -159,14 +154,7 @@ declare class Logger extends EventEmitter { * (including the stack) and sets `msg` to the exception * message or you can specify the `msg`. */ - error(error: Error, format?: any, ...params: any[]): void; - - error(buffer: Buffer, format?: any, ...params: any[]): void; - - /** - * Uses `util.format` for msg formatting. - */ - error(format: string | number, ...params: any[]): void; + error(error: Error, ...params: any[]): void; /** * The first field can optionally be a "fields" object, which @@ -175,7 +163,12 @@ declare class Logger extends EventEmitter { * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ - error(obj: Object, format?: any, ...params: any[]): void; + error(obj: Object, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + error(format: any, ...params: any[]): void; /** * Returns a boolean: is the `fatal` level enabled? @@ -190,14 +183,7 @@ declare class Logger extends EventEmitter { * (including the stack) and sets `msg` to the exception * message or you can specify the `msg`. */ - fatal(error: Error, format?: any, ...params: any[]): void; - - fatal(buffer: Buffer, format?: any, ...params: any[]): void; - - /** - * Uses `util.format` for msg formatting. - */ - fatal(format: string | number, ...params: any[]): void; + fatal(error: Error, ...params: any[]): void; /** * The first field can optionally be a "fields" object, which @@ -206,7 +192,14 @@ declare class Logger extends EventEmitter { * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ - fatal(obj: Object, format?: any, ...params: any[]): void; + fatal(obj: Object, ...params: any[]): void; + + /** + * Uses `util.format` for msg formatting. + */ + fatal(format: any, ...params: any[]): void; + + /* tslint:enable:unified-signatures */ } declare namespace Logger { @@ -242,20 +235,18 @@ declare namespace Logger { streams?: Stream[]; level?: LogLevel; stream?: NodeJS.WritableStream; - serializers?: Serializers | StdSerializers; + serializers?: Serializers; src?: boolean; [custom: string]: any; } - interface Serializer { - (input:any): any; - } + type Serializer = (input: any) => any; interface Serializers { - [key: string]: Serializer + [key: string]: Serializer; } - interface StdSerializers { + interface StdSerializers extends Serializers { err: Serializer; res: Serializer; req: Serializer; diff --git a/types/bunyan/tslint.json b/types/bunyan/tslint.json new file mode 100644 index 0000000000..09f94cd344 --- /dev/null +++ b/types/bunyan/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // ban-types needs to be disabled to support TypeScript <2.2 + "ban-types": false + } +} From 276c04e9dd96e8d8846b12fa64d73db22b93fa38 Mon Sep 17 00:00:00 2001 From: Chris Thompson Date: Mon, 5 Jun 2017 17:56:27 -0600 Subject: [PATCH 19/98] Add name as contributor per README recommendations --- types/tedious/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/tedious/index.d.ts b/types/tedious/index.d.ts index b8cef4ad9c..ac589e0d66 100644 --- a/types/tedious/index.d.ts +++ b/types/tedious/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for tedious 1.8.0 // Project: https://pekim.github.io/tedious // Definitions by: Rogier Schouten +// Chris Thompson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From a9e528c77a5a595d2e09b63c387f2a330f5e96ff Mon Sep 17 00:00:00 2001 From: Eli Young Date: Mon, 5 Jun 2017 16:36:59 -0700 Subject: [PATCH 20/98] [bunyan] Reformat code --- types/bunyan/bunyan-tests.ts | 8 +-- types/bunyan/index.d.ts | 124 +++++++++++++++++------------------ 2 files changed, 66 insertions(+), 66 deletions(-) diff --git a/types/bunyan/bunyan-tests.ts b/types/bunyan/bunyan-tests.ts index e1d1e4571b..657a59c3a8 100644 --- a/types/bunyan/bunyan-tests.ts +++ b/types/bunyan/bunyan-tests.ts @@ -56,10 +56,10 @@ let options: Logger.LoggerOptions = { let log = Logger.createLogger(options); let customSerializer = (anything: any) => { - return { obj: anything}; + return { obj: anything }; }; -log.addSerializers({anything: customSerializer}); +log.addSerializers({ anything: customSerializer }); log.addSerializers(Logger.stdSerializers); log.addSerializers( { @@ -69,9 +69,9 @@ log.addSerializers( } ); -let child = log.child({name: 'child'}); +let child = log.child({ name: 'child' }); child.reopenFileStreams(); -log.addStream({path: '/dev/null'}); +log.addStream({ path: '/dev/null' }); child.level(Logger.DEBUG); child.level('debug'); child.levels(0, Logger.ERROR); diff --git a/types/bunyan/index.d.ts b/types/bunyan/index.d.ts index aad597de4e..d46396023f 100644 --- a/types/bunyan/index.d.ts +++ b/types/bunyan/index.d.ts @@ -27,7 +27,7 @@ declare class Logger extends EventEmitter { /** * Returns a boolean: is the `trace` level enabled? - * + * * This is equivalent to `log.isTraceEnabled()` or `log.isEnabledFor(TRACE)` in log4j. */ trace(): boolean; @@ -43,7 +43,7 @@ declare class Logger extends EventEmitter { /** * The first field can optionally be a "fields" object, which * is merged into the log record. - * + * * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ @@ -56,7 +56,7 @@ declare class Logger extends EventEmitter { /** * Returns a boolean: is the `debug` level enabled? - * + * * This is equivalent to `log.isDebugEnabled()` or `log.isEnabledFor(DEBUG)` in log4j. */ debug(): boolean; @@ -72,7 +72,7 @@ declare class Logger extends EventEmitter { /** * The first field can optionally be a "fields" object, which * is merged into the log record. - * + * * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ @@ -85,7 +85,7 @@ declare class Logger extends EventEmitter { /** * Returns a boolean: is the `info` level enabled? - * + * * This is equivalent to `log.isInfoEnabled()` or `log.isEnabledFor(INFO)` in log4j. */ info(): boolean; @@ -101,7 +101,7 @@ declare class Logger extends EventEmitter { /** * The first field can optionally be a "fields" object, which * is merged into the log record. - * + * * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ @@ -114,7 +114,7 @@ declare class Logger extends EventEmitter { /** * Returns a boolean: is the `warn` level enabled? - * + * * This is equivalent to `log.isWarnEnabled()` or `log.isEnabledFor(WARN)` in log4j. */ warn(): boolean; @@ -130,7 +130,7 @@ declare class Logger extends EventEmitter { /** * The first field can optionally be a "fields" object, which * is merged into the log record. - * + * * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ @@ -143,7 +143,7 @@ declare class Logger extends EventEmitter { /** * Returns a boolean: is the `error` level enabled? - * + * * This is equivalent to `log.isErrorEnabled()` or `log.isEnabledFor(ERROR)` in log4j. */ error(): boolean; @@ -159,7 +159,7 @@ declare class Logger extends EventEmitter { /** * The first field can optionally be a "fields" object, which * is merged into the log record. - * + * * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ @@ -172,7 +172,7 @@ declare class Logger extends EventEmitter { /** * Returns a boolean: is the `fatal` level enabled? - * + * * This is equivalent to `log.isFatalEnabled()` or `log.isEnabledFor(FATAL)` in log4j. */ fatal(): boolean; @@ -188,7 +188,7 @@ declare class Logger extends EventEmitter { /** * The first field can optionally be a "fields" object, which * is merged into the log record. - * + * * To pass in an Error *and* other fields, use the `err` * field name for the Error instance. */ @@ -203,70 +203,70 @@ declare class Logger extends EventEmitter { } declare namespace Logger { - const TRACE: number; - const DEBUG: number; - const INFO: number; - const WARN: number; - const ERROR: number; - const FATAL: number; + const TRACE: number; + const DEBUG: number; + const INFO: number; + const WARN: number; + const ERROR: number; + const FATAL: number; - type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | number; + type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | number; - const stdSerializers: StdSerializers; + const stdSerializers: StdSerializers; - function createLogger(options: LoggerOptions): Logger; + function createLogger(options: LoggerOptions): Logger; - function safeCycles(): (key: string, value: any) => any; + function safeCycles(): (key: string, value: any) => any; - function resolveLevel(value: LogLevel): number; + function resolveLevel(value: LogLevel): number; - interface Stream { - type?: string; - level?: LogLevel; - path?: string; - stream?: NodeJS.WritableStream | Stream; - closeOnExit?: boolean; - period?: string; - count?: number; - } + interface Stream { + type?: string; + level?: LogLevel; + path?: string; + stream?: NodeJS.WritableStream | Stream; + closeOnExit?: boolean; + period?: string; + count?: number; + } - interface LoggerOptions { - name: string; - streams?: Stream[]; - level?: LogLevel; - stream?: NodeJS.WritableStream; - serializers?: Serializers; - src?: boolean; - [custom: string]: any; - } + interface LoggerOptions { + name: string; + streams?: Stream[]; + level?: LogLevel; + stream?: NodeJS.WritableStream; + serializers?: Serializers; + src?: boolean; + [custom: string]: any; + } - type Serializer = (input: any) => any; + type Serializer = (input: any) => any; - interface Serializers { - [key: string]: Serializer; - } + interface Serializers { + [key: string]: Serializer; + } - interface StdSerializers extends Serializers { - err: Serializer; - res: Serializer; - req: Serializer; - } + interface StdSerializers extends Serializers { + err: Serializer; + res: Serializer; + req: Serializer; + } - interface RingBufferOptions { - limit?: number; - } + interface RingBufferOptions { + limit?: number; + } - class RingBuffer extends EventEmitter implements NodeJS.WritableStream { - constructor(options: RingBufferOptions); + class RingBuffer extends EventEmitter implements NodeJS.WritableStream { + constructor(options: RingBufferOptions); - writable: boolean; - records: any[]; + writable: boolean; + records: any[]; - write(record: any): boolean; - end(record?: any): void; - destroy(): void; - destroySoon(): void; - } + write(record: any): boolean; + end(record?: any): void; + destroy(): void; + destroySoon(): void; + } } export = Logger; From 26c627e69b1630e1bbe76ccbe4c710a220002188 Mon Sep 17 00:00:00 2001 From: Thiago Lacerda Date: Mon, 5 Jun 2017 22:04:14 -0700 Subject: [PATCH 21/98] Add missing TinyMCE Setting props from latest docs Signed-off-by: Thiago Lacerda --- types/tinymce/index.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/tinymce/index.d.ts b/types/tinymce/index.d.ts index 7cc40943e7..99e7bbd2a9 100644 --- a/types/tinymce/index.d.ts +++ b/types/tinymce/index.d.ts @@ -74,8 +74,12 @@ export interface Settings { target?: Element; + branding?: boolean; + color_picker_callback?(callback: (hexColor: string) => void, value: string): void; + custom_ui_selector?: string; + elementpath?: boolean; event_root?: boolean; @@ -132,6 +136,8 @@ export interface Settings { content_style?: string; + inline_boundaries?: boolean; + visual_anchor_class?: string; visual_table_class?: string; From 76879cce23fcae9847a57bb61cc27432e2a20532 Mon Sep 17 00:00:00 2001 From: Konstantin Vasilev Date: Tue, 6 Jun 2017 10:04:43 +0300 Subject: [PATCH 22/98] export types references --- types/react-swipeable/index.d.ts | 58 ++++++++++--------- .../react-swipeable/react-swipeable-tests.tsx | 24 ++++---- 2 files changed, 42 insertions(+), 40 deletions(-) diff --git a/types/react-swipeable/index.d.ts b/types/react-swipeable/index.d.ts index 489964ee0c..b646a46268 100644 --- a/types/react-swipeable/index.d.ts +++ b/types/react-swipeable/index.d.ts @@ -1,39 +1,41 @@ // Type definitions for react-swipeable 4.0 // Project: https://www.npmjs.com/package/react-swipeable -// Definitions by: Giedrius Grabauskas +// Definitions by: Giedrius Grabauskas , +// Konstantin Vasilev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import * as React from 'react'; -type onSwipingCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, absX: number, absY: number, velocity: number) => void; -type OnSwipedCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, isFlick: boolean, velocity: number) => void; -type OnSwipedDirectionCallback = (event: React.TouchEvent, delta: number, isFlick: boolean) => void; -type OnSwipingDirectionCallback = (event: React.TouchEvent, delta: number) => void; -type OnTapCallback = (event: React.TouchEvent) => void; +declare class ReactSwipeable extends React.Component {} -interface Props extends React.ClassAttributes, React.HTMLAttributes { - onSwiped?: OnSwipedCallback; - onSwiping?: onSwipingCallback; - onSwipingUp?: OnSwipingDirectionCallback; - onSwipingRight?: OnSwipingDirectionCallback; - onSwipingDown?: OnSwipingDirectionCallback; - onSwipingLeft?: OnSwipingDirectionCallback; - onSwipedUp?: OnSwipedDirectionCallback; - onSwipedRight?: OnSwipedDirectionCallback; - onSwipedDown?: OnSwipedDirectionCallback; - onSwipedLeft?: OnSwipedDirectionCallback; - onTap?: OnTapCallback; - flickThreshold?: number; - delta?: number; - preventDefaultTouchmoveEvent?: boolean; - stopPropagation?: boolean; - nodeName?: string; - trackMouse?: boolean; - children?: React.ReactNode; +declare namespace ReactSwipeable { + type OnSwipingCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, absX: number, absY: number, velocity: number) => void; + type OnSwipedCallback = (event: React.TouchEvent, deltaX: number, deltaY: number, isFlick: boolean, velocity: number) => void; + type OnSwipedDirectionCallback = (event: React.TouchEvent, delta: number, isFlick: boolean) => void; + type OnSwipingDirectionCallback = (event: React.TouchEvent, delta: number) => void; + type OnTapCallback = (event: React.TouchEvent) => void; + + interface SwipeableProps extends React.ClassAttributes, React.HTMLAttributes { + onSwiped?: OnSwipedCallback; + onSwiping?: OnSwipingCallback; + onSwipingUp?: OnSwipingDirectionCallback; + onSwipingRight?: OnSwipingDirectionCallback; + onSwipingDown?: OnSwipingDirectionCallback; + onSwipingLeft?: OnSwipingDirectionCallback; + onSwipedUp?: OnSwipedDirectionCallback; + onSwipedRight?: OnSwipedDirectionCallback; + onSwipedDown?: OnSwipedDirectionCallback; + onSwipedLeft?: OnSwipedDirectionCallback; + onTap?: OnTapCallback; + flickThreshold?: number; + delta?: number; + preventDefaultTouchmoveEvent?: boolean; + stopPropagation?: boolean; + nodeName?: string; + trackMouse?: boolean; + children?: React.ReactNode; + } } -declare class ReactSwipeable extends React.Component {} -declare namespace ReactSwipeable {} - export = ReactSwipeable; diff --git a/types/react-swipeable/react-swipeable-tests.tsx b/types/react-swipeable/react-swipeable-tests.tsx index 05e057c11f..c75869bdb0 100644 --- a/types/react-swipeable/react-swipeable-tests.tsx +++ b/types/react-swipeable/react-swipeable-tests.tsx @@ -1,18 +1,18 @@ import * as React from 'react'; import * as Swipeable from 'react-swipeable'; -class SampleComponent extends React.PureComponent { - private handleSwiped = () => {}; - private handleSwiping = () => {}; - private handleSwipingUp = () => {}; - private handleSwipingRight = () => {}; - private handleSwipingDown = () => {}; - private handleSwipingLeft = () => {}; - private handleSwipedUp = () => {}; - private handleSwipedRight = () => {}; - private handleSwipedDown = () => {}; - private handleSwipedLeft = () => {}; - private handleTap = () => {}; +class SampleComponent extends React.PureComponent { + private handleSwiped: Swipeable.OnSwipedCallback = () => {}; + private handleSwiping: Swipeable.OnSwipingCallback = () => {}; + private handleSwipingUp: Swipeable.OnSwipingDirectionCallback = () => {}; + private handleSwipingRight: Swipeable.OnSwipingDirectionCallback = () => {}; + private handleSwipingDown: Swipeable.OnSwipingDirectionCallback = () => {}; + private handleSwipingLeft: Swipeable.OnSwipingDirectionCallback = () => {}; + private handleSwipedUp: Swipeable.OnSwipedDirectionCallback = () => {}; + private handleSwipedRight: Swipeable.OnSwipedDirectionCallback = () => {}; + private handleSwipedDown: Swipeable.OnSwipedDirectionCallback = () => {}; + private handleSwipedLeft: Swipeable.OnSwipedDirectionCallback = () => {}; + private handleTap: Swipeable.OnTapCallback = () => {}; private handleClick = () => {}; render() { From 67596b61d7f848328d80a02bdf1d385d917cdaf6 Mon Sep 17 00:00:00 2001 From: Konstantin Vasilev Date: Tue, 6 Jun 2017 16:24:59 +0300 Subject: [PATCH 23/98] remove unnecessary comma in authors section --- types/react-swipeable/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-swipeable/index.d.ts b/types/react-swipeable/index.d.ts index b646a46268..7692abd859 100644 --- a/types/react-swipeable/index.d.ts +++ b/types/react-swipeable/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-swipeable 4.0 // Project: https://www.npmjs.com/package/react-swipeable -// Definitions by: Giedrius Grabauskas , +// Definitions by: Giedrius Grabauskas // Konstantin Vasilev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 From ca3a06d9f3c59ea60593087269632e9b4a214ad5 Mon Sep 17 00:00:00 2001 From: Dan Corder Date: Tue, 6 Jun 2017 17:46:46 +0100 Subject: [PATCH 24/98] Revert history version change as discussed on pull request 16912 --- types/react-router-redux/v4/tsconfig.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-router-redux/v4/tsconfig.json b/types/react-router-redux/v4/tsconfig.json index 93628aea73..83cf349881 100644 --- a/types/react-router-redux/v4/tsconfig.json +++ b/types/react-router-redux/v4/tsconfig.json @@ -13,8 +13,8 @@ "../../" ], "paths": { - "history": ["history/v2"], - "history/*": ["history/v2/*"], + "history": ["history/v3"], + "history/*": ["history/v3/*"], "react-router-redux": ["react-router-redux/v4"] }, "types": [], From a683b93fa296410097b28945a033bbae1e3951e7 Mon Sep 17 00:00:00 2001 From: Adam Herrmann Date: Tue, 6 Jun 2017 16:13:57 -0400 Subject: [PATCH 25/98] feat(undertaker): add description to TaskFunctionParams --- types/undertaker/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/undertaker/index.d.ts b/types/undertaker/index.d.ts index 23b5b7b65c..b19ad4ac79 100644 --- a/types/undertaker/index.d.ts +++ b/types/undertaker/index.d.ts @@ -11,6 +11,7 @@ declare namespace Undertaker { interface TaskFunctionParams { name?: string; displayName?: string; + description?: string; } interface TaskFunction extends TaskFunctionParams { From d456855e53c4766a88a41215ed8ce8cf55acdcfb Mon Sep 17 00:00:00 2001 From: Kamil Szostak Date: Tue, 6 Jun 2017 15:56:43 -0700 Subject: [PATCH 26/98] Update trackTrack definition --- types/applicationinsights-js/applicationinsights-js-tests.ts | 3 ++- types/applicationinsights-js/index.d.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/applicationinsights-js/applicationinsights-js-tests.ts b/types/applicationinsights-js/applicationinsights-js-tests.ts index 1a4d585795..8967356426 100644 --- a/types/applicationinsights-js/applicationinsights-js-tests.ts +++ b/types/applicationinsights-js/applicationinsights-js-tests.ts @@ -44,7 +44,7 @@ appInsights = { trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; }, trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; }, trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; }, - trackTrace(message: string, properties?: { [name: string]: string; }) { return null; }, + trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: AI.SeverityLevel) { return null; }, flush() { return null; }, setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null; }, clearAuthenticatedUserContext() { return null; }, @@ -77,6 +77,7 @@ appInsights.trackException(new Error("sample error"), "handledAt", null, null); // trackTrace appInsights.trackTrace("message"); appInsights.trackTrace("message", null); +appInsights.trackTrace("message", { a: '1', b: '2' }, AI.SeverityLevel.Error); // trackDependency appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null); diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index cce53f5823..0a01d726a4 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -763,7 +763,7 @@ declare module Microsoft.ApplicationInsights { * @param message A message string * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. */ - trackTrace(message: string, properties?: { [name: string]: string }): any; + trackTrace(message: string, properties?: { [name: string]: string }, severityLevel?: AI.SeverityLevel): any; /** * Immediately send all queued telemetry. */ From bf3471c59d169f8b101a5a2f0ea9ce053fad5645 Mon Sep 17 00:00:00 2001 From: Yoni Lerner Date: Tue, 6 Jun 2017 17:00:02 -0700 Subject: [PATCH 27/98] Add onLimitReached for express-rate-limit RateLimit.Options, and add function signatures for all Options (#17009) * Update index.d.ts * Update index.d.ts * Update index.d.ts --- types/express-rate-limit/index.d.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/types/express-rate-limit/index.d.ts b/types/express-rate-limit/index.d.ts index 54bdacb936..86b8d497b0 100644 --- a/types/express-rate-limit/index.d.ts +++ b/types/express-rate-limit/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for express-rate-limit 2.6 +// Type definitions for express-rate-limit 2.8 // Project: https://github.com/nfriedly/express-rate-limit // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,14 +17,15 @@ declare namespace RateLimit { interface Options { delayAfter?: number; delayMs?: number; - handlers?(): any; + handlers?(req?: express.Request, res?: express.Response, next?: express.NextFunction): any; headers?: boolean; - keyGenerator?(): string; + keyGenerator?(req?: express.Request, res?: express.Response): string; max?: number; message?: string; - skip?(): boolean; + skip?(req?: express.Request, res?: express.Response): boolean; statusCode?: number; store?: Store; + onLimitReached?(req?: express.Request, res?: express.Response, optionsUsed?: Options): void; windowMs?: number; } } From 501ea7986b960b3fe6b511c56466073340dc16ec Mon Sep 17 00:00:00 2001 From: Simon Males Date: Wed, 7 Jun 2017 02:18:42 +0200 Subject: [PATCH 28/98] Add definition for AWS Lambda Cognito User Pool event: request.usernameParameter (#16998) * request.usernameParameter * usernameParameter test --- types/aws-lambda/aws-lambda-tests.ts | 1 + types/aws-lambda/index.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index e3356cae42..55a3d6b99f 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -188,6 +188,7 @@ str = cognitoUserPoolEvent.callerContext.clientId; str = cognitoUserPoolEvent.request.userAttributes["email"]; str = cognitoUserPoolEvent.request.validationData["k1"]; str = cognitoUserPoolEvent.request.codeParameter; +str = cognitoUserPoolEvent.request.usernameParameter; b = cognitoUserPoolEvent.request.newDeviceUsed; cognitoUserPoolEvent.request.session[0].challengeName === "CUSTOM_CHALLENGE"; cognitoUserPoolEvent.request.session[0].challengeName === "PASSWORD_VERIFIER"; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 2af4e09ae7..ca84cd350d 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -142,6 +142,7 @@ interface CognitoUserPoolEvent { userAttributes: {[key: string]: string}; validationData?: {[key: string]: string}; codeParameter?: string; + usernameParameter?: string; newDeviceUsed?: boolean; session?: { challengeName: "CUSTOM_CHALLENGE" | "PASSWORD_VERIFIER" | "SMS_MFA" | "DEVICE_SRP_AUTH" | "DEVICE_PASSWORD_VERIFIER" | "ADMIN_NO_SRP_AUTH"; From 9bb76af07f5a1aa109b2c676f2d4c645399bcb6d Mon Sep 17 00:00:00 2001 From: StickerFiend Date: Tue, 6 Jun 2017 17:19:01 -0700 Subject: [PATCH 29/98] [types/paper] Updated from clark-stevenson repo (#16997) * Updated index.d.ts from clark-stevenson paperjs type repo * Fixed failing test --- types/paper/index.d.ts | 391 ++++++++++++++++++++++++++----------- types/paper/paper-tests.ts | 2 +- 2 files changed, 279 insertions(+), 114 deletions(-) diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 41b958fd50..197707058b 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -3,6 +3,8 @@ // Definitions by: Clark Stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +type NativeMouseEvent = MouseEvent; + declare module 'paper' { /** @@ -285,7 +287,7 @@ declare module 'paper' { * Transforms a point and returns the result. * @param point - the point to be transformed */ - transform(point: Point): Point; + transform(point: Point): Matrix; /** * Transforms an array of coordinates by this matrix and stores the results into the destination array, which is also returned. @@ -299,7 +301,7 @@ declare module 'paper' { * Inverse transforms a point and returns the result. * @param point - the point to be transformed */ - inverseTransform(point: Point): Point; + inverseTransform(point: Point): Matrix; /** * Attempts to decompose the affine transformation described by this matrix into scaling, rotation and shearing, and returns an object with these properties if it succeeded, null otherwise. @@ -550,6 +552,36 @@ declare module 'paper' { */ abs(): Point; + /* + * Returns a new point + * @param point - The point you want to add with + */ + add(point: Point): Point; + add(point: number[]): Point; + + /* + * Returns a new point + * @param point - The point you want to subtract with + */ + subtract(point: Point): Point; + subtract(point: number[]): Point; + + /* + * Returns the new multiplied point + * @param point - The point you want to multiply with + */ + multiply(point: Point): Point; + multiply(point: number[]): Point; + multiply(point: number): Point; + + /* + * Returns the new divided point + * @param point - The point you want to divide with + */ + divide(point: Point): Point; + divide(point: number[]): Point; + divide(point: number): Point; + } /** * A Rectangle specifies an area that is enclosed by it's top-left point (x, y), its width, and its height. It should not be confused with a rectangular path, it is not an item. @@ -894,6 +926,22 @@ declare module 'paper' { */ abs(): Size; + /* + * Returns the new multiplied size + * @param point - The size you want to multiply with + */ + multiply(point: Size): Size; + multiply(point: number[]): Size; + multiply(point: number): Size; + + /* + * Returns the new divided size + * @param point - The size you want to divide with + */ + divide(point: Size): Size; + divide(point: number[]): Size; + divide(point: number): Size; + } export interface IFrameEvent { @@ -1223,6 +1271,11 @@ declare module 'paper' { */ fillColor: Color | string; + /** + * The fill rule. + */ + fillRule: string; + /** * The color the item is highlighted with when selected. If the item does not specify its own color, the color defined by its layer is used instead. */ @@ -1432,6 +1485,20 @@ declare module 'paper' { */ insertBelow(item: Item): Item; + /** + * Moves this item above the specified item. Returns true if the item + * was moved. + * @param item - the item above which it should be moved + */ + moveAbove(item: Item): boolean; + + /** + * Moves this item below the specified item. Returns true if the item + * was moved. + * @param item - the item below which it should be moved + */ + moveBelow(item: Item): boolean; + /** * Sends this item to the back of all other items within the same parent. */ @@ -1551,7 +1618,7 @@ declare module 'paper' { * Translates (moves) the item by the given offset point. * @param delta - the offset to translate the item by */ - translate(delta: number): Point; + translate(delta: Point): Point; /** * Rotates the item by a given angle around the given point. @@ -1561,6 +1628,11 @@ declare module 'paper' { */ rotate(angle: number, center?: Point): void; + /** + * Gets the current rotation of the item. + */ + getRotation(): number; + /** * Scales the item by the given value from its center point, or optionally from a supplied point. * @param scale - the scale factor @@ -1883,6 +1955,7 @@ declare module 'paper' { * @param position [optional] - the center position at which the raster item is placed */ constructor(source?: HTMLImageElement | HTMLCanvasElement | string, position?: Point); + constructor(config: any); /** * The size of the raster in pixels. @@ -2105,7 +2178,7 @@ declare module 'paper' { * @param handle2 - The second control point handle for the curve * @param to - The end control point of the curve */ - cublicCurveTo(handle1: Point, handle2: Point, to: Point): void; + cubicCurveTo(handle1: Point, handle2: Point, to: Point): void; /** * Adds a quadratic bezier curve to the path, defined by a handle and a to point. @@ -2168,7 +2241,7 @@ declare module 'paper' { * @param handle2 - * @param to - */ - cublicCurveBy(handle1: Point, handle2: Point, to: Point): void; + cubicCurveBy(handle1: Point, handle2: Point, to: Point): void; /** * @@ -2227,118 +2300,11 @@ declare module 'paper' { */ export class Path extends PathItem { - /** - * Creates a linear path item from two points describing a line. - * @param from - the line's starting point - * @param to - the line's ending point - */ - static Line(from: Point, to: Point): Path; - - /** - * Creates a linear path item from the properties described by an object literal. - * @param object - an object literal containing properties describing the path's attributes - */ - static Line(object: any): Path; - - /** - * Creates a circular path item. - * @param center - the center point of the circle - * @param radius - the radius of the circle - */ - static Circle(center: Point, radius: number): Path; - - /** - * Creates a circular path item from the properties described by an object literal. - * @param object - an object literal containing properties describing the path's attributes - */ - static Circle(object: any): Path; - - /** - * Creates a rectangular path item, with optionally rounded corners. - * @param rectangle - the rectangle object describing the geometry of the rectangular path to be created. - * @param radius [optional] - the size of the rounded corners default: null - */ - static Rectangle(rectangle: Rectangle, radius?: number): Path; - - /** - * Creates a rectangular path item from a point and a size object. - * @param point - the rectangle's top-left corner. - * @param size - the rectangle's size. - */ - static Rectangle(point: Point, size: Size): Path; - - /** - * Creates a rectangular path item from the passed points. These do not necessarily need to be the top left and bottom right corners, the constructor figures out how to fit a rectangle between them. - * @param from - the first point defining the rectangle - * @param to - the second point defining the rectangle - */ - static Rectangle(from: Point, to: Point): Path; - - /** - * Creates a rectangular path item from the properties described by an object literal. - * @param object - an object literal containing properties describing the path's attributes - */ - static Rectangle(object: any): Path; - - /** - * Creates an elliptical path item. - * @param rectangle - the rectangle circumscribing the ellipse - */ - static Ellipse(rectangle: Rectangle): Path; - - /** - * Creates an elliptical path item from the properties described by an object literal. - * @param object - an object literal containing properties describing the path's attributes - */ - static Ellipse(object: any): Path; - /** - * Creates a circular arc path item - * @param from - the starting point of the circular arc - * @param through - the point the arc passes through - * @param to - the end point of the arc - */ - static Arc(from: Point, through: Point, to: Point): Path; - - /** - * Creates an circular arc path item from the properties described by an object literal. - * @param object - an object literal containing properties describing the path's attributes - */ - static Arc(object: any): Path; - - /** - * Creates a regular polygon shaped path item. - * @param center - the center point of the polygon - * @param sides - the number of sides of the polygon - * @param radius - the radius of the polygon - */ - static RegularPolygon(center: Point, sides: number, radius: number): Path; - - /** - * Creates a regular polygon shaped path item from the properties described by an object literal. - * @param object - an object literal containing properties describing the path's attributes - */ - static RegularPolygon(object: any): Path; - - /** - * Creates a star shaped path item. The largest of radius1 and radius2 will be the outer radius of the star. The smallest of radius1 and radius2 will be the inner radius. - * @param center - the center point of the star - * @param points - the number of points of the star - * @param radius1 - * @param radius2 - */ - static Star(center: Point, points: number, radius1: number, radius2: number): Path; - - /** - * Creates a star shaped path item from the properties described by an object literal. - * @param object - an object literal containing properties describing the path's attributes - */ - static Star(object: any): Path; - /** * Creates a new path item and places it at the top of the active layer. * @param segments [optional] - An array of segments (or points to be converted to segments) that will be added to the path */ - constructor(segments?: Segment[]| Point[]); + constructor(segments?: Segment[] | Point[]); /** * Creates a new path item from an object description and places it at the top of the active layer. @@ -2574,6 +2540,130 @@ declare module 'paper' { } + module Path { + export class Line extends Path { + /** + * Creates a linear path item from two points describing a line. + * @param from - the line's starting point + * @param to - the line's ending point + */ + constructor(from: Point, to: Point); + + /** + * Creates a linear path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + } + + export class Circle extends Path { + /** + * Creates a circular path item. + * @param center - the center point of the circle + * @param radius - the radius of the circle + */ + constructor(center: Point, radius: number); + + /** + * Creates a circular path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + } + + export class Rectangle extends Path { + /** + * Creates a rectangular path item, with optionally rounded corners. + * @param rectangle - the rectangle object describing the geometry of the rectangular path to be created. + * @param radius [optional] - the size of the rounded corners default: null + */ + constructor(rectangle: Rectangle, radius?: number); + + /** + * Creates a rectangular path item from a point and a size object. + * @param point - the rectangle's top-left corner. + * @param size - the rectangle's size. + */ + constructor(point: Point, size: Size); + + /** + * Creates a rectangular path item from the passed points. These do not necessarily need to be the top left and bottom right corners, the constructor figures out how to fit a rectangle between them. + * @param from - the first point defining the rectangle + * @param to - the second point defining the rectangle + */ + constructor(from: Point, to: Point); + + /** + * Creates a rectangular path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + } + + export class Ellipse extends Path { + /** + * Creates an elliptical path item. + * @param rectangle - the rectangle circumscribing the ellipse + */ + constructor(rectangle: Rectangle); + + /** + * Creates an elliptical path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + } + + export class Arc extends Path { + /** + * Creates a circular arc path item + * @param from - the starting point of the circular arc + * @param through - the point the arc passes through + * @param to - the end point of the arc + */ + constructor(from: Point, through: Point, to: Point); + + /** + * Creates an circular arc path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + } + + export class RegularPolygon extends Path { + /** + * Creates a regular polygon shaped path item. + * @param center - the center point of the polygon + * @param sides - the number of sides of the polygon + * @param radius - the radius of the polygon + */ + constructor(center: Point, sides: number, radius: number); + + /** + * Creates a regular polygon shaped path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + } + + export class Star extends Path { + /** + * Creates a star shaped path item. The largest of radius1 and radius2 will be the outer radius of the star. The smallest of radius1 and radius2 will be the inner radius. + * @param center - the center point of the star + * @param points - the number of points of the star + * @param radius1 + * @param radius2 + */ + constructor(center: Point, points: number, radius1: number, radius2: number); + + /** + * Creates a star shaped path item from the properties described by an object literal. + * @param object - an object literal containing properties describing the path's attributes + */ + constructor(object: any); + } + } + /** * A compound path contains two or more paths, holes are drawn where the paths overlap. All the paths in a compound path take on the style of the backmost path and can be accessed through its item.children list. */ @@ -4005,4 +4095,79 @@ declare module 'paper' { } + /** + * A Javascript MouseEvent wrapper + */ + export class MouseEvent extends Event { + constructor(type: string, event: NativeMouseEvent, point: Point, target: Item, delta: Point) + + /** + * The JavaScript mouse event + */ + event: NativeMouseEvent; + + /** + * The position of the mouse in project coordinates when the event was + * fired. + */ + point: Point; + + /** + * The last event's position of the mouse in project coordinates when + * the event was fired. + */ + lastPoint: Point; + + /** + * + */ + delta: Point; + + /** + * The item that dispatched the event. It is different from + * currentTarget when the event handler is called during the bubbling + * phase of the event. + */ + target: Item; + + /** + * The current target for the event, as the event traverses the scene + * graph. It always refers to the element the event handler has been + * attached to as opposed to target which identifies the element on + * which the event occurred. + */ + currentTarget: Item; + + /** + * Type of mouse event + */ + type: 'mousedown' | 'mouseup' | 'mousedrag' | 'click' | 'doubleclick' | 'mousemove' | 'mouseenter' | 'mouseleave'; + + /** + * The time at which the event was created, in milliseconds since the + * epoch. + */ + timeStamp(): number; + + /** + * Cancels the event if it is cancelable, without stopping further + * propagation of the event. + */ + preventDefault(): void; + + /** + * Prevents further propagation of the current event. + */ + stopPropagation(): void; + + /** + * Cancels the event if it is cancelable, and stops stopping further + * propagation of the event. This is has the same effect as calling + * both stopPropagation() and preventDefault(). + * + * Any handler can also return false to indicate that stop() should be + * called right after. + */ + stop(): void; + } } diff --git a/types/paper/paper-tests.ts b/types/paper/paper-tests.ts index 39d015db87..444ffb8725 100644 --- a/types/paper/paper-tests.ts +++ b/types/paper/paper-tests.ts @@ -5,7 +5,7 @@ var canvas = document.createElement('canvas') paper.setup(canvas); // Circle -var path = paper.Path.Circle({ +var path = new paper.Path.Circle({ center: [80, 50], radius: 35, fillColor: 'red' From 99d808a93f7f21b31a1b10a58242a4a82f04cdf3 Mon Sep 17 00:00:00 2001 From: Bernd Date: Wed, 7 Jun 2017 02:21:44 +0200 Subject: [PATCH 30/98] add type definitions for HERE data lens (#16690) * add type definitions for HERE data lens * add missing test file to tsconfig.json * fix tests and dtslint and improve typings --- types/heredatalens/heredatalens-tests.ts | 123 +++ types/heredatalens/index.d.ts | 947 +++++++++++++++++++++++ types/heredatalens/tsconfig.json | 23 + types/heredatalens/tslint.json | 3 + 4 files changed, 1096 insertions(+) create mode 100644 types/heredatalens/heredatalens-tests.ts create mode 100644 types/heredatalens/index.d.ts create mode 100644 types/heredatalens/tsconfig.json create mode 100644 types/heredatalens/tslint.json diff --git a/types/heredatalens/heredatalens-tests.ts b/types/heredatalens/heredatalens-tests.ts new file mode 100644 index 0000000000..37f20f2f84 --- /dev/null +++ b/types/heredatalens/heredatalens-tests.ts @@ -0,0 +1,123 @@ +/** + * Typescript definition tests for heredatalens + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +let serviceOptions: H.datalens.Service.Options = { + subDomain: 'sub', + version: 'version', + access_token: 'token', + refresh_token: 'token', + domainSharding: ['a', 'b'], + baseUrl: 'url' +}; + +let queryTileProviderTileParamNames: H.datalens.QueryTileProvider.TileParamNames = { + x: 'x', + y: 'y', + z: 'z' +}; + +let queryTileProviderOptions: H.datalens.QueryTileProvider.Options = { + queryId: 'id', + queryParams: 'params', + tileParamNames: queryTileProviderTileParamNames +}; + +let service: H.datalens.Service = new H.datalens.Service(serviceOptions); +service.request('method', 'endpoint', 'params', 'body', (result: any) => {}, (error: any) => {}).then((data: any) => {}); +service.fetchQueryData('id', 'params', (result: any) => {}, (error: any) => {}).then((data: any) => {}); +service.fetchQueryStats('id', 'query', (result: any) => {}, (error: any) => {}).then((data: any) => {}); +service.fetchLayer('name', 'params', (result: any) => {}, (error: any) => {}).then((data: any) => {}); +service.fetchLayerTile('name', 1, 2, 3, 'params', (result: any) => {}, (error: any) => {}).then((data: any) => {}); +service.setTokens('token', 'refresh_token'); +service.configure('app_id', 'app_code', true, true, new H.service.Url('scheme', 'host')); + +let queryTileProvider = new H.datalens.QueryTileProvider(service, queryTileProviderOptions); +queryTileProvider.setQueryId('some id'); +queryTileProvider.setQueryParams('some params'); +queryTileProvider.setTileParamNames(queryTileProviderTileParamNames); + +let provider = new H.datalens.Provider({ columns: ['1', '2'], rows: [[], []]}); +provider.getData(); +provider.setData({ columns: ['3', '4'], rows: [[], []]}); + +let queryProviderOptions: H.datalens.QueryProvider.Options = { + queryId: 'id', + queryParams: 'params' +}; +let queryProvider = new H.datalens.QueryProvider({ columns: ['1', '2'], rows: [[], []]}, queryProviderOptions); +queryProvider.setQueryId('id'); +queryProvider.setQueryParams('params'); +queryProvider.reload(); +queryProvider.getData(); +queryProvider.setData({ columns: ['3', '4'], rows: [[], []]}); + +let rasterLayerOptions: H.datalens.RasterLayer.Options = { + dataToRows: (): H.datalens.RasterLayer.Row[] => [], + rowToTilePoint: (): H.datalens.RasterLayer.TilePoint => ({ x: 1, y: 2 }), + buffer: (): number => 1, + renderTile: () => {} +}; + +let rasterLayer = new H.datalens.RasterLayer(); +rasterLayer.redraw(); + +let heatmapLayerOptions: H.datalens.HeatmapLayer.Options = { + dataToRows: (): H.datalens.HeatmapLayer.Row[] => [], + rowToTilePoint: (): H.datalens.HeatmapLayer.TilePoint => ({ x: 1, y: 2, value: 5, count: 5 }), + bandwidth: 5, + valueRange: (): number[] => [], + countRange: (): number[] => [], + colorScale: (): string => '2', + alphaScale: (): number => 1, + aggregation: H.datalens.HeatmapLayer.Aggregation.SUM, + inputScale: H.datalens.HeatmapLayer.InputScale.LINEAR +}; + +let heatmapLayer = new H.datalens.HeatmapLayer(queryTileProvider, heatmapLayerOptions); +heatmapLayer.getOptionsPerZoom(5); +heatmapLayer.dispose(); +heatmapLayer.redraw(); + +let objectLayerOptions: H.datalens.ObjectLayer.Options = { + dataToRows: (): H.datalens.ObjectLayer.Row[] => [], + rowToMapObject: (): H.map.Object => new H.map.Object(), + rowToStyle: (): H.datalens.ObjectLayer.ObjectStyleOptions => ({ icon: new H.map.Icon('x'), style: {}, arrows: {}, zIndex: 1 }), + dataDomains: 2, + clustering: { rowToDataPoint: (): H.clustering.DataPoint => ({ lat: 12.1, lng: 1.12, alt: 5, ctx: H.geo.AltitudeContext.GL, wt: 2, data: {} }), + options: (): H.clustering.Provider.ClusteringOptions => ({}) } +}; + +let objectLayer = new H.datalens.ObjectLayer(provider, objectLayerOptions); +objectLayer.redraw(); +objectLayer.updateObjectStyle(new H.map.Object(), { icon: new H.map.Icon('x'), style: {}, arrows: {}, zIndex: 1 }); + +let rawDataProviderOptions: H.datalens.RawDataProvider.Options = { + dataUrl: 'url', + dataToFeatures: (): H.datalens.RawDataProvider.Feature[] => [], + featuresToRows: (): H.datalens.ObjectLayer.Row[] => [] +}; + +let rawDataProvider = new H.datalens.RawDataProvider(rawDataProviderOptions); + +let spatialTileProviderOptions: H.datalens.SpatialTileProvider.Options = { + layerName: 'name', + queryParams: 'params' +}; + +let spatialProvider: H.datalens.SpatialTileProvider = new H.datalens.SpatialTileProvider(service, spatialTileProviderOptions); + +let spatialLayerOptions: H.datalens.SpatialLayer.Options = { + dataToRows: (): H.datalens.SpatialLayer.Row[] => [], + rowToSpatialId: (): string => 'asd', + featureToSpatialId: (): string => 'asd', + rowToStyle: (): any => { return; }, + defaultStyle: (): any => { return; }, + transformFeature: 1 +}; + +let spatialLayer = new H.datalens.SpatialLayer(provider, spatialProvider, spatialLayerOptions); diff --git a/types/heredatalens/index.d.ts b/types/heredatalens/index.d.ts new file mode 100644 index 0000000000..9b3ff44431 --- /dev/null +++ b/types/heredatalens/index.d.ts @@ -0,0 +1,947 @@ +// Type definitions for HERE Data Lens API for JavaScript 2.3 +// Project: https://developer.here.com/ +// Definitions by: Bernd Hacker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace H { + /** + * Data Lens REST API connector for HERE Maps API + * Data Lens JavaScript API is a module for HERE Maps API. + * It connects Data Lens REST API and provides data-driven styling of data on a map. + */ + namespace datalens { + /** + * HERE Maps API and Data Lens JavaScript API can be used to visualize data from different network sources. + * For each network source type, a service class is required. The service also stores API connection credentials. + * The service instance must be configured with a H.service.Platform instance. + */ + class Service implements H.service.IConfigurable { + /** + * Constructor + * @param options {H.datalens.Service.Options=} - Overrides the configuration from the H.service.Platform instance + */ + constructor(options?: H.datalens.Service.Options); + + /** + * This method makes an HTTP request to the Data Lens REST API. + * It makes any CRUD request (GET, PUT, POST, DELETE). + * This method can be used when implementing a custom provider or implementing data management. + * Otherwise existing providers are used to get data from the Data Lens REST API. + * @param method {string} - Any HTTP method (GET, PUT, POST, etc.) + * @param endpoint {string} - The REST API endpoint + * @param params {any=} - URL parameters + * @param body {any=} - The payload of the request + * @param onResult {function(any)=} - Callback called on a successful request with response data + * @param onError {function(Error)=} - Callback called on an unsuccessful request with the Error object + * @returns {Promise} - Response Promise + */ + request(method: string, endpoint: string, params?: any, body?: any, onResult?: (result: any) => void, onError?: (error: any) => void): Promise; + + /** + * This method fetches query data for a given query ID. + * This method can be used when implementing a custom provider. + * Otherwise existing providers are used to get data from the Data Lens REST API. + * @param queryId {string} - The ID of the Data Lens REST API query + * @param params {any=} - Query dynamic parameters + * @param onResult {function(any)=} - Callback called on a successful request with response data + * @param onError {function(Error)=} - Callback called on an unsuccessful request with the Error object + * @returns {Promise} - Response Promise + */ + fetchQueryData(queryId: string, params?: any, onResult?: (result: any) => void, onError?: (error: any) => void): Promise; + + /** + * This method fetches statistical data for the Data Lens query (eg minimum and maximum values for the query metric). + * It can be used to define visualization boundaries, scales and legends. + * @param queryId {string} - The ID of the Data Lens REST API query + * @param statsQuery {any} - A JSON object which defines a statistics query for the Data Lens query + * @param onResult {function(any)=} - Callback called on a successful request with response data + * @param onError {function(Error)=} - Callback called on an unsuccessful request with the Error object + * @returns {Promise} - Response Promise + */ + fetchQueryStats(queryId: string, statsQuery: any, onResult?: (result: any) => void, onError?: (error: any) => void): Promise; + + /** + * This method fetches a layer of geometries (eg buildings or administrative boundaries). + * @param layerName {string} - The name of the layer + * @param params {any=} - URL parameters (eg bounding box) + * @param onResult {function(any)=} - Callback called on a successful request with response data + * @param onError {function(Error)=} - Callback called on an unsuccessful request with the Error object + * @returns {Promise} - Response Promise + */ + fetchLayer(layerName: string, params?: any, onResult?: (result: any) => void, onError?: (error: any) => void): Promise; + + /** + * This method fetches vector tile data from the layer. + * @param layerName {string} + * @param x {H.datalens.QueryTileProvider.X} - Tile columns + * @param y {H.datalens.QueryTileProvider.Y} - Tile row + * @param z {H.datalens.QueryTileProvider.Zoom} - zoom level + * @param params {any=} - URL parameters (eg bounding box) + * @param onResult {function(any)=} - Callback called on a successful request with response data + * @param onError {function(Error)=} - Callback called on an unsuccessful request with the Error object + * @returns {Promise} - Typed array with tile data + */ + fetchLayerTile(layerName: string, x: H.datalens.QueryTileProvider.X, y: H.datalens.QueryTileProvider.Y, z: H.datalens.QueryTileProvider.Zoom, + params?: any, onResult?: (result: any) => void, onError?: (error: any) => void): Promise; + + /** + * Sets the access and refresh tokens used to authenticate all requests against the Data Lens REST API. + * Use this method to implement custom authentication to the Data Lens REST API. + * @param accessToken {string} - The token used to authenticate all requests + * @param refreshToken {string} - The token used to fetch a new access token after the previous access token has expired. + * When refreshToken is provided, Service will automatically update the expired accessToken. + */ + setTokens(accessToken: string, refreshToken: string): void; + + /** + * This method implements H.service.IConfigurable interface. It is called by the H.service.Platform instance. + * @param appId {string} - The appId + * @param appCode {string} - The appCode + * @param useHTTPS {boolean} - A flag to use HTTPS or not + * @param useCIT {boolean} - A flag to use the staging server (CIT) or not + * @param baseUrl {H.service.Url=} - The base URL for all requests to the Data Lens REST API + * @returns {H.datalens.Service} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, baseUrl?: H.service.Url): H.datalens.Service; + } + + namespace Service { + /** + * Overrides the H.datalens.Service configuration + * Normally the H.datalens.Service instance is configured with the H.service.Platform instance. + * This configuration can be overridden by specifying these options. + * It can be useful when the Data Lens environment is different from the HERE Platform environment. + * @property subDomain {string=} - Subdomain of the Data Lens REST API URL + * @property version {string=} - Pathname prefix of the Data Lens REST API endpoints + * @property access_token {string=} - The token used to authenticate all requests + * @property refresh_token {string=} - The token used to fetch a new access token after the previous access token has expired. + * When refresh_token is provided, Service will automatically update the expired access_token. + * @property domainSharding {string[]=} - To increase the number of simultaneous requests to the Data Lens REST API, domain sharding is used. + * This option can be used when the Data Lens environment does not support domain sharding. + * @property baseUrl {string=} - Defines an alternative host for the Data Lens REST API URL + */ + interface Options { + subDomain?: string; + version?: string; + access_token?: string; + refresh_token?: string; + domainSharding?: string[]; + baseUrl?: string; + } + + /** + * The format of Data Lens query data. + * The Data Lens query data has a table-like structure with named columns and rows. + * @property columns {string[]} - Column names + * @property rows {Array} - Rows of data + */ + interface Data { + columns: string[]; + rows: [any[]]; // rows : { Array. } + } + } + + /** + * Providers define interfaces for layers to access data. + * The input data can be stored locally or loaded from the network. Data can be loaded by tiles or in one chunk. + * This provider allows you to supply data stored locally or fetched using external tools. + */ + class Provider extends H.map.provider.Provider { + /** + * Constructor + * @param data {H.datalens.Service.Data=} - JSON object + * @param options {H.map.provider.Provider.Options=} - Configures data accessibility parameters + */ + constructor(data?: H.datalens.Service.Data, options?: H.map.provider.Provider.Options); + + /** + * Updates the provider data. When data is updated, the update event is triggered so that the consuming layers are redrawn. + * @param data {H.datalens.Service.Data} - JSON object + */ + setData(data: H.datalens.Service.Data): void; + + /** + * Retrieves the provider data. + * @returns {H.datalens.Service.Data} - JSON object + */ + getData(): H.datalens.Service.Data; + } + + /** + * Defines the source of the data for layers from a Data Lens query. + * Providers define interfaces for layers to access data. The input data can be stored locally or loaded from the network. + * Data can be loaded by tiles or in one chunk. This provider loads query data with the Data Lens REST API. + * Note that this provider must be used only for non-tiled queries. + */ + class QueryProvider extends H.datalens.Provider { + /** + * Constructor + * @param service {H.datalens.Service} - Data Lens REST API service + * @param options {H.datalens.QueryProvider.Options=} - Configures source query and data accessibility parameters + */ + constructor(data: H.datalens.Service.Data, options?: H.map.provider.Provider.Options); + + /** + * Updates the query ID to be used in the next call of the Data Lens REST API. + * Note that new data will be fetched only after the reload method is called. + * @param queryId {string} + */ + setQueryId(queryId: string): void; + + /** + * Updates the query's dynamic parameters to be used in the next call of the Data Lens REST API. + * Note that new data will be fetched only after the reload method is called. + * This method is normally used when updating your visualization. + * @param queryParams {any|null} - Query dynamic parameters + */ + setQueryParams(queryParams: any|null): void; + + /** + * Fetches new data from the Data Lens REST API. + * When data is fetched, the update event is triggered so that the consuming layers are redrawn. + */ + reload(): void; + + /** + * Updates the provider data. + * When data is updated, the update event is triggered so that the consuming layers are redrawn. + * @param data {H.datalens.Service.Data} - JSON object + */ + setData(data: H.datalens.Service.Data): void; + + /** + * Retrieves the provider data. + * @returns {H.datalens.Service.Data} - JSON object + */ + getData(): H.datalens.Service.Data; + } + + namespace QueryProvider { + /** + * Configures source query and data accessibility parameters for H.datalens.QueryProvider + * Specifies the query credentials and dynamic parameters required for fetching query data with the Data Lens REST API. Other options from H.datalens.Provider.Options are available. + * @property queryId {string} - The ID of the Data Lens REST API query + * @property queryParams {any=} - The query's dynamic parameters. The dynamic parameters can be used to filter data provided by the query. + */ + interface Options { + queryId: string; + queryParams?: any; + } + } + + /** + * Providers define interfaces for layers to access data. + * The input data can be stored locally or loaded from the network. Data can be loaded by tiles or in one chunk. + * This provider loads tiled query data with the Data Lens REST API. Tiled queries are used to load data only for the current viewport. + * This optimizes memory and network usage and enables progressive rendering. + */ + class QueryTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {H.datalens.Service} - Data Lens REST API service + * @param options {H.datalens.QueryTileProvider.Options} - Configures source query and data accessibility parameters + */ + constructor(service: H.datalens.Service, options: H.datalens.QueryTileProvider.Options); + + /** + * Updates the query ID to be used in the next call of the Data Lens REST API. + * Note that new data will be fetched only after the reload method is called. + * @param queryId {string} + */ + setQueryId(queryId: string): void; + + /** + * Updates the query's dynamic parameters to be used in the next call of the Data Lens REST API. + * Note that new data will be fetched only after the reload method is called. This method is normally used when updating your visualization. + * @param queryParams {any|null} + */ + setQueryParams(queryParams: any|null): void; + + /** + * Updates the names of the dynamic parameters that defines tiles. This method is only needed when the query ID is updated. + * Note that new data will be fetched only after the reload method is called. + * @param tileParamNames {H.datalens.QueryTileProvider.TileParamNames} - Names of the URI parameters that control the x/y/z of a tiled query + */ + setTileParamNames(tileParamNames: H.datalens.QueryTileProvider.TileParamNames): void; + } + + namespace QueryTileProvider { + /** + * Represents the names of the URI parameters that control the x/y/z of tiled query. + * When defining the Data Lens query, dynamic parameters that control tiling can be arbitrarily named. + * Names of these parameters must be specified to fetch tiles. + * @property x {string} - Name of the dynamic parameter that defines tile column + * @property y {string} - Name of the dynamic parameter that defines tile row + * @property z {string} - Name of the dynamic parameter that defines zoom level + */ + interface TileParamNames { + x: string; + y: string; + z: string; + } + + /** + * Configures source query and data accessibility parameters for H.datalens.QueryTileProvider + * Specifies the query credentials and dynamic parameters required for fetching tiled query data with the Data Lens REST API. + * Other options from H.datalens.Provider.Options are available. + * @property tileParamNames {H.datalens.QueryTileProvider.TileParamNames=} - Names of the URI parameters that control the x/y/z of a tiled query + * @property queryId {string} - The ID for the Data Lens REST API query + * @property queryParams {any=} - The query's dynamic parameters. The dynamic parameters can be used to filter data provided by the query. + */ + interface Options { + tileParamNames: H.datalens.QueryTileProvider.TileParamNames; + queryId: string; + queryParams?: string; + } + + /** + * Tile X coordinate (column) + * Coordinate in XYZ tile numbering scheme. + */ + type X = number; + + /** + * Tile Y coordinate (row) + * Coordinate in XYZ tile numbering scheme. + */ + type Y = number; + + /** + * Zoom level + * Coordinate in XYZ tile numbering scheme. May vary within range 1 to 20. + */ + type Zoom = number; + } + + /** + * Provides pixel-wise rendering of data. + * Layer used when you need to visualize more than 10k points. The layer requires source data to be located in pixel coordinates. + * The rendering is implemented by drawing directly on a canvas. The layer is often used together with a Data Lens query which groups rows by pixels. + * This reduces the amount of data delivered to the client. + */ + class RasterLayer extends H.map.layer.TileLayer { + /** + * Constructor + */ + constructor(); + + /** + * Default value for dataToRows callback option. + * It represents each row as an object where property names correspond to data column names. + */ + static defaultDataToRows: any; + + /** + * Force re-rendering of the layer. + * In the case where the callbacks passed to the layer options are not pure functions, you can call this method to force re-rendering. + */ + redraw(): void; + + /** + * This is a default implementation of renderTile callback. This method represents each point as a black 1x1 pixel square. + * @param points {Array} - Input data points within a tile + * @param canvas {HTMLCanvasElement} - The target canvas + */ + static defaultRenderTile(points: H.datalens.RasterLayer.TilePoint[], canvas: HTMLCanvasElement): void; + } + + namespace RasterLayer { + /** + * Defines data processing and rendering options for RasterLayer. + * The initial step of rendering is to split the tile data by rows, where each row represents a bucket. + * By default this step is processed with H.datalens.RasterLayer.defaultDataToRows. + * This behavior can be changed by defining the dataToRows callback. + * To collect the rows for a tile including buffer, the rows must be translated to H.datalens.RasterLayer.TilePoint. + * This translation must be specified with the rowToTilePoint callback. The final rendering on the tile canvas must be defined in renderTile. + * @property dataToRows {function(H.datalens.Service.Data, H.datalens.QueryTileProvider.X, H.datalens.QueryTileProvider.Y, H.datalens.QueryTileProvider.Zoom)=} - + * Defines how the input tile data is split by rows. You can specify this callback to define client-side aggregation and filtering. This callback is called for each tile. + * @property rowToTilePoint {function(H.datalens.RasterLayer.Row, H.datalens.RasterLayer.X, H.datalens.RasterLayer.Y)=} - + * Defines how the row is translated to the H.datalens.RasterLayer.TilePoint. This callback is called for each row that is returned from dataToRows. + * @property buffer {function(H.datalens.QueryTileProvider.Zoom)=} - Defines the buffer as a function of the zoom level. + * The buffer is a value (in pixels) that defines an extra area around each tile to capture data points from. + * This is done to avoid drawing edges between tiles. For example, if data points represented with circles with a maximum radius of 10 pixels, then the buffer must be 10 pixels. + * @property renderTile {function(Array, HTMLCanvasElement, H.datalens.QueryTileProvider.Zoom)=} - + * Defines how tile data is represented on a canvas. Input points for each tile are collected with respect to the buffer. + * For progressive rendering this callback may be called more than once for the tile. + */ + interface Options { + dataToRows?(data: H.datalens.Service.Data, x: H.datalens.QueryTileProvider.X, y: H.datalens.QueryTileProvider.Y, zoom: H.datalens.QueryTileProvider.Zoom): + H.datalens.RasterLayer.Row[]; + rowToTilePoint?(row: H.datalens.RasterLayer.Row, x: H.datalens.RasterLayer.X, y: H.datalens.RasterLayer.Y): H.datalens.RasterLayer.TilePoint; + buffer?(zoom: H.datalens.QueryTileProvider.Zoom): number; + renderTile?(points: H.datalens.RasterLayer.TilePoint[], canvas: HTMLCanvasElement, zoom: H.datalens.QueryTileProvider.Zoom): void; + } + + /** + * Defines the input data format for heat map rendering. + * To collect data rows for each tile with respect to the buffer, each row must be represented as a point within the map tile. + * @property x {number} - Row relative to tile + * @property y {number} - Column relative to tile + * @property data {H.datalens.RasterLayer.Row=} - Reference to source data row + */ + interface TilePoint { + x: number; + y: number; + data?: H.datalens.RasterLayer.Row; + } + + /** + * Tile X coordinate (column) + * Coordinate in XYZ tile numbering scheme. + */ + type X = number; + + /** + * Tile Y coordinate (row) + * Coordinate in XYZ tile numbering scheme. + */ + type Y = number; + + /** + * Slice of data (eg Data Lens query data row) that represents a data point. + * Each row is transformed into TilePoint and passed to renderTile callback. By default each row is an Object where property names correspond to data column names. + * This representation can be changed with the dataToRows callback. + */ + type Row = number; + } + + /** + * Provides functionality of value-based heat map with density alpha mask. + * Layer support different types of blending, including weighted average. Also it allows to apply alpha mask calculated by density. + * In most cases, the layer consumes data grouped by 1x1 pixels buckets. For proper averaging it requires aggregated value and count (number of rows in bucket) for each bucket. + * Blending of buckets is implemented via kernel density estimation (KDE) with a Gaussian kernel. + */ + class HeatmapLayer extends H.datalens.RasterLayer { + /** + * Constructor + * @param provider {H.datalens.QueryTileProvider} - Source of tiled data + * @param options {H.datalens.HeatmapLayer.Options} - Configuration for data processing and rendering + */ + constructor(provider: H.datalens.QueryTileProvider, options: H.datalens.HeatmapLayer.Options); + + /** + * Default value for dataToRows callback option. It represents each row as an object where property names correspond to data column names. + * @param data {H.datalens.Service.Data} + * @param x {H.datalens.QueryTileProvider.X} + * @param y {H.datalens.QueryTileProvider.Y} + * @param zoom {H.datalens.QueryTileProvider.Zoom} + * @returns {Array} + */ + static defaultDataToRows: (data: H.datalens.Service.Data, x: H.datalens.QueryTileProvider.X, y: H.datalens.QueryTileProvider.Y, zoom: H.datalens.QueryTileProvider.Zoom) => + H.datalens.HeatmapLayer.Row[]; + + /** + * Set of possible values for the inputScale option + * @type {H.datalens.HeatmapLayer.InputScale} + */ + static inputScale: H.datalens.HeatmapLayer.InputScale; + + /** + * Set of possible values for the aggregation option + * @type {H.datalens.HeatmapLayer.Aggregation} + */ + static aggregation: H.datalens.HeatmapLayer.Aggregation; + + /** + * @param zoom {number} - zoom level + * @return {H.datalens.HeatmapLayer.Options} + */ + getOptionsPerZoom(zoom: number): H.datalens.HeatmapLayer.Options; + + /** + * Removes listeners, and references to memory consuming objects, from this layer. Call this method when you no longer need the layer. + */ + dispose(): void; + + /** + * Force re-rendering of the layer. In the case where the callbacks passed to the layer options are not pure functions, you can call this method to force re-rendering. + */ + redraw(): void; + } + + namespace HeatmapLayer { + /** + * Defines data processing and rendering options for HeatmapLayer. + * The data processing flow of HeatmapLayer is similar to RasterLayer. The initial step of rendering is to split the tile data by rows, where each row represents a bucket. + * By default this step is processed with H.datalens.HeatmapLayer.defaultDataToRows. This behavior can be changed by defining the dataToRows callback. + * To collect the rows for a tile including buffer, the rows must be translated to H.datalens.HeatmapLayer.TilePoint. This translation must be specified with the rowToTilePoint callback. + * Other options define the blending options for the heat map. + * @property dataToRows {function(H.datalens.Service.Data, H.datalens.QueryTileProvider.X, H.datalens.QueryTileProvider.Y, H.datalens.QueryTileProvider.Zoom)=} - + * Defines how the input tile data is split by rows. You can specify this callback to define client-side aggregation and filtering. This callback is called for each tile. + * @property rowToTilePoint {function(H.datalens.HeatmapLayer.Row, H.datalens.HeatmapLayer.X, H.datalens.HeatmapLayer.Y)=} - + * Defines how the row is translated to the H.datalens.HeatmapLayer.TilePoint. This callback is called for each row that is returned from dataToRows. + * @property bandwidth {H.datalens.HeatmapLayer~Bandwidth | H.datalens.HeatmapLayer~BandwidthStop | Array. | + * H.datalens.HeatmapLayer~BandwidthCallback=} - Describes the bandwidth behavior in relation to current zoom level A numeric value sets it static across all levels + * An Object with zoom, value and optional zoomIncrementFactor (1 equals doubling on every zoom increment) defines a behavior across all zoom levels + * An Array of one or more zoom, value objects describes the behavior between the two defined levels and extrapolates the implied change outside of the defined range + * Alternatively defines the level of smoothing as a function of the zoom level. The callback must return a value in pixels. + * The cut-off of the Gaussian kernel is defined as 3 * bandwidth , a multiple (default 3) of bandwidth. + * @property valueRange {function(H.datalens.QueryTileProvider.Zoom)} - Defines the range for the color scale as a function of the zoom level. + * The returned value must be an array of 2 numbers. + * @property countRange {function(H.datalens.QueryTileProvider.Zoom)} - Defines the range for the density alpha mask as a function of the zoom level. + * When defined, the density alpha mask is applied. The returned value must be an array of 2 numbers. + * @property colorScale {function(number)} - Defines a color palette as a function of the normalized value. You can use D3.js library scale functions with the domain [0, 1]. + * @property alphaScale {function(number)} - Defines the alpha mask value as a function of the normalized count. + * You can use D3.js library scale functions with the domain [0, 1] and the range [0, 1]. + * @property aggregation {H.datalens.HeatmapLayer.Aggregation} - Specifies which type of aggregation was applied (eg. type of aggregation function for bucket in the Data Lens query). + * Possible values are SUM or AVERAGE. If the aggregation type is AVERAGE , then an averaged heat map is rendered. + * @property inputScale {H.datalens.HeatmapLayer.InputScale} - Defines the scale (eg logarithmic scale) of the TilePoint value. + * Note: if the value is not in a linear scale, then the aggregation in the source query must be defined with respect to the scale type. + * For example, before applying the average aggregation function in a query, the value must be transformed to the linear scale. This guarantees correct linear averaging of values. + */ + interface Options { + dataToRows?(data: H.datalens.Service.Data, x: H.datalens.QueryTileProvider.X, y: H.datalens.QueryTileProvider.Y, zoom: H.datalens.QueryTileProvider.Zoom): + H.datalens.HeatmapLayer.Row[]; + rowToTilePoint(row: H.datalens.HeatmapLayer.Row, x: H.datalens.HeatmapLayer.X, y: H.datalens.HeatmapLayer.Y): H.datalens.HeatmapLayer.TilePoint; + bandwidth?: H.datalens.HeatmapLayer.Bandwidth | H.datalens.HeatmapLayer.BandwidthStop | H.datalens.HeatmapLayer.BandwidthStop[] | H.datalens.HeatmapLayer.BandwidthCallback; + valueRange?(zoom: H.datalens.QueryTileProvider.Zoom): number[]; + countRange?(zoom: H.datalens.QueryTileProvider.Zoom): number[]; + colorScale?(scale: number): string; + alphaScale?(scale: number): number; + aggregation?: H.datalens.HeatmapLayer.Aggregation; + inputScale?: H.datalens.HeatmapLayer.InputScale; + } + + /** + * Tile X coordinate (column) + * Coordinate in XYZ tile numbering scheme. + */ + type X = number; + + /** + * Tile Y coordinate (row) + * Coordinate in XYZ tile numbering scheme. + */ + type Y = number; + + /** + * Slice of data (eg Data Lens query data row) that represents a data point. + * Each row is transformed into TilePoint and then rendered on a heat map. By default each row is an Object where property names correspond to data column names. + * This representation can be changed with the dataToRows callback. + */ + interface Row { + tx?: number; + ty?: number; + count?: number; + } + + /** + * Defines a constant for the bandwidth + * A number that sets a constant for the bandwidth across all zoom levels. + */ + type Bandwidth = number; + + /** + * Sets the bandwidth for a given zoom level and uses this to calculate the increment or decrement of the bandwidth at other zoom levels + * This object defines the behavior of the bandwidth value across all zoom levels, initialized by a reference zoom level and its value at that level. + * The default behavior with zoomIncrementFactor = 1 doubles the bandwidth with every increasing zoom level and halves it on every decrease in zoom level. + * For example, a bandwidth of 10@zoom1 turns to 20@zoom2 and 5@zoom0. A zoomIncrementFactor of 0 effectively equals the bandwidth number, ignoring the provided zoom level. + * A zoomIncrementFactor of 0.5 mean a bandwidth increase of 50% compared to a factor of 1. So a bandwidth of 10@zoom1 computes to 15@zoom2. + */ + interface BandwidthStop { + zoom: number; + value: number; + zoomIncrementFactor?: number; + } + + /** + * TODO: this is missing in the documentation: https://developer.here.com/visualization/documentation/datalens/h-datalens-heatmaplayer-options.html + */ + type BandwidthCallback = () => void; + + /** + * Defines the input data format for heat map rendering. + * For heat map rendering, each row of data must be represented as a point within the map tile. + * @property x {number} - Row relative to tile + * @property y {number} - Column relative to tile + * @property value {number} - Value at the point (eg aggregated bucket value) + * @property count {number} - Number of contributors to the value at the point (eg number of rows in a bucket) + * @property data {H.datalens.HeatmapLayer.Row} - Reference to source data row + */ + interface TilePoint { + x: number; + y: number; + value: number; + count: number; + data?: H.datalens.HeatmapLayer.Row; + } + + /** + * Set of possible values for the aggregation option. + * If the heat map input data is buckets, then different types of aggregation can be applied to the rows in a bucket. + * The aggregation type is required for proper blending mode of the heat map. For the AVERAGE aggregation type, an averaged heat map is rendered. + * @property SUM {string} - Specifies that the sum aggregation was applied to the bucket value + * @property AVERAGE {string} - Specifies that the average aggregation was applied to the bucket value + */ + enum Aggregation { + SUM, + AVERAGE + } + + /** + * Set of possible values for the inputScale option. + * The input scale is required for proper heat map blending. If the input scale is not linear, then the TilePoint.value is converted to linear scale before calculating the sum or average. + * @property DB {string} - Decibel (dB) scale + * @property LINEAR {string} - Linear scale + * @property LOG {string} - Logarithmic scale + */ + enum InputScale { + DB, + LINEAR, + LOG + } + } + + /** + * Presents data as points or spatial map objects with data-driven styles and client-side clustering. + * Applicable for drawing interactive map objects like markers, polygons, circles and other instances of H.map.Object. Source of data can be either tiled or not tiled. + * Styles for objects can be parametrized with data rows and zoom level. Allows to create data-driven icons for markers like donuts or bars. + * Also enables clustering and data domains for visualizing up to 100k points or more. + */ + class ObjectLayer extends H.map.layer.ObjectLayer { + /** + * Constructor + * @param provider {H.map.provider.RemoteTileProvider | H.datalens.Provider | H.datalens.QueryProvider | H.datalens.QueryTileProvider} - Data source (tiled or not) + * @param options {H.datalens.ObjectLayer.Options} - Defines data processing, clustering and data-driven styling + */ + constructor(provider: H.map.provider.RemoteTileProvider | H.datalens.Provider | H.datalens.QueryProvider | H.datalens.QueryTileProvider, options: H.datalens.ObjectLayer.Options); + + /** + * Default value for dataToRows callback option. It represents each row as an object where property names correspond to data column names. + * @property data {H.datalens.Service.Data} + * @returns {Array} + */ + static defaultDataToRows(data: H.datalens.Service.Data): H.datalens.ObjectLayer.Row[]; + + /** + * A factory method for data-driven icons. The method allows you to build an icon from SVG markup or JsonML object. Provides caching of icons with the same markup. + * @param svg {string | Array} - SVG presented as markup or JsonML Array + * @param options {H.map.Icon.Options} - Icon options (eg size and anchor). Note that the default anchor is in the middle. + * @param options.size {H.math.ISize | number} - When the icon is a square, you can define the size as a number in pixels + * @returns {H.map.Icon} - Icon which can be used for marker or cluster + */ + static createIcon(svg: string | any[], options?: H.map.Icon.Options): H.map.Icon; + + /** + * Returns cache of icons created with the createIcon method. Can be used to clean the icon cache. + * @return {H.util.Cache} - Icon cache + */ + static getIconCache(): H.util.Cache; + + /** + * Force re-rendering of the layer. In the case where the callbacks passed to the layer options are not pure functions, you can call this method to force re-rendering. + */ + redraw(): void; + + /** + * Recalculates the style and applies it to the map object based on the new StyleState + * @param object {H.map.Object} - Map object + * @param state {H.datalens.ObjectLayer.StyleState} - New state + */ + updateObjectStyle(any: H.map.Object, state: H.datalens.ObjectLayer.StyleState): void; + } + + namespace ObjectLayer { + /** + * Defines data processing and data-driven styling for ObjectLayer + * The initial step of rendering is to split the tile data by rows, where each row represents a bucket. + * By default this step is processed with H.datalens.ObjectLayer.defaultDataToRows. This behavior can be changed by defining the dataToRows callback. + * In the next step each row must be presented as a map object with the rowToMapObject callback. Data-driven styling can be provided with the rowToStyle callback. + * @property dataToRows {function(H.datalens.Service.Data)=} - Defines how the input data is split by rows. You can specify this callback to define client-side aggregation and filtering. + * @property rowToMapObject {function(H.datalens.ObjectLayer.Row, H.datalens.QueryTileProvider.Zoom)} - Defines how each row is presented on the map (eg marker, polygon) + * @property rowToStyle {function(H.datalens.ObjectLayer.Row, H.datalens.QueryTileProvider.Zoom, H.datalens.ObjectLayer.StyleState)=} - + * Defines map object style and icon according to data row and zoom level. Also it can define different styles depending on the StyleState (eg hovered, selected). + * @property dataDomains {H.datalens.ObjectLayer.DataDomains=} - Defines quantization of data for improving data-driven styling performance + * @property clustering {H.datalens.ObjectLayer.Clustering=} - When present, client-side clustering is applied + */ + interface Options { + dataToRows?(data: H.datalens.Service.Data): H.datalens.ObjectLayer.Row[]; + rowToMapObject(row: H.datalens.ObjectLayer.Row, z: H.datalens.QueryTileProvider.Zoom): H.map.Object; + rowToStyle?(row: H.datalens.ObjectLayer.Row, z: H.datalens.QueryTileProvider.Zoom, styleState: H.datalens.ObjectLayer.StyleState): H.datalens.ObjectLayer.ObjectStyleOptions; + dataDomains?: H.datalens.ObjectLayer.DataDomains; + clustering?: H.datalens.ObjectLayer.Clustering; + } + + /** + * Defines client-side clustering in the ObjectLayer. + * When the clustering option is provided, rows returned from dataToRows go to the clustering.rowToDataPoint callback to be transformed to data points. + * Then, the data points are clustered according to clustering.options. Clustering produces clusters and noise points (data points that are not clustered). + * Clusters and noise points must be presented as map objects with the rowToMapObject callback and can be styled with the rowToStyle callback. + * @property rowToDataPoint {H.datalens.ObjectLayer.Row} - Defines data points from rows + * @property options {function(H.datalens.QueryTileProvider.Zoom)} - Defines clustering options as a function of the zoom level + */ + interface Clustering { + rowToDataPoint(row: H.datalens.ObjectLayer.Row): H.clustering.DataPoint; + options(zoom: H.datalens.QueryTileProvider.Zoom): H.clustering.Provider.ClusteringOptions; + } + + /** + * Slice of data (eg Data Lens query data row) that represents a data point. + * Each row is translated to map objects with the rowToMapObject callback. By default each row is an Object where property names correspond to data column names. + * This representation can be changed with the dataToRows callback. + */ + interface Row { + getPosition(): H.geo.Point; + lat: number; + lng: number; + } + + /** + * User defined modification of a data-driven style + * StyleState appears as a parameter in the rowToStyle callback. By default it is 'DEFAULT_STATE'. To change StyleState, use the ObjectLayer.updateObjectStyle method. + */ + type StyleState = any; + + /** + * Output from the rowToStyle callback. + * Defines the styles or the icon that is applied to the map object. + * @property icon {H.map.Icon} - Marker icon + * @property style {H.map.SpatialStyle.Options} - Spatial style + * @property arrows {H.map.ArrowStyle.Options} - Style of arrows to render along a polyline + * @property zIndex {number} - The z-index value of the map object, default is 0 + */ + interface ObjectStyleOptions { + icon: H.map.Icon; + style: H.map.SpatialStyle.Options; + arrows: H.map.ArrowStyle.Options; + zIndex: number; + } + + /** + * Input data quantization domain, used to optimize styling performance. + * The option must have properties corresponding to the properties of H.datalens.ObjectLayer.Row. Values must be represented as an Array of Numbers that defines the quantization domain. + * When provided, the input data will be quantized, and rowToStyle will be called only for quantized values. + */ + type DataDomains = any; + } + + /** + * Defines how to load data from a raw data file + * This provider defines the interface for loading data, such as geometries or coordinates, from a local or remote data file in GeoJSON or CSV format + */ + class RawDataProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.datalens.RawDataProvider.Options} - Configures options + */ + constructor(options: H.datalens.RawDataProvider.Options); + + /** + * Updates the data url. Note that new data will be fetched only after the reload method is called. + * @param dataUrl {string} + */ + setDataUrl(dataUrl: string): void; + } + + namespace RawDataProvider { + /** + * Defines options for RawDataProvider + * Options for RawDataProvider + * @property dataUrl - The data url to fetch + * @property dataToFeatures {function(any)=} - Defines how the input data is mapped to an array of GeoJSON features + * @property featuresToRows {function(Array, H.datalens.QueryTileProvider.X, H.datalens.QueryTileProvider.Y, H.datalens.QueryTileProvider.Zoom, + * H.datalens.RawDataProvider.TileSize, H.datalens.RawDataProvider.Helpers)=} - + * Defines how GeoJSON features on a tile should be mapped to data rows, which are inputs to layers such as ObjectLayer and HeatmapLayer + */ + interface Options { + dataUrl?: string; + dataToFeatures?(obj: any): H.datalens.RawDataProvider.Feature[]; + featuresToRows?(features: H.datalens.RawDataProvider.Feature[], x: H.datalens.QueryTileProvider.X, y: H.datalens.QueryTileProvider.Y, z: H.datalens.QueryTileProvider.Zoom, + tileSize: H.datalens.RawDataProvider.TileSize, helpers: H.datalens.RawDataProvider.Helpers): H.datalens.ObjectLayer.Row[]; + } + + /** + * A GeoJSON feature + * A GeoJSON feature object which conforms to the standard GeoJSON spec + */ + type Feature = any; + + /** + * Tile size + * The tile size in pixels. + */ + type TileSize = any; + + /** + * A helper class used in the worker thread + * This helper class provides convenience functions you can use in the worker thread + * @property latLngToPixel {function(H.datalens.RawDataProvider.Latitude, H.datalens.RawDataProvider.Longitude, H.datalens.QueryTileProvider.Zoom, H.datalens.RawDataProvider.TileSize)=} - + * Translates geographical coordinates (latitude, longitude) to world pixel coordinates. + * @property pixelToLatLng {function(H.datalens.RawDataProvider.PX, H.datalens.RawDataProvider.PY, H.datalens.QueryTileProvider.Zoom, H.datalens.RawDataProvider.TileSize)=} - + * Translates world pixel coordinates to geographical coordinates (latitude, longitude). + * @property parseCSV {function(any)=} - Takes CSV data as input, parses it, and return the parsed result. + */ + interface Helpers { + latLngToPixel?(latitude: H.datalens.RawDataProvider.Latitude, longitude: H.datalens.RawDataProvider.Longitude, z: H.datalens.QueryTileProvider.Zoom, + tileSize: H.datalens.RawDataProvider.TileSize): H.datalens.RawDataProvider.PixelCoordinates; + pixelToLatLng?(x: H.datalens.RawDataProvider.PX, y: H.datalens.RawDataProvider.PY, z: H.datalens.QueryTileProvider.Zoom, tileSize: H.datalens.RawDataProvider.TileSize): + H.datalens.RawDataProvider.GeoCoordinates; + parseCSV?(obj: any): any[]; + } + + /** + * Geographic coordinates + * A geographic coordinates pair [lat, lng] + */ + type GeoCoordinates = [number, number]; + + /** + * Latitude coordinate + * The latitude in the geographic coordinates pair + */ + type Latitude = number; + + /** + * Longitude coordinate + * The longitude in the geographic coordinates pair + */ + type Longitude = number; + + /** + * Pixel coordinates + * Pixel coordinates [px, py] pair + */ + type PixelCoordinates = [number, number]; + + /** + * Pixel coordinate in the x direction + * The x coordinate of the pixel coordinates pair [px, py] + */ + type PX = number; + + /** + * Pixel coordinate in the y direction + * The y coordinate of the pixel coordinates pair [px, py] + */ + type PY = number; + } + + /** + * Renders vector tiles using data-driven styles + * This layer binds the spatial data and user data, all provided by the Data Lens REST API. The layer renders geometry features using data-driven styles. + */ + class SpatialLayer extends H.map.layer.TileLayer { + /** + * Constructor + * @param dataProvider {H.datalens.Provider} - Source of tiled data (pass in null if data come from feature properties) + * @param spatialProvider {H.datalens.SpatialTileProvider} - Source of geometry data + * @param options {H.datalens.SpatialLayer.Options} - Configuration for data processing and rendering + */ + constructor(dataProvider: H.datalens.Provider, spatialProvider: H.datalens.SpatialTileProvider, options: H.datalens.SpatialLayer.Options); + + static DEFAULT_STATE: any; + static Spatial: any; + + /** + * Default value for dataToRows callback option. It represents each row as an object where property names correspond to data column names. + */ + static defaultDataToRows: any; + + /** + * Forces re-rendering of the layer. When the callbacks passed to the layer options are not pure functions, you can call this method to force re-rendering. + */ + redraw(): void; + + /** + * This method changes the state of a map object; for example, style on mouse event. + * @param {H.map.Object} spatial + * @param {H.datalens.SpatialLayer.StyleState} state + */ + updateSpatialStyle(spatial: H.map.Object, state: H.datalens.SpatialLayer.StyleState): void; + } + + namespace SpatialLayer { + /** + * Defines data processing and rendering options for SpatialLayer + * The initial step of rendering is to split the tile data by rows, where each row represents a bucket. + * By default this step is processed with H.datalens.SpatialLayer.defaultDataToRows. This behavior can be changed by defining the dataToRows callback. + * @property dataToRows {function(H.datalens.Service.Data, H.datalens.QueryTileProvider.X, H.datalens.QueryTileProvider.Y, H.datalens.QueryTileProvider.Zoom)=} - + * Defines how the input tile data is split by rows. You can specify this callback to define client-side aggregation and filtering. This callback is called for each tile. + * @property rowToSpatialId {function(H.datalens.SpatialLayer.Row)} - + * Defines how to get the spatial ID from a data row. This callback is called for each row that is returned from dataToRows. + * @property featureToSpatialId {function(H.datalens.SpatialLayer.Feature)} - + * Defines how to get the spatial ID from a geometry feature. This callback is called for each geometry feature in the vector tile. + * @property rowToStyle {function(H.datalens.SpatialLayer.Row, H.datalens.QueryTileProvider.Zoom, H.datalens.SpatialLayer.StyleState)} - + * Defines how the row is translated to map object style. This callback is called for each row that is returned from dataToRows. + * @property defaultStyle {function(H.datalens.QueryTileProvider.Zoom, H.datalens.SpatialLayer.StyleState)} - Defines the default map object style. + * @property transformFeature {H.datalens.SpatialLayer.transformFeature} - Defines how to transform the features. + */ + interface Options { + dataToRows?(data: H.datalens.Service.Data, x: H.datalens.QueryTileProvider.X, y: H.datalens.QueryTileProvider.Y, z: H.datalens.QueryTileProvider.Zoom): + H.datalens.SpatialLayer.Row[]; + rowToSpatialId(row: H.datalens.SpatialLayer.Row): string; + featureToSpatialId(feature: H.datalens.SpatialLayer.Feature): string; + rowToStyle(row: H.datalens.SpatialLayer.Row, z: H.datalens.QueryTileProvider.Zoom, styleState: H.datalens.SpatialLayer.StyleState): any; + defaultStyle(z: H.datalens.QueryTileProvider.Zoom, styleState: H.datalens.SpatialLayer.StyleState): any; + transformFeature: H.datalens.SpatialLayer.transformFeature; + } + + /** + * Defines modification of a data-driven style + * StyleState appears as a parameter in the rowToStyle callback. By default it is 'DEFAULT_STATE'. To change StyleState, use the SpatialLayer.updateSpatialStyle method. + */ + type StyleState = any; + + /** + * Defines a slice of data (eg Data Lens query data row) that represents a data point + * By default each row is an object where property names correspond to data column names. This representation can be changed with the dataToRows callback. + */ + type Row = any; + + /** + * Defines a geometry in the vector tile + * Each geometry is described by various properties, including a unique identifier which must be used to map the geometry to user data. + */ + type Feature = any; + + /** + * TODO: missing in documentation: https://developer.here.com/visualization/documentation/datalens/h-datalens-spatiallayer-options.html + */ + type transformFeature = any; + } + + /** + * Specifies how to access layer data (shapes, geometries) using the Data Lens REST API. + * This provider defines the interface for accessing shape layers via the Data Lens REST API. The input data is provided as vector tiles in the MapBox format (Protobuf). + * Data is loaded by tiles. + */ + class SpatialTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {H.datalens.Service} - Data Lens REST API service + * @param options {H.datalens.SpatialTileProvider.Options} - Configures layer name + */ + constructor(service: H.datalens.Service, options: H.datalens.SpatialTileProvider.Options); + + static VectorTile: any; + + /** + * Updates the layer name to be used in the next call of the Data Lens REST API. Note that new data will be fetched only after the reload method is called. + * @param {string} layerName + */ + setLayerName(layerName: string): void; + + /** + * Updates the query's dynamic parameters to be used in the next call of the Data Lens REST API. Note that new data will be fetched only after the reload method is called. + * This method is normally used when updating your visualization. + * @param {any|null} queryParams + */ + setQueryParams(queryParams: any | null): void; + } + + namespace SpatialTileProvider { + /** + * Defines layer name and data accessibility parameters for H.datalens.SpatialTileProvider + * This defines the layer name and dynamic parameters required for fetching tiled geometry data with the Data Lens REST API. Other options from H.datalens.Provider.Options are available. + * @property layerName {string} - The name of the layer to fetch with the Data Lens REST API query + * @property queryParams {any} - The query's dynamic parameters. The dynamic parameters can be used to filter data provided by the query. + */ + interface Options { + layerName: string; + queryParams?: any; + } + } + } +} diff --git a/types/heredatalens/tsconfig.json b/types/heredatalens/tsconfig.json new file mode 100644 index 0000000000..9c60b13753 --- /dev/null +++ b/types/heredatalens/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "heredatalens-tests.ts" + ] +} \ No newline at end of file diff --git a/types/heredatalens/tslint.json b/types/heredatalens/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/heredatalens/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file From 879a6039ac7035742eb4636a551a7d8ebd99dbc8 Mon Sep 17 00:00:00 2001 From: Deividas Bakanas Date: Wed, 7 Jun 2017 03:22:10 +0300 Subject: [PATCH 31/98] Types for rrc 0.10 (#16996) * rrc types files added. rrc types definitions. * TS config updated. Types definitions updated. Tests added. * withScroll return type adjusted to `react-router` RouteProps.component type. * Test values updated. * rrc types file lint errors fixed. * rrc tests file updated. --- types/rrc/index.d.ts | 75 ++++++++++++++++++++++++ types/rrc/rrc-tests.tsx | 122 ++++++++++++++++++++++++++++++++++++++++ types/rrc/tsconfig.json | 24 ++++++++ types/rrc/tslint.json | 1 + 4 files changed, 222 insertions(+) create mode 100644 types/rrc/index.d.ts create mode 100644 types/rrc/rrc-tests.tsx create mode 100644 types/rrc/tsconfig.json create mode 100644 types/rrc/tslint.json diff --git a/types/rrc/index.d.ts b/types/rrc/index.d.ts new file mode 100644 index 0000000000..5ebf120c74 --- /dev/null +++ b/types/rrc/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for rrc 0.10 +// Project: https://github.com/pshrmn/rrc#readme +// Definitions by: Deividas Bakanas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from "react"; +import * as H from "history"; +import { RouteProps, RouteComponentProps, match as MatchObject } from "react-router-dom"; + +export interface ScrollIntoViewProps { + alignToTop?: boolean; + id: string; +} + +export class ScrollIntoView extends React.Component { } + +export type PropIdCallback = () => string; + +export interface WithScrollOptions { + propId?: PropIdCallback; + alignToTop?: boolean; +} + +export type ComponentConstructor = React.ComponentClass | React.SFC; + +export function withScroll(component: ComponentConstructor | undefined>, options?: WithScrollOptions) + : ComponentConstructor | undefined>; + +export type RouteConfiguration = RouteProps & { inject?: { [key: string]: any } }; + +export interface SwitchProps { + routes: RouteConfiguration[]; + location: H.LocationDescriptorObject & { pathname: H.Pathname }; +} + +export class ConfigSwitch extends React.Component { } + +export type OnUpdateCall = (location: H.Location) => void; + +export interface OnUpdateProps { + call: OnUpdateCall; + immediate?: boolean; +} + +export class OnUpdate extends React.Component { } + +export type IsActiveCallback = () => boolean; + +export interface WhenActiveOptions { + exact?: boolean; + strict?: boolean; + pathProp?: string; + className?: string; + style?: React.CSSProperties; + isActive?: IsActiveCallback; +} + +export type WhenActiveReturnType = (component: ComponentConstructor) => ComponentConstructor; + +export function whenActive(options?: WhenActiveOptions): WhenActiveReturnType; + +export interface StatusProps { + code: string; +} + +export class Status extends React.Component { } + +export type GetKeyFunction = (match: MatchObject, route: RouteConfiguration, location: H.Location) => string; + +export interface WrapSwitchProps extends SwitchProps { + getKey?: GetKeyFunction; +} + +export function wrapSwitch(Wrapper: ComponentConstructor): + ComponentConstructor & WrapperProps>; diff --git a/types/rrc/rrc-tests.tsx b/types/rrc/rrc-tests.tsx new file mode 100644 index 0000000000..084f921614 --- /dev/null +++ b/types/rrc/rrc-tests.tsx @@ -0,0 +1,122 @@ +import * as React from "react"; +import { Switch, Route, RouteComponentProps, BrowserRouter, Link } from "react-router-dom"; +import { + ScrollIntoView, + ConfigSwitch, + withScroll, + OnUpdate, + whenActive, + Status, + wrapSwitch, + RouteConfiguration, + GetKeyFunction, + OnUpdateCall +} from "rrc"; + +class RouteOne extends React.Component, {}> { + render() { + return
+ +
Main view
+
+ }, + { path: "/one/two", render: () =>
One two route
} + ]} /> +
; + } +} + +class RouteTwo extends React.Component, {}> { + private onUpdate: OnUpdateCall = (location) => { console.log("update"); }; + + render() { + return
+ Route 2 + Go to Route 1 + +
; + } +} + +interface LayoutProps { + title: string; + subtitle?: string; +} + +class Layout extends React.Component { + render() { + return
+
{`Layout ${this.props.title}`}
+
+ Content + {this.props.children} +
+
; + } +} + +const WrappedLayout = wrapSwitch(Layout); + +interface Params { + page: number; +} + +class RouteFour extends React.Component, {}> { + private routes: RouteConfiguration[] = [ + { path: "/four/something/:page", component: RouteTwo } + ]; + + private getKey: GetKeyFunction = (match, route, location) => { + return "my-key-" + match.url; + } + + render() { + return
+
+ Route four +
+
+ +
+
; + } +} + +interface MyContainerProps { + className?: string; + color: number; +} + +class MyContainer extends React.Component { + render() { + return
+ {this.props.children} +
; + } +} + +const ExtendedContainer = whenActive({ className: "active" })(MyContainer); + +const RouteTwoWithScroll = withScroll(RouteTwo); + +export const Routes = + +
+
My page
+ + + + + Route 3} /> + + +
+
; diff --git a/types/rrc/tsconfig.json b/types/rrc/tsconfig.json new file mode 100644 index 0000000000..12588363b6 --- /dev/null +++ b/types/rrc/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rrc-tests.tsx" + ] +} diff --git a/types/rrc/tslint.json b/types/rrc/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rrc/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e366674da8a8265eee509e3ffe272c539d4db813 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 6 Jun 2017 20:22:36 -0400 Subject: [PATCH 32/98] [semantic-ui-site] Add type definitions. (#16995) --- types/semantic-ui-site/global.d.ts | 85 +++++++++++++++++++ types/semantic-ui-site/index.d.ts | 11 +++ .../semantic-ui-site-tests.ts | 52 ++++++++++++ types/semantic-ui-site/tsconfig.json | 24 ++++++ types/semantic-ui-site/tslint.json | 7 ++ 5 files changed, 179 insertions(+) create mode 100644 types/semantic-ui-site/global.d.ts create mode 100644 types/semantic-ui-site/index.d.ts create mode 100644 types/semantic-ui-site/semantic-ui-site-tests.ts create mode 100644 types/semantic-ui-site/tsconfig.json create mode 100644 types/semantic-ui-site/tslint.json diff --git a/types/semantic-ui-site/global.d.ts b/types/semantic-ui-site/global.d.ts new file mode 100644 index 0000000000..1cd7caa858 --- /dev/null +++ b/types/semantic-ui-site/global.d.ts @@ -0,0 +1,85 @@ +interface JQueryStatic { + site: SemanticUI.Site; +} + +interface JQuery { + site: SemanticUI.Site; +} + +declare namespace SemanticUI { + interface Site { + settings: SiteSettings; + + (behavior: 'destroy'): JQuery; + (behavior: 'setting', name: K, value?: undefined): SiteSettings[K]; + (behavior: 'setting', name: K, value: SiteSettings[K]): JQuery; + (behavior: 'setting', value: SiteSettings.Param): JQuery; + (settings?: SiteSettings.Param): JQuery; + } + + interface SiteSettings extends Pick { } + + namespace SiteSettings { + type Param = SiteSettings | object; + + interface _Impl { + modules: string[]; + siteNamespace: string; + namespaceStub: Site.NamespaceStubSettings; + + // region Component Settings + + // region DOM Settings + + /** + * Event namespace. Makes sure module teardown does not effect other events attached to an element. + */ + namespace: string; + + // endregion + + // region Debug Settings + + /** + * Name used in log statements + */ + name: string; + /** + * Silences all console output including error messages, regardless of other debug settings. + */ + silent: boolean; + /** + * Debug output to console + */ + debug: boolean; + /** + * Show console.table output with performance metrics + */ + performance: boolean; + /** + * Debug output includes all internal behaviors + */ + verbose: boolean; + + // endregion + + // endregion + } + } + + namespace Site { + interface NamespaceStubSettings extends Pick { } + + namespace NamespaceStubSettings { + type Param = NamespaceStubSettings | object; + + interface _Impl { + cache: any; + config: any; + sections: any; + section: any; + utilities: any; + } + } + } +} diff --git a/types/semantic-ui-site/index.d.ts b/types/semantic-ui-site/index.d.ts new file mode 100644 index 0000000000..6b2eeff1ef --- /dev/null +++ b/types/semantic-ui-site/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for semantic-ui-site 2.2 +// Project: http://www.semantic-ui.com +// Definitions by: Leonard Thieu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// + +declare const site: SemanticUI.Site; +export = site; diff --git a/types/semantic-ui-site/semantic-ui-site-tests.ts b/types/semantic-ui-site/semantic-ui-site-tests.ts new file mode 100644 index 0000000000..0eaddfc5b2 --- /dev/null +++ b/types/semantic-ui-site/semantic-ui-site-tests.ts @@ -0,0 +1,52 @@ +function test_site_static() { + $.site.settings.namespace = 'namespace'; + $.site.settings.name = 'name'; + $.site.settings.silent = false; + $.site.settings.debug = true; + $.site.settings.performance = true; + $.site.settings.verbose = true; + + $.fn.site.settings.namespace = 'namespace'; + $.fn.site.settings.name = 'name'; + $.fn.site.settings.silent = false; + $.fn.site.settings.debug = true; + $.fn.site.settings.performance = true; + $.fn.site.settings.verbose = true; +} + +function test_site() { + const selector = '.ui.site'; + $(selector).site('destroy') === $(); + $(selector).site('setting', 'debug', undefined) === false; + $(selector).site('setting', 'debug') === false; + $(selector).site('setting', 'debug', true) === $(); + $(selector).site('setting', { + namespace: 'namespace', + name: 'name', + silent: false, + debug: true, + performance: true, + verbose: true + }) === $(); + $(selector).site({ + modules: [ + 'module1', + 'module2', + ], + siteNamespace: 'siteNamespace', + namespaceStub: { + cache: {}, + config: {}, + sections: {}, + section: {}, + utilities: {} + } + }) === $(); + $(selector).site() === $(); +} + +import site = require('semantic-ui-site'); + +function test_module() { + $.fn.site = site; +} diff --git a/types/semantic-ui-site/tsconfig.json b/types/semantic-ui-site/tsconfig.json new file mode 100644 index 0000000000..0ea895173c --- /dev/null +++ b/types/semantic-ui-site/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "global.d.ts", + "semantic-ui-site-tests.ts" + ] +} diff --git a/types/semantic-ui-site/tslint.json b/types/semantic-ui-site/tslint.json new file mode 100644 index 0000000000..758e484744 --- /dev/null +++ b/types/semantic-ui-site/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false, + "unified-signatures": false + } +} From 8109b32f883e81f36957f84dfe0fc3a6dd02e312 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 6 Jun 2017 20:22:55 -0400 Subject: [PATCH 33/98] [semantic-ui-visibility] Add type definitions. (#16994) --- types/semantic-ui-visibility/global.d.ts | 366 ++++++++++++++++++ types/semantic-ui-visibility/index.d.ts | 11 + .../semantic-ui-visibility-tests.ts | 161 ++++++++ types/semantic-ui-visibility/tsconfig.json | 24 ++ types/semantic-ui-visibility/tslint.json | 7 + 5 files changed, 569 insertions(+) create mode 100644 types/semantic-ui-visibility/global.d.ts create mode 100644 types/semantic-ui-visibility/index.d.ts create mode 100644 types/semantic-ui-visibility/semantic-ui-visibility-tests.ts create mode 100644 types/semantic-ui-visibility/tsconfig.json create mode 100644 types/semantic-ui-visibility/tslint.json diff --git a/types/semantic-ui-visibility/global.d.ts b/types/semantic-ui-visibility/global.d.ts new file mode 100644 index 0000000000..fa735676c5 --- /dev/null +++ b/types/semantic-ui-visibility/global.d.ts @@ -0,0 +1,366 @@ +interface JQuery { + visibility: SemanticUI.Visibility; +} + +declare namespace SemanticUI { + interface Visibility { + settings: VisibilitySettings; + + /** + * Disable callbacks temporarily. This is useful if you need to adjust scroll position and do not want to trigger callbacks during the position change. + */ + (behavior: 'disable callbacks'): JQuery; + /** + * Re-enable callbacks + */ + (behavior: 'enable callbacks'): JQuery; + /** + * Returns whether element is on screen + */ + (behavior: 'is on screen'): boolean; + /** + * Returns whether element is off screen + */ + (behavior: 'is off screen'): boolean; + /** + * Returns number of pixels passed in current element from top of element + */ + (behavior: 'get pixels passed'): number; + /** + * Returns element calculations as object + */ + (behavior: 'get element calculations'): Visibility.ElementCalculations; + /** + * Returns screen calculations as object + */ + (behavior: 'get screen calculations'): Visibility.ScreenCalculations; + /** + * Returns screen size as object + */ + (behavior: 'get screen size'): Visibility.ScreenSize; + (behavior: 'destroy'): JQuery; + (behavior: 'setting', name: K, value?: undefined): VisibilitySettings[K]; + (behavior: 'setting', name: K, value: VisibilitySettings[K]): JQuery; + (behavior: 'setting', value: VisibilitySettings.Param): JQuery; + (settings?: VisibilitySettings.Param): JQuery; + } + + /** + * @see {@link http://semantic-ui.com/behaviors/visibility.html#/settings} + */ + interface VisibilitySettings extends Pick { } + + namespace VisibilitySettings { + type Param = VisibilitySettings | object; + + interface _Impl { + // region Functionality + + /** + * When set to false a callback will occur each time an element passes the threshold for a condition. + * + * @default true + */ + once: boolean; + /** + * When set to true a callback will occur anytime an element passes a condition not just immediately after the threshold is met. + * + * @default false + */ + continuous: boolean; + /** + * Set to image to load images when on screen. Set to fixed to add class name fixed when passed. + * + * @default false + */ + type: false | 'image' | 'fixed'; + /** + * Whether visibility conditions should be checked immediately on init + * + * @default true + */ + initialCheck: boolean; + /** + * The scroll context visibility should use. + * + * @default 'window' + */ + context: string | JQuery; + /** + * Whether visibility conditions should be checked on window load. This ensures that after images load content positions will be updated correctly. + * + * @default true + */ + refreshOnLoad: boolean; + /** + * Whether visibility conditions should be checked on window resize. Useful when content resizes causes continuous changes in position + * + * @default true + */ + refreshOnResize: boolean; + /** + * Whether visibility conditions should be checked on calls to refresh. + * These calls can be triggered from either resize, load or manually calling $('.foo').visibility('refresh') + * + * @default true + */ + checkOnRefresh: boolean; + /** + * Specify a z-index when using type: 'fixed'. + * + * @default 1 + * @since 2.2 + */ + zIndex: number; + /** + * Value that context scrollTop should be adjusted in pixels. Useful for making content appear below content fixed to the page. + * + * @default 0 + */ + offset: number; + /** + * Whether element calculations should include its margin + * + * @default false + */ + includeMargin: boolean; + /** + * When set to an integer, scroll position will be debounced using this ms value. false will debounce with requestAnimationFrame. + * + * @default false + */ + throttle: false | number; + /** + * Whether to automatically refresh content when changes are made to the element's DOM subtree + * + * @default true + */ + observeChanges: boolean; + /** + * When using type: image allows you to specify transition when showing a loaded image + * + * @default false + */ + transition: false | string; + /** + * When using type: image allows you to specify transition duration + * + * @default 1000 + */ + duration: number; + + // endregion + + // region Visibility Callbacks + + /** + * Element's top edge has passed bottom of screen + */ + onTopVisible(this: JQuery): void; + /** + * Element's top edge has passed top of the screen + */ + onTopPassed(this: JQuery): void; + /** + * Element's bottom edge has passed bottom of screen + */ + onBottomVisible(this: JQuery): void; + /** + * Any part of an element is visible on screen + */ + onPassing(this: JQuery): void; + /** + * Element's bottom edge has passed top of screen + */ + onBottomPassed(this: JQuery): void; + /** + * Element's top edge has not passed bottom of screen + */ + onTopVisibleReverse(this: JQuery): void; + /** + * Element's top edge has not passed top of the screen + */ + onTopPassedReverse(this: JQuery): void; + /** + * Element's bottom edge has not passed bottom of screen + */ + onBottomVisibleReverse(this: JQuery): void; + /** + * Element's top has not passed top of screen but bottom has + */ + onPassingReverse(this: JQuery): void; + /** + * Element's bottom edge has not passed top of screen + */ + onBottomPassedReverse(this: JQuery): void; + onOnScreen(this: JQuery): void; + onOffScreen(this: JQuery): void; + + // endregion + + // region Image Callbacks + + /** + * Occurs after an image has completed loading + * + * @since 2.2 + */ + onLoad(this: JQuery): void; + /** + * Occurs after all img initialized at the same time have loaded. + * + * @since 2.2 + */ + onAllLoaded(this: JQuery): void; + + // endregion + + // region Fixed Callbacks + + /** + * Occurs after element has been assigned position fixed + * + * @since 2.2 + */ + onFixed(this: JQuery): void; + /** + * Occurs after element has been removed from fixed position + * + * @since 2.2 + */ + onUnfixed(this: JQuery): void; + + // endregion + + // region Utility Callbacks + + /** + * Occurs each time an elements calculations are updated + */ + onUpdate(this: JQuery, calculations: Visibility.ElementCalculations): void; + /** + * Occurs whenever element's visibility is refreshed + */ + onRefresh(this: JQuery): void; + + // endregion + + // region DOM Settings + + /** + * Class names used to attach style to state + */ + className: Visibility.ClassNameSettings; + + // endregion + + // region Debug Settings + + error: Visibility.ErrorSettings; + + // endregion + + // region Component Settings + + // region DOM Settings + + /** + * Event namespace. Makes sure module teardown does not effect other events attached to an element. + */ + namespace: string; + + // endregion + + // region Debug Settings + + /** + * Name used in log statements + */ + name: string; + /** + * Silences all console output including error messages, regardless of other debug settings. + */ + silent: boolean; + /** + * Debug output to console + */ + debug: boolean; + /** + * Show console.table output with performance metrics + */ + performance: boolean; + /** + * Debug output includes all internal behaviors + */ + verbose: boolean; + + // endregion + + // endregion + } + } + + namespace Visibility { + interface ElementPosition { + fits: boolean; + offset: JQueryCoordinates; + width: number; + height: number; + } + + interface ElementCalculations extends ElementPosition { + margin?: { + top: number; + bottom: number; + }; + top: number; + bottom: number; + + topVisible: boolean; + topPassed: boolean; + bottomVisible: boolean; + bottomPassed: boolean; + pixelsPassed: number; + percentagePassed: number; + + onScreen: boolean; + passing: boolean; + offScreen: boolean; + } + + interface ScreenCalculations { + top: number; + bottom: number; + } + + interface ScreenSize { + height: number; + } + + interface ClassNameSettings extends Pick { } + + namespace ClassNameSettings { + type Param = ClassNameSettings | object; + + interface _Impl { + /** + * @default 'fixed' + */ + fixed: string; + } + } + + interface ErrorSettings extends Pick { } + + namespace ErrorSettings { + type Param = ErrorSettings | object; + + interface _Impl { + /** + * @default 'The method you called is not defined.' + */ + method: string; + } + } + } +} diff --git a/types/semantic-ui-visibility/index.d.ts b/types/semantic-ui-visibility/index.d.ts new file mode 100644 index 0000000000..14873ba2ea --- /dev/null +++ b/types/semantic-ui-visibility/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for semantic-ui-visibility 2.2 +// Project: http://www.semantic-ui.com +// Definitions by: Leonard Thieu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// + +declare const visibility: SemanticUI.Visibility; +export = visibility; diff --git a/types/semantic-ui-visibility/semantic-ui-visibility-tests.ts b/types/semantic-ui-visibility/semantic-ui-visibility-tests.ts new file mode 100644 index 0000000000..960eeb5215 --- /dev/null +++ b/types/semantic-ui-visibility/semantic-ui-visibility-tests.ts @@ -0,0 +1,161 @@ +function test_visibility_static() { + $.fn.visibility.settings.error.method = 'method'; + $.fn.visibility.settings.namespace = 'namespace'; + $.fn.visibility.settings.name = 'name'; + $.fn.visibility.settings.silent = false; + $.fn.visibility.settings.debug = true; + $.fn.visibility.settings.performance = true; + $.fn.visibility.settings.verbose = true; +} + +function test_visibility() { + const selector = '.ui.visibility'; + $(selector).visibility('disable callbacks') === $(); + $(selector).visibility('enable callbacks') === $(); + $(selector).visibility('is on screen') === false; + $(selector).visibility('is off screen') === true; + $(selector).visibility('get pixels passed') === 20; + $(selector).visibility('get element calculations') === { + fits: false, + offset: { + top: 955.96875, + left: 292 + }, + width: 466, + height: 1665.890625, + top: 955.96875, + bottom: 2621.859375, + topPassed: true, + bottomPassed: false, + topVisible: true, + bottomVisible: false, + pixelsPassed: 742.03125, + percentagePassed: 0.44542615155182, + onScreen: true, + passing: true, + offScreen: false + }; + $(selector).visibility('get screen calculations') === { + bottom: 2658, + top: 1698 + }; + $(selector).visibility('get screen size') === { + height: 960 + }; + $(selector).visibility('destroy') === $(); + $(selector).visibility('setting', 'debug', undefined) === false; + $(selector).visibility('setting', 'debug') === false; + $(selector).visibility('setting', 'debug', true) === $(); + $(selector).visibility('setting', { + namespace: 'namespace', + name: 'name', + silent: false, + debug: true, + performance: true, + verbose: true + }) === $(); + $(selector).visibility({ + once: false, + continuous: true, + type: 'image', + initialCheck: false, + context: $(), + refreshOnLoad: true, + refreshOnResize: false, + checkOnRefresh: true, + zIndex: 2, + offset: 3, + includeMargin: false, + throttle: 10, + observeChanges: true, + transition: 'fade', + duration: 5, + onTopVisible() { + this === $(); + }, + onTopPassed() { + this === $(); + }, + onBottomVisible() { + this === $(); + }, + onPassing() { + this === $(); + }, + onBottomPassed() { + this === $(); + }, + onTopVisibleReverse() { + this === $(); + }, + onTopPassedReverse() { + this === $(); + }, + onBottomVisibleReverse() { + this === $(); + }, + onPassingReverse() { + this === $(); + }, + onBottomPassedReverse() { + this === $(); + }, + onOnScreen() { + this === $(); + }, + onOffScreen() { + this === $(); + }, + onLoad() { + this === $(); + }, + onAllLoaded() { + this === $(); + }, + onFixed() { + this === $(); + }, + onUnfixed() { + this === $(); + }, + onUpdate(calculations) { + this === $(); + calculations === { + fits: false, + offset: { + top: 955.96875, + left: 292 + }, + width: 466, + height: 1665.890625, + top: 955.96875, + bottom: 2621.859375, + topPassed: true, + bottomPassed: false, + topVisible: true, + bottomVisible: false, + pixelsPassed: 742.03125, + percentagePassed: 0.44542615155182, + onScreen: true, + passing: true, + offScreen: false + }; + }, + onRefresh() { + this === $(); + }, + className: { + fixed: 'fixed', + }, + error: { + method: 'method' + } + }) === $(); + $(selector).visibility() === $(); +} + +import visibility = require('semantic-ui-visibility'); + +function test_module() { + $.fn.visibility = visibility; +} diff --git a/types/semantic-ui-visibility/tsconfig.json b/types/semantic-ui-visibility/tsconfig.json new file mode 100644 index 0000000000..dcf5313a0a --- /dev/null +++ b/types/semantic-ui-visibility/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "global.d.ts", + "semantic-ui-visibility-tests.ts" + ] +} diff --git a/types/semantic-ui-visibility/tslint.json b/types/semantic-ui-visibility/tslint.json new file mode 100644 index 0000000000..758e484744 --- /dev/null +++ b/types/semantic-ui-visibility/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false, + "unified-signatures": false + } +} From dc6ff26ec2e2affed08c3df3c170cb9cee245bcd Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 6 Jun 2017 20:23:50 -0400 Subject: [PATCH 34/98] [semantic-ui-tab] Add type definitions. (#16992) --- .../semantic-ui-api/semantic-ui-api-tests.ts | 3 +- types/semantic-ui-tab/global.d.ts | 357 ++++++++++++++++++ types/semantic-ui-tab/index.d.ts | 12 + .../semantic-ui-tab/semantic-ui-tab-tests.ts | 204 ++++++++++ types/semantic-ui-tab/tsconfig.json | 24 ++ types/semantic-ui-tab/tslint.json | 7 + 6 files changed, 605 insertions(+), 2 deletions(-) create mode 100644 types/semantic-ui-tab/global.d.ts create mode 100644 types/semantic-ui-tab/index.d.ts create mode 100644 types/semantic-ui-tab/semantic-ui-tab-tests.ts create mode 100644 types/semantic-ui-tab/tsconfig.json create mode 100644 types/semantic-ui-tab/tslint.json diff --git a/types/semantic-ui-api/semantic-ui-api-tests.ts b/types/semantic-ui-api/semantic-ui-api-tests.ts index c365765934..683c1a35c4 100644 --- a/types/semantic-ui-api/semantic-ui-api-tests.ts +++ b/types/semantic-ui-api/semantic-ui-api-tests.ts @@ -1,4 +1,4 @@ -function test_static() { +function test_api_static() { $.api.settings.className.error = 'error'; $.api.settings.namespace = 'namespace'; $.api.settings.name = 'name'; @@ -42,7 +42,6 @@ function test_api() { loadingDuration: 3, hideError: true, errorDuration: 10, - action: 'action', url: 'url', urlData: false, diff --git a/types/semantic-ui-tab/global.d.ts b/types/semantic-ui-tab/global.d.ts new file mode 100644 index 0000000000..7bd8aad4fc --- /dev/null +++ b/types/semantic-ui-tab/global.d.ts @@ -0,0 +1,357 @@ +interface JQuery { + tab: SemanticUI.Tab; +} + +declare namespace SemanticUI { + interface Tab { + settings: TabSettings; + + // Documentation says this exists but it does not. + // /** + // * Attaches tab action to given selector. Default event if none specified is toggle + // */ + // (behavior: 'attach events', selector: Selector, event?: string): JQuery; + /** + * Changes tab to path + */ + (behavior: 'change tab', path: string): JQuery; + /** + * Sets current path to state + */ + (behavior: 'set state', path: string): JQuery; + /** + * Returns current path + */ + (behavior: 'get path'): string; + /** + * Returns whether tab exists + */ + (behavior: 'is tab'): boolean; + /** + * Returns cached HTML for path + */ + (behavior: 'cache read', path: string): string | false; + /** + * Sets cached HTML for path + */ + (behavior: 'cache add', path: string, html: string): JQuery; + /** + * Removes cached HTML for path + */ + (behavior: 'cache remove', path: string): JQuery; + (behavior: 'destroy'): JQuery; + (behavior: 'setting', name: K, value?: undefined): TabSettings[K]; + (behavior: 'setting', name: K, value: TabSettings[K]): JQuery; + (behavior: 'setting', value: TabSettings.Param): JQuery; + (settings?: TabSettings.Param): JQuery; + } + + /** + * @see {@link http://semantic-ui.com/modules/tab.html#/settings} + */ + interface TabSettings extends Pick { } + + namespace TabSettings { + type Param = TabSettings | object; + + interface _Impl { + // region Tab Settings + + /** + * Whether tab should load remote content as same url as history + * + * @default false + */ + auto: boolean; + /** + * When set to siblings will only deactivate elements that are DOM siblings with the activated element. + * When set to all the component will deactivate all other elements initialized at the same time. + * + * @default 'siblings' + * @since 2.2 + */ + deactivate: 'siblings' | 'all'; + /** + * Whether to record history events for tab changes + * + * @default false + */ + history: boolean; + /** + * Do not load content remotely on first tab load. Useful when open tab is rendered on server. + * + * @default false + */ + ignoreFirstLoad: boolean; + /** + * Whether inline scripts in tab HTML should be parsed on tab load. + * Defaults to once, parsing only on first load. + * Can also be set to true or false to always parse or never parse inline scripts. + * + * @default 'once' + */ + evaluateScripts: 'once' | boolean; + /** + * Tab should reload content every time it is opened + */ + alwaysRefresh: boolean; + /** + * Can be set to either response, DOM or html. + * Using DOM will cache the a clone of the DOM tree, preserving all events as they existed on render. + * response will cache the original response on load, this way callbacks always receive the same content. + * Using html will cache the resulting html after all callbacks, making sure any changes to content are preserved. + * + * @default 'response' + */ + cacheType: 'response' | 'DOM' | 'html'; + /** + * Tab should cache content after loading locally to avoid server trip on second load + * + * @default true + */ + cache: boolean; + /** + * Settings object for $.api call + * + * @default false + * @see {@link http://semantic-ui.com/behaviors/api.html} + */ + apiSettings: ApiSettings; + /** + * Can be set to hash or state. + * Hash will use an in-page link to create history events. + * State will use DOM History and load pages from server on refresh. + * + * @default 'hash' + * @see {@link https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history} + */ + historyType: 'hash' | 'state'; + /** + * When using historyType state you must specify the base URL for all internal links. + * + * @default false + */ + path: false | string; + /** + * Tabs are limited to those found inside this context + * + * @default false + */ + context: false | string | JQuery; + /** + * If enabled limits tabs to children of passed context + * + * @default false + */ + childrenOnly: boolean; + /** + * Maximum amount of nested tabs allowed (avoids recursion) + * + * @default 25 + */ + maxDepth: number; + /** + * When enabled only calls remote endpoint for tab data on first load and leaves the DOM undisturbed afterwards. + * + * @default false + * @since 2.2.8 + */ + loadOnce: boolean; + + // endregion + + // region Callbacks + + /** + * Callback only the first time a tab is loaded + */ + onFirstLoad(this: JQuery, tabPath: string, parameterArray: any[], historyEvent: any): void; + /** + * Callback every time a tab is loaded + */ + onLoad(this: JQuery, tabPath: string, parameterArray: any[], historyEvent: any): void; + /** + * Called when a tab begins loading remote content + */ + onRequest(this: JQuery, tabPath: string): void; + /** + * Called after a tab becomes visible + */ + onVisible(this: JQuery, tabPath: string): void; + + // endregion + + // region DOM Settings + + /** + * Functions used to return content + */ + templates: Tab.TemplatesSettings; + /** + * Selectors used by module + */ + selector: Tab.SelectorSettings; + /** + * DOM metadata used by module + */ + metadata: Tab.MetadataSettings; + /** + * Class names used to attach style to state + */ + className: Tab.ClassNameSettings; + + // endregion + + // region Debug Settings + + error: Tab.ErrorSettings; + + // endregion + + // region Component Settings + + // region DOM Settings + + /** + * Event namespace. Makes sure module teardown does not effect other events attached to an element. + */ + namespace: string; + + // endregion + + // region Debug Settings + + /** + * Name used in log statements + */ + name: string; + /** + * Silences all console output including error messages, regardless of other debug settings. + */ + silent: boolean; + /** + * Debug output to console + */ + debug: boolean; + /** + * Show console.table output with performance metrics + */ + performance: boolean; + /** + * Debug output includes all internal behaviors + */ + verbose: boolean; + + // endregion + + // endregion + } + } + + namespace Tab { + interface TemplatesSettings extends Pick { } + + namespace TemplatesSettings { + type Param = TemplatesSettings | object; + + interface _Impl { + /** + * returns page title + */ + determineTitle(tabArray: any[]): string; + } + } + + interface SelectorSettings extends Pick { } + + namespace SelectorSettings { + type Param = SelectorSettings | object; + + interface _Impl { + /** + * @default '.ui.tab' + */ + tabs: string; + /** + * @default '.ui:not(.menu)' + */ + parent: string; + } + } + + interface MetadataSettings extends Pick { } + + namespace MetadataSettings { + type Param = MetadataSettings | object; + + interface _Impl { + /** + * @default 'tab' + */ + tab: string; + /** + * @default 'loaded' + */ + loaded: string; + /** + * @default 'promise' + */ + promise: string; + } + } + + interface ClassNameSettings extends Pick { } + + namespace ClassNameSettings { + type Param = ClassNameSettings | object; + + interface _Impl { + /** + * @default 'loading' + */ + loading: string; + /** + * @default 'active' + */ + active: string; + } + } + + interface ErrorSettings extends Pick { } + + namespace ErrorSettings { + type Param = ErrorSettings | object; + + interface _Impl { + /** + * @default 'You attempted to load content without API module' + */ + api: string; + /** + * @default 'The method you called is not defined' + */ + method: string; + /** + * @default 'Activated tab cannot be found for this context.' + */ + missingTab: string; + /** + * @default 'The tab you specified is missing a content url.' + */ + noContent: string; + /** + * @default 'History enabled, but no path was specified' + */ + path: string; + /** + * @default 'Max recursive depth reached' + */ + recursion: string; + /** + * @default 'The state library has not been initialized' + */ + state: string; + } + } + } +} diff --git a/types/semantic-ui-tab/index.d.ts b/types/semantic-ui-tab/index.d.ts new file mode 100644 index 0000000000..4becf66817 --- /dev/null +++ b/types/semantic-ui-tab/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for semantic-ui-tab 2.2 +// Project: http://www.semantic-ui.com +// Definitions by: Leonard Thieu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// +/// + +declare const tab: SemanticUI.Tab; +export = tab; diff --git a/types/semantic-ui-tab/semantic-ui-tab-tests.ts b/types/semantic-ui-tab/semantic-ui-tab-tests.ts new file mode 100644 index 0000000000..a3bbc096c4 --- /dev/null +++ b/types/semantic-ui-tab/semantic-ui-tab-tests.ts @@ -0,0 +1,204 @@ +function test_tab_static() { + $.fn.tab.settings.error.method = 'method'; + $.fn.tab.settings.namespace = 'namespace'; + $.fn.tab.settings.name = 'name'; + $.fn.tab.settings.silent = false; + $.fn.tab.settings.debug = true; + $.fn.tab.settings.performance = true; + $.fn.tab.settings.verbose = true; +} + +function test_tab() { + const selector = '.ui.tab'; + $(selector).tab('change tab', 'path') === $(); + $(selector).tab('set state', 'path') === $(); + $(selector).tab('get path') === 'path'; + $(selector).tab('is tab') === false; + $(selector).tab('cache read', 'path') === false; + $(selector).tab('cache add', 'path', 'html') === $(); + $(selector).tab('cache remove', 'path') === $(); + $(selector).tab('destroy') === $(); + $(selector).tab('setting', 'debug', undefined) === false; + $(selector).tab('setting', 'debug') === false; + $(selector).tab('setting', 'debug', true) === $(); + $(selector).tab('setting', { + namespace: 'namespace', + name: 'name', + silent: false, + debug: true, + performance: true, + verbose: true + }) === $(); + $(selector).tab({ + auto: false, + deactivate: 'siblings', + history: true, + ignoreFirstLoad: false, + evaluateScripts: 'once', + alwaysRefresh: true, + cacheType: 'DOM', + cache: false, + apiSettings: { + on: 'on', + cache: true, + stateContext: $(), + encodeParameters: false, + defaultData: true, + serializeForm: false, + throttle: 10, + throttleFirstRequest: true, + interruptRequests: false, + loadingDuration: 3, + hideError: true, + errorDuration: 10, + action: 'action', + url: 'url', + urlData: false, + response: false, + responseAsync(settings, callback) { + settings === ({} as SemanticUI.ApiSettings); + callback === ((response: any) => { }); + }, + mockResponse: false, + mockResponseAsync(settings, callback) { + settings === ({} as SemanticUI.ApiSettings); + callback === ((response: any) => { }); + }, + method: 'post', + dataType: 'xml', + data: {}, + beforeSend(settings) { + settings === ({} as SemanticUI.ApiSettings); + }, + beforeXHR(xhrObject) { + xhrObject === ({} as JQueryXHR); + }, + onRequest(promise, xhr) { + promise === ({} as JQueryDeferred); + xhr === ({} as JQueryXHR); + }, + onResponse(response) { + response === ({} as any); + }, + successTest(response) { + return response === ({} as any); + }, + onSuccess(response, element, xhr) { + response === ({} as any); + element === $(); + xhr === ({} as JQueryXHR); + }, + onComplete(response, element, xhr) { + response === ({} as any); + element === $(); + xhr === ({} as JQueryXHR); + }, + onFailure(response, element) { + response === ({} as any); + element === $(); + }, + onError(errorMessage, element, xhr) { + errorMessage === ''; + element === $(); + xhr === ({} as JQueryXHR); + }, + onAbort(errorMessage, element, xhr) { + errorMessage === ''; + element === $(); + xhr === ({} as JQueryXHR); + }, + regExp: { + required: /{\$*[A-z0-9]+}/g, + optional: /{\/\$*[A-z0-9]+}/g + }, + selector: { + disabled: '.disabled', + form: 'form' + }, + className: { + loading: 'loading', + error: 'error' + }, + metadata: { + action: 'action', + url: 'url' + }, + error: { + beforeSend: 'beforeSend', + error: 'error', + exitConditions: 'exitConditions', + JSONParse: 'JSONParse', + legacyParameters: 'legacyParameters', + missingAction: 'missingAction', + missingSerialize: 'missingSerialize', + missingURL: 'missingURL', + noReturnedValue: 'noReturnedValue', + parseError: 'parseError', + requiredParameter: 'requiredParameter', + statusMessage: 'statusMessage', + timeout: 'timeout' + } + }, + historyType: 'state', + path: 'path', + context: $(), + childrenOnly: true, + maxDepth: 10, + loadOnce: false, + onFirstLoad(tabPath, parameterArray, historyEvent) { + this === $(); + tabPath === 'tabPath'; + parameterArray === []; + historyEvent === {}; + }, + onLoad(tabPath, parameterArray, historyEvent) { + this === $(); + tabPath === 'tabPath'; + parameterArray === []; + historyEvent === {}; + }, + onRequest(tabPath) { + this === $(); + tabPath === 'tabPath'; + }, + onVisible(tabPath) { + this === $(); + tabPath === 'tabPath'; + }, + templates: { + determineTitle(tabArray) { + tabArray === []; + return 'title'; + } + }, + selector: { + tabs: 'tabs', + parent: 'parent' + }, + metadata: { + tab: 'tab', + loaded: 'loaded', + promise: 'promise' + }, + className: { + loading: 'loading', + active: 'active' + }, + error: { + api: 'api', + method: 'method', + missingTab: 'missingTab', + noContent: 'noContent', + path: 'path', + recursion: 'recursion', + state: 'state' + } + }) === $(); + $(selector).tab() === $(); +} + +import tab = require('semantic-ui-tab'); + +function test_module() { + $.fn.tab = tab; +} diff --git a/types/semantic-ui-tab/tsconfig.json b/types/semantic-ui-tab/tsconfig.json new file mode 100644 index 0000000000..2896defde1 --- /dev/null +++ b/types/semantic-ui-tab/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "global.d.ts", + "semantic-ui-tab-tests.ts" + ] +} diff --git a/types/semantic-ui-tab/tslint.json b/types/semantic-ui-tab/tslint.json new file mode 100644 index 0000000000..758e484744 --- /dev/null +++ b/types/semantic-ui-tab/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false, + "unified-signatures": false + } +} From 2529651e84146d29881a837813aaf41013346a21 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 6 Jun 2017 20:24:16 -0400 Subject: [PATCH 35/98] [semantic-ui-sticky] Add type definitions. (#16991) --- types/semantic-ui-sticky/global.d.ts | 219 ++++++++++++++++++ types/semantic-ui-sticky/index.d.ts | 11 + .../semantic-ui-sticky-tests.ts | 74 ++++++ types/semantic-ui-sticky/tsconfig.json | 24 ++ types/semantic-ui-sticky/tslint.json | 7 + 5 files changed, 335 insertions(+) create mode 100644 types/semantic-ui-sticky/global.d.ts create mode 100644 types/semantic-ui-sticky/index.d.ts create mode 100644 types/semantic-ui-sticky/semantic-ui-sticky-tests.ts create mode 100644 types/semantic-ui-sticky/tsconfig.json create mode 100644 types/semantic-ui-sticky/tslint.json diff --git a/types/semantic-ui-sticky/global.d.ts b/types/semantic-ui-sticky/global.d.ts new file mode 100644 index 0000000000..683d1aafc7 --- /dev/null +++ b/types/semantic-ui-sticky/global.d.ts @@ -0,0 +1,219 @@ +interface JQuery { + sticky: SemanticUI.Sticky; +} + +declare namespace SemanticUI { + interface Sticky { + settings: StickySettings; + + /** + * recalculates offsets + */ + (behavior: 'refresh'): JQuery; + (behavior: 'destroy'): JQuery; + (behavior: 'setting', name: K, value?: undefined): StickySettings[K]; + (behavior: 'setting', name: K, value: StickySettings[K]): JQuery; + (behavior: 'setting', value: StickySettings.Param): JQuery; + (settings?: StickySettings.Param): JQuery; + } + + /** + * @see {@link http://semantic-ui.com/modules/sticky.html#/settings} + */ + interface StickySettings extends Pick { } + + namespace StickySettings { + type Param = StickySettings | object; + + interface _Impl { + // region Sticky Settings + + /** + * Whether element should be "pushed" by the viewport, attaching to the bottom of the screen when scrolling up + * + * @default false + */ + pushing: boolean; + /** + * Sticky container height will only be set if the difference between heights of container and context is larger than this jitter value. + * + * @default 5 + */ + jitter: number; + /** + * Whether any change in context DOM should automatically refresh cached sticky positions + * + * @default false + */ + observeChanges: boolean; + /** + * Context which sticky element should stick to + * + * @default false + */ + context: false | string | JQuery; + /** + * Context which sticky should attach onscroll events. + * + * @default 'window' + */ + scrollContext: string | JQuery; + /** + * Offset in pixels from the top of the screen when fixing element to viewport + * + * @default 0 + */ + offset: number; + /** + * Offset in pixels from the bottom of the screen when fixing element to viewport + * + * @default 0 + */ + bottomOffset: number; + + // endregion + + // region Callbacks + + /** + * Callback when element is repositioned from layout change + */ + onReposition(this: JQuery): void; + /** + * Callback when requestAnimationFrame fires from scroll handler. + */ + onScroll(this: JQuery): void; + /** + * Callback when element is fixed to page + */ + onStick(this: JQuery): void; + /** + * Callback when element is unfixed from page + */ + onUnstick(this: JQuery): void; + /** + * Callback when element is bound to top of parent container + */ + onTop(this: JQuery): void; + /** + * Callback when element is bound to bottom of parent container + */ + onBottom(this: JQuery): void; + + // endregion + + // region DOM Settings + + /** + * Class names used to attach style to state + */ + className: Sticky.ClassNameSettings; + + // endregion + + // region Debug Settings + + error: Sticky.ErrorSettings; + + // endregion + + // region Component Settings + + // region DOM Settings + + /** + * Event namespace. Makes sure module teardown does not effect other events attached to an element. + */ + namespace: string; + + // endregion + + // region Debug Settings + + /** + * Name used in log statements + */ + name: string; + /** + * Silences all console output including error messages, regardless of other debug settings. + */ + silent: boolean; + /** + * Debug output to console + */ + debug: boolean; + /** + * Show console.table output with performance metrics + */ + performance: boolean; + /** + * Debug output includes all internal behaviors + */ + verbose: boolean; + + // endregion + + // endregion + } + } + + namespace Sticky { + interface ClassNameSettings extends Pick { } + + namespace ClassNameSettings { + type Param = ClassNameSettings | object; + + interface _Impl { + /** + * @default 'bound' + */ + bound: string; + /** + * @default 'fixed' + */ + fixed: string; + /** + * @default 'native' + */ + supported: string; + /** + * @default 'top' + */ + top: string; + /** + * @default 'bottom' + */ + bottom: string; + } + } + + interface ErrorSettings extends Pick { } + + namespace ErrorSettings { + type Param = ErrorSettings | object; + + interface _Impl { + /** + * @default 'Sticky element must be inside a relative container' + */ + container: string; + /** + * @default 'Element is hidden, you must call refresh after element becomes visible' + */ + visible: string; + /** + * @default 'The method you called is not defined.' + */ + method: string; + /** + * @default 'Context specified does not exist' + */ + invalidContext: string; + /** + * @default 'Sticky element is larger than its container, cannot create sticky.' + */ + elementSize: string; + } + } + } +} diff --git a/types/semantic-ui-sticky/index.d.ts b/types/semantic-ui-sticky/index.d.ts new file mode 100644 index 0000000000..9bc36ca270 --- /dev/null +++ b/types/semantic-ui-sticky/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for semantic-ui-sticky 2.2 +// Project: http://www.semantic-ui.com +// Definitions by: Leonard Thieu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// + +declare const sticky: SemanticUI.Sticky; +export = sticky; diff --git a/types/semantic-ui-sticky/semantic-ui-sticky-tests.ts b/types/semantic-ui-sticky/semantic-ui-sticky-tests.ts new file mode 100644 index 0000000000..0a3585f08d --- /dev/null +++ b/types/semantic-ui-sticky/semantic-ui-sticky-tests.ts @@ -0,0 +1,74 @@ +function test_sticky_static() { + $.fn.sticky.settings.error.method = 'method'; + $.fn.sticky.settings.namespace = 'namespace'; + $.fn.sticky.settings.name = 'name'; + $.fn.sticky.settings.silent = false; + $.fn.sticky.settings.debug = true; + $.fn.sticky.settings.performance = true; + $.fn.sticky.settings.verbose = true; +} + +function test_sticky() { + const selector = '.ui.sticky'; + $(selector).sticky('refresh') === $(); + $(selector).sticky('destroy') === $(); + $(selector).sticky('setting', 'debug', undefined) === false; + $(selector).sticky('setting', 'debug') === false; + $(selector).sticky('setting', 'debug', true) === $(); + $(selector).sticky('setting', { + namespace: 'namespace', + name: 'name', + silent: false, + debug: true, + performance: true, + verbose: true + }) === $(); + $(selector).sticky({ + pushing: false, + jitter: 4, + observeChanges: true, + context: $(), + scrollContext: $(), + offset: 1, + bottomOffset: 200, + onReposition() { + this === $(); + }, + onScroll() { + this === $(); + }, + onStick() { + this === $(); + }, + onUnstick() { + this === $(); + }, + onTop() { + this === $(); + }, + onBottom() { + this === $(); + }, + className: { + bound: 'bound', + fixed: 'fixed', + supported: 'supported', + top: 'top', + bottom: 'bottom' + }, + error: { + container: 'container', + visible: 'visible', + method: 'method', + invalidContext: 'invalidContext', + elementSize: 'elementSize' + } + }) === $(); + $(selector).sticky() === $(); +} + +import sticky = require('semantic-ui-sticky'); + +function test_module() { + $.fn.sticky = sticky; +} diff --git a/types/semantic-ui-sticky/tsconfig.json b/types/semantic-ui-sticky/tsconfig.json new file mode 100644 index 0000000000..8a60c43a02 --- /dev/null +++ b/types/semantic-ui-sticky/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "global.d.ts", + "semantic-ui-sticky-tests.ts" + ] +} diff --git a/types/semantic-ui-sticky/tslint.json b/types/semantic-ui-sticky/tslint.json new file mode 100644 index 0000000000..758e484744 --- /dev/null +++ b/types/semantic-ui-sticky/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false, + "unified-signatures": false + } +} From 4ab8603649b8ace29d5970603608288a4d3b2d84 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 6 Jun 2017 20:24:34 -0400 Subject: [PATCH 36/98] [semantic-ui-form] Add type definitions. (#16993) --- types/semantic-ui-form/global.d.ts | 465 ++++++++++++++++++ types/semantic-ui-form/index.d.ts | 11 + .../semantic-ui-form-tests.ts | 156 ++++++ types/semantic-ui-form/tsconfig.json | 24 + types/semantic-ui-form/tslint.json | 7 + 5 files changed, 663 insertions(+) create mode 100644 types/semantic-ui-form/global.d.ts create mode 100644 types/semantic-ui-form/index.d.ts create mode 100644 types/semantic-ui-form/semantic-ui-form-tests.ts create mode 100644 types/semantic-ui-form/tsconfig.json create mode 100644 types/semantic-ui-form/tslint.json diff --git a/types/semantic-ui-form/global.d.ts b/types/semantic-ui-form/global.d.ts new file mode 100644 index 0000000000..13fefb8147 --- /dev/null +++ b/types/semantic-ui-form/global.d.ts @@ -0,0 +1,465 @@ +interface JQuery { + form: SemanticUI.Form; +} + +declare namespace SemanticUI { + interface Form { + settings: FormSettings; + + /** + * Submits selected form + */ + (behavior: 'submit'): JQuery; + /** + * Returns true/false whether a form passes its validation rules + */ + (behavior: 'is valid'): boolean; + /** + * Validates form and calls onSuccess or onFailure + */ + (behavior: 'validate form'): JQuery; + /** + * gets browser property change event + */ + (behavior: 'get change event'): string; + /** + * Returns element with matching name, id, or data-validate metadata to ID + */ + (behavior: 'get field', id: string): JQuery; + /** + * Returns value of element with id + */ + (behavior: 'get value', id: string): any; + /** + * Returns object of element values that match array of ids. If no IDS are passed will return all fields + */ + (behavior: 'get values', ids?: string[]): any; + /** + * Sets value of element with id + */ + (behavior: 'set value', id: string): JQuery; + /** + * Sets key/value pairs from passed values object to matching ids + */ + (behavior: 'set values', values: any): JQuery; + /** + * Returns validation rules for a given jQuery-referenced input field + */ + (behavior: 'get validation', element: JQuery): any; + /** + * Returns whether a field exists + */ + (behavior: 'has field', identifier: string): boolean; + /** + * Adds errors to form, given an array errors + */ + (behavior: 'add errors', errors: string[]): JQuery; + (behavior: 'destroy'): JQuery; + (behavior: 'setting', name: K, value?: undefined): FormSettings[K]; + (behavior: 'setting', name: K, value: FormSettings[K]): JQuery; + (behavior: 'setting', value: FormSettings.Param): JQuery; + (settings?: FormSettings.Param): JQuery; + } + + /** + * @see {@link http://semantic-ui.com/behaviors/form.html#/settings} + */ + interface FormSettings extends Pick { } + + namespace FormSettings { + type Param = FormSettings | object; + + interface _Impl { + // region Form Settings + + /** + * Adds keyboard shortcuts for enter and escape keys to submit form and blur fields respectively + * + * @default true + */ + keyboardShortcuts: boolean; + /** + * Event used to trigger validation. Can be either submit, blur or change. + * + * @default 'submit' + */ + on: 'submit' | 'blur' | 'change'; + /** + * If set to true will revalidate fields with errors on input change + * + * @default true + */ + revalidate: boolean; + /** + * Delay from last typed letter to validate a field when using on: change or when revalidating a field. + * + * @default true + */ + delay: boolean; + /** + * Adds inline error on field validation error + * + * @default false + */ + inline: boolean; + /** + * Named transition to use when animating validation errors. Fade and slide down are available without including ui transitions + * + * @default 'scale' + * @see {@link http://semantic-ui.com/modules/transition.html} + */ + transition: string; + /** + * Animation speed for inline prompt + * + * @default 150 + */ + duration: number; + fields: { + [name: string]: string | string[] | Form.Field; + }; + + // endregion + + // region Form Prompts + + text: Form.TextSettings; + prompt: Form.PromptSettings; + + // endregion + + // region Callbacks + + /** + * Callback on each valid field + */ + onValid(this: JQuery): void; + /** + * Callback on each invalid field + */ + onInvalid(this: JQuery): void; + /** + * Callback if a form is all valid + */ + onSuccess(this: JQuery, event: JQueryEventObject, fields: any): void; + /** + * Callback if any form field is invalid + */ + onFailure(this: JQuery, formErrors: string[], fields: any): void; + + // endregion + + // region Templates + + templates: Form.TemplatesSettings; + + // endregion + + // region Rules + + rules: { + [name: string]: (this: HTMLElement, ...args: any[]) => boolean; + }; + + // endregion + + // region DOM Settings + + /** + * Selectors used to match functionality to DOM + */ + selector: Form.SelectorSettings; + /** + * HTML5 metadata attributes + */ + metadata: Form.MetadataSettings; + /** + * Class names used to attach style to state + */ + className: Form.ClassNameSettings; + + // endregion + + // region Debug Settings + + error: Form.ErrorSettings; + + // endregion + + // region Component Settings + + // region DOM Settings + + /** + * Event namespace. Makes sure module teardown does not effect other events attached to an element. + */ + namespace: string; + + // endregion + + // region Debug Settings + + /** + * Name used in log statements + */ + name: string; + /** + * Silences all console output including error messages, regardless of other debug settings. + */ + silent: boolean; + /** + * Debug output to console + */ + debug: boolean; + /** + * Show console.table output with performance metrics + */ + performance: boolean; + /** + * Debug output includes all internal behaviors + */ + verbose: boolean; + + // endregion + + // endregion + } + } + + namespace Form { + interface Field { + identifier: string; + rules: Rule[]; + } + + interface Rule { + type: string; + prompt: string; + } + + interface TextSettings extends Pick { } + + namespace TextSettings { + type Param = TextSettings | object; + + interface _Impl { + /** + * @default 'Please enter a valid value' + */ + unspecifiedRule: string; + /** + * @default 'This field' + */ + unspecifiedField: string; + } + } + + interface PromptSettings extends Pick { } + + namespace PromptSettings { + type Param = PromptSettings | object; + + interface _Impl { + /** + * @default '{name} must have a value' + */ + empty: string; + /** + * @default '{name} must be checked' + */ + checked: string; + /** + * @default '{name} must be a valid e-mail' + */ + email: string; + /** + * @default '{name} must be a valid url' + */ + url: string; + /** + * @default '{name} is not formatted correctly' + */ + regExp: string; + /** + * @default '{name} must be an integer' + */ + integer: string; + /** + * @default '{name} must be a decimal number' + */ + decimal: string; + /** + * @default '{name} must be set to a number' + */ + number: string; + /** + * @default '{name} must be \'{ruleValue}\'' + */ + is: string; + /** + * @default '{name} must be exactly \'{ruleValue}\'' + */ + isExactly: string; + /** + * @default '{name} cannot be set to \'{ruleValue}\'' + */ + not: string; + /** + * @default '{name} cannot be set to exactly \'{ruleValue}\'' + */ + notExactly: string; + /** + * @default '{name} cannot contain \'{ruleValue}\'' + */ + contain: string; + /** + * @default '{name} cannot contain exactly \'{ruleValue}\'' + */ + containExactly: string; + /** + * @default '{name} must contain \'{ruleValue}\'' + */ + doesntContain: string; + /** + * @default '{name} must contain exactly \'{ruleValue}\'' + */ + doesntContainExactly: string; + /** + * @default '{name} must be at least {ruleValue} characters' + */ + minLength: string; + /** + * @default '{name} must be at least {ruleValue} characters' + */ + length: string; + /** + * @default '{name} must be exactly {ruleValue} characters' + */ + exactLength: string; + /** + * @default '{name} cannot be longer than {ruleValue} characters' + */ + maxLength: string; + /** + * @default '{name} must match {ruleValue} field' + */ + match: string; + /** + * @default '{name} must have a different value than {ruleValue} field' + */ + different: string; + /** + * @default '{name} must be a valid credit card number' + */ + creditCard: string; + /** + * @default '{name} must have at least {ruleValue} choices' + */ + minCount: string; + /** + * @default '{name} must have exactly {ruleValue} choices' + */ + exactCount: string; + /** + * @default '{name} must have {ruleValue} or less choices' + */ + maxCount: string; + } + } + + interface TemplatesSettings extends Pick { } + + namespace TemplatesSettings { + type Param = TemplatesSettings | object; + + interface _Impl { + error(errors: string[]): JQuery; + prompt(errors: string[]): JQuery; + } + } + + interface SelectorSettings extends Pick { } + + namespace SelectorSettings { + type Param = SelectorSettings | object; + + interface _Impl { + /** + * @default '.error.message' + */ + message: string; + /** + * @default 'input, textarea, select' + */ + field: string; + /** + * @default '.field' + */ + group: string; + /** + * @default 'input' + */ + input: string; + /** + * @default '.prompt' + */ + prompt: string; + /** + * @default '.submit' + */ + submit: string; + } + } + + interface MetadataSettings extends Pick { } + + namespace MetadataSettings { + type Param = MetadataSettings | object; + + interface _Impl { + /** + * @default 'validate' + */ + validate: string; + } + } + + interface ClassNameSettings extends Pick { } + + namespace ClassNameSettings { + type Param = ClassNameSettings | object; + + interface _Impl { + /** + * @default 'active' + */ + active: string; + /** + * @default 'default' + */ + placeholder: string; + /** + * @default 'disabled' + */ + disabled: string; + /** + * @default 'visible' + */ + visible: string; + } + } + + interface ErrorSettings extends Pick { } + + namespace ErrorSettings { + type Param = ErrorSettings | object; + + interface _Impl { + /** + * @default 'The method you called is not defined.' + */ + method: string; + } + } + } +} diff --git a/types/semantic-ui-form/index.d.ts b/types/semantic-ui-form/index.d.ts new file mode 100644 index 0000000000..bf2dd88bdd --- /dev/null +++ b/types/semantic-ui-form/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for semantic-ui-form 2.2 +// Project: http://www.semantic-ui.com +// Definitions by: Leonard Thieu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// + +declare const form: SemanticUI.Form; +export = form; diff --git a/types/semantic-ui-form/semantic-ui-form-tests.ts b/types/semantic-ui-form/semantic-ui-form-tests.ts new file mode 100644 index 0000000000..58e8a18f70 --- /dev/null +++ b/types/semantic-ui-form/semantic-ui-form-tests.ts @@ -0,0 +1,156 @@ +function test_form_static() { + $.fn.form.settings.error.method = 'method'; + $.fn.form.settings.namespace = 'namespace'; + $.fn.form.settings.name = 'name'; + $.fn.form.settings.silent = false; + $.fn.form.settings.debug = true; + $.fn.form.settings.performance = true; + $.fn.form.settings.verbose = true; +} + +function test_form() { + const selector = '.ui.form'; + $(selector).form('submit') === $(); + $(selector).form('is valid') === false; + $(selector).form('validate form') === $(); + $(selector).form('get change event') === 'change event'; + $(selector).form('get field', 'id') === $(); + $(selector).form('get value', 'id') === {}; + $(selector).form('get values', ['id1', 'id2']) === {}; + $(selector).form('set value', 'id') === $(); + $(selector).form('set values', ['id1', 'id2']) === $(); + $(selector).form('get validation', $()) === {}; + $(selector).form('has field', 'identifier') === true; + $(selector).form('add errors', ['error1', 'error2']) === $(); + $(selector).form('destroy') === $(); + $(selector).form('setting', 'debug', undefined) === false; + $(selector).form('setting', 'debug') === false; + $(selector).form('setting', 'debug', true) === $(); + $(selector).form('setting', { + namespace: 'namespace', + name: 'name', + silent: false, + debug: true, + performance: true, + verbose: true + }) === $(); + $(selector).form({ + keyboardShortcuts: false, + on: 'submit', + revalidate: true, + delay: 20, + inline: false, + transition: 'fade', + duration: 22, + fields: { + field1: 'field1', + field2: ['field1', 'field2'], + field3: { + identifier: 'identifier', + rules: [ + { + type: 'type', + prompt: 'prompt' + }, + { + type: 'type', + prompt: 'prompt' + } + ] + } + }, + text: { + unspecifiedRule: 'unspecifiedRule', + unspecifiedField: 'unspecifiedField' + }, + prompt: { + empty: 'empty', + checked: 'checked', + email: 'email', + url: 'url', + regExp: 'regExp', + integer: 'integer', + decimal: 'decimal', + number: 'number', + is: 'is', + isExactly: 'isExactly', + not: 'not', + notExactly: 'notExactly', + contain: 'contain', + containExactly: 'containExactly', + doesntContain: 'doesntContain', + doesntContainExactly: 'doesntContainExactly', + minLength: 'minLength', + length: 'length', + exactLength: 'exactLength', + maxLength: 'maxLength', + match: 'match', + different: 'different', + creditCard: 'creditCard', + minCount: 'minCount', + exactCount: 'exactCount', + maxCount: 'maxCount' + }, + onValid() { + this === $(); + }, + onInvalid() { + this === $(); + }, + onSuccess(event, fields) { + this === $(); + event.stopPropagation(); + fields === {}; + }, + onFailure(formErrors, fields) { + this === $(); + formErrors === []; + fields === {}; + }, + templates: { + error(errors) { + errors === []; + return $(); + }, + prompt(errors) { + errors === []; + return $(); + } + }, + rules: { + empty(value) { + return !(value === undefined || '' === value || $.isArray(value) && value.length === 0); + }, + checked() { + return ($(this).filter(':checked').length > 0); + } + }, + selector: { + message: 'message', + field: 'field', + group: 'group', + input: 'input', + prompt: 'prompt', + submit: 'submit' + }, + metadata: { + validate: 'validate' + }, + className: { + active: 'active', + placeholder: 'placeholder', + disabled: 'disabled', + visible: 'visible' + }, + error: { + method: 'method' + } + }) === $(); + $(selector).form() === $(); +} + +import form = require('semantic-ui-form'); + +function test_module() { + $.fn.form = form; +} diff --git a/types/semantic-ui-form/tsconfig.json b/types/semantic-ui-form/tsconfig.json new file mode 100644 index 0000000000..172834b107 --- /dev/null +++ b/types/semantic-ui-form/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "global.d.ts", + "semantic-ui-form-tests.ts" + ] +} diff --git a/types/semantic-ui-form/tslint.json b/types/semantic-ui-form/tslint.json new file mode 100644 index 0000000000..758e484744 --- /dev/null +++ b/types/semantic-ui-form/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false, + "unified-signatures": false + } +} From 7d5307d0ec3d2340ac75b7a066a86ffc31986dce Mon Sep 17 00:00:00 2001 From: flushentitypacket Date: Tue, 6 Jun 2017 21:31:41 -0400 Subject: [PATCH 37/98] Export as `export = moxios` to match the moxios package export. (#16913) --- types/moxios/index.d.ts | 2 +- types/moxios/moxios-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/moxios/index.d.ts b/types/moxios/index.d.ts index d3d6dd5b51..94756158c9 100644 --- a/types/moxios/index.d.ts +++ b/types/moxios/index.d.ts @@ -189,4 +189,4 @@ declare let moxios: { wait(fn: () => void, delay?: number): void; }; -export default moxios; +export = moxios; diff --git a/types/moxios/moxios-tests.ts b/types/moxios/moxios-tests.ts index 82ceb8535b..0e6820d287 100644 --- a/types/moxios/moxios-tests.ts +++ b/types/moxios/moxios-tests.ts @@ -1,7 +1,7 @@ // from https://github.com/mzabriskie/moxios/blob/master/test.js import {equal, notEqual, deepEqual} from 'power-assert'; // compatible with 'assert'; import axios from 'axios'; -import moxios from 'moxios'; +import * as moxios from 'moxios'; declare const sinon: any; declare const describe: any; From ac1db88fa889b1780d33c3f1ba2a46d6f021546c Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 6 Jun 2017 21:36:00 -0400 Subject: [PATCH 38/98] [semantic-ui] Update type definitions. Depend on modules. --- types/semantic-ui/index.d.ts | 5601 +----------------------- types/semantic-ui/semantic-ui-tests.ts | 492 +-- types/semantic-ui/tslint.json | 2 +- 3 files changed, 69 insertions(+), 6026 deletions(-) diff --git a/types/semantic-ui/index.d.ts b/types/semantic-ui/index.d.ts index b069899b69..e36ff8c748 100644 --- a/types/semantic-ui/index.d.ts +++ b/types/semantic-ui/index.d.ts @@ -2,5584 +2,29 @@ // Project: http://semantic-ui.com/ // Definitions by: Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 /// -interface JQueryStatic { - site: SemanticUI.Site; - - api: SemanticUI.Api; -} - -interface JQuery { - site: SemanticUI.Site; - - accordion: SemanticUI.Accordion; - checkbox: SemanticUI.Checkbox; - dimmer: SemanticUI.Dimmer; - dropdown: SemanticUI.Dropdown; - embed: SemanticUI.Embed; - modal: SemanticUI.Modal; - nag: SemanticUI.Nag; - popup: SemanticUI.Popup; - progress: SemanticUI.Progress; - rating: SemanticUI.Rating; - search: SemanticUI.Search; - shape: SemanticUI.Shape; - sidebar: SemanticUI.Sidebar; - sticky: SemanticUI.Sticky; - tab: SemanticUI.Tab; - transition: SemanticUI.Transition; - - api: SemanticUI.Api; - form: SemanticUI.Form; - visibility: SemanticUI.Visibility; -} - -declare namespace SemanticUI { - type Selector = string | JQuery; - - /** - * These settings are native to all modules, and define how the component ties content to DOM attributes, and debugging settings for the module. - */ - interface ComponentSettings { - // region DOM Settings - - /** - * Event namespace. Makes sure module teardown does not effect other events attached to an element. - */ - namespace?: string; - - // endregion - - // region Debug Settings - - /** - * Name used in log statements - */ - name?: string; - /** - * Silences all console output including error messages, regardless of other debug settings. - */ - silent?: boolean; - /** - * Debug output to console - */ - debug?: boolean; - /** - * Show console.table output with performance metrics - */ - performance?: boolean; - /** - * Debug output includes all internal behaviors - */ - verbose?: boolean; - - // endregion - } - - // region Globals - - // region Site - - interface Site { - settings: SiteSettings; - - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): SiteSettings[K]; - (behavior: 'setting', name: K, value: SiteSettings[K]): JQuery; - (behavior: 'setting', value: SiteSettings): JQuery; - (settings?: SiteSettings): JQuery; - } - - interface SiteSettings extends ComponentSettings { - modules?: string[]; - siteNamespace?: string; - namespaceStub?: { - cache?: any; - config?: any; - sections?: any; - section?: any; - utilities?: any; - }; - } - - // endregion - - // endregion - - // region Modules - - // region Accordion - - interface Accordion { - settings: AccordionSettings; - - /** - * Refreshes all cached selectors and data - */ - (behavior: 'refresh'): JQuery; - /** - * Opens accordion content at index - */ - (behavior: 'open', index: number): JQuery; - /** - * Closes accordion content that are not active - */ - (behavior: 'close others'): JQuery; - /** - * Closes accordion content at index - */ - (behavior: 'close', index: number): JQuery; - /** - * Toggles accordion content at index - */ - (behavior: 'toggle', index: number): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): AccordionSettings[K]; - (behavior: 'setting', name: K, value: AccordionSettings[K]): JQuery; - (behavior: 'setting', value: AccordionSettings): JQuery; - (settings?: AccordionSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/accordion.html#/settings} - */ - interface AccordionSettings extends ComponentSettings { - // region Behavior - - /** - * Only allow one section open at a time - * - * @default true - */ - exclusive?: boolean; - /** - * Event on title that will cause accordion to open - * - * @default 'click' - */ - on?: string; - /** - * Whether child content opacity should be animated (may cause performance issues with many child elements) - * - * @default true - */ - animateChildren?: boolean; - /** - * Close open nested accordion content when an element closes - * - * @default true - */ - closeNested?: boolean; - /** - * Allow active sections to collapse - * - * @default true - */ - collapsible?: boolean; - /** - * Duration in ms of opening animation - * - * @default 500 - */ - duration?: number; - /** - * Easing of opening animation. EaseInOutQuint is included with accordion, for additional options you must include easing equations. - * - * @default 'easeInOutQuint' - * @see {@link http://gsgd.co.uk/sandbox/jquery/easing/} - */ - easing?: string; - /** - * whether accordion should automatically refresh on DOM insertion - * - * @default true - */ - observeChanges?: boolean; - - // endregion - - // region Callbacks - - /** - * Callback before element opens - */ - onOpening?(this: JQuery): void; - /** - * Callback after element is open - */ - onOpen?(this: JQuery): void; - /** - * Callback before element closes - */ - onClosing?(this: JQuery): void; - /** - * Callback after element is closed - */ - onClose?(this: JQuery): void; - /** - * Callback on element open or close - */ - onChange?(this: JQuery): void; - - // endregion - - // region DOM Settings - - /** - * Selectors used to find parts of a module - */ - selector?: { - /** - * @default '.accordion' - */ - accordion?: string; - /** - * @default '.title' - */ - title?: string; - /** - * @default '.title' - */ - trigger?: string; - /** - * @default '.content' - */ - content?: string; - }; - /** - * Class names used to determine element state - */ - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'animating' - */ - animating?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The method you called is not defined.' - */ - method?: string; - }; - - // endregion - } - - // endregion - - // region Checkbox - - interface Checkbox { - settings: CheckboxSettings; - - /** - * Switches a checkbox from current state - */ - (behavior: 'toggle'): JQuery; - /** - * Set a checkbox state to checked - */ - (behavior: 'check'): JQuery; - /** - * Set a checkbox state to unchecked - */ - (behavior: 'uncheck'): JQuery; - /** - * Set as indeterminate checkbox - */ - (behavior: 'indeterminate'): JQuery; - /** - * Set as determinate checkbox - */ - (behavior: 'determinate'): JQuery; - /** - * Enable interaction with a checkbox - */ - (behavior: 'enable'): JQuery; - /** - * Set a checkbox state to checked without callbacks - */ - (behavior: 'set checked'): JQuery; - /** - * Set a checkbox state to unchecked without callbacks - */ - (behavior: 'set unchecked'): JQuery; - /** - * Set as indeterminate checkbox without callbacks - */ - (behavior: 'set indeterminate'): JQuery; - /** - * Set as determinate checkbox without callbacks - */ - (behavior: 'set determinate'): JQuery; - /** - * Enable interaction with a checkbox without callbacks - */ - (behavior: 'set enabled'): JQuery; - /** - * Disable interaction with a checkbox without callbacks - */ - (behavior: 'set disabled'): JQuery; - /** - * Attach checkbox events to another element - */ - (behavior: 'attach events', selector: Selector, event?: string): JQuery; - /** - * Returns whether element is radio selection - */ - (behavior: 'is radio'): boolean; - /** - * Returns whether element is currently checked - */ - (behavior: 'is checked'): boolean; - /** - * Returns whether element is not checked - */ - (behavior: 'is unchecked'): boolean; - /** - * Returns whether element is able to be changed - */ - (behavior: 'can change'): boolean; - /** - * Returns whether element can be checked (checking if already checked or `beforeChecked` would cancel) - */ - (behavior: 'should allow check'): boolean; - /** - * Returns whether element can be unchecked (checking if already unchecked or `beforeUnchecked` would cancel) - */ - (behavior: 'should allow uncheck'): boolean; - /** - * Returns whether element can be determinate (checking if already determinate or `beforeDeterminate` would cancel) - */ - (behavior: 'should allow determinate'): boolean; - /** - * Returns whether element can be indeterminate (checking if already indeterminate or `beforeIndeterminate` would cancel) - */ - (behavior: 'should allow indeterminate'): boolean; - /** - * Returns whether element is able to be unchecked - */ - (behavior: 'can uncheck'): boolean; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): CheckboxSettings[K]; - (behavior: 'setting', name: K, value: CheckboxSettings[K]): JQuery; - (behavior: 'setting', value: CheckboxSettings): JQuery; - (settings?: CheckboxSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/checkbox.html#/settings} - */ - interface CheckboxSettings extends ComponentSettings { - // region Behavior - - /** - * Setting to true/false will determine whether an input will allow no selection. Auto will set disallow this behavior only for radio boxes - * - * @default 'auto' - */ - uncheckable?: 'auto' | boolean; - /** - * Whether callbacks for checked status should be fired on init as well as change - * - * @default false - */ - fireOnInit?: boolean; - - // endregion - - // region Callbacks - - /** - * Callback after a checkbox is either checked or unchecked. - */ - onChange?(this: HTMLElement): void; - /** - * Callback after a checkbox is checked. - */ - onChecked?(this: HTMLElement): void; - /** - * Callback after a checkbox is set to undeterminate. - */ - onIndeterminate?(this: HTMLElement): void; - /** - * Callback after a checkbox is set to determinate. - */ - onDeterminate?(this: HTMLElement): void; - /** - * Callback after a checkbox is unchecked. - */ - onUnchecked?(this: HTMLElement): void; - /** - * Callback before a checkbox is checked. Can cancel change by returning false - */ - beforeChecked?(this: HTMLElement): boolean; - /** - * Callback before a checkbox is set to undeterminate. Can cancel change by returning false - */ - beforeIndeterminate?(this: HTMLElement): boolean; - /** - * Callback before a checkbox is set to determinate. Can cancel change by returning false - */ - beforeDeterminate?(this: HTMLElement): boolean; - /** - * Callback before a checkbox is unchecked. Can cancel change by returning false - */ - beforeUnchecked?(this: HTMLElement): boolean; - /** - * Callback after a checkbox is enabled. - */ - onEnable?(this: HTMLElement): void; - /** - * Callback after a checkbox is disabled. - */ - onDisable?(this: HTMLElement): void; - /** - * Callback after a checkbox is enabled. - * - * @deprecated - */ - onEnabled?(this: HTMLElement): void; - /** - * Callback after a checkbox is disabled. - * - * @deprecated - */ - onDisabled?(this: HTMLElement): void; - - // endregion - - // region DOM Settings - - /** - * Selectors used to find parts of a module - */ - selector?: { - /** - * @default 'input[type=checkbox], input[type=radio]' - */ - input?: string; - /** - * @default 'label' - */ - label?: string; - }; - /** - * Class names used to determine element state - */ - className?: { - /** - * @default 'checked' - */ - checked?: string; - /** - * @default 'disabled' - */ - disabled?: string; - /** - * @default 'radio' - */ - radio?: string; - /** - * @default 'read-only' - */ - readOnly?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The method you called is not defined.' - */ - method?: string; - }; - - // endregion - } - - // endregion - - // region Dimmer - - interface Dimmer { - settings: DimmerSettings; - - /** - * Detaches a given element from DOM and reattaches element inside dimmer - */ - (behavior: 'add content', element: Selector): JQuery; - /** - * Shows dimmer - */ - (behavior: 'show'): JQuery; - /** - * Hides dimmer - */ - (behavior: 'hide'): JQuery; - /** - * Toggles current dimmer visibility - */ - (behavior: 'toggle'): JQuery; - /** - * Changes dimmer opacity - */ - (behavior: 'set opacity', opacity: number): JQuery; - /** - * Creates a new dimmer in dimmable context - */ - (behavior: 'create'): JQuery; - /** - * Returns current duration for show or hide event depending on current visibility - */ - (behavior: 'get duration'): number; - /** - * Returns DOM element for dimmer - */ - (behavior: 'get dimmer'): JQuery; - /** - * Returns whether current dimmable has a dimmer - */ - (behavior: 'has dimmer'): boolean; - /** - * Whether section's dimmer is active - */ - (behavior: 'is active'): boolean; - /** - * Whether dimmer is animating - */ - (behavior: 'is animating'): boolean; - /** - * Whether current element is a dimmer - */ - (behavior: 'is dimmer'): boolean; - /** - * Whether current element is a dimmable section - */ - (behavior: 'is dimmable'): boolean; - /** - * Whether dimmer is disabled - */ - (behavior: 'is disabled'): boolean; - /** - * Whether dimmer is not disabled - */ - (behavior: 'is enabled'): boolean; - /** - * Whether dimmable section is body - */ - (behavior: 'is page'): boolean; - /** - * Whether dimmer is a page dimmer - */ - (behavior: 'is page dimmer'): boolean; - /** - * Sets page dimmer to active - */ - (behavior: 'set active'): JQuery; - /** - * Sets an element as a dimmable section - */ - (behavior: 'set dimmable'): JQuery; - /** - * Sets a dimmable section as dimmed - */ - (behavior: 'set dimmed'): JQuery; - /** - * Sets current dimmer as a page dimmer - */ - (behavior: 'set page dimmer'): JQuery; - /** - * Sets a dimmer as disabled - */ - (behavior: 'set disabled'): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): DimmerSettings[K]; - (behavior: 'setting', name: K, value: DimmerSettings[K]): JQuery; - (behavior: 'setting', value: DimmerSettings): JQuery; - (settings?: DimmerSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/dimmer.html#/settings} - */ - interface DimmerSettings extends ComponentSettings { - // region Behavior - - /** - * Dimmers opacity from 0-1. Defaults to auto which uses the CSS specified opacity. - * - * @default 'auto' - */ - opacity?: 'auto' | number; - /** - * Specify a variation to add when generating dimmer, like inverted - * - * @default false - */ - variation?: false | string; - /** - * If initializing a dimmer on a dimmable context, you can use dimmerName to distinguish between multiple dimmers in that context. - * - * @default false - */ - dimmerName?: false | string; - /** - * Whether clicking on the dimmer should hide the dimmer (Defaults to auto, closable only when settings.on is not hover - * - * @default 'auto' - */ - closable?: 'auto' | boolean; - /** - * Can be set to hover or click to show/hide dimmer on dimmable event - * - * @default false - */ - on?: false | 'hover' | 'click'; - /** - * Whether to dim dimmers using CSS transitions. - * - * @default true - */ - useCSS?: boolean; - /** - * Animation duration of dimming. If an integer is used, that value will apply to both show and hide animations. - */ - duration?: number | { - /** - * @default 500 - */ - show?: number; - /** - * @default 500 - */ - hide?: number; - }; - /** - * Named transition to use when animating menu in and out. Fade and slide down are available without including ui transitions - * - * @default 'fade' - * @see {@link http://semantic-ui.com/modules/transition.html} - */ - transition?: string; - - // endregion - - // region Callbacks - - /** - * Callback on element show - */ - onShow?(this: JQuery): void; - /** - * Callback on element hide - */ - onHide?(this: JQuery): void; - /** - * Callback on element show or hide - */ - onChange?(this: JQuery): void; - - // endregion - - // region DOM Settings - - /** - * Object containing selectors used by module. - */ - selector?: { - /** - * @default '.dimmable' - */ - dimmable?: string; - /** - * @default '.ui.dimmer' - */ - dimmer?: string; - /** - * @default '.ui.dimmer > .content, .ui.dimmer > .content > .center' - */ - content?: string; - }; - /** - * Templates used to generate dimmer content - */ - template?: { - dimmer?(): JQuery; - }; - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'dimmable' - */ - dimmable?: string; - /** - * @default 'dimmed' - */ - dimmed?: string; - /** - * @default 'disabled' - */ - disabled?: string; - /** - * @default 'page' - */ - pageDimmer?: string; - /** - * @default 'hide' - */ - hide?: string; - /** - * @default 'show' - */ - show?: string; - /** - * @default 'transition' - */ - transition?: string; - }; - - // endregion - - // region Debug Settings - - /** - * Error messages displayed to console - */ - error?: { - /** - * @default 'The method you called is not defined.' - */ - method?: string; - }; - - // endregion - } - - // endregion - - // region Dropdown - - // TODO: Should 'value'/'values' parameters be of type 'string' instead of 'any'? - - interface Dropdown { - settings: DropdownSettings; - - /** - * Recreates dropdown menu from select option values. - */ - (behavior: 'setup menu'): JQuery; - /** - * Refreshes all cached selectors and data - */ - (behavior: 'refresh'): JQuery; - /** - * Toggles current visibility of dropdown - */ - (behavior: 'toggle'): JQuery; - /** - * Shows dropdown - */ - (behavior: 'show'): JQuery; - /** - * Hides dropdown - */ - (behavior: 'hide'): JQuery; - /** - * Clears dropdown of selection - */ - (behavior: 'clear'): JQuery; - /** - * Hides all other dropdowns that is not current dropdown - */ - (behavior: 'hide others'): JQuery; - /** - * Restores dropdown text and value to its value on page load - */ - (behavior: 'restore defaults'): JQuery; - /** - * Restores dropdown text to its value on page load - */ - (behavior: 'restore default text'): JQuery; - /** - * Restores dropdown text to its prompt, placeholder text - */ - (behavior: 'restore placeholder text'): JQuery; - /** - * Restores dropdown value to its value on page load - */ - (behavior: 'restore default value'): JQuery; - /** - * Saves current text and value as new defaults (for use with restore) - */ - (behavior: 'save defaults'): JQuery; - /** - * Sets value as selected - */ - (behavior: 'set selected', value: any): JQuery; - /** - * Remove value from selected - */ - (behavior: 'remove selected', value: any): JQuery; - /** - * Adds a group of values as selected - */ - (behavior: 'set selected', values: any[]): JQuery; - /** - * Sets selected values to exactly specified values, removing current selection - */ - (behavior: 'set exactly', values: any[]): JQuery; - /** - * Sets dropdown text to a value - */ - (behavior: 'set text', text: string): JQuery; - /** - * Sets dropdown input to value (does not update display state) - */ - (behavior: 'set value', value: any): JQuery; - /** - * Returns current dropdown text - */ - (behavior: 'get text'): string; - /** - * Returns current dropdown input value - */ - (behavior: 'get value'): any; - /** - * Returns DOM element that matches a given input value - */ - (behavior: 'get item', value: any): JQuery; - /** - * Adds touch events to element - */ - (behavior: 'bind touch events'): JQuery; - /** - * Adds mouse events to element - */ - (behavior: 'bind mouse events'): JQuery; - /** - * Binds a click to document to determine if you click away from a dropdown - */ - (behavior: 'bind intent'): JQuery; - /** - * Unbinds document intent click - */ - (behavior: 'unbind intent'): JQuery; - /** - * Returns whether event occurred inside dropdown - */ - (behavior: 'determine intent'): boolean; - /** - * Triggers preset item selection action based on settings passing text/value - */ - (behavior: 'determine select action', text: string, value: any): JQuery; - /** - * Sets dropdown to active state - */ - (behavior: 'set active'): JQuery; - /** - * Sets dropdown to visible state - */ - (behavior: 'set visible'): JQuery; - /** - * Removes dropdown active state - */ - (behavior: 'remove active'): JQuery; - /** - * Removes dropdown visible state - */ - (behavior: 'remove visible'): JQuery; - /** - * Returns whether dropdown is a selection dropdown - */ - (behavior: 'is selection'): boolean; - /** - * Returns whether dropdown is animated - */ - (behavior: 'is animated'): boolean; - /** - * Returns whether dropdown is visible - */ - (behavior: 'is visible'): boolean; - /** - * Returns whether dropdown is hidden - */ - (behavior: 'is hidden'): boolean; - /** - * Returns dropdown value as set on page load - */ - (behavior: 'get default text'): string; - /** - * Returns placeholder text - */ - (behavior: 'get placeholder text'): string; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): DropdownSettings[K]; - (behavior: 'setting', name: K, value: DropdownSettings[K]): JQuery; - (behavior: 'setting', value: DropdownSettings): JQuery; - (settings?: DropdownSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/dropdown.html#/settings} - */ - interface DropdownSettings extends ComponentSettings { - // region Frequently Used Settings - - /** - * Event used to trigger dropdown (Hover, Click, Custom Event) - * - * @default 'click' - */ - on?: string; - /** - * When set to true will fire onChange even when the value a user select matches the currently selected value. - * - * @default false - */ - allowReselection?: boolean; - /** - * Whether search selection should allow users to add their own selections, works for single or multi-select. - * - * @default false - */ - allowAdditions?: boolean; - /** - * When disabled user additions will appear in the results menu using a specially formatted selection item formatted by templates.addition. - * - * @default true - */ - hideAdditions?: boolean; - /** - * Sets a default action to occur. (See usage guide) - * - * @default 'activate' - * @see {@link http://semantic-ui.com/modules/dropdown.html#/usage} - */ - action?: 'activate' | 'select' | 'combo' | 'nothing' | 'hide' | ((this: JQuery, text: string, value: string | false, element: JQuery) => void); - /** - * The minimum characters for a search to begin showing results - * - * @default 1 - */ - minCharacters?: number; - /** - * When using search selection specifies how to match values. - * - * @default 'both' - */ - match?: 'both' | 'value' | 'text'; - /** - * Whether dropdown should select new option when using keyboard shortcuts. Setting to false will require enter or left click to confirm a choice. - * - * @default true - */ - selectOnKeydown?: boolean; - /** - * Whether search selection will force currently selected choice when element is blurred. - * - * @default true - */ - forceSelection?: boolean; - /** - * Whether menu items with sub-menus (categories) should be selectable - * - * @default false - */ - allowCategorySelection?: boolean; - /** - * @default 'auto' - */ - placeholder?: 'auto' | 'value' | false; - - // endregion - - // region Remote Settings - - /** - * Can be set to an object to specify API settings for retrieving remote selection menu content from an API endpoint - * - * @default false - * @see {@link http://semantic-ui.com/behaviors/api.html} - */ - apiSettings?: false | ApiSettings; - /** - * List mapping dropdown content to JSON Property when using API - */ - fields?: { - /** - * grouping for api results - * - * @default 'results' - */ - remoteValues?: string; - /** - * grouping for all dropdown values - * - * @default 'values' - */ - values?: string; - /** - * displayed dropdown text - * - * @default 'name' - */ - name?: string; - /** - * actual dropdown value - * - * @default 'value' - */ - value?: string; - }; - /** - * When enabled will automatically store selected name/value pairs in sessionStorage to preserve user selection on page refresh. Disabling will clear remote dropdown values on refresh. - * - * @default true - */ - saveRemoteData?: boolean; - /** - * When set to true API will be expected to return the complete result set, which will then be filtered clientside to only display matching results. - * - * @default false - * @since 2.2.8 - */ - filterRemoteData?: boolean; - - // endregion - - // region Multiple Select Settings - - /** - * Whether multiselect should use labels. Must be set to true when allowAdditions is true - * - * @default true - */ - useLabels?: boolean; - /** - * When set to a number, sets the maximum number of selections - * - * @default false - */ - maxSelections?: boolean; - /** - * Maximum glyph width, used to calculate search size. This is usually size of a "W" in your font in em - * - * @default 1.0714 - */ - glyphWidth?: number; - /** - * Allows customization of multi-select labels - */ - label?: { - /** - * @default 'horizontal flip' - */ - transition?: string; - /** - * @default 200 - */ - duration?: number; - /** - * @default false - */ - variation?: false | string; - }; - - // endregion - - // region Additional Settings - - /** - * When set to auto determines direction based on whether dropdown can fit on screen. Set to upward or downward to always force a direction. - * - * @default 'auto' - */ - direction?: 'auto' | 'upward' | 'downward'; - /** - * Whether dropdown should try to keep itself on screen by checking whether menus display position in its context (Default context is page). - * - * @default true - */ - keepOnScreen?: boolean; - /** - * Element context to use when checking whether can show when keepOnScreen: true - * - * @default 'window' - */ - context?: Selector; - /** - * Specifying to "true" will use a fuzzy full text search, setting to "exact" will force the exact search to be matched somewhere in the string - * - * @default false - */ - fullTextSearch?: boolean | 'exact'; - /** - * Whether HTML included in dropdown values should be preserved. (Allows icons to show up in selected value) - * - * @default true - */ - preserveHTML?: boolean; - /** - * Whether to sort values when creating a dropdown automatically from a select element. - * - * @default false - */ - sortSelect?: boolean; - /** - * Whether to show dropdown menu automatically on element focus. - * - * @default true - */ - showOnFocus?: boolean; - /** - * Whether to allow the element to be navigable by keyboard, by automatically creating a tabindex - * - * @default true - */ - allowTab?: boolean; - /** - * Named transition to use when animating menu in and out. - * Defaults to slide down or slide up depending on dropdown direction. - * Fade and slide down are available without including ui transitions - * - * @default 'auto' - * @see {@link http://semantic-ui.com/modules/transition.html} - */ - transition?: 'auto' | string; - /** - * Duration of animation events - * - * @default 200 - */ - duration?: number; - /** - * The keycode used to represent keyboard shortcuts. To avoid issues with some foreign languages, you can pass false for comma delimiter's value - */ - keys?: { - /** - * @default 8 - */ - backspace?: number; - /** - * @default 188 - */ - delimiter?: number | false; - /** - * @default 46 - */ - deleteKey?: number; - /** - * @default 13 - */ - enter?: number; - /** - * @default 27 - */ - escape?: number; - /** - * @default 33 - */ - pageUp?: number; - /** - * @default 34 - */ - pageDown?: number; - /** - * @default 37 - */ - leftArrow?: number; - /** - * @default 38 - */ - upArrow?: number; - /** - * @default 39 - */ - rightArrow?: number; - /** - * @default 40 - */ - downArrow?: number; - }; - /** - * Time in milliseconds to debounce show or hide behavior when on: hover is used, or when touch is used. - */ - delay?: { - /** - * @default 300 - */ - hide?: number; - /** - * @default 200 - */ - show?: number; - /** - * @default 50 - */ - search?: number; - /** - * @default 50 - */ - touch?: number; - }; - - // endregion - - // region Callbacks - - /** - * Is called after a dropdown value changes. Receives the name and value of selection and the active menu element - */ - onChange?(this: JQuery, value: any, text: string, $choice: JQuery): void; - /** - * Is called after a dropdown selection is added using a multiple select dropdown, only receives the added value - */ - onAdd?(this: JQuery, addedValue: any, addedText: string, $addedChoice: JQuery): void; - /** - * Is called after a dropdown selection is removed using a multiple select dropdown, only receives the removed value - */ - onRemove?(this: JQuery, removedValue: any, removedText: string, $removedChoice: JQuery): void; - /** - * Allows you to modify a label before it is added. Expects the jQ DOM element for a label to be returned. - */ - onLabelCreate?(this: JQuery, value: any, text: string): JQuery; - /** - * Called when a label is remove, return false; will prevent the label from being removed. - */ - onLabelRemove?(this: JQuery, value: any): false | void; - /** - * Is called after a label is selected by a user - */ - onLabelSelect?(this: JQuery, $selectedLabels: JQuery): void; - /** - * Is called after a dropdown is searched with no matching values - */ - onNoResults?(this: JQuery, searchValue: any): void; - /** - * Is called before a dropdown is shown. If false is returned, dropdown will not be shown. - */ - onShow?(this: JQuery): false | void; - /** - * Is called before a dropdown is hidden. If false is returned, dropdown will not be hidden. - */ - onHide?(this: JQuery): false | void; - - // endregion - - // region DOM Settings - - /** - * You can specify site wide messages by modifying $.fn.dropdown.settings.message that will apply on any dropdown if it appears in the page. - */ - message?: { - /** - * @default 'Add {term}' - */ - addResult?: string; - /** - * @default '{count} selected' - */ - count?: string; - /** - * @default 'Max {maxCount} selections' - */ - maxSelections?: string; - /** - * 'No results found.' - */ - noResults?: string; - }; - selector?: { - /** - * @default '.addition' - */ - addition?: string; - /** - * @default '.ui.dropdown' - */ - dropdown?: string; - /** - * @default '> .dropdown.icon' - */ - icon?: string; - /** - * @default '> input[type="hidden"], > select' - */ - input?: string; - /** - * @default '.item' - */ - item?: string; - /** - * @default '> .label' - */ - label?: string; - /** - * @default '> .label > .delete.icon' - */ - remove?: string; - /** - * @default '.label' - */ - siblingLabel?: string; - /** - * @default '.menu' - */ - menu?: string; - /** - * @default '.message' - */ - message?: string; - /** - * @default '.dropdown.icon' - */ - menuIcon?: string; - /** - * @default 'input.search, .menu > .search > input' - */ - search?: string; - /** - * @default '> .text:not(.icon)' - */ - text?: string; - }; - regExp?: { - /** - * @default /[-[\]{}()*+?.,\\^$|#\s]/g - */ - escape?: RegExp; - }; - metadata?: { - /** - * @default 'defaultText' - */ - defaultText?: string; - /** - * @default 'defaultValue' - */ - defaultValue?: string; - /** - * @default 'placeholderText' - */ - placeholderText?: string; - /** - * @default 'text' - */ - text?: string; - /** - * @default 'value' - */ - value?: string; - }; - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'addition' - */ - addition?: string; - /** - * @default 'animating' - */ - animating?: string; - /** - * @default 'disabled' - */ - disabled?: string; - /** - * @default 'ui dropdown' - */ - dropdown?: string; - /** - * @default 'filtered' - */ - filtered?: string; - /** - * @default 'hidden transition' - */ - hidden?: string; - /** - * @default 'item' - */ - item?: string; - /** - * @default 'ui label' - */ - label?: string; - /** - * @default 'loading' - */ - loading?: string; - /** - * @default 'menu' - */ - menu?: string; - /** - * @default 'message' - */ - message?: string; - /** - * @default 'multiple' - */ - multiple?: string; - /** - * @default 'default' - */ - placeholder?: string; - /** - * @default 'search' - */ - search?: string; - /** - * @default 'selected' - */ - selected?: string; - /** - * @default 'selection' - */ - selection?: string; - /** - * @default 'upward' - */ - upward?: string; - /** - * @default 'visible' - */ - visible?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'You called a dropdown action that was not defined' - */ - action?: string; - /** - * @default 'Once a select has been initialized behaviors must be called on the created ui dropdown' - */ - alreadySetup?: string; - /** - * @default 'Allowing user additions currently requires the use of labels.' - */ - labels?: string; - /** - * @default 'The method you called is not defined.' - */ - method?: string; - /** - * @default 'This module requires ui transitions ' - */ - noTransition?: string; - }; - - // endregion - } - - // endregion - - // region Embed - - interface Embed { - settings: EmbedSettings; - - /** - * Changes iframe to a new content source - */ - (behavior: 'change', source: string, id: string, url: string): JQuery; - /** - * Removes embed and shows placeholder content if available - */ - (behavior: 'reset'): JQuery; - /** - * Shows embed content - */ - (behavior: 'show'): JQuery; - /** - * Hides embed content and shows placeholder content - */ - (behavior: 'hide'): JQuery; - /** - * Returns current content id - */ - (behavior: 'get id'): string; - /** - * Returns placeholder image url - */ - (behavior: 'get placeholder'): string; - /** - * Returns source name - */ - (behavior: 'get sources'): string; - /** - * Returns source type - */ - (behavior: 'get type'): string; - /** - * Returns URL with all parameters added - */ - (behavior: 'get url'): string; - /** - * Returns whether embed content has placeholder - */ - (behavior: 'has placeholder'): boolean; - /** - * Destroys instance and removes all events - */ - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): EmbedSettings[K]; - (behavior: 'setting', name: K, value: EmbedSettings[K]): JQuery; - (behavior: 'setting', value: EmbedSettings): JQuery; - (settings?: EmbedSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/embed.html#/settings} - */ - interface EmbedSettings extends ComponentSettings { - /** - * Specifies a url to use for embed - * - * @default false - */ - url?: false | string; - - // region Embed Settings - - /** - * Specifies an icon to use with placeholder content - * - * @default false - */ - icon?: false | string; - /** - * Specifies a source to use, if no source is provided it will be determined from the domain of a specified url. - * - * @default false - */ - source?: false | string; - /** - * Specifies an id value to replace with the {id} value found in templated urls - * - * @default false - */ - id?: false | string; - /** - * Specify an object containing key/value pairs to add to the iframes GET parameters - * - * @default false - */ - parameters?: false | any; - - // endregion - - // region Video Settings - - /** - * Default setting auto will only autoplay content when a placeholder is specified. Setting to true or false will force autoplay. - * - * @default 'auto' - */ - autoplay?: 'auto' | boolean; - /** - * Specifies a default chrome color with Vimeo or YouTube. - * - * @default '#444444' - */ - color?: string; - /** - * Whether to prefer HD content - * - * @default true - */ - hd?: boolean; - /** - * Whether to show networks branded UI like title cards, or after video calls to action. - * - * @default false - */ - brandedUI?: boolean; - - // endregion - - // region Callbacks - - /** - * Callback when iframe is generated - */ - onCreate?(this: JQuery, url: string): void; - /** - * Whenever an iframe contents is shown - */ - onDisplay?(this: JQuery): void; - /** - * Callback immediately before Embed is removed from DOM - */ - onPlaceholderDisplay?(this: JQuery): void; - /** - * Callback when module parameters are determined. Allows you to adjust parameters at run time by returning a new parameters object. - */ - onEmbed?(this: JQuery, parameters: any): any; - - // endregion - - // region DOM Settings - - /** - * DOM Selectors used internally - */ - selector?: { - /** - * @default '.embed' - */ - embed?: string; - /** - * @default '.placeholder' - */ - placeholder?: string; - /** - * @default '.play' - */ - play?: string; - }; - /** - * HTML Data attributes used to store data - */ - metadata?: { - /** - * @default 'id' - */ - id?: string; - /** - * @default 'icon' - */ - icon?: string; - /** - * @default 'placeholder' - */ - placeholder?: string; - /** - * @default 'source' - */ - source?: string; - /** - * @default 'url' - */ - url?: string; - }; - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'embed' - */ - embed?: string; - }; - templates?: { - /** - * returns html for iframe - */ - iframe?(url: string, parameters: string): string; - /** - * returns html for placeholder element - */ - placeholder?(image: string, icon: string): string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'No URL specified' - */ - noURL?: string; - /** - * @default 'The method you called is not defined' - */ - method?: string; - }; - - // endregion - } - - // endregion - - // region Modal - - interface Modal { - settings: ModalSettings; - - /** - * Shows the modal - */ - (behavior: 'show'): JQuery; - /** - * Hides the modal - */ - (behavior: 'hide'): JQuery; - /** - * Toggles the modal - */ - (behavior: 'toggle'): JQuery; - /** - * Refreshes centering of modal on page - */ - (behavior: 'refresh'): JQuery; - /** - * Shows associated page dimmer - */ - (behavior: 'show dimmer'): JQuery; - /** - * Hides associated page dimmer - */ - (behavior: 'hide dimmer'): JQuery; - /** - * Hides all modals not selected modal in a dimmer - */ - (behavior: 'hide others'): JQuery; - /** - * Hides all visible modals in the same dimmer - */ - (behavior: 'hide all'): JQuery; - /** - * Caches current modal size - */ - (behavior: 'cache sizes'): JQuery; - /** - * Returns whether the modal can fit on the page - */ - (behavior: 'can fit'): boolean; - /** - * Returns whether the modal is active - */ - (behavior: 'is active'): boolean; - /** - * Sets modal to active - */ - (behavior: 'set active'): JQuery; - (behavior: 'attach events', selector: Selector, event?: string): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): ModalSettings[K]; - (behavior: 'setting', name: K, value: ModalSettings[K]): JQuery; - (behavior: 'setting', value: ModalSettings): JQuery; - (settings?: ModalSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/modal.html#/settings} - */ - interface ModalSettings extends ComponentSettings { - // region Modal Settings - - /** - * If set to false will prevent the modal from being moved to inside the dimmer - * - * @default true - */ - detachable?: boolean; - /** - * When true, the first form input inside the modal will receive focus when shown. Set this to false to prevent this behavior. - * - * @default true - */ - autofocus?: boolean; - /** - * Whether any change in modal DOM should automatically refresh cached positions - * - * @default false - */ - observeChanges?: boolean; - /** - * If set to true will not close other visible modals when opening a new one - * - * @default false - */ - allowMultiple?: boolean; - /** - * Whether to automatically bind keyboard shortcuts - * - * @default true - */ - keyboardShortcuts?: boolean; - /** - * A vertical offset to allow for content outside of modal, for example a close button, to be centered. - * - * @default 0 - */ - offset?: number; - /** - * Selector or jquery object specifying the area to dim - * - * @default 'body' - */ - context?: Selector; - /** - * Setting to false will not allow you to close the modal by clicking on the dimmer - * - * @default true - */ - closable?: boolean; - /** - * You can specify custom settings to extend UI dimmer - * - * @see {@link http://semantic-ui.com/modules/dimmer.html} - */ - dimmerSettings?: DimmerSettings; - /** - * Named transition to use when animating menu in and out, full list can be found in ui transitions docs. - * - * @default 'scale' - * @see {@link http://semantic-ui.com/modules/transition.html} - */ - transition?: string; - /** - * Duration of animation - * - * @default 400 - */ - duration?: number; - /** - * Whether additional animations should queue - * - * @default false - */ - queue?: boolean; - - // endregion - - // region Callbacks - - /** - * Is called when a modal starts to show. - */ - onShow?(this: JQuery): void; - /** - * Is called after a modal has finished showing animating. - */ - onVisible?(this: JQuery): void; - /** - * Is called after a modal starts to hide. If the function returns false, the modal will not hide. - */ - onHide?(this: JQuery, $element: JQuery): false | void; - /** - * Is called after a modal has finished hiding animation. - */ - onHidden?(this: JQuery): void; - /** - * Is called after a positive, approve or ok button is pressed. If the function returns false, the modal will not hide. - */ - onApprove?(this: JQuery, $element: JQuery): false | void; - /** - * Is called after a negative, deny or cancel button is pressed. If the function returns false the modal will not hide. - */ - onDeny?(this: JQuery, $element: JQuery): false | void; - - // endregion - - // region DOM Settings - - selector?: { - /** - * @default '.close, .actions .button' - */ - close?: string; - /** - * @default '.actions .positive, .actions .approve, .actions .ok' - */ - approve?: string; - /** - * @default '.actions .negative, .actions .deny, .actions .cancel' - */ - deny?: string; - }; - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'scrolling' - */ - scrolling?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The method you called is not defined.' - */ - method?: string; - }; - - // endregion - } - - // endregion - - // region Nag - - interface Nag { - settings: NagSettings; - - (behavior: 'show'): JQuery; - (behavior: 'hide'): JQuery; - /** - * Clears cookie so nag shows again - */ - (behavior: 'clear'): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): NagSettings[K]; - (behavior: 'setting', name: K, value: NagSettings[K]): JQuery; - (behavior: 'setting', value: NagSettings): JQuery; - (settings?: NagSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/nag.html} - */ - interface NagSettings extends ComponentSettings { - // region Behavior - - /** - * allows cookie to be overridden - * - * @default false - */ - persist?: boolean; - /** - * set to zero to require manually dismissal, otherwise hides on its own - * - * @default 0 - */ - displayTime?: number; - animation?: { - /** - * @default 'slide' - */ - show?: string; - /** - * @default 'slide' - */ - hide?: string; - }; - /** - * @default false - */ - context?: false | Selector; - /** - * @default false - */ - detachable?: boolean; - - /** - * @default 30 - */ - expires?: number; - /** - * @default false - */ - domain?: false | string; - /** - * @default '/' - */ - path?: string; - - /** - * type of storage to use - * - * @default 'cookie' - */ - storageMethod?: 'cookie' | 'localstorage' | 'sessionstorage'; - - /** - * @default 'nag' - */ - key?: any; - /** - * @default 'dismiss' - */ - value?: any; - - /** - * @default 500 - */ - speed?: number; - /** - * @default 'easeOutQuad' - */ - easing?: string; - - // endregion - - // region Callbacks - - onHide?(this: JQuery): void; - - // endregion - - // region DOM Settings - - className?: { - /** - * @default 'bottom' - */ - bottom?: string; - /** - * @default 'fixed' - */ - fixed?: string; - }; - selector?: { - /** - * @default '.close.icon' - */ - close?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default '$.cookie is not included. A storage solution is required.' - */ - noCookieStorage?: string; - /** - * @default 'Neither $.cookie or store is defined. A storage solution is required for storing state' - */ - noStorage?: string; - /** - * @default 'The method you called is not defined.' - */ - method?: string; - }; - - // endregion - } - - // endregion - - // region Popup - - interface Popup { - settings: PopupSettings; - - /** - * Shows popup - */ - (behavior: 'show'): JQuery; - /** - * Hides popup - */ - (behavior: 'hide'): JQuery; - /** - * Hides all visible pop ups on the page - */ - (behavior: 'hide all'): JQuery; - /** - * Returns current popup dom element - */ - (behavior: 'get popup'): JQuery; - /** - * Changes current popup content - */ - (behavior: 'change content', html: string): JQuery; - /** - * Toggles visibility of popup - */ - (behavior: 'toggle'): JQuery; - /** - * Returns whether popup is visible - */ - (behavior: 'is visible'): boolean; - /** - * Returns whether popup is hidden - */ - (behavior: 'is hidden'): boolean; - /** - * Returns whether popup is created and inserted into the page - */ - (behavior: 'exists'): boolean; - /** - * Adjusts popup when content size changes (only necessary for centered popups) - */ - (behavior: 'reposition'): JQuery; - /** - * Repositions a popup - */ - (behavior: 'set position', position: string): JQuery; - /** - * Removes popup from the page and removes all events - */ - (behavior: 'destroy'): JQuery; - /** - * Removes popup from the page - */ - (behavior: 'remove popup'): JQuery; - (behavior: 'setting', name: K, value?: undefined): PopupSettings[K]; - (behavior: 'setting', name: K, value: PopupSettings[K]): JQuery; - (behavior: 'setting', value: PopupSettings): JQuery; - (settings?: PopupSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/popup.html#/settings} - */ - interface PopupSettings extends ComponentSettings { - // region Popup Settings - - /** - * Can specify a DOM element that should be used as the popup. This is useful for including a pre-formatted popup. - * - * @default false - */ - popup?: false | Selector; - /** - * Whether all other popups should be hidden when this popup is opened - * - * @default false - */ - exclusive?: boolean; - /** - * Whether to move popup to same offset container as target element when popup already exists on the page. - * Using a popup inside of an element without overflow:visible, like a sidebar, may require you to set this to false - * - * @default true - */ - movePopup?: boolean; - /** - * Whether popup should attach mutationObservers to automatically run destroy when the element is removed from the page's DOM. - * - * @default true - */ - observeChanges?: boolean; - /** - * When the popup surpasses the boundary of this element, it will attempt to find another display position. - */ - boundary?: Selector; - /** - * Selector or jquery object specifying where the popup should be created. - * - * @default 'body' - */ - context?: Selector; - /** - * Will automatically hide a popup on scroll event in this context - */ - scrollContext?: Selector; - /** - * Number of pixels that a popup is allowed to appear outside the boundaries of its context. - * This allows for permissible rounding errors when an element is against the edge of its context. - * - * @default 2 - */ - jitter?: number; - /** - * Position that the popup should appear - * - * @default 'top left' - */ - position?: string; - /** - * If a popup is inline it will be created next to current element, allowing for local css rules to apply. - * It will not be removed from the DOM after being hidden. - * Otherwise popups will appended to body and removed after being hidden. - * - * @default false - */ - inline?: boolean; - /** - * Whether popup contents should be preserved in the page after being hidden, allowing it to re-appear slightly faster on subsequent loads. - * - * @default false - */ - preserve?: boolean; - /** - * Can be set to adjacent or opposite to prefer adjacent or opposite position if popup cannot fit on screen - * - * @default 'adjacent' - */ - prefer?: 'adjacent' | 'opposite'; - /** - * When set to false, a popup will not appear and produce an error message if it cannot entirely fit on page. - * Setting this to a position like, right center forces the popup to use this position as a last resort even if it is partially offstage. - * Setting this to true will use the last attempted position. - * - * @default false - */ - lastResort?: boolean | string; - /** - * Event used to trigger popup. Can be either focus, click, hover, or manual. Manual popups must be triggered with $('.element').popup('show'); - * - * @default 'hover' - */ - on?: 'focus' | 'click' | 'hover' | 'manual'; - /** - * Delay in milliseconds before showing or hiding a popup on hover or focus - */ - delay?: { - show?: number; - hide?: number; - }; - /** - * Named transition to use when animating menu in and out. Fade and slide down are available without including ui transitions - * - * @default 'slide down' - * @see {@link http://semantic-ui.com/modules/transition.html} - */ - transition?: string; - /** - * Duration of animation events - * - * @default 200 - */ - duration?: number; - /** - * Whether popup should set fluid popup variation width on load to avoid width: 100% including padding - * - * @default true - */ - setFluidWidth?: boolean; - /** - * Whether popup should not close on hover (useful for popup navigation menus) - * - * @default false - */ - hoverable?: boolean; - /** - * When using on: 'click' specifies whether clicking the page should close the popup - * - * @default true - */ - closable?: boolean; - /** - * When using on: 'hover' whether touchstart events should be added to allow the popup to be triggered - */ - addTouchEvents?: boolean; - /** - * Whether popup should hide on scroll or touchmove, auto only hides for popups without on: 'click'. - * Set this to false to prevent mobile browsers from closing popups when you tap inside input fields. - * - * @default 'auto' - */ - hideOnScroll?: 'auto' | false; - /** - * If a selector or jQuery object is specified this allows the popup to be positioned relative to that element. - * - * @default false - */ - target?: false | Selector; - /** - * Offset for distance of popup from element - * - * @default 0 - */ - distanceAway?: number; - /** - * Offset in pixels from calculated position - * - * @default 0 - */ - offset?: number; - /** - * Number of iterations before giving up search for popup position when a popup cannot fit on screen - * - * @default 10 - */ - maxSearchDepth?: number; - - // endregion - - // region Callbacks - - /** - * Callback on popup element creation, with created popup - */ - onCreate?(this: JQuery, $module: JQuery): void; - /** - * Callback immediately before Popup is removed from DOM - */ - onRemove?(this: JQuery, $module: JQuery): void; - /** - * Callback before popup is shown. Returning false from this callback will cancel the popup from showing. - */ - onShow?(this: JQuery, $module: JQuery): false | void; - /** - * Callback after popup is shown - */ - onVisible?(this: JQuery, $module: JQuery): void; - /** - * Callback before popup is hidden. Returning false from this callback will cancel the popup from hiding. - */ - onHide?(this: JQuery, $module: JQuery): false | void; - /** - * Callback after popup is hidden - */ - onHidden?(this: JQuery, $module: JQuery): void; - /** - * Callback after popup cannot be placed on screen - */ - onUnplaceable?(this: JQuery, $module: JQuery): void; - - // endregion - - // region Content Settings - - /** - * Popup variation to use, can use multiple variations with a space delimiter - */ - variation?: string; - /** - * Content to display - */ - content?: string; - /** - * Title to display alongside content - */ - title?: string; - /** - * HTML content to display instead of preformatted title and content - */ - html?: string | JQuery; - - // endregion - - // region DOM Settings - - /** - * DOM Selectors used internally - */ - selector?: { - /** - * @default '.ui.popup' - */ - popup?: string; - }; - /** - * HTML Data attributes used to store data - */ - metadata?: { - /** - * @default 'content' - */ - content?: string; - /** - * @default 'html' - */ - html?: string; - /** - * @default 'offset' - */ - offset?: string; - /** - * @default 'position' - */ - position?: string; - /** - * @default 'title' - */ - title?: string; - /** - * @default 'variation' - */ - variation?: string; - }; - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'loading' - */ - loading?: string; - /** - * @default 'ui popup' - */ - popup?: string; - /** - * @default 'top left center bottom right' - */ - position?: string; - /** - * @default 'visible' - */ - visible?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The position you specified is not a valid position' - */ - invalidPosition?: string; - /** - * @default 'Popup does not fit within the boundaries of the viewport' - */ - cannotPlace?: string; - /** - * @default 'The method you called is not defined.' - */ - method?: string; - /** - * @default 'This module requires ui transitions ' - */ - noTransition?: string; - /** - * @default 'The target or popup you specified does not exist on the page' - */ - notFound?: string; - }; - - // endregion - } - - // endregion - - // region Progress - - interface Progress { - settings: ProgressSettings; - - /** - * Sets current percent of progress to value. If using a total will convert from percent to estimated value. - */ - (behavior: 'set percent', percent: number): JQuery; - /** - * Sets progress to specified value. Will automatically calculate percent from total. - */ - (behavior: 'set progress', value: number): JQuery; - /** - * Increments progress by increment value, if not passed a value will use random amount specified in settings - */ - (behavior: 'increment', incrementValue: number): JQuery; - /** - * Decrements progress by decrement value, if not passed a value will use random amount specified in settings - */ - (behavior: 'decrement', decrementValue: number): JQuery; - /** - * Immediately updates progress to value, ignoring progress animation interval delays - */ - (behavior: 'update progress', value: number): JQuery; - /** - * Finishes progress and sets loaded to 100% - */ - (behavior: 'complete'): JQuery; - /** - * Resets progress to zero - */ - (behavior: 'reset'): JQuery; - /** - * Set total to a new value - */ - (behavior: 'set total', total: number): JQuery; - /** - * Replaces templated string with value, total, percent left and percent. - */ - (behavior: 'get text', text: string): string; - /** - * Returns normalized value inside acceptable range specified by total. - */ - (behavior: 'get normalized value', value: number): number; - /** - * Returns percent as last specified - */ - (behavior: 'get percent'): number; - /** - * Returns current progress value - */ - (behavior: 'get value'): number; - /** - * Returns total - */ - (behavior: 'get total'): number; - /** - * Returns whether progress is completed - */ - (behavior: 'is complete'): boolean; - /** - * Returns whether progress was a success - */ - (behavior: 'is success'): boolean; - /** - * Returns whether progress is in warning state - */ - (behavior: 'is warning'): boolean; - /** - * Returns whether progress is in error state - */ - (behavior: 'is error'): boolean; - /** - * Returns whether progress is in active state - */ - (behavior: 'is active'): boolean; - /** - * Sets progress to active state - */ - (behavior: 'set active'): JQuery; - /** - * Sets progress to warning state - */ - (behavior: 'set warning'): JQuery; - /** - * Sets progress to success state - */ - (behavior: 'set success'): JQuery; - /** - * Sets progress to error state - */ - (behavior: 'set error'): JQuery; - /** - * Changes progress animation speed - */ - (behavior: 'set duration', value: number): JQuery; - /** - * Sets progress exterior label to text - */ - (behavior: 'set label', text: string): JQuery; - /** - * Sets progress bar label to text - */ - (behavior: 'set bar label', text: string): JQuery; - /** - * Removes progress to active state - */ - (behavior: 'remove active'): JQuery; - /** - * Removes progress to warning state - */ - (behavior: 'remove warning'): JQuery; - /** - * Removes progress to success state - */ - (behavior: 'remove success'): JQuery; - /** - * Removes progress to error state - */ - (behavior: 'remove error'): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): ProgressSettings[K]; - (behavior: 'setting', name: K, value: ProgressSettings[K]): JQuery; - (behavior: 'setting', value: ProgressSettings): JQuery; - (settings?: ProgressSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/progress.html#/settings} - */ - interface ProgressSettings extends ComponentSettings { - // region Progress Settings - - /** - * Whether success state should automatically trigger when progress completes - * - * @default true - */ - autoSuccess?: boolean; - /** - * Whether progress should automatically show activity when incremented - * - * @default true - */ - showActivity?: boolean; - /** - * When set to true, values that calculate to above 100% or below 0% will be adjusted. - * When set to false, inappropriate values will produce an error. - * - * @default true - */ - limitValues?: boolean; - /** - * Can be set to either to display progress as percent or ratio. Matches up to corresponding text template with the same name. - * - * @default 'percent' - */ - label?: 'percent' | 'ratio'; - /** - * When incrementing without value, sets range for random increment value - */ - random?: { - /** - * @default 2 - */ - min?: number; - /** - * @default 5 - */ - max?: number; - }; - /** - * Decimal point precision for calculated progress - * - * @default 1 - */ - precision?: number; - /** - * Setting a total value will make each call to increment get closer to this total (i.e. 1/20, 2/20 etc) - * - * @default false - */ - total?: false | number; - /** - * Sets current value, when total is specified, this is used to calculate a ratio of the total, with percent this should be the overall percent - * - * @default false - */ - value?: false | number; - - // endregion - - // region Callbacks - - /** - * Callback on percentage change - */ - onChange?(this: JQuery, percent: number, value: number, total: number): void; - /** - * Callback on success state - */ - onSuccess?(this: JQuery, total: number): void; - /** - * Callback on active state - */ - onActive?(this: JQuery, value: number, total: number): void; - /** - * Callback on error state - */ - onError?(this: JQuery, value: number, total: number): void; - /** - * Callback on warning state - */ - onWarning?(this: JQuery, value: number, total: number): void; - - // endregion - - // region DOM Settings - - /** - * Text content for each state, uses simple templating with {percent}, {value}, {total} - */ - text?: { - /** - * @default false - */ - active?: false | string; - /** - * @default false - */ - error?: false | string; - /** - * @default false - */ - success?: false | string; - /** - * @default false - */ - warning?: false | string; - /** - * @default '{percent}%' - */ - percent?: false | string; - /** - * @default '{value} of {total}' - */ - ratio?: false | string; - }; - /** - * Regular expressions used by module - */ - regExp?: { - /** - * @default /\{\$*[A-z0-9]+\}/g - */ - variable?: RegExp; - }; - /** - * Selectors used by module - */ - selector?: { - /** - * @default '> .bar - */ - bar?: string; - /** - * @default '> .label' - */ - label?: string; - /** - * @default '.bar > .progress' - */ - progress?: string; - }; - /** - * DOM metadata used by module - */ - metadata?: { - /** - * @default 'percent' - */ - percent?: string; - /** - * @default 'total' - */ - total?: string; - /** - * @default 'value' - */ - value?: string; - }; - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'error' - */ - error?: string; - /** - * @default 'success' - */ - success?: string; - /** - * @default 'warning' - */ - warning?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The method you called is not defined.' - */ - method?: string; - /** - * @default 'Progress value is non numeric' - */ - nonNumeric?: string; - }; - - // endregion - } - - // endregion - - // region Rating - - interface Rating { - settings: RatingSettings; - - /** - * Sets rating programmatically - */ - (behavior: 'set rating', rating: number): JQuery; - /** - * Gets current rating - */ - (behavior: 'get rating'): number; - /** - * Disables interactive rating mode - */ - (behavior: 'disable'): JQuery; - /** - * Enables interactive rating mode - */ - (behavior: 'enable'): JQuery; - /** - * Clears current rating - */ - (behavior: 'clear rating'): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): RatingSettings[K]; - (behavior: 'setting', name: K, value: RatingSettings[K]): JQuery; - (behavior: 'setting', value: RatingSettings): JQuery; - (settings?: RatingSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/rating.html#/settings} - */ - interface RatingSettings extends ComponentSettings { - // region Rating Settings - - /** - * A number representing the default rating to apply - * - * @default 0 - */ - initialRating?: number; - /** - * Whether callbacks like onRate should fire immediately after initializing with the current value. - * - * @default false - */ - fireOnInit?: boolean; - /** - * By default a rating will be only clearable if there is 1 icon. Setting to true/false will allow or disallow a user to clear their rating - * - * @default 'auto' - */ - clearable?: 'auto' | boolean; - /** - * Whether to enable user's ability to rate - * - * @default true - */ - interactive?: boolean; - - // endregion - - // region Callbacks - - /** - * Is called after user selects a new rating - */ - onRate?(this: JQuery, value: number): void; - - // endregion - - // region DOM Settings - - selector?: { - /** - * @default '.icon' - */ - icon?: string; - }; - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'hover' - */ - hover?: string; - /** - * @default 'loading' - */ - loading?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'You called a rating action that was not defined' - */ - action?: string; - }; - - // endregion - } - - // endregion - - // region Search - - interface Search { - settings: SearchSettings; - - /** - * Search for value currently set in search input - */ - (behavior: 'query', callback?: () => void): JQuery; - /** - * Displays message in search results with text, using template matching type - */ - (behavior: 'display message', text: string, type: string): JQuery; - /** - * Cancels current remote search query - */ - (behavior: 'cancel query'): JQuery; - /** - * Search local object for specified query and display results - */ - (behavior: 'search local', query: string): JQuery; - /** - * Whether has minimum characters - */ - (behavior: 'has minimum characters'): boolean; - /** - * Search remote endpoint for specified query and display results - */ - (behavior: 'search remote', query: string, callback?: () => void): JQuery; - /** - * Search object for specified query and return results - */ - (behavior: 'search object', query: string, object: any, searchFields: string[]): any; - /** - * Cancels current remote search request - */ - (behavior: 'cancel query'): JQuery; - /** - * Whether search is currently focused - */ - (behavior: 'is focused'): boolean; - /** - * Whether search results are visible - */ - (behavior: 'is visible'): boolean; - /** - * Whether search results are empty - */ - (behavior: 'is empty'): boolean; - /** - * Returns current search value - */ - (behavior: 'get value'): any; - /** - * Returns JSON object matching searched title or id (see above) - */ - (behavior: 'get result', value: any): any; - /** - * Sets search input to value - */ - (behavior: 'set value', value: any): JQuery; - /** - * Reads cached results for query - */ - (behavior: 'read cache', query: string): JQuery; - /** - * Clears value from cache, if no parameter passed clears all cache - */ - (behavior: 'clear cache', query?: string): JQuery; - /** - * Writes cached results for query - */ - (behavior: 'write cache', query: string): JQuery; - /** - * Adds HTML to results and displays - */ - (behavior: 'add results', html: string): JQuery; - /** - * Shows results container - */ - (behavior: 'show results', callback?: () => void): JQuery; - /** - * Hides results container - */ - (behavior: 'hide results', callback?: () => void): JQuery; - /** - * Generates results using parser specified by settings.template - */ - (behavior: 'generate results', response: any): JQuery; - /** - * Removes all events - */ - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): SearchSettings[K]; - (behavior: 'setting', name: K, value: SearchSettings[K]): JQuery; - (behavior: 'setting', value: SearchSettings): JQuery; - (settings?: SearchSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/search.html#/settings} - */ - interface SearchSettings extends ComponentSettings { - // region Behavior - - /** - * Settings for API call. - * - * @see {@link http://semantic-ui.com/behaviors/api.html#/usage} - */ - apiSettings?: ApiSettings; - /** - * Minimum characters to query for results - * - * @default 1 - */ - minCharacters?: number; - /** - * Named transition to use when animating menu in and out. Fade and slide down are available without including ui transitions - * - * @default 'fade' - * @see {@link http://semantic-ui.com/modules/transition.html} - */ - transition?: string; - /** - * Duration of animation events - * - * @default 300 - */ - duration?: number; - /** - * Maximum results to display when using local and simple search, maximum category count for category search - * - * @default 7 - */ - maxResults?: number; - /** - * Caches results locally to avoid requerying server - * - * @default true - */ - cache?: boolean; - /** - * Specify a Javascript object which will be searched locally - * - * @default false - */ - source?: false | any; - /** - * Whether the search should automatically select the first search result after searching - * - * @default false - */ - selectFirstResult?: boolean; - /** - * Whether a "no results" message should be shown if no results are found. (These messages can be modified using the template object specified below) - * - * @default false - */ - showNoResults?: boolean; - /** - * Return local results that match anywhere inside your content - * - * @default true - */ - searchFullText?: boolean; - /** - * List mapping display content to JSON property, either with API or source. - */ - fields?: { - /** - * array of categories (category view) - * - * @default 'results' - */ - categories?: string; - /** - * name of category (category view) - * - * @default 'name' - */ - categoryName?: string; - /** - * array of results (category view) - * - * @default 'results' - */ - categoryResults?: string; - /** - * result description - * - * @default 'description' - */ - description?: string; - /** - * result image - * - * @default 'image' - */ - image?: string; - /** - * result price - * - * @default 'price' - */ - price?: string; - /** - * array of results (standard) - * - * @default 'results' - */ - results?: string; - /** - * result title - * - * @default 'title' - */ - title?: string; - /** - * "view more" object name - * - * @default 'action' - */ - action?: string; - /** - * "view more" text - * - * @default 'text' - */ - actionText?: string; - /** - * "view more" url - * - * @default 'url' - */ - actionURL?: string; - }; - /** - * Specify object properties inside local source object which will be searched - */ - searchFields?: string[]; - /** - * Delay before hiding results after search blur - * - * @default 0 - */ - hideDelay?: number; - /** - * Delay before querying results on inputchange - * - * @default 100 - */ - searchDelay?: number; - /** - * Easing equation when using fallback Javascript animation - * - * @default 'easeOutExpo' - */ - easing?: string; - - // endregion - - // region Callbacks - - /** - * Callback on element selection by user. - * The first parameter includes the filtered response results for that element. - * The function should return false to prevent default action (closing search results and selecting value). - */ - onSelect?(this: JQuery, result: any, response: any): false | void; - /** - * Callback after processing element template to add HTML to results. Function should return false to prevent default actions. - */ - onResultsAdd?(this: JQuery, html: string): false | void; - /** - * Callback on search query - */ - onSearchQuery?(this: JQuery, query: string): void; - /** - * Callback on server response - */ - onResults?(this: JQuery, response: any): void; - /** - * Callback when results are opened - */ - onResultsOpen?(this: JQuery): void; - /** - * Callback when results are closed - */ - onResultsClose?(this: JQuery): void; - - // endregion - - // region Templates - - templates?: { - escape?(string: string): string; - message?(message: string, type: string): string; - category?(response: any): string; - standard?(response: any): string; - }; - - // endregion - - // region DOM Settings - - /** - * Regular expressions used for matching - */ - regExp?: { - /** - * @default /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g - */ - escape?: RegExp; - /** - * @default '(?:\s|^)' - */ - beginsWith?: string; - }; - /** - * Selectors used to find parts of a module - */ - selector?: { - /** - * @default '.prompt' - */ - prompt?: string; - /** - * @default '.search.button' - */ - searchButton?: string; - /** - * @default '.results' - */ - results?: string; - /** - * @default '.category' - */ - category?: string; - /** - * @default '.result' - */ - result?: string; - }; - /** - * HTML5 metadata attributes used internally - */ - metadata?: { - /** - * @default 'cache' - */ - cache?: string; - /** - * @default 'results' - */ - results?: string; - }; - /** - * Class names used to determine element state - */ - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'empty' - */ - empty?: string; - /** - * @default 'focus' - */ - focus?: string; - /** - * @default 'loading' - */ - loading?: string; - /** - * @default 'down' - */ - pressed?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'Cannot search. No source used, and Semantic API module was not included' - */ - source?: string; - /** - * @default 'Your search returned no results' - */ - noResults?: string; - /** - * @default 'Error in debug logging, exiting.' - */ - logging?: string; - /** - * @default 'A valid template name was not specified.' - */ - noTemplate?: string; - /** - * @default 'There was an issue with querying the server.' - */ - serverError?: string; - /** - * @default 'Results must be an array to use maxResults setting' - */ - maxResults?: string; - /** - * @default 'The method you called is not defined.' - */ - method?: string; - }; - - // endregion - } - - // endregion - - // region Shape - - interface Shape { - settings: ShapeSettings; - - /** - * Flips the shape upward - */ - (behavior: 'flip up'): JQuery; - /** - * Flips the shape downward - */ - (behavior: 'flip down'): JQuery; - /** - * Flips the shape right - */ - (behavior: 'flip right'): JQuery; - /** - * Flips the shape left - */ - (behavior: 'flip left'): JQuery; - /** - * Flips the shape over clock-wise - */ - (behavior: 'flip over'): JQuery; - /** - * Flips the shape over counter-clockwise - */ - (behavior: 'flip back'): JQuery; - /** - * Set the next side to a specific selector - */ - (behavior: 'set next side', selector: Selector): JQuery; - /** - * Returns whether shape is currently animating - */ - (behavior: 'is animating'): boolean; - /** - * Removes all inline styles - */ - (behavior: 'reset'): JQuery; - /** - * Queues an animation until after current animation - */ - (behavior: 'queue', animation: string): JQuery; - /** - * Forces a reflow on element - */ - (behavior: 'repaint'): JQuery; - /** - * Set the next side to next sibling to active element - */ - (behavior: 'set default side'): JQuery; - /** - * Sets shape to the content size of the next side - */ - (behavior: 'set stage size'): JQuery; - /** - * Refreshes the selector cache for element sides - */ - (behavior: 'refresh'): JQuery; - /** - * Returns translation for next side staged below - */ - (behavior: 'get transform down'): Translation; - /** - * Returns translation for next side staged left - */ - (behavior: 'get transform left'): Translation; - /** - * Returns translation for next side staged right - */ - (behavior: 'get transform right'): Translation; - /** - * Returns translation for next side staged up - */ - (behavior: 'get transform up'): Translation; - /** - * Returns translation for next side staged down - */ - (behavior: 'get transform down'): Translation; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): ShapeSettings[K]; - (behavior: 'setting', name: K, value: ShapeSettings[K]): JQuery; - (behavior: 'setting', value: ShapeSettings): JQuery; - (settings?: ShapeSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/shape.html#/settings} - */ - interface ShapeSettings extends ComponentSettings { - // region Shape Settings - - /** - * Duration of side change animation - * - * @default 700 - */ - duration?: number; - /** - * When set to next will use the width of the next side during the shape's animation. - * When set to initial it will use the width of the shape at initialization. - * When set to a specific pixel height, will force the width to that height. - * - * @default 'initial' - * @since 2.2 - */ - width?: 'next' | 'initial' | number; - /** - * When set to next will use the height of the next side during the shape's animation. - * When set to initial it will use the height of the shape at initialization. - * When set to a specific pixel height, will force the height to that height. - * - * @default 'initial' - * @since 2.2 - */ - height?: 'next' | 'initial' | number; - - // endregion - - // region Callbacks - - /** - * Is called before side change - */ - beforeChange?(this: JQuery): void; - /** - * Is called after visible side change - */ - onChange?(this: JQuery): void; - - // endregion - - // region DOM Settings - - selector?: { - /** - * @default '.sides' - */ - sides?: string; - /** - * @default '.side' - */ - side?: string; - }; - className?: { - /** - * @default 'animating' - */ - animating?: string; - /** - * @default 'hidden' - */ - hidden?: string; - /** - * @default 'loading' - */ - loading?: string; - /** - * @default 'active' - */ - active?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'You tried to switch to a side that does not exist.' - */ - side?: string; - /** - * @default 'The method you called is not defined' - */ - method?: string; - }; - - // endregion - } - - interface Translation { - transform: string; - } - - // endregion - - // region Sidebar - - interface Sidebar { - settings: SidebarSettings; - - /** - * Attaches sidebar action to given selector. Default event if none specified is toggle - */ - (behavior: 'attach events', selector: string, event?: string): JQuery; - /** - * Shows sidebar - */ - (behavior: 'show'): JQuery; - /** - * Hides sidebar - */ - (behavior: 'hide'): JQuery; - /** - * Toggles visibility of sidebar - */ - (behavior: 'toggle'): JQuery; - /** - * Returns whether sidebar is visible - */ - (behavior: 'is visible'): boolean; - /** - * Returns whether sidebar is hidden - */ - (behavior: 'is hidden'): boolean; - /** - * Pushes page content to be visible alongside sidebar - */ - (behavior: 'push page'): JQuery; - /** - * Returns direction of current sidebar - */ - (behavior: 'get direction'): string; - /** - * Returns page content to original position - */ - (behavior: 'pull page'): JQuery; - /** - * Adds stylesheet to page head to trigger sidebar animations - */ - (behavior: 'add body CSS'): JQuery; - /** - * Removes any inline stylesheets for sidebar animation - */ - (behavior: 'remove body CSS'): JQuery; - /** - * Returns vendor prefixed transition end event - */ - (behavior: 'get transition event'): string; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): SidebarSettings[K]; - (behavior: 'setting', name: K, value: SidebarSettings[K]): JQuery; - (behavior: 'setting', value: SidebarSettings): JQuery; - (settings?: SidebarSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/sidebar.html#/settings} - */ - interface SidebarSettings extends ComponentSettings { - // region Behavior - - /** - * Context which sidebar will appear inside - * - * @default 'body' - */ - context?: Selector; - /** - * Whether multiple sidebars can be open at once - * - * @default false - */ - exclusive?: boolean; - /** - * Whether sidebar can be closed by clicking on page - * - * @default true - */ - closable?: boolean; - /** - * Whether to dim page contents when sidebar is visible - * - * @default true - */ - dimPage?: boolean; - /** - * Whether to lock page scroll when sidebar is visible - * - * @default false - */ - scrollLock?: boolean; - /** - * Whether to return to original scroll position when sidebar is hidden, automatically occurs with transition: scale - * - * @default false - */ - returnScroll?: boolean; - /** - * When sidebar is initialized without the proper HTML, using this option will defer creation of DOM to use requestAnimationFrame. - * - * @default false - */ - delaySetup?: boolean; - - // endregion - - // region Animation - - /** - * Named transition to use when animating sidebar. Defaults to 'auto' which selects transition from defaultTransition based on direction. - * - * @default 'auto' - */ - transition?: string; - /** - * Named transition to use when animating when detecting mobile device. Defaults to 'auto' which selects transition from defaultTransition based on direction. - * - * @default 'auto' - */ - mobileTransition?: string; - /** - * Default transitions for each direction and screen size, used with transition: auto - */ - defaultTransition?: { - computer?: { - /** - * @default 'uncover' - */ - left?: string; - /** - * @default 'uncover' - */ - right?: string; - /** - * @default 'overlay' - */ - top?: string; - /** - * @default 'overlay' - */ - bottom?: string; - }; - mobile?: { - /** - * @default 'uncover' - */ - left?: string; - /** - * @default 'uncover' - */ - right?: string; - /** - * @default 'overlay' - */ - top?: string; - /** - * @default 'overlay' - */ - bottom?: string; - }; - }; - /** - * Whether Javascript animations should be used. Defaults to false. Setting to auto will use legacy animations only for browsers that do not support CSS transforms - * - * @default false - */ - useLegacy?: 'auto' | boolean; - /** - * Duration of sidebar animation when using legacy Javascript animation - * - * @default 500 - */ - duration?: number; - /** - * Easing to use when using legacy Javascript animation - * - * @default 'easeInOutQuint' - */ - easing?: string; - - // endregion - - // region Callbacks - - /** - * Is called when a sidebar begins animating in. - */ - onVisible?(this: JQuery): void; - /** - * Is called when a sidebar has finished animating in. - */ - onShow?(this: JQuery): void; - /** - * Is called when a sidebar begins to hide or show - */ - onChange?(this: JQuery): void; - /** - * Is called before a sidebar begins to animate out. - */ - onHide?(this: JQuery): void; - /** - * Is called after a sidebar has finished animating out. - */ - onHidden?(this: JQuery): void; - - // endregion - - // region DOM Settings - - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'animating' - */ - animating?: string; - /** - * @default 'dimmed' - */ - dimmed?: string; - /** - * @default 'ios' - */ - ios?: string; - /** - * @default 'pushable' - */ - pushable?: string; - /** - * @default 'pushed' - */ - pushed?: string; - /** - * @default 'right' - */ - right?: string; - /** - * @default 'top' - */ - top?: string; - /** - * @default 'left' - */ - left?: string; - /** - * @default 'bottom' - */ - bottom?: string; - /** - * @default 'visible' - */ - visible?: string; - }; - regExp?: { - /** - * @default /(iPad|iPhone|iPod)/g - */ - ios?: RegExp; - /** - * @default /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/g - */ - mobile?: RegExp; - }; - selector?: { - /** - * @default '.fixed' - */ - fixed?: string; - /** - * @default 'script, link, style, .ui.modal, .ui.dimmer, .ui.nag, .ui.fixed' - */ - omitted?: string; - /** - * @default '.pusher' - */ - pusher?: string; - /** - * @default '.ui.sidebar' - */ - sidebar?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The method you called is not defined.' - */ - method?: string; - /** - * @default 'Had to add pusher element. For optimal performance make sure body content is inside a pusher element' - */ - pusher?: string; - /** - * @default 'Had to move sidebar. For optimal performance make sure sidebar and pusher are direct children of your body tag' - */ - movedSidebar?: string; - /** - * @default 'The overlay setting is no longer supported, use animation: overlay' - */ - overlay?: string; - /** - * @default 'There were no elements that matched the specified selector' - */ - notFound?: string; - }; - - // endregion - } - - // endregion - - // region Sticky - - interface Sticky { - settings: StickySettings; - - /** - * recalculates offsets - */ - (behavior: 'refresh'): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): StickySettings[K]; - (behavior: 'setting', name: K, value: StickySettings[K]): JQuery; - (behavior: 'setting', value: StickySettings): JQuery; - (settings?: StickySettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/sticky.html#/settings} - */ - interface StickySettings extends ComponentSettings { - // region Sticky Settings - - /** - * Whether element should be "pushed" by the viewport, attaching to the bottom of the screen when scrolling up - * - * @default false - */ - pushing?: boolean; - /** - * Sticky container height will only be set if the difference between heights of container and context is larger than this jitter value. - * - * @default 5 - */ - jitter?: number; - /** - * Whether any change in context DOM should automatically refresh cached sticky positions - * - * @default false - */ - observeChanges?: boolean; - /** - * Context which sticky element should stick to - * - * @default false - */ - context?: false | Selector; - /** - * Context which sticky should attach onscroll events. - * - * @default 'window' - */ - scrollContext?: Selector; - /** - * Offset in pixels from the top of the screen when fixing element to viewport - * - * @default 0 - */ - offset?: number; - /** - * Offset in pixels from the bottom of the screen when fixing element to viewport - * - * @default 0 - */ - bottomOffset?: number; - - // endregion - - // region Callbacks - - /** - * Callback when element is repositioned from layout change - */ - onReposition?(this: JQuery): void; - /** - * Callback when requestAnimationFrame fires from scroll handler. - */ - onScroll?(this: JQuery): void; - /** - * Callback when element is fixed to page - */ - onStick?(this: JQuery): void; - /** - * Callback when element is unfixed from page - */ - onUnstick?(this: JQuery): void; - /** - * Callback when element is bound to top of parent container - */ - onTop?(this: JQuery): void; - /** - * Callback when element is bound to bottom of parent container - */ - onBottom?(this: JQuery): void; - - // endregion - - // region DOM Settings - - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'bound' - */ - bound?: string; - /** - * @default 'fixed' - */ - fixed?: string; - /** - * @default 'native' - */ - supported?: string; - /** - * @default 'top' - */ - top?: string; - /** - * @default 'bottom' - */ - bottom?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'Sticky element must be inside a relative container' - */ - container?: string; - /** - * @default 'Element is hidden, you must call refresh after element becomes visible' - */ - visible?: string; - /** - * @default 'The method you called is not defined.' - */ - method?: string; - /** - * @default 'Context specified does not exist' - */ - invalidContext?: string; - /** - * @default 'Sticky element is larger than its container, cannot create sticky.' - */ - elementSize?: string; - }; - - // endregion - } - - // endregion - - // region Tab - - interface Tab { - settings: TabSettings; - - // Documentation says this exists but it does not. - // /** - // * Attaches tab action to given selector. Default event if none specified is toggle - // */ - // (behavior: 'attach events', selector: Selector, event?: string): JQuery; - /** - * Changes tab to path - */ - (behavior: 'change tab', path: string): JQuery; - /** - * Sets current path to state - */ - (behavior: 'set state', path: string): JQuery; - /** - * Returns current path - */ - (behavior: 'get path'): string; - /** - * Returns whether tab exists - */ - (behavior: 'is tab'): boolean; - /** - * Returns cached HTML for path - */ - (behavior: 'cache read', path: string): string | false; - /** - * Sets cached HTML for path - */ - (behavior: 'cache add', path: string, html: string): JQuery; - /** - * Removes cached HTML for path - */ - (behavior: 'cache remove', path: string): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): TabSettings[K]; - (behavior: 'setting', name: K, value: TabSettings[K]): JQuery; - (behavior: 'setting', value: TabSettings): JQuery; - (settings?: TabSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/tab.html#/settings} - */ - interface TabSettings extends ComponentSettings { - // region Tab Settings - - /** - * Whether tab should load remote content as same url as history - * - * @default false - */ - auto?: boolean; - /** - * When set to siblings will only deactivate elements that are DOM siblings with the activated element. - * When set to all the component will deactivate all other elements initialized at the same time. - * - * @default 'siblings' - * @since 2.2 - */ - deactivate?: 'siblings' | 'all'; - /** - * Whether to record history events for tab changes - * - * @default false - */ - history?: boolean; - /** - * Do not load content remotely on first tab load. Useful when open tab is rendered on server. - * - * @default false - */ - ignoreFirstLoad?: boolean; - /** - * Whether inline scripts in tab HTML should be parsed on tab load. - * Defaults to once, parsing only on first load. - * Can also be set to true or false to always parse or never parse inline scripts. - * - * @default 'once' - */ - evaluateScripts?: 'once' | boolean; - /** - * Tab should reload content every time it is opened - */ - alwaysRefresh?: boolean; - /** - * Can be set to either response, DOM or html. - * Using DOM will cache the a clone of the DOM tree, preserving all events as they existed on render. - * response will cache the original response on load, this way callbacks always receive the same content. - * Using html will cache the resulting html after all callbacks, making sure any changes to content are preserved. - * - * @default 'response' - */ - cacheType?: 'response' | 'DOM' | 'html'; - /** - * Tab should cache content after loading locally to avoid server trip on second load - * - * @default true - */ - cache?: boolean; - /** - * Settings object for $.api call - * - * @default false - * @see {@link http://semantic-ui.com/behaviors/api.html} - */ - apiSettings?: ApiSettings; - /** - * Can be set to hash or state. - * Hash will use an in-page link to create history events. - * State will use DOM History and load pages from server on refresh. - * - * @default 'hash' - * @see {@link https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history} - */ - historyType?: 'hash' | 'state'; - /** - * When using historyType state you must specify the base URL for all internal links. - * - * @default false - */ - path?: false | string; - /** - * Tabs are limited to those found inside this context - * - * @default false - */ - context?: false | Selector; - /** - * If enabled limits tabs to children of passed context - * - * @default false - */ - childrenOnly?: boolean; - /** - * Maximum amount of nested tabs allowed (avoids recursion) - * - * @default 25 - */ - maxDepth?: number; - /** - * When enabled only calls remote endpoint for tab data on first load and leaves the DOM undisturbed afterwards. - * - * @default false - * @since 2.2.8 - */ - loadOnce?: boolean; - - // endregion - - // region Callbacks - - /** - * Callback only the first time a tab is loaded - */ - onFirstLoad?(this: JQuery, tabPath: string, parameterArray: any[], historyEvent: any): void; - /** - * Callback every time a tab is loaded - */ - onLoad?(this: JQuery, tabPath: string, parameterArray: any[], historyEvent: any): void; - /** - * Called when a tab begins loading remote content - */ - onRequest?(this: JQuery, tabPath: string): void; - /** - * Called after a tab becomes visible - */ - onVisible?(this: JQuery, tabPath: string): void; - - // endregion - - // region DOM Settings - - /** - * Functions used to return content - */ - templates?: { - /** - * returns page title - */ - determineTitle?(tabArray: any[]): string; - }; - /** - * Selectors used by module - */ - selector?: { - /** - * @default '.ui.tab' - */ - tabs?: string; - /** - * @default '.ui:not(.menu)' - */ - parent?: string; - }; - /** - * DOM metadata used by module - */ - metadata?: { - /** - * @default 'tab' - */ - tab?: string; - /** - * @default 'loaded' - */ - loaded?: string; - /** - * @default 'promise' - */ - promise?: string; - }; - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'loading' - */ - loading?: string; - /** - * @default 'active' - */ - active?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'You attempted to load content without API module' - */ - api?: string; - /** - * @default 'The method you called is not defined' - */ - method?: string; - /** - * @default 'Activated tab cannot be found for this context.' - */ - missingTab?: string; - /** - * @default 'The tab you specified is missing a content url.' - */ - noContent?: string; - /** - * @default 'History enabled, but no path was specified' - */ - path?: string; - /** - * @default 'Max recursive depth reached' - */ - recursion?: string; - /** - * @default 'The state library has not been initialized' - */ - state?: string; - }; - - // endregion - } - - // endregion - - // region Transition - - interface Transition { - settings: TransitionSettings; - - /** - * Stop current animation and preserve queue - */ - (behavior: 'stop'): JQuery; - /** - * Stop current animation and queued animations - */ - (behavior: 'stop all'): JQuery; - /** - * Clears all queued animations - */ - (behavior: 'clear queue'): JQuery; - /** - * Stop current animation and show element - */ - (behavior: 'show'): JQuery; - /** - * Stop current animation and hide element - */ - (behavior: 'hide'): JQuery; - /** - * Toggles between hide and show - */ - (behavior: 'toggle'): JQuery; - /** - * Forces reflow using a more expensive but stable method - */ - (behavior: 'force repaint'): JQuery; - /** - * Triggers reflow on element - */ - (behavior: 'repaint'): JQuery; - /** - * Resets all conditions changes during transition - */ - (behavior: 'reset'): JQuery; - /** - * Enables animation looping - */ - (behavior: 'looping'): JQuery; - /** - * Removes looping state from element - */ - (behavior: 'remove looping'): JQuery; - /** - * Adds disabled state (stops ability to animate) - */ - (behavior: 'disable'): JQuery; - /** - * Removes disabled state - */ - (behavior: 'enable'): JQuery; - /** - * Modifies element animation duration - */ - (behavior: 'set duration', duration: number): JQuery; - /** - * Saves all class names and styles to cache to be retrieved after animation - */ - (behavior: 'save conditions'): JQuery; - /** - * Adds back cached names and styles to element - */ - (behavior: 'restore conditions'): JQuery; - /** - * Returns vendor prefixed animation property for animationname - */ - (behavior: 'get animation name'): string; - /** - * Returns vendor prefixed animation property for animationend - */ - (behavior: 'get animation event'): string; - /** - * Returns whether element is currently visible - */ - (behavior: 'is visible'): boolean; - /** - * Returns whether transition is currently occurring - */ - (behavior: 'is animating'): boolean; - /** - * Returns whether animation looping is set - */ - (behavior: 'is looping'): boolean; - /** - * Returns whether animations are supported - */ - (behavior: 'is supported'): boolean; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): TransitionSettings[K]; - (behavior: 'setting', name: K, value: TransitionSettings[K]): JQuery; - (behavior: 'setting', value: TransitionSettings): JQuery; - (transition: string): JQuery; - (settings?: TransitionSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/modules/transition.html#/settings} - */ - interface TransitionSettings extends ComponentSettings { - // region Transition Settings - - /** - * Named animation event to used. Must be defined in CSS. - * - * @default 'fade' - */ - animation?: string; - /** - * Interval in MS between each elements transition - * - * @default 0 - */ - interval?: number; - /** - * When an interval is specified, sets order of animations. auto reverses only animations that are hiding. - * - * @default 'auto' - */ - reverse?: 'auto' | boolean; - /** - * Specify the final display type (block, inline-block etc) so that it doesn't have to be calculated. - * - * @default false - */ - displayType?: false | string; - /** - * Duration of the CSS transition animation - * - * @default 500 - */ - duration?: number; - /** - * If enabled a timeout will be added to ensure animationend callback occurs even if element is hidden - */ - useFailSafe?: boolean; - /** - * If enabled will allow same animation to be queued while it is already occurring - */ - allowRepeats?: boolean; - /** - * Whether to automatically queue animation if another is occurring - */ - queue?: boolean; - - // endregion - - // region Callbacks - - /** - * Callback on each transition that changes visibility to shown - */ - onShow?(this: JQuery): void; - /** - * Callback on each transition that changes visibility to hidden - */ - onHide?(this: JQuery): void; - /** - * Callback on animation start, useful for queued animations - */ - onStart?(this: JQuery): void; - /** - * Callback on each transition complete - */ - onComplete?(this: JQuery): void; - - // endregion - - // region DOM Settings - - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'animating' - */ - animating?: string; - /** - * @default 'disabled' - */ - disabled?: string; - /** - * @default 'hidden' - */ - hidden?: string; - /** - * @default 'in' - */ - inward?: string; - /** - * @default 'loading' - */ - loading?: string; - /** - * @default 'looping' - */ - looping?: string; - /** - * @default 'out' - */ - outward?: string; - /** - * @default 'transition' - */ - transition?: string; - /** - * @default 'visible' - */ - visible?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'There is no CSS animation matching the one you specified.' - */ - noAnimation?: string; - /** - * @default 'The method you called is not defined' - */ - method?: string; - }; - - // endregion - } - - // endregion - - // endregion - - // region Behaviors - - // region API - - interface Api { - settings: ApiSettings; - - /** - * Execute query using existing API settings - */ - (behavior: 'query'): JQuery; - /** - * Adds data to existing templated url and returns full url string - */ - (behavior: 'add url data', url: string, data: any): string; - /** - * Gets promise for current API request - */ - (behavior: 'get request'): JQueryDeferred | false; - /** - * Aborts current API request - */ - (behavior: 'abort'): JQuery; - /** - * Removes loading and error state from element - */ - (behavior: 'reset'): JQuery; - /** - * Returns whether last request was cancelled - */ - (behavior: 'was cancelled'): boolean; - /** - * Returns whether last request was failure - */ - (behavior: 'was failure'): boolean; - /** - * Returns whether last request was successful - */ - (behavior: 'was successful'): boolean; - /** - * Returns whether last request was completed - */ - (behavior: 'was complete'): boolean; - /** - * Returns whether element is disabled - */ - (behavior: 'is disabled'): boolean; - /** - * Returns whether element response is mocked - */ - (behavior: 'is mocked'): boolean; - /** - * Returns whether element is loading - */ - (behavior: 'is loading'): boolean; - /** - * Sets loading state to element - */ - (behavior: 'set loading'): JQuery; - /** - * Sets error state to element - */ - (behavior: 'set error'): JQuery; - /** - * Removes loading state to element - */ - (behavior: 'remove loading'): JQuery; - /** - * Removes error state to element - */ - (behavior: 'remove error'): JQuery; - /** - * Gets event that API request will occur on - */ - (behavior: 'get event'): string; - /** - * Returns encodeURIComponent value only if value passed is not already encoded - */ - (behavior: 'get url encoded value', value: any): string; - /** - * Reads a locally cached response for a URL - */ - (behavior: 'read cached response', url: string): any; - /** - * Writes a cached response for a URL - */ - (behavior: 'write cached response', url: string, response: any): JQuery; - /** - * Creates new cache, removing all locally cached URLs - */ - (behavior: 'create cache'): JQuery; - /** - * Removes API settings from the page and all events - */ - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): ApiSettings[K]; - (behavior: 'setting', name: K, value: ApiSettings[K]): JQuery; - (behavior: 'setting', value: ApiSettings): JQuery; - (settings?: ApiSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/behaviors/api.html#/settings} - */ - interface ApiSettings extends ComponentSettings { - // region Behavior - - /** - * When API event should occur - * - * @default 'auto' - */ - on?: string; - /** - * Can be set to 'local' to cache successful returned AJAX responses when using a JSON API. - * This helps avoid server round trips when API endpoints will return the same results when accessed repeatedly. - * Setting to false, will add cache busting parameters to the URL. - * - * @default true - */ - cache?: 'local' | boolean; - /** - * UI state will be applied to this element, defaults to triggering element. - */ - stateContext?: Selector; - /** - * Whether to encode parameters with encodeURIComponent before adding into url string - * - * @default true - */ - encodeParameters?: boolean; - /** - * Whether to automatically include default data like {value} and {text} - * - * @default true - */ - defaultData?: boolean; - /** - * Whether to serialize closest form and include in request - * - * @default false - */ - serializeForm?: boolean; - /** - * How long to wait when a request is made before triggering request, useful for rate limiting oninput - * - * @default 0 - */ - throttle?: number; - /** - * When set to false will not delay the first request made, when no others are queued - * - * @default true - */ - throttleFirstRequest?: boolean; - /** - * Whether an API request can occur while another request is still pending - * - * @default false - */ - interruptRequests?: boolean; - /** - * Minimum duration to show loading indication - * - * @default 0 - */ - loadingDuration?: number; - /** - * The default auto will automatically remove error state after error duration, unless the element is a form - * - * @default 'auto' - */ - hideError?: 'auto' | boolean; - /** - * Setting to true, will not remove error. - * Setting to a duration in milliseconds to show error state after request error. - * - * @default 2000 - */ - errorDuration?: true | number; - - // endregion - - // region Request Settings - - /** - * Named API action for query, originally specified in $.fn.settings.api - */ - action?: string | false; - /** - * Templated URL for query, will override specified action - */ - url?: string | false; - /** - * Variables to use for replacement - */ - urlData?: any | false; - /** - * Can be set to a Javascript object which will be returned automatically instead of requesting JSON from server - */ - response?: any | false; - /** - * When specified, this function can be used to retrieve content from a server and return it asynchronously instead of a standard AJAX call. - * The callback function should return the server response. - * - * @default false - */ - responseAsync?: ((settings: ApiSettings, callback: (response: any) => void) => void) | false; - /** - * @see response - */ - mockResponse?: any | false; - /** - * @see responseAsync - */ - mockResponseAsync?: ((settings: ApiSettings, callback: (response: any) => void) => void) | false; - /** - * Method for transmitting request to server - */ - method?: 'post' | 'get'; - /** - * Expected data type of response - */ - dataType?: 'xml' | 'json' | 'jsonp' | 'script' | 'html' | 'text'; - /** - * POST/GET Data to Send with Request - */ - data?: any; - - // endregion - - // region Callbacks - - /** - * Allows modifying settings before request, or cancelling request - */ - beforeSend?(settings: ApiSettings): any; - /** - * Allows modifying XHR object for request - */ - beforeXHR?(xhrObject: JQueryXHR): any; - /** - * Callback that occurs when request is made. Receives both the API success promise and the XHR request promise. - */ - onRequest?(promise: JQueryDeferred, xhr: JQueryXHR): void; - /** - * Allows modifying the server's response before parsed by other callbacks to determine API event success - */ - onResponse?(response: any): void; - /** - * Determines whether completed JSON response should be treated as successful - * - * @see {@link http://semantic-ui.com/behaviors/api.html#determining-json-success} - */ - successTest?(response: any): boolean; - /** - * Callback after successful response, JSON response must pass successTest - */ - onSuccess?(response: any, element: JQuery, xhr: JQueryXHR): void; - /** - * Callback on request complete regardless of conditions - */ - onComplete?(response: any, element: JQuery, xhr: JQueryXHR): void; - /** - * Callback on failed response, or JSON response that fails successTest - */ - onFailure?(response: any, element: JQuery): void; - /** - * Callback on server error from returned status code, or XHR failure. - */ - onError?(errorMessage: string, element: JQuery, xhr: JQueryXHR): void; - /** - * Callback on abort caused by user clicking a link or manually cancelling request. - */ - onAbort?(errorMessage: string, element: JQuery, xhr: JQueryXHR): void; - - // endregion - - // region DOM Settings - - /** - * Regular expressions used for template matching - */ - regExp?: { - /** - * @default /\{\$*[A-z0-9]+\}/g - */ - required?: RegExp; - /** - * @default /\{\/\$*[A-z0-9]+\}/g - */ - optional?: RegExp; - }; - /** - * Selectors used to find parts of a module - */ - selector?: { - /** - * @default '.disabled' - */ - disabled?: string; - /** - * @default 'form' - */ - form?: string; - }; - /** - * Class names used to determine element state - */ - className?: { - /** - * @default 'loading' - */ - loading?: string; - /** - * @default 'error' - */ - error?: string; - }; - /** - * Metadata used to store XHR and response promise - */ - metadata?: { - /** - * @default 'action' - */ - action?: string; - /** - * @default 'url' - */ - url?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The before send function has aborted the request' - */ - beforeSend?: string; - /** - * @default 'There was an error with your request' - */ - error?: string; - /** - * @default 'API Request Aborted. Exit conditions met' - */ - exitConditions?: string; - /** - * @default 'JSON could not be parsed during error handling' - */ - JSONParse?: string; - /** - * @default 'You are using legacy API success callback names' - */ - legacyParameters?: string; - /** - * @default 'API action used but no url was defined' - */ - missingAction?: string; - /** - * @default 'Required dependency jquery-serialize-object missing, using basic serialize' - */ - missingSerialize?: string; - /** - * @default 'No URL specified for API event' - */ - missingURL?: string; - /** - * @default 'The beforeSend callback must return a settings object, beforeSend ignored.' - */ - noReturnedValue?: string; - /** - * @default 'There was an error parsing your request' - */ - parseError?: string; - /** - * @default 'Missing a required URL parameter: ' - */ - requiredParameter?: string; - /** - * @default 'Server gave an error: ' - */ - statusMessage?: string; - /** - * @default 'Your request timed out' - */ - timeout?: string; - }; - - // endregion - } - - // endregion - - // region Form Validation - - interface Form { - settings: FormSettings; - - /** - * Submits selected form - */ - (behavior: 'submit'): JQuery; - /** - * Returns true/false whether a form passes its validation rules - */ - (behavior: 'is valid'): boolean; - /** - * Validates form and calls onSuccess or onFailure - */ - (behavior: 'validate form'): JQuery; - /** - * gets browser property change event - */ - (behavior: 'get change event'): string; - /** - * Returns element with matching name, id, or data-validate metadata to ID - */ - (behavior: 'get field', id: string): JQuery; - /** - * Returns value of element with id - */ - (behavior: 'get value', id: string): any; - /** - * Returns object of element values that match array of ids. If no IDS are passed will return all fields - */ - (behavior: 'get values', ids?: string[]): any; - /** - * Sets value of element with id - */ - (behavior: 'set value', id: string): JQuery; - /** - * Sets key/value pairs from passed values object to matching ids - */ - (behavior: 'set values', values: any): JQuery; - /** - * Returns validation rules for a given jQuery-referenced input field - */ - (behavior: 'get validation', element: JQuery): any; - /** - * Returns whether a field exists - */ - (behavior: 'has field', identifier: string): boolean; - /** - * Adds errors to form, given an array errors - */ - (behavior: 'add errors', errors: string[]): JQuery; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): FormSettings[K]; - (behavior: 'setting', name: K, value: FormSettings[K]): JQuery; - (behavior: 'setting', value: FormSettings): JQuery; - (settings?: FormSettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/behaviors/form.html#/settings} - */ - interface FormSettings extends ComponentSettings { - // region Form Settings - - /** - * Adds keyboard shortcuts for enter and escape keys to submit form and blur fields respectively - * - * @default true - */ - keyboardShortcuts?: boolean; - /** - * Event used to trigger validation. Can be either submit, blur or change. - * - * @default 'submit' - */ - on?: 'submit' | 'blur' | 'change'; - /** - * If set to true will revalidate fields with errors on input change - * - * @default true - */ - revalidate?: boolean; - /** - * Delay from last typed letter to validate a field when using on: change or when revalidating a field. - * - * @default true - */ - delay?: boolean; - /** - * Adds inline error on field validation error - * - * @default false - */ - inline?: boolean; - /** - * Named transition to use when animating validation errors. Fade and slide down are available without including ui transitions - * - * @default 'scale' - * @see {@link http://semantic-ui.com/modules/transition.html} - */ - transition?: string; - /** - * Animation speed for inline prompt - * - * @default 150 - */ - duration?: number; - fields?: { - [name: string]: string | string[] | Field; - }; - - // endregion - - // region Form Prompts - - text?: { - /** - * @default 'Please enter a valid value' - */ - unspecifiedRule?: string; - /** - * @default 'This field' - */ - unspecifiedField?: string; - }; - prompt?: { - /** - * @default '{name} must have a value' - */ - empty?: string; - /** - * @default '{name} must be checked' - */ - checked?: string; - /** - * @default '{name} must be a valid e-mail' - */ - email?: string; - /** - * @default '{name} must be a valid url' - */ - url?: string; - /** - * @default '{name} is not formatted correctly' - */ - regExp?: string; - /** - * @default '{name} must be an integer' - */ - integer?: string; - /** - * @default '{name} must be a decimal number' - */ - decimal?: string; - /** - * @default '{name} must be set to a number' - */ - number?: string; - /** - * @default '{name} must be \'{ruleValue}\'' - */ - is?: string; - /** - * @default '{name} must be exactly \'{ruleValue}\'' - */ - isExactly?: string; - /** - * @default '{name} cannot be set to \'{ruleValue}\'' - */ - not?: string; - /** - * @default '{name} cannot be set to exactly \'{ruleValue}\'' - */ - notExactly?: string; - /** - * @default '{name} cannot contain \'{ruleValue}\'' - */ - contain?: string; - /** - * @default '{name} cannot contain exactly \'{ruleValue}\'' - */ - containExactly?: string; - /** - * @default '{name} must contain \'{ruleValue}\'' - */ - doesntContain?: string; - /** - * @default '{name} must contain exactly \'{ruleValue}\'' - */ - doesntContainExactly?: string; - /** - * @default '{name} must be at least {ruleValue} characters' - */ - minLength?: string; - /** - * @default '{name} must be at least {ruleValue} characters' - */ - length?: string; - /** - * @default '{name} must be exactly {ruleValue} characters' - */ - exactLength?: string; - /** - * @default '{name} cannot be longer than {ruleValue} characters' - */ - maxLength?: string; - /** - * @default '{name} must match {ruleValue} field' - */ - match?: string; - /** - * @default '{name} must have a different value than {ruleValue} field' - */ - different?: string; - /** - * @default '{name} must be a valid credit card number' - */ - creditCard?: string; - /** - * @default '{name} must have at least {ruleValue} choices' - */ - minCount?: string; - /** - * @default '{name} must have exactly {ruleValue} choices' - */ - exactCount?: string; - /** - * @default '{name} must have {ruleValue} or less choices' - */ - maxCount?: string; - }; - - // endregion - - // region Callbacks - - /** - * Callback on each valid field - */ - onValid?(this: JQuery): void; - /** - * Callback on each invalid field - */ - onInvalid?(this: JQuery): void; - /** - * Callback if a form is all valid - */ - onSuccess?(this: JQuery, event: JQueryEventObject, fields: any): void; - /** - * Callback if any form field is invalid - */ - onFailure?(this: JQuery, formErrors: string[], fields: any): void; - - // endregion - - // region Templates - - templates?: { - error?(errors: string[]): JQuery; - prompt?(errors: string[]): JQuery; - }; - - // endregion - - // region Rules - - rules?: { - [name: string]: (...args: any[]) => boolean; - }; - - // endregion - - // region DOM Settings - - /** - * Selectors used to match functionality to DOM - */ - selector?: { - /** - * @default '.error.message' - */ - message?: string; - /** - * @default 'input, textarea, select' - */ - field?: string; - /** - * @default '.field' - */ - group?: string; - /** - * @default 'input' - */ - input?: string; - /** - * @default '.prompt' - */ - prompt?: string; - /** - * @default '.submit' - */ - submit?: string; - }; - /** - * HTML5 metadata attributes - */ - metadata?: { - /** - * @default 'validate' - */ - validate?: string; - }; - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'active' - */ - active?: string; - /** - * @default 'default' - */ - placeholder?: string; - /** - * @default 'disabled' - */ - disabled?: string; - /** - * @default 'visible' - */ - visible?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The method you called is not defined.' - */ - method?: string; - }; - - // endregion - } - - interface Field { - identifier: string; - rules: Rule[]; - } - - interface Rule { - type: string; - prompt: string; - } - - // endregion - - // region Visibility - - interface Visibility { - settings: VisibilitySettings; - - /** - * Disable callbacks temporarily. This is useful if you need to adjust scroll position and do not want to trigger callbacks during the position change. - */ - (behavior: 'disable callbacks'): JQuery; - /** - * Re-enable callbacks - */ - (behavior: 'enable callbacks'): JQuery; - /** - * Returns whether element is on screen - */ - (behavior: 'is on screen'): boolean; - /** - * Returns whether element is off screen - */ - (behavior: 'is off screen'): boolean; - /** - * Returns number of pixels passed in current element from top of element - */ - (behavior: 'get pixels passed'): number; - /** - * Returns element calculations as object - */ - (behavior: 'get element calculations'): ElementCalculations; - /** - * Returns screen calculations as object - */ - (behavior: 'get screen calculations'): ScreenCalculations; - /** - * Returns screen size as object - */ - (behavior: 'get screen size'): ScreenSize; - (behavior: 'destroy'): JQuery; - (behavior: 'setting', name: K, value?: undefined): VisibilitySettings[K]; - (behavior: 'setting', name: K, value: VisibilitySettings[K]): JQuery; - (behavior: 'setting', value: VisibilitySettings): JQuery; - (settings?: VisibilitySettings): JQuery; - } - - /** - * @see {@link http://semantic-ui.com/behaviors/visibility.html#/settings} - */ - interface VisibilitySettings extends ComponentSettings { - // region Functionality - - /** - * When set to false a callback will occur each time an element passes the threshold for a condition. - * - * @default true - */ - once?: boolean; - /** - * When set to true a callback will occur anytime an element passes a condition not just immediately after the threshold is met. - * - * @default false - */ - continuous?: boolean; - /** - * Set to image to load images when on screen. Set to fixed to add class name fixed when passed. - * - * @default false - */ - type?: false | 'image' | 'fixed'; - /** - * Whether visibility conditions should be checked immediately on init - * - * @default true - */ - initialCheck?: boolean; - /** - * The scroll context visibility should use. - * - * @default 'window' - */ - context?: Selector; - /** - * Whether visibility conditions should be checked on window load. This ensures that after images load content positions will be updated correctly. - * - * @default true - */ - refreshOnLoad?: boolean; - /** - * Whether visibility conditions should be checked on window resize. Useful when content resizes causes continuous changes in position - * - * @default true - */ - refreshOnResize?: boolean; - /** - * Whether visibility conditions should be checked on calls to refresh. - * These calls can be triggered from either resize, load or manually calling $('.foo').visibility('refresh') - * - * @default true - */ - checkOnRefresh?: boolean; - /** - * Specify a z-index when using type: 'fixed'. - * - * @default 1 - * @since 2.2 - */ - zIndex?: number; - /** - * Value that context scrollTop should be adjusted in pixels. Useful for making content appear below content fixed to the page. - * - * @default 0 - */ - offset?: number; - /** - * Whether element calculations should include its margin - * - * @default false - */ - includeMargin?: boolean; - /** - * When set to an integer, scroll position will be debounced using this ms value. false will debounce with requestAnimationFrame. - * - * @default false - */ - throttle?: false | number; - /** - * Whether to automatically refresh content when changes are made to the element's DOM subtree - * - * @default true - */ - observeChanges?: boolean; - /** - * When using type: image allows you to specify transition when showing a loaded image - * - * @default false - */ - transition?: false | string; - /** - * When using type: image allows you to specify transition duration - * - * @default 1000 - */ - duration?: number; - - // endregion - - // region Visibility Callbacks - - /** - * Element's top edge has passed bottom of screen - */ - onTopVisible?(this: JQuery): void; - /** - * Element's top edge has passed top of the screen - */ - onTopPassed?(this: JQuery): void; - /** - * Element's bottom edge has passed bottom of screen - */ - onBottomVisible?(this: JQuery): void; - /** - * Any part of an element is visible on screen - */ - onPassing?(this: JQuery): void; - /** - * Element's bottom edge has passed top of screen - */ - onBottomPassed?(this: JQuery): void; - /** - * Element's top edge has not passed bottom of screen - */ - onTopVisibleReverse?(this: JQuery): void; - /** - * Element's top edge has not passed top of the screen - */ - onTopPassedReverse?(this: JQuery): void; - /** - * Element's bottom edge has not passed bottom of screen - */ - onBottomVisibleReverse?(this: JQuery): void; - /** - * Element's top has not passed top of screen but bottom has - */ - onPassingReverse?(this: JQuery): void; - /** - * Element's bottom edge has not passed top of screen - */ - onBottomPassedReverse?(this: JQuery): void; - onOnScreen?(this: JQuery): void; - onOffScreen?(this: JQuery): void; - - // endregion - - // region Image Callbacks - - /** - * Occurs after an image has completed loading - * - * @since 2.2 - */ - onLoad?(this: JQuery): void; - /** - * Occurs after all img initialized at the same time have loaded. - * - * @since 2.2 - */ - onAllLoaded?(this: JQuery): void; - - // endregion - - // region Fixed Callbacks - - /** - * Occurs after element has been assigned position fixed - * - * @since 2.2 - */ - onFixed?(this: JQuery): void; - /** - * Occurs after element has been removed from fixed position - * - * @since 2.2 - */ - onUnfixed?(this: JQuery): void; - - // endregion - - // region Utility Callbacks - - /** - * Occurs each time an elements calculations are updated - */ - onUpdate?(this: JQuery, calculations: ElementCalculations): void; - /** - * Occurs whenever element's visibility is refreshed - */ - onRefresh?(this: JQuery): void; - - // endregion - - // region DOM Settings - - /** - * Class names used to attach style to state - */ - className?: { - /** - * @default 'fixed' - */ - fixed?: string; - }; - - // endregion - - // region Debug Settings - - error?: { - /** - * @default 'The method you called is not defined.' - */ - method?: string; - }; - - // endregion - } - - interface ElementPosition { - fits: boolean; - offset: JQueryCoordinates; - width: number; - height: number; - } - - interface ElementCalculations extends ElementPosition { - margin?: { - top: number; - bottom: number; - }; - top: number; - bottom: number; - - topVisible: boolean; - topPassed: boolean; - bottomVisible: boolean; - bottomPassed: boolean; - pixelsPassed: number; - percentagePassed: number; - - onScreen: boolean; - passing: boolean; - offScreen: boolean; - } - - interface ScreenCalculations { - top: number; - bottom: number; - } - - interface ScreenSize { - height: number; - } - - // endregion - - // endregion -} +/// + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// +/// +/// diff --git a/types/semantic-ui/semantic-ui-tests.ts b/types/semantic-ui/semantic-ui-tests.ts index ca5951d516..843604940d 100644 --- a/types/semantic-ui/semantic-ui-tests.ts +++ b/types/semantic-ui/semantic-ui-tests.ts @@ -1,453 +1,51 @@ -function test_site() { - const selector = '.ui.site'; - $(selector).site('destroy') === $(); - $(selector).site('setting', 'debug', undefined) === false; - $(selector).site('setting', 'debug') === false; - $(selector).site('setting', 'debug', true) === $(); - $(selector).site('setting', { - namespace: 'namespace', - name: 'name', - silent: false, - debug: true, - performance: true, - verbose: true - }) === $(); - $(selector).site({ - modules: [ - 'accordion', - 'api', - 'checkbox', - 'dimmer', - 'dropdown', - 'embed', - 'form', - 'modal', - 'nag', - 'popup', - 'rating', - 'shape', - 'sidebar', - 'state', - 'sticky', - 'tab', - 'transition', - 'visit', - 'visibility' - ], - siteNamespace: 'site', - namespaceStub: { - cache: {}, - config: {}, - sections: {}, - section: {}, - utilities: {} - } - }) === $(); - $(selector).site() === $(); -} +function test_static() { + $.site.settings.debug = true; + $.fn.site.settings.debug = true; -function test_accordion() { - const selector = '.ui.accordion'; - $(selector).accordion('refresh'); - $(selector).accordion('open', 0); - $(selector).accordion('close others'); - $(selector).accordion('close', 0); - $(selector).accordion('toggle', 0); - $(selector).accordion('destroy'); - $(selector).accordion('setting', 'exclusive', undefined) === true; - $(selector).accordion('setting', 'exclusive', true) === $(); - $(selector).accordion('setting', 'exclusive') === true; - $(selector).accordion({ - selector: { - trigger: '.title .icon' - } - }); - $(selector).accordion(); -} - -function test_checkbox() { - const selector = '.ui.checkbox'; - $(selector).checkbox({}); - $(selector).checkbox(); -} - -function test_dimmer_settings() { - $.fn.dimmer.settings.namespace = 'namespace'; - $.fn.dimmer.settings.name = 'name'; - $.fn.dimmer.settings.silent = false; + $.fn.accordion.settings.debug = true; + $.fn.checkbox.settings.debug = true; $.fn.dimmer.settings.debug = true; - $.fn.dimmer.settings.performance = true; - $.fn.dimmer.settings.verbose = true; -} - -function test_dimmer() { - const selector = '.ui.dimmer'; - $(selector).dimmer('add content', $()) === $(); - $(selector).dimmer('show') === $(); - $(selector).dimmer('hide') === $(); - $(selector).dimmer('toggle') === $(); - $(selector).dimmer('set opacity', 1) === $(); - $(selector).dimmer('create') === $(); - $(selector).dimmer('get duration') === 10; - $(selector).dimmer('get dimmer') === $(); - $(selector).dimmer('has dimmer') === true; - $(selector).dimmer('is active') === true; - $(selector).dimmer('is animating') === true; - $(selector).dimmer('is dimmer') === true; - $(selector).dimmer('is dimmable') === true; - $(selector).dimmer('is disabled') === true; - $(selector).dimmer('is enabled') === true; - $(selector).dimmer('is page') === true; - $(selector).dimmer('is page dimmer') === true; - $(selector).dimmer('set active') === $(); - $(selector).dimmer('set dimmable') === $(); - $(selector).dimmer('set dimmed') === $(); - $(selector).dimmer('set page dimmer') === $(); - $(selector).dimmer('set disabled') === $(); - $(selector).dimmer('destroy') === $(); - $(selector).dimmer('setting', 'debug', undefined) === false; - $(selector).dimmer('setting', 'debug') === false; - $(selector).dimmer('setting', 'debug', true) === $(); - $(selector).dimmer('setting', { - namespace: 'namespace', - name: 'name', - silent: false, - debug: true, - performance: true, - verbose: true - }) === $(); - $(selector).dimmer({ - opacity: 1, - variation: 'variation', - dimmerName: 'dimmerName', - closable: true, - on: 'click', - useCSS: true, - duration: { - show: 200, - hide: 300 - }, - transition: 'fade', - onShow() { - this === $(); - }, - onHide() { - this === $(); - }, - onChange() { - this === $(); - }, - selector: { - dimmable: '.dimmable', - dimmer: '.dimmer', - content: '.content' - }, - template: { - dimmer() { - return $(); - } - }, - className: { - active: 'active', - dimmable: 'dimmable', - dimmed: 'dimmed', - disabled: 'disabled', - pageDimmer: 'pageDimmer', - hide: 'hide', - show: 'show', - transition: 'transition' - }, - error: { - method: 'method' - } - }) === $(); - $(selector).dimmer() === $(); -} - -function test_dropdown() { - const selector = '.ui.dropdown'; - $(selector).dropdown({}); - $(selector).dropdown(); -} - -function test_embed() { - const selector = '.ui.embed'; - $(selector).embed({}); - $(selector).embed(); -} - -function test_modal() { - const selector = '.ui.modal'; - $(selector).modal({}); - $(selector).modal(); -} - -function test_nag() { - const selector = '.ui.nag'; - $(selector).nag({}); -} - -function test_popup() { - const selector = '.ui.popup'; - $(selector).popup({ - html: '
Content
' - }); - $(selector).popup({ - html: $('
Content
') - }); - $(selector).popup(); -} - -function test_progress() { - const selector = '.ui.progress'; - $(selector).progress({}); - $(selector).progress(); -} - -function test_rating() { - const selector = '.ui.rating'; - $(selector).rating({}); - $(selector).rating(); -} - -function test_search() { - const selector = '.ui.search'; - $(selector).search({}); - $(selector).search(); -} - -function test_shape() { - const selector = '.ui.shape'; - $(selector).shape({}); - $(selector).shape(); -} - -function test_sidebar() { - const selector = '.ui.sidebar'; - $(selector).sidebar({}); - $(selector).sidebar(); -} - -function test_sticky() { - const selector = '.ui.sticky'; - $(selector).sticky({}); - $(selector).sticky(); -} - -function test_tab() { - const selector = '.ui.tab'; - $(selector).tab({}); - $(selector).tab(); -} - -function test_transition_settings() { - $.fn.transition.settings.namespace = 'namespace'; - $.fn.transition.settings.name = 'name'; - $.fn.transition.settings.silent = false; + $.fn.dropdown.settings.debug = true; + $.fn.embed.settings.debug = true; + $.fn.modal.settings.debug = true; + $.fn.nag.settings.debug = true; + $.fn.popup.settings.debug = true; + $.fn.progress.settings.debug = true; + $.fn.rating.settings.debug = true; + $.fn.search.settings.debug = true; + $.fn.shape.settings.debug = true; + $.fn.sidebar.settings.debug = true; + $.fn.sticky.settings.debug = true; + $.fn.tab.settings.debug = true; $.fn.transition.settings.debug = true; - $.fn.transition.settings.performance = true; - $.fn.transition.settings.verbose = true; + + $.api.settings.debug = true; + $.fn.api.settings.debug = true; + $.fn.form.settings.debug = true; + $.fn.visibility.settings.debug = true; } -function test_transition() { - const selector = '.ui.transition'; - $(selector).transition('stop') === $(); - $(selector).transition('stop all') === $(); - $(selector).transition('clear queue') === $(); - $(selector).transition('show') === $(); - $(selector).transition('hide') === $(); - $(selector).transition('toggle') === $(); - $(selector).transition('force repaint') === $(); - $(selector).transition('repaint') === $(); - $(selector).transition('reset') === $(); - $(selector).transition('looping') === $(); - $(selector).transition('remove looping') === $(); - $(selector).transition('disable') === $(); - $(selector).transition('enable') === $(); - $(selector).transition('set duration', 10) === $(); - $(selector).transition('save conditions') === $(); - $(selector).transition('restore conditions') === $(); - $(selector).transition('get animation name') === 'animation name'; - $(selector).transition('get animation event') === 'animation event'; - $(selector).transition('is visible') === false; - $(selector).transition('is animating') === false; - $(selector).transition('is looping') === false; - $(selector).transition('is supported') === false; - $(selector).transition('destroy') === $(); - $(selector).transition('setting', 'debug', undefined) === false; - $(selector).transition('setting', 'debug') === false; - $(selector).transition('setting', 'debug', true) === $(); - $(selector).transition('setting', { - namespace: 'namespace', - name: 'name', - silent: false, - debug: true, - performance: true, - verbose: true - }) === $(); - $(selector).transition('fade') === $(); - $(selector).transition({ - animation: 'fade', - interval: 200, - reverse: true, - displayType: 'inline-block', - duration: 300, - useFailSafe: false, - allowRepeats: true, - queue: false, - onShow() { - this === $(); - }, - onHide() { - this === $(); - }, - onStart() { - this === $(); - }, - onComplete() { - this === $(); - }, - className: { - animating: 'animating', - disabled: 'disabled', - hidden: 'hidden', - inward: 'inward', - loading: 'loading', - looping: 'looping', - outward: 'outward', - transition: 'transition', - visible: 'visible' - }, - error: { - noAnimation: 'noAnimation', - method: 'method' - } - }); - $(selector).transition() === $(); -} - -function test_api() { - const selector = '.ui.api'; - $(selector).api({}); - $(selector).api(); -} - -function test_form() { - const selector = '.ui.form'; - $(selector).form({}); - $(selector).form(); -} - -function test_form_specifyingValidationRules() { - $('.ui.form').form({ - fields: { - name: 'empty', - gender: 'empty', - username: 'empty', - password: ['minLength[6]', 'empty'], - skills: ['minCount[2]', 'empty'], - terms: 'checked' - } - }); - - $('.ui.form').form({ - fields: { - name: { - identifier: 'name', - rules: [{ - type: 'empty', - prompt: 'Please enter your name' - }] - }, - skills: { - identifier: 'skills', - rules: [{ - type: 'minCount[2]', - prompt: 'Please select at least two skills' - }] - }, - gender: { - identifier: 'gender', - rules: [{ - type: 'empty', - prompt: 'Please select a gender' - }] - }, - username: { - identifier: 'username', - rules: [{ - type: 'empty', - prompt: 'Please enter a username' - }] - }, - password: { - identifier: 'password', - rules: [{ - type: 'empty', - prompt: 'Please enter a password' - }, { - type: 'minLength[6]', - prompt: 'Your password must be at least {ruleValue} characters' - }] - }, - terms: { - identifier: 'terms', - rules: [{ - type: 'checked', - prompt: 'You must agree to the terms and conditions' - }] - } - } - }); -} - -function test_form_addCustomRule() { - const user = { adminLevel: 1 }; - $.fn.form.settings.rules!['adminLevel'] = (value: any, adminLevel: number) => { - return (user.adminLevel >= adminLevel); - }; - $('.ui.form').form({ - fields: { - dog: { - identifier: 'dog', - rules: [{ - type: 'adminLevel[2]', - prompt: 'You must be at least a level-2 admin to add a dog' - }] - } - } - }); -} - -function test_visibility() { - const selector = '.ui.visibility'; - $(selector).visibility({}); - $(selector).visibility(); -} - -function test_settings() { - $.site.settings.verbose = true; - - $.api.settings.verbose = true; - - $.fn.site.settings.verbose = true; - - $.fn.accordion.settings.verbose = true; - $.fn.checkbox.settings.verbose = true; - $.fn.dropdown.settings.verbose = true; - $.fn.embed.settings.verbose = true; - $.fn.modal.settings.verbose = true; - $.fn.nag.settings.verbose = true; - $.fn.popup.settings.verbose = true; - $.fn.progress.settings.verbose = true; - $.fn.rating.settings.verbose = true; - $.fn.search.settings.verbose = true; - $.fn.shape.settings.verbose = true; - $.fn.sidebar.settings.verbose = true; - $.fn.sticky.settings.verbose = true; - $.fn.tab.settings.verbose = true; - - $.fn.api.settings.verbose = true; - $.fn.form.settings.verbose = true; - $.fn.visibility.settings.verbose = true; +function test() { + $('.ui.site').site() === $(); + + $('.ui.accordion').accordion() === $(); + $('.ui.checkbox').checkbox() === $(); + $('.ui.dimmer').dimmer() === $(); + $('.ui.dropdown').dropdown() === $(); + $('.ui.embed').embed() === $(); + $('.ui.modal').modal() === $(); + $('.ui.nag').nag() === $(); + $('.ui.popup').popup() === $(); + $('.ui.progress').progress() === $(); + $('.ui.rating').rating() === $(); + $('.ui.search').search() === $(); + $('.ui.shape').shape() === $(); + $('.ui.sidebar').sidebar() === $(); + $('.ui.sticky').sticky() === $(); + $('.ui.tab').tab() === $(); + $('.ui.transition').transition() === $(); + + $('.ui.api').api() === $(); + $('.ui.form').form() === $(); + $('.ui.visibility').visibility() === $(); } diff --git a/types/semantic-ui/tslint.json b/types/semantic-ui/tslint.json index 08b1465cd6..946997cb87 100644 --- a/types/semantic-ui/tslint.json +++ b/types/semantic-ui/tslint.json @@ -1,6 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "unified-signatures": false + "no-useless-files": false } } From 68153fbcfac8fc2c23c150299ac9fdc50318bb19 Mon Sep 17 00:00:00 2001 From: beary Date: Wed, 7 Jun 2017 09:40:02 +0800 Subject: [PATCH 39/98] Add "// TypeScript Version: 2.3"' --- types/mongodb/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 02208e721b..b1f85ed22c 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mongodb/node-mongodb-native/tree/2.2 // Definitions by: Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // Documentation : http://mongodb.github.io/node-mongodb-native/2.2/api/ From f421bc7be56beabe69f5cace6e43f22fdad56cfd Mon Sep 17 00:00:00 2001 From: beary Date: Wed, 7 Jun 2017 09:51:29 +0800 Subject: [PATCH 40/98] Move ts version comment to end of the header --- types/mongodb/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index b1f85ed22c..916b04cc66 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -2,10 +2,11 @@ // Project: https://github.com/mongodb/node-mongodb-native/tree/2.2 // Definitions by: Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 // Documentation : http://mongodb.github.io/node-mongodb-native/2.2/api/ +// TypeScript Version: 2.3 + /// /// From e33c2ab476567a17fc262a0b237f207650e0eab5 Mon Sep 17 00:00:00 2001 From: beary Date: Wed, 7 Jun 2017 10:19:50 +0800 Subject: [PATCH 41/98] Move ts version comment to correct location --- types/mongodb/index.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 916b04cc66..42060ba190 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -2,10 +2,9 @@ // Project: https://github.com/mongodb/node-mongodb-native/tree/2.2 // Definitions by: Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// Documentation : http://mongodb.github.io/node-mongodb-native/2.2/api/ - // TypeScript Version: 2.3 + +// Documentation : http://mongodb.github.io/node-mongodb-native/2.2/api/ /// /// From 18949a7319931be15c639aea1c0a6f76a50c403c Mon Sep 17 00:00:00 2001 From: Julien Roncaglia Date: Wed, 7 Jun 2017 11:19:58 +0200 Subject: [PATCH 42/98] Allow false as a result of React render() `false` is treated the same as `null` when returned from `render()` in react but it wasn't allowed in the typings --- types/react/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 7d71c2d183..a8f827ee0a 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -185,7 +185,7 @@ declare namespace React { setState(f: (prevState: S, props: P) => Pick, callback?: () => any): void; setState(state: Pick, callback?: () => any): void; forceUpdate(callBack?: () => any): void; - render(): JSX.Element | null; + render(): JSX.Element | null | false; // React.Props is now deprecated, which means that the `children` // property is not available on `P` by default, even though you can @@ -2728,7 +2728,7 @@ declare global { namespace JSX { interface Element extends React.ReactElement { } interface ElementClass extends React.Component { - render(): JSX.Element | null; + render(): JSX.Element | null | false; } interface ElementAttributesProperty { props: {}; } interface ElementChildrenAttribute { children: {}; } From 62c91567aa209d446bfe9f0d79f346c0cc984afe Mon Sep 17 00:00:00 2001 From: E020873 Date: Wed, 7 Jun 2017 01:31:12 +0200 Subject: [PATCH 43/98] [mongoose] set strictNullChecks to true --- types/mongoose/index.d.ts | 58 +++++++++--------- types/mongoose/mongoose-tests.ts | 100 ++++++++++++++++++++++--------- types/mongoose/tsconfig.json | 2 +- 3 files changed, 102 insertions(+), 58 deletions(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 8f5d6bdad6..c918c3950e 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1476,33 +1476,33 @@ declare module "mongoose" { * @param criteria mongodb selector * @param projection optional fields to return */ - findOne(callback?: (err: any, res: DocType) => void): DocumentQuery; + findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery; findOne(criteria: Object, - callback?: (err: any, res: DocType) => void): DocumentQuery; + callback?: (err: any, res: DocType | null) => void): DocumentQuery; /** * Issues a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndRemove(callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; + findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; findOneAndRemove(conditions: Object, - callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, - callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command. * Finds a matching document, updates it according to the update arg, passing any options, and returns * the found document (if any) to the callback. The query executes immediately if callback is passed. */ - findOneAndUpdate(callback?: (err: any, doc: DocType) => void): DocumentQuery; + findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery; findOneAndUpdate(update: Object, - callback?: (err: any, doc: DocType) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null) => void): DocumentQuery; findOneAndUpdate(query: Object | Query, update: Object, - callback?: (err: any, doc: DocType) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null) => void): DocumentQuery; findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: DocType) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null) => void): DocumentQuery; /** * Specifies a $geometry condition. geometry() must come after either intersects() or within(). @@ -2334,11 +2334,11 @@ declare module "mongoose" { * @param projection optional fields to return */ findById(id: Object | string | number, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; findById(id: Object | string | number, projection: Object, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; findById(id: Object | string | number, projection: Object, options: Object, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; model(name: string): Model; @@ -2395,9 +2395,9 @@ declare module "mongoose" { */ find(callback?: (err: any, res: T[]) => void): DocumentQuery; find(conditions: Object, callback?: (err: any, res: T[]) => void): DocumentQuery; - find(conditions: Object, projection: Object, + find(conditions: Object, projection?: Object | null, callback?: (err: any, res: T[]) => void): DocumentQuery; - find(conditions: Object, projection: Object, options: Object, + find(conditions: Object, projection?: Object | null, options?: Object | null, callback?: (err: any, res: T[]) => void): DocumentQuery; @@ -2409,27 +2409,27 @@ declare module "mongoose" { * Executes immediately if callback is passed, else a Query object is returned. * @param id value of _id to query by */ - findByIdAndRemove(): DocumentQuery; + findByIdAndRemove(): DocumentQuery; findByIdAndRemove(id: Object | number | string, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; findByIdAndRemove(id: Object | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: Object; /** sets the document fields to return */ select?: Object; - }, callback?: (err: any, res: T) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) * is equivalent to findOneAndUpdate({ _id: id }, ...). * @param id value of _id to query by */ - findByIdAndUpdate(): DocumentQuery; + findByIdAndUpdate(): DocumentQuery; findByIdAndUpdate(id: Object | number | string, update: Object, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; findByIdAndUpdate(id: Object | number | string, update: Object, options: ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; /** * Finds one document. @@ -2437,20 +2437,20 @@ declare module "mongoose" { * @param projection optional fields to return */ findOne(conditions?: Object, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; findOne(conditions: Object, projection: Object, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; findOne(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; /** * Issue a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed else a Query object is returned. */ - findOneAndRemove(): DocumentQuery; + findOneAndRemove(): DocumentQuery; findOneAndRemove(conditions: Object, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; findOneAndRemove(conditions: Object, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2461,7 +2461,7 @@ declare module "mongoose" { maxTimeMS?: number; /** sets the document fields to return */ select?: Object; - }, callback?: (err: any, res: T) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command. @@ -2469,12 +2469,12 @@ declare module "mongoose" { * and returns the found document (if any) to the callback. The query executes immediately * if callback is passed else a Query object is returned. */ - findOneAndUpdate(): DocumentQuery; + findOneAndUpdate(): DocumentQuery; findOneAndUpdate(conditions: Object, update: Object, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; findOneAndUpdate(conditions: Object, update: Object, options: ModelFindOneAndUpdateOptions, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery; /** * geoNear support for Mongoose diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index c6de968430..3763d5975e 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -71,7 +71,7 @@ mongoose.version.toLowerCase(); * section querystream.js * http://mongoosejs.com/docs/api.html#querystream-js */ -var querystream: mongoose.QueryStream; +var querystream = {}; querystream.destroy(new Error()); querystream.pause(); querystream.pipe(process.stdout, {end: true}).end(); @@ -81,7 +81,7 @@ querystream.readable; /* inherited properties */ querystream.getMaxListeners(); /* practical examples */ -var QSModel: typeof mongoose.Model; +var QSModel = {}; var QSStream: mongoose.QueryStream = QSModel.find().stream(); QSStream.on('data', function (doc: any) { doc.save(); @@ -97,7 +97,7 @@ QSModel.where('created').gte(20000).stream().pipe(process.stdout); * section drivers/node-mongodb-native/collection.js * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js */ -var coll1: mongoose.Collection; +var coll1 = {}; coll1.$format(999).toLowerCase(); coll1.$print('name', 'i', [1, 2, 3]); coll1.getIndexes(); @@ -109,7 +109,7 @@ coll1.ensureIndex(); coll1.find({}); coll1.insert({}, {}); -var coll2 = new mongoose.Collection('', new mongoose.Connection(null)); +var coll2 = new mongoose.Collection('', new mongoose.Connection(mongoose)); coll2.$format(999).toLowerCase(); /* inherited properties */ coll2.initializeOrderedBulkOp; @@ -155,7 +155,7 @@ conn1.addListener('close', cb); * section error/validation.js * http://mongoosejs.com/docs/api.html#error-validation-js */ -var validationError: mongoose.ValidationError; +var validationError = {}; validationError.toString().toLowerCase(); /* inherited properties */ validationError.stack; @@ -178,7 +178,7 @@ mongoose.Error.Messages.hasOwnProperty(''); * section querycursor.js * http://mongoosejs.com/docs/api.html#querycursor-js */ -var querycursor: mongoose.QueryCursor; +var querycursor = > {}; querycursor.close(function (error, result) { result.execPopulate(); }).catch(cb); @@ -267,8 +267,10 @@ schema.method('name', cb).method({ schema.path('a', mongoose.Schema.Types.Buffer).path('a'); schema.pathType('m1').toLowerCase(); schema.plugin(function (schema, opts) { -schema.get('path'); - opts.hasOwnProperty(''); + schema.get('path'); + if (opts) { + opts.hasOwnProperty(''); + } }).plugin(cb, {opts: true}); schema @@ -426,7 +428,7 @@ new mongoose.Schema({ * section document.js * http://mongoosejs.com/docs/api.html#document-js */ -var doc: mongoose.MongooseDocument; +var doc = {}; doc.$isDefault('path').valueOf(); doc.depopulate('path'); doc.equals(doc).valueOf(); @@ -483,7 +485,9 @@ var MyModel = mongoose.model('test', new mongoose.Schema({ doc = new MyModel(); doc.$isDefault('name'); MyModel.findOne().populate('author').exec(function (err, doc) { - doc.depopulate('author'); + if (doc) { + doc.depopulate('author'); + } }); doc.populate('path'); doc.populate({path: 'hello'}); @@ -540,7 +544,7 @@ interface MySubEntity extends mongoose.Types.Subdocument { interface MyEntity extends mongoose.Document { sub: mongoose.Types.Array } -var myEntity: MyEntity; +var myEntity = {}; var subDocArray = _.filter(myEntity.sub, function (sd) { sd.property1; sd.property2.toLowerCase(); @@ -570,7 +574,7 @@ interface MySubEntity1 extends mongoose.Types.Subdocument { interface MyEntity1 extends mongoose.Document { sub: mongoose.Types.DocumentArray } -var newEnt: MyEntity1; +var newEnt = {}; var newSub: MySubEntity1 = newEnt.sub.create({ property1: "example", property2: "example" }); /* @@ -645,7 +649,7 @@ embeddedDocument.execPopulate(); * section query.js * http://mongoosejs.com/docs/api.html#query-js */ -var query: mongoose.Query; +var query = > {}; query.$where('').$where(cb); query.all(99).all('path', 99); query.and([{ color: 'green' }, { status: 'ok' }]).and([]); @@ -877,7 +881,7 @@ schemaArray.sparse(true); * section schema/string.js * http://mongoosejs.com/docs/api.html#schema-string-js */ -var MongoDocument: mongoose.Document; +var MongoDocument = {}; var schemastring: mongoose.Schema.Types.String = new mongoose.Schema.Types.String('hello'); schemastring.checkRequired(234, MongoDocument).valueOf(); schemastring.enum(['hi', 'a', 'b']).enum('hi').enum({}); @@ -1161,7 +1165,9 @@ mongoose.model('') .findOne({}) .exec() .then(function (arg) { - arg.save; + if (arg) { + arg.save; + } return 1; }).then(function (num) { num.toFixed; @@ -1172,7 +1178,9 @@ mongoose.model('') str.toLowerCase return (mongoose.model('')).findOne({}).exec(); }).then(function (arg) { - arg.save; + if (arg) { + arg.save; + } return 1; }).catch(function (err) { return 1; @@ -1188,7 +1196,9 @@ mongoose.model('') mongoose.model('').findOne({}) .then(function (arg) { - arg.save; + if (arg) { + arg.save; + } return 2; }).then(function (num) { num.toFixed; @@ -1237,6 +1247,9 @@ MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { }); MongoModel.findById(999, function (err, doc) { var handleSave = function(err: Error, product: mongoose.Document, numAffected: number) {}; + if (!doc) { + return; + } doc.increment(); doc.save(handleSave).then(cb).catch(cb); doc.save({ validateBeforeSave: false }, handleSave).then(cb).catch(cb); @@ -1256,7 +1269,9 @@ var mongoModel = new MongoModel(); mongoModel.remove(function (err, product) { if (err) throw(err); MongoModel.findById(product._id, function (err, product) { - product.remove(); + if (product) { + product.remove(); + } }); }); mongoModel.save().then(function (product) { @@ -1304,11 +1319,15 @@ MongoModel.find({ name: /john/i }, null, { skip: 10 }).exec(function (err, docs) MongoModel.findById(999, function (err, adventure) {}); MongoModel.findById(999).exec(cb); MongoModel.findById(999, 'name length', function (err, adventure) { - adventure.save(); + if (adventure) { + adventure.save(); + } }); MongoModel.findById(999, 'name length').exec(cb); MongoModel.findById(999, '-length').exec(function (err, adventure) { - adventure.addListener('click', cb); + if (adventure) { + adventure.addListener('click', cb); + } }); MongoModel.findById(999, 'name', { lean: true }, function (err, doc) {}); MongoModel.findById(999, 'name').lean().exec(function (err, doc) {}); @@ -1372,6 +1391,9 @@ MongoModel.mapReduce({ console.log(docs); }).then(null, cb); MongoModel.findById(999, function (err, user) { + if (!user) { + return; + } var opts = [ { path: 'company', match: { x: 1 }, select: 'name' } , { path: 'notes', options: { limit: 10 }, model: 'override' } @@ -1425,7 +1447,9 @@ mongoModel.addListener('event', cb); MongoModel.findOne({ title: /timex/i }) .populate('_creator', 'name') .exec(function (err, story) { - story.execPopulate(); + if (story) { + story.execPopulate(); + } }); MongoModel.find({ id: 999 @@ -1460,6 +1484,9 @@ var LocModel = mongoose.model("Location", locationSchema); LocModel.findById(999) .select("-reviews -rating") .exec(function (err, location) { + if (!location) { + return; + } location.name = 'blah'; location.address = 'blah'; location.reviews.forEach(review => {}); @@ -1496,18 +1523,35 @@ LocModel.distinct('') .then(cb).catch(cb); LocModel.findByIdAndRemove() .exec(function (err, doc) { + if (!doc) { + return; + } doc.addListener; doc.openingTimes; }); LocModel.findByIdAndUpdate() .select({}) .exec(function (err, location) { - location.reviews; + if (location) { + location.reviews; + } }); -LocModel.findOne({}, function (err, doc) { doc.openingTimes; }); +LocModel.findOne({}, function (err, doc) { + if (doc) { + doc.openingTimes; + } +}); LocModel.findOneAndRemove() - .exec(function (err, location) { location.name; }); -LocModel.findOneAndUpdate().exec().then(function (arg) { arg.openingTimes; }); + .exec(function (err, location) { + if (location) { + location.name; + } + }); +LocModel.findOneAndUpdate().exec().then(function (arg) { + if (arg) { + arg.openingTimes; + } +}); LocModel.geoSearch({}, { near: [1, 2], maxDistance: 22 @@ -1528,7 +1572,7 @@ interface ModelStruct { model: MyModel; method1: (callback: (model: MyModel, doc: MyDocument) => void) => MyModel; } -var modelStruct1: ModelStruct; +var modelStruct1 = {}; var myModel1: MyModel; var myDocument1: MyDocument; modelStruct1.method1(function (myModel1, myDocument1) { @@ -1555,8 +1599,8 @@ final2.method;interface ibase extends mongoose.Document { interface extended extends ibase { email: string; } -const base: mongoose.Model = mongoose.model('testfour', null) -const extended: mongoose.Model = base.discriminator('extendedS', null); +const base: mongoose.Model = mongoose.model('testfour') +const extended: mongoose.Model = base.discriminator('extendedS', schema); const x = new extended({ username: 'hi', // required in baseSchema email: 'beddiw', // required in extededSchema diff --git a/types/mongoose/tsconfig.json b/types/mongoose/tsconfig.json index 0c7d49295c..de340232f7 100644 --- a/types/mongoose/tsconfig.json +++ b/types/mongoose/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": false, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" From 1e85e1d7fb862dda0814c6df869bb957f5be4ac3 Mon Sep 17 00:00:00 2001 From: Brendan McKeown Date: Wed, 7 Jun 2017 09:25:29 -0400 Subject: [PATCH 44/98] Numeral.js - add missing second optional argument to `format` method for rounding function --- types/numeral/index.d.ts | 4 +++- types/numeral/numeral-tests.ts | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/types/numeral/index.d.ts b/types/numeral/index.d.ts index f08f46b8c2..83ed71bdec 100644 --- a/types/numeral/index.d.ts +++ b/types/numeral/index.d.ts @@ -35,6 +35,8 @@ interface NumeralJsFormat { type RegisterType = 'format' | 'locale'; +type RoundingFunction = (value: number) => number; + // http://numeraljs.com/#use-it interface Numeral { (value?: any): Numeral; @@ -60,7 +62,7 @@ interface Numeral { nullFormat(format: string): void; defaultFormat(format: string): void; clone(): Numeral; - format(inputString?: string): string; + format(inputString?: string, roundingFunction?: RoundingFunction): string; formatCurrency(inputString?: string): string; unformat(inputString: string): number; value(): number; diff --git a/types/numeral/numeral-tests.ts b/types/numeral/numeral-tests.ts index 7be34cc8f9..b58d6e7411 100644 --- a/types/numeral/numeral-tests.ts +++ b/types/numeral/numeral-tests.ts @@ -6,6 +6,9 @@ var valueFormat: string = numeral(1000).format('0,0'); var valueUnformat: number = numeral().unformat('($10,000.00)'); // '-10000' +var valueFormatFloor: string = numeral(1.357).format('0.00', Math.floor); +// '1.35' + var value3: Numeral = numeral(1000); var added: Numeral = value3.add(10); // 1010 From d45137018d2a289d7bc898a311e11002e5a3a409 Mon Sep 17 00:00:00 2001 From: Niklas Wulf Date: Wed, 7 Jun 2017 15:37:05 +0200 Subject: [PATCH 45/98] [Hapi] Fix input and response validation function signatures (#16802) * [Hapi] Fix input and response validation function signatures Fixes #16750 * [Hapi] Allow custom validation options in route input and response * [Hapi] Adjust validation contexts to match Hapi version 16.1.1 * [Hapi] Adjust test/route/validate.ts to match newest changes * [Hapi] Add custom options to response validation test * [Hapi] Update TypeScript version to 2.3 in packages that import Hapi * [Hapi] Clarify documentation on validation function value, allow null --- types/h2o2/index.d.ts | 2 +- types/hapi-auth-basic/index.d.ts | 2 +- types/hapi-decorators/index.d.ts | 1 + types/hapi/index.d.ts | 149 +++++++++++++++++++++--------- types/hapi/test/route/validate.ts | 46 ++++++++- types/inert/index.d.ts | 1 + types/nes/index.d.ts | 1 + types/vision/index.d.ts | 2 +- 8 files changed, 154 insertions(+), 50 deletions(-) diff --git a/types/h2o2/index.d.ts b/types/h2o2/index.d.ts index a1a3680e5c..7ca3ccb85f 100644 --- a/types/h2o2/index.d.ts +++ b/types/h2o2/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/catbox // Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// diff --git a/types/hapi-auth-basic/index.d.ts b/types/hapi-auth-basic/index.d.ts index 23b06de111..07c3c8cc20 100644 --- a/types/hapi-auth-basic/index.d.ts +++ b/types/hapi-auth-basic/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/hapi-auth-basic // Definitions by: AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as Hapi from 'hapi'; diff --git a/types/hapi-decorators/index.d.ts b/types/hapi-decorators/index.d.ts index 2933945e64..e4d7c40991 100644 --- a/types/hapi-decorators/index.d.ts +++ b/types/hapi-decorators/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/knownasilya/hapi-decorators // Definitions by: Ken Howard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as hapi from 'hapi'; import * as Joi from 'joi'; diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 8dca27d66e..9b03944e9a 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/hapi // Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1310,7 +1310,7 @@ export interface RoutePrerequisiteObjects { /** * For context see RouteAdditionalConfigurationOptions > response */ -export interface RouteResponseConfigurationObject { +export interface RouteResponseConfigurationObject { /** the default HTTP status code when the payload is empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time or response transmission (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ emptyStatusCode?: number; /** @@ -1326,16 +1326,20 @@ export interface RouteResponseConfigurationObject { failAction?: 'error' | 'log' | ((request: Request, reply: ReplyWithContinue, source: string, error: Boom.BoomError) => void); /** if true, applies the validation rule changes to the response payload. Defaults to false. */ modify?: boolean; - /** options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is available [here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback) ). Defaults to no options. */ - options?: JoiValidationOptions; + /** + * options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is available [here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback) ). + * If a custom validation function (see `schema` or `status` below) is defined then `options` can an arbitrary object that will be passed to this function as the second parameter. + * Defaults to no options. + */ + options?: ValidationOptions; /** if false, payload range support is disabled. Defaults to true. */ ranges?: boolean; /** the percent of response payloads validated (0 - 100). Set to 0 to disable all validation. Defaults to 100 (all response payloads). */ sample?: number; /** the default response payload validation rules (for all non-error responses) */ - schema?: RouteResponseConfigurationScheme; + schema?: RouteResponseConfigurationScheme; /** HTTP status-code-specific payload validation rules. The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. If a response status code is not present in the status object, the schema definition is used, except for errors which are not validated by default. */ - status?: Dictionary; + status?: Dictionary>; } /** @@ -1343,27 +1347,54 @@ export interface RouteResponseConfigurationObject { * * true - any payload allowed (no validation performed). This is the default. * * false - no payload allowed. * * a Joi validation object. This will receive the request's headers, params, query, payload, and auth credentials and isAuthenticated flags as context. - * * a validation function using the signature function(value, options, next) where: - * * value - the object containing the response object. - * * options - the server validation options, merged with an object containing the request's headers, params, payload, and auth credentials object and isAuthenticated flag. - * * next(err) - the callback function called when validation is completed. + * * a validation function + * * TODO check JoiValidationObject is correct for "a Joi validation object" * * For context see RouteAdditionalConfigurationOptions > response > schema * and * For context see RouteAdditionalConfigurationOptions > response > status */ -export type RouteResponseConfigurationScheme = boolean | JoiValidationObject | ValidationFunctionForRouteResponse; +export type RouteResponseConfigurationScheme = boolean | JoiValidationObject | ValidationFunctionForRouteResponse; /** * see RouteResponseConfigurationScheme * - * TODO check `value: Response` is correct as it says "**the object containing** the response object." not just "the response object". - * TODO check `options: JoiValidationOptions` is correct - * Also see ValidationFunctionForRouteValidate + * a validation function using the signature function(value, options, next) where: + * * value - the value of the response passed to `reply(value)` in the handler. + * * options - the server validation options, merged with an object containing the request's headers, params, payload, and auth credentials object and `isAuthenticated` flag. + * * next([err, [value]]) - the callback function called when validation is completed. `value` will be used as the response value when `err` is falsy, when `value` is not `undefined`, and when `route.settings.response.modify` is `true`. If the response is already a `Boom` error it will be set as its `message` value. */ -export interface ValidationFunctionForRouteResponse { - (value: Response, options: JoiValidationOptions, next: ContinuationFunction): void; +export interface ValidationFunctionForRouteResponse { + (value: any, options: RouteResponseValidationContext & ValidationOptions, next: ContinuationValueFunction): void; +} + +/** + * A context for route input validation via a Joi schema or validation function. + * + * This object is merged with the route response options and passed into the validation function. + * + * See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L217 + */ +export interface RouteResponseValidationContext { + context: { + /** The request headers */ + headers: Dictionary; + /** The request path parameters */ + params: any; + /** The request query parameters */ + query: any; + /** The request payload parameters */ + payload: any; + + /** Partial request authentication information */ + auth: { + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: AuthenticatedCredentials; + }; + } } /** @@ -1399,7 +1430,7 @@ export interface RouteSecurityConfigurationObject { * For context see RouteAdditionalConfigurationOptions > validate * TODO check JoiValidationObject is correct for "a Joi validation object" */ -export interface RouteValidationConfigurationObject { +export interface RouteValidationConfigurationObject { /** * validation rules for incoming request headers (note that all header field names must be in lowercase to match the headers normalized by node). Values allowed: * * true - any headers allowed (no validation performed). This is the default. @@ -1408,25 +1439,25 @@ export interface RouteValidationConfigurationObject { * * a validation function using the signature function(value, options, next) where: * * value - the object containing the request headers. * * options - the server validation options. - * * next(err, value) - the callback function called when validation is completed. + * * next(err, value) - the callback function called when validation is completed. `value` will be used as the `headers` value when `err` is falsy. If `next` is called with `undefined` or no arguments then the original value of `value` will be used. */ - headers?: boolean | JoiValidationObject | ValidationFunctionForRouteValidate; + headers?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; /** * validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params. Values allowed: * Same as `headers`, see above. */ - params?: boolean | JoiValidationObject | ValidationFunctionForRouteValidate; + params?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; /** * validation rules for an incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs and stored in request.query prior to validation. Values allowed: * Same as `headers`, see above. */ - query?: boolean | JoiValidationObject | ValidationFunctionForRouteValidate; + query?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; /** * validation rules for an incoming request payload (request body). Values allowed: * Same as `headers`, see above, with the addition that: * * a Joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are supported, it must be explicitly defined by setting the payload value to a joi schema with null allowed (e.g. Joi.object({ /* keys here * / }).allow(null)). */ - payload?: boolean | JoiValidationObject | ValidationFunctionForRouteValidate; + payload?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; /** an optional object with error fields copied into every validation error response. */ errorFields?: any; /** @@ -1437,24 +1468,46 @@ export interface RouteValidationConfigurationObject { * * a custom error handler function with the signature function(request, reply, source, error) see RouteFailFunction */ failAction?: 'error' | 'log' | 'ignore' | RouteFailFunction; - /** options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is [available here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback)). Defaults to no options. */ - options?: JoiValidationOptions; + /** + * options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is [available here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback)). + * If a custom validation function (see `headers`, `params`, `query`, or `payload` above) is defined then `options` can an arbitrary object that will be passed to this function as the second parameter. + * Defaults to no options. + */ + options?: ValidationOptions; } /** * a validation function using the signature function(value, options, next) where: - * For context see RouteAdditionalConfigurationOptions > validate (IRouteValidationConfigurationObject) + * For context see RouteAdditionalConfigurationOptions > validate (RouteValidationConfigurationObject) * - * TODO check `value: Response` is correct as it says "**the object containing** the response object." not just "the response object". - * TODO check `options: JoiValidationOptions` is correct - * TODO type of the returned value? * Also see ValidationFunctionForRouteResponse - * @param value - the object containing the request headers. + * @param value - the object containing the request headers, query, path params or payload. * @param options - the server validation options. - * @param next(err, value) - the callback function called when validation is completed. + * @param next([err, [value]]) - the callback function called when validation is completed. */ -export interface ValidationFunctionForRouteValidate { - (value: Response, options: JoiValidationOptions, next: ContinuationValueFunction): void; +export interface ValidationFunctionForRouteInput { + (value: any, options: RouteInputValidationContext & ValidationOptions, next: ContinuationValueFunction): void; +} + +/** + * A context for route input validation via a Joi schema or validation function. + * + * This object is merged with the route validation options and passed into the validation function. + * + * See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L122 + */ +export interface RouteInputValidationContext { + context: { + // These are only set when *not* validating the respective source (e.g. params, query and payload are set when validating headers): + // See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L132 + headers?: Dictionary; + params?: any; + query?: any; + payload?: any; + + /** The request authentication information */ + auth: RequestAuthenticationInformation; + } } /** @@ -1795,18 +1848,7 @@ export class Request extends Podium { /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. */ app: any; /** authentication information */ - auth: { - /** true if the request has been successfully authenticated, otherwise false. */ - isAuthenticated: boolean; - /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ - credentials: any; - /** an artifact object received from the authentication strategy and used in authentication-related actions. */ - artifacts: any; - /** the route authentication mode. */ - mode: string; - /** the authentication error is failed and mode set to 'try'. */ - error: Error; - }; + auth: RequestAuthenticationInformation; /** the connection the request was received by. */ connection: ServerConnection; /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains. Set to null when the server useDomains options is false. */ @@ -1964,6 +2006,19 @@ export class Request extends Podium { // [index: string]: any; } +export interface RequestAuthenticationInformation { + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: any; + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: any; + /** the route authentication mode. */ + mode: string; + /** the authentication error is failed and mode set to 'try'. */ + error: Error; +} + export type HTTP_METHODS_PARTIAL_lowercase = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_lowercase; export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; @@ -2049,7 +2104,7 @@ export interface RequestHandler { /** * Used by server extension points - * err can be BoomError or Error that will be wrapped as a BoomError + * err can be `Boom` error or Error that will be wrapped as a `Boom` error * For source [See code](https://github.com/hapijs/hapi/blob/v16.1.1/lib/reply.js#L109-L118) * For source [See code](https://github.com/hapijs/hapi/blob/v16.1.1/lib/response.js#L60-L65) */ @@ -2061,7 +2116,9 @@ export interface ContinuationFunction { * TODO Can value be typed with a useful generic? */ export interface ContinuationValueFunction { - (err: Boom.BoomError, value: any): void; + (err: Boom.BoomError): void; + (err: null | undefined, value: any): void; + (): void; } /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/types/hapi/test/route/validate.ts b/types/hapi/test/route/validate.ts index f160641016..f579bff8a8 100644 --- a/types/hapi/test/route/validate.ts +++ b/types/hapi/test/route/validate.ts @@ -13,8 +13,52 @@ const validate: Hapi.RouteValidationConfigurationObject = { query: { providerId: Joi.string(), }, + options: { + abortEarly: true, + }, }; -const config: Hapi.RouteAdditionalConfigurationOptions = { +let config: Hapi.RouteAdditionalConfigurationOptions = { validate, + response: { + schema: Joi.object(), + }, +}; + +interface CustomValidationOptions { + myOption: number; +} + +const inputValidationFunction: Hapi.ValidationFunctionForRouteInput = (value, options, next) => { + options.myOption; // check custom options + options.context.auth.artifacts; // check context + next(null, value); // check with value + next(); // check without value +}; + +const validateWithFunctions: Hapi.RouteValidationConfigurationObject = { + params: inputValidationFunction, + headers: inputValidationFunction, + payload: inputValidationFunction, + query: inputValidationFunction, + options: { + myOption: 18 + } +}; + +const responseValidationFunction: Hapi.ValidationFunctionForRouteResponse = (value, options, next) => { + options.myOption; // check custom options + options.context.auth.isAuthenticated; // check context + next(null, value); // check with value + next(); // check without value +}; + +config = { + validate: validateWithFunctions, + response: >{ + schema: responseValidationFunction, + options: { + myOption: 18 + } + } }; diff --git a/types/inert/index.d.ts b/types/inert/index.d.ts index a54841eac7..28e4efbe58 100644 --- a/types/inert/index.d.ts +++ b/types/inert/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/hapijs/inert/ // Definitions by: Steve Ognibene , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as hapi from 'hapi'; diff --git a/types/nes/index.d.ts b/types/nes/index.d.ts index 87e428bc29..aab6827ed7 100644 --- a/types/nes/index.d.ts +++ b/types/nes/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/hapijs/nes // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/types/vision/index.d.ts b/types/vision/index.d.ts index 2b0164cc0f..4257e0f7b9 100644 --- a/types/vision/index.d.ts +++ b/types/vision/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/vision // Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as Hapi from 'hapi'; From 887a4e87b0e7db208fc68b76b9585b158f7b1ffd Mon Sep 17 00:00:00 2001 From: Berton Zhu Date: Wed, 7 Jun 2017 21:40:21 +0800 Subject: [PATCH 46/98] fix(redux-actions): createAction(actionType: string) and createAction(actionType: string) is incorrect. (#16643) also see #15697 --- types/redux-actions/index.d.ts | 6 +++++- types/redux-actions/redux-actions-tests.ts | 11 +++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/types/redux-actions/index.d.ts b/types/redux-actions/index.d.ts index b4aaa8474e..d5b825e28c 100644 --- a/types/redux-actions/index.d.ts +++ b/types/redux-actions/index.d.ts @@ -58,6 +58,10 @@ export type ActionFunction3 = (t1: T1, t2: T2, t3: T3) => R; export type ActionFunction4 = (t1: T1, t2: T2, t3: T3, t4: T4) => R; export type ActionFunctionAny = (...args: any[]) => R; +export function createAction( + actionType: string +): ActionFunction0>; + export function createAction( actionType: string, payloadCreator: ActionFunction0 @@ -85,7 +89,7 @@ export function createAction( export function createAction( actionType: string -): ActionFunctionAny>; +): ActionFunction1>; export function createAction( actionType: string, diff --git a/types/redux-actions/redux-actions-tests.ts b/types/redux-actions/redux-actions-tests.ts index f2d7cef7d1..e4c51aa662 100644 --- a/types/redux-actions/redux-actions-tests.ts +++ b/types/redux-actions/redux-actions-tests.ts @@ -110,8 +110,11 @@ const typedActionHandlerWithReduceMap = ReduxActions.handleAction('ACTION1'); -act('hello').payload === 'hello'; +const act0 = ReduxActions.createAction('ACTION0'); +act0().payload === null; + +const act1 = ReduxActions.createAction('ACTION1'); +act1('hello').payload === 'hello'; const act2 = ReduxActions.createAction('ACTION2', (s: {load: boolean}) => s); act2({load: true}).payload.load === true; @@ -119,7 +122,7 @@ act2({load: true}).payload.load === true; const act3 = ReduxActions.createAction('ACTION3', (s: string) => ({s})); act3('hello').payload.s === 'hello'; -ReduxActions.handleAction<{ hello: string }, string>(act, (state, action) => { +ReduxActions.handleAction<{ hello: string }, string>(act1, (state, action) => { return { hello: action.payload }; }, {hello: 'greetings'}); @@ -131,7 +134,7 @@ ReduxActions.handleAction(act3, (state, action) => { return { hello: action.payload.s }; }, {hello: 'greetings'}); -ReduxActions.handleAction(ReduxActions.combineActions(act, act3, act2), (state, action) => {}, 0); +ReduxActions.handleAction(ReduxActions.combineActions(act1, act3, act2), (state, action) => {}, 0); /* can't do this until it lands in 2.2, HKTs ReduxActions.handleAction(act, (state, action) => { From f7636dec131dff3f251c4bbcb07b035f33b19bae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Goetz?= Date: Wed, 7 Jun 2017 15:42:05 +0200 Subject: [PATCH 47/98] [enhanced-resolve] update signature of synchronous calls (#16429) * [enhanced-resolve] update signature of synchronous calls, return string and not ResolveResult * [enhanced-resolve] Add my name to the definition * Fix recommended changes * onlyModule is optional Fixed following recommendation of @e-cloud --- types/enhanced-resolve/index.d.ts | 35 +++++++++++--------- types/enhanced-resolve/lib/Resolver.d.ts | 3 +- types/enhanced-resolve/lib/common-types.d.ts | 5 --- types/enhanced-resolve/test/index.ts | 23 +++++++++---- 4 files changed, 37 insertions(+), 29 deletions(-) diff --git a/types/enhanced-resolve/index.d.ts b/types/enhanced-resolve/index.d.ts index d773f52b16..aa85a8336f 100644 --- a/types/enhanced-resolve/index.d.ts +++ b/types/enhanced-resolve/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for enhanced-resolve v3.0.0 // Project: http://github.com/webpack/enhanced-resolve.git -// Definitions by: e-cloud +// Definitions by: e-cloud , Onigoetz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,7 +8,6 @@ import fs = require('fs'); import { - ResolveResult, LoggingCallbackWrapper, ResolverRequest, ResolveContext, @@ -19,31 +18,35 @@ import Resolver = require('./lib/Resolver'); import Tapable = require('tapable'); declare namespace Resolve { - function sync(path: string, request: string): ResolveResult; - function sync(context: ResolveContext, path: string, request: string): ResolveResult; + function sync(path: string, request: string): string; + function sync(context: ResolveContext, path: string, request: string): string; function context(path: string, request: string, callback: LoggingCallbackWrapper): void; function context(context: ResolveContext, path: string, request: string, callback: LoggingCallbackWrapper): void; namespace context { - function sync(path: string, request: string): ResolveResult; - function sync(context: ResolveContext, path: string, request: string): ResolveResult; + function sync(path: string, request: string): string; + function sync(context: ResolveContext, path: string, request: string): string; } function loader(path: string, request: string, callback: LoggingCallbackWrapper): void; function loader(context: ResolveContext, path: string, request: string, callback: LoggingCallbackWrapper): void; - namespace context { - function sync(path: string, request: string): ResolveResult; - function sync(context: ResolveContext, path: string, request: string): ResolveResult; + namespace loader { + function sync(path: string, request: string): string; + function sync(context: ResolveContext, path: string, request: string): string; } - function create(path: string, request: string, callback: LoggingCallbackWrapper): void; - function create(context: ResolveContext, path: string, request: string, callback: LoggingCallbackWrapper): void; + function create(options: ResolverFactory.ResolverOption): { + (path: string, request: string, callback: LoggingCallbackWrapper): void; + (context: ResolveContext, path: string, request: string, callback: LoggingCallbackWrapper): void; + } export namespace create { - function sync(path: string, request: string): ResolveResult; - function sync(context: ResolveContext, path: string, request: string): ResolveResult; + function sync(options: ResolverFactory.ResolverOption): { + (path: string, request: string): string; + (context: ResolveContext, path: string, request: string): string; + } } export namespace ResolverFactory { @@ -54,8 +57,8 @@ declare namespace Resolve { descriptionFiles?: string[]; enforceExtension?: boolean; enforceModuleExtension?: boolean; - extensions: string[]; - fileSystem: AbstractInputFileSystem; + extensions?: string[]; + fileSystem?: AbstractInputFileSystem; mainFields?: string[]; mainFiles?: string[]; moduleExtensions?: string[]; @@ -70,7 +73,7 @@ declare namespace Resolve { interface AliasItem { alias: string; name: string; - onlyModule: boolean; + onlyModule?: boolean; } function createResolver(options: ResolverOption): Resolver; } diff --git a/types/enhanced-resolve/lib/Resolver.d.ts b/types/enhanced-resolve/lib/Resolver.d.ts index 20fc1c0914..1799fba39b 100644 --- a/types/enhanced-resolve/lib/Resolver.d.ts +++ b/types/enhanced-resolve/lib/Resolver.d.ts @@ -2,7 +2,6 @@ import Tapable = require('tapable'); import { ResolveParseResult, - ResolveResult, ResolverRequest, LoggingCallbackWrapper, AbstractInputFileSystem, @@ -14,7 +13,7 @@ declare class Resolver extends Tapable { constructor(fileSystem: AbstractInputFileSystem); - resolveSync(context: ResolveContext, path: string, request: string): ResolveResult; + resolveSync(context: ResolveContext, path: string, request: string): string; resolve(context: ResolveContext, path: string, request: string, callback: LoggingCallbackWrapper): any; diff --git a/types/enhanced-resolve/lib/common-types.d.ts b/types/enhanced-resolve/lib/common-types.d.ts index 6607dee64f..b0ec925c0b 100644 --- a/types/enhanced-resolve/lib/common-types.d.ts +++ b/types/enhanced-resolve/lib/common-types.d.ts @@ -23,11 +23,6 @@ export interface ResolveContext { issuer?: string; } -export interface ResolveResult { - path: boolean | string; - query: string; -} - export interface ResolverRequest { context: ResolveContext; descriptionFileData?: DescriptionFileData; diff --git a/types/enhanced-resolve/test/index.ts b/types/enhanced-resolve/test/index.ts index dfd5087be4..aeec1d57d8 100644 --- a/types/enhanced-resolve/test/index.ts +++ b/types/enhanced-resolve/test/index.ts @@ -1,5 +1,5 @@ import resolve = require('enhanced-resolve'); -import { ResolveResult, AbstractInputFileSystem } from 'enhanced-resolve/lib/common-types' +import { AbstractInputFileSystem } from 'enhanced-resolve/lib/common-types' import Resolver = require('enhanced-resolve/lib/Resolver') resolve('lib', 'string', function (err) { }); @@ -20,19 +20,30 @@ const nfs = new resolve.NodeJsInputFileSystem(); const cfs = new resolve.CachedInputFileSystem(nfs, 4); -let result: ResolveResult +let result: string result = resolve.sync(context, 'path', 'string'); result = resolve.sync('path', 'string'); + +// Context + resolve.context('lib', 'string', function (err) { }); resolve.context(context, 'path', 'string', function () { }); result = resolve.context.sync(context, 'path', 'string'); result = resolve.context.sync('path', 'string'); -resolve.create('lib', 'string', function (err) { }); -resolve.create(context, 'path', 'string', function () { }); +// Loader -result = resolve.create.sync(context, 'path', 'string'); -result = resolve.create.sync('path', 'string'); +resolve.loader('lib', 'string', function (err) { }); +resolve.loader(context, 'path', 'string', function () { }); + +result = resolve.loader.sync(context, 'path', 'string'); +result = resolve.loader.sync('path', 'string'); + +// Create + +resolve.create({extensions: [".js", ".json", ".node"]})(context, 'path', 'string', function () { }); + +result = resolve.create.sync({mainFields: ["loader", "main"]})(context, 'path', 'string'); From 833819c1aa9d8951400084ab0f3eb6890cd77539 Mon Sep 17 00:00:00 2001 From: "McKeown, Brendan" Date: Wed, 7 Jun 2017 09:51:24 -0400 Subject: [PATCH 48/98] Numeral.js - use new RoundingFunction type in NumeralJsFormat interface format method --- types/numeral/index.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/types/numeral/index.d.ts b/types/numeral/index.d.ts index 83ed71bdec..5e2970a0e7 100644 --- a/types/numeral/index.d.ts +++ b/types/numeral/index.d.ts @@ -22,6 +22,7 @@ interface NumeralJSLocale { }; } +type RoundingFunction = (value: number) => number; // http://numeraljs.com/#custom-formats interface NumeralJsFormat { @@ -29,14 +30,12 @@ interface NumeralJsFormat { format: RegExp, unformat: RegExp, }, - format: (value: any, format: string, roundingFunction: Function) => string, + format: (value: any, format: string, roundingFunction: RoundingFunction) => string, unformat: (value: string) => number } type RegisterType = 'format' | 'locale'; -type RoundingFunction = (value: number) => number; - // http://numeraljs.com/#use-it interface Numeral { (value?: any): Numeral; From 3386890a9852298026b18c7110dfc27372fd5caa Mon Sep 17 00:00:00 2001 From: Jan Hommes Date: Wed, 7 Jun 2017 18:09:13 +0200 Subject: [PATCH 49/98] Updated o.js and odata types. --- types/o.js/index.d.ts | 9 ++- types/o.js/o.js-tests.ts | 7 +- types/odata/index.d.ts | 84 +++++++++++++++++++++ types/odata/odata-tests.ts | 151 +++++++++++++++++++++++++++++++++++++ types/odata/tsconfig.json | 26 +++++++ 5 files changed, 270 insertions(+), 7 deletions(-) create mode 100644 types/odata/index.d.ts create mode 100644 types/odata/odata-tests.ts create mode 100644 types/odata/tsconfig.json diff --git a/types/o.js/index.d.ts b/types/o.js/index.d.ts index 00a5f2b5ae..7cca909391 100644 --- a/types/o.js/index.d.ts +++ b/types/o.js/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for o.js v0.2.2 +// Type definitions for o.js v0.3.3 // Project: https://github.com/janhommes/o.js -// Definitions by: Matteo Antony Mistretta , Brad Zacher +// Definitions by: Matteo Antony Mistretta , Brad Zacher , Jan Hommes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'o.js' { @@ -8,13 +8,14 @@ declare module 'o.js' { interface Options { endpoint : string - json ?: boolean + format ?: string + autoFormat ?: boolean version ?: number strictMode ?: boolean start ?: () => any ready ?: () => any error ?: () => any - headers ?: string[] + headers ?: { name: string, value: string }[] username ?: string password ?: string isAsync ?: boolean diff --git a/types/o.js/o.js-tests.ts b/types/o.js/o.js-tests.ts index f40a84ac84..26cc187723 100644 --- a/types/o.js/o.js-tests.ts +++ b/types/o.js/o.js-tests.ts @@ -129,7 +129,7 @@ o().config({ }); // after you have set an endpoint, you can shorten your queries: o('Products').get(function(data) { - //same result like the first exmple on this page + //same result like the first example on this page }); @@ -137,13 +137,14 @@ o('Products').get(function(data) { //basic config o().config({ endpoint:null, // your odata endpoint for the service - json:true, // currently only json is supported + format:'json', // currently only json is supported + autoFormat: false, version:4, // oData version (currently supported version 4. However most also work with version 3.) strictMode:true, // strict mode throws exception, non strict mode only logs them start:null, // a function which is executed on loading ready:null, // a function which is executed on ready error:null, // a function which is executed on error - headers:[], // a array of additional headers e.g.: [{name:'headername',value:'headervalue'}] + headers:[{name: '', value: ''}], // a array of additional headers e.g.: [{name:'headername',value:'headervalue'}] username:null, // a basic auth username password:null, // a basic auth password isAsync:true //set this to false to make synced (a)jax calls. (dosn't work with basic auth!) diff --git a/types/odata/index.d.ts b/types/odata/index.d.ts new file mode 100644 index 0000000000..9419dd0ba4 --- /dev/null +++ b/types/odata/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for odata v0.3.3 +// Project: https://github.com/janhommes/odata +// Definitions by: Jan Hommes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'odata' { + import Q = require("q"); + + interface Options { + endpoint : string + format ?: boolean + autoFormat ?: string + version ?: number + strictMode ?: boolean + start ?: () => any + ready ?: () => any + error ?: () => any + headers ?: { name: string, value: string }[] + username ?: string + password ?: string + isAsync ?: boolean + } + + interface OHandler { + inlinecount : number + data : T + + config(options ?: Options) : OHandler + progress(callback : () => any) : OHandler + + get(callback ?: (data : T) => void) : Q.Promise> + save(callback ?: (data : T) => void) : Q.Promise> + + post(params : any) : OHandler + patch(params : any) : OHandler + put(params : any) : OHandler + remove(params ?: any) : OHandler + + routes(path : string, callback ?: (data : T) => void) : OHandler + route(path : string, callback ?: (data : T) => void) : OHandler + triggerRoute(hash : string) : OHandler + beforeRouting(callback : (routeParams : any) => boolean) : OHandler + + isEndpoint() : boolean + loading(startFn : () => any | boolean, endFn : () => any) : OHandler + + find(selector : string|number) : OHandler + + top(quantity : number) : OHandler + take(quantity : number) : OHandler + skip(quantity : number) : OHandler + first() : OHandler + + include(column : string, data : string) : OHandler + exclude(column : string, data : string) : OHandler + filterByList(column : string, data : string) : OHandler + + filter(filter : string) : OHandler + where(filter : string) : OHandler + any(filter : string, resource : string) : OHandler + search(columns : string[], term : string) : OHandler + + orderBy(column : string, direction ?: boolean) : OHandler + orderByDesc(column : string) : OHandler + select(selectStr : string) : OHandler + + count() : OHandler + inlineCount(paramName ?: string) : OHandler + + batch(resource : string) : OHandler + expand(resource : string) : OHandler + ref(resource : string, id : string | number) : OHandler + removeRef(resource : string, id : string | number) : OHandler + deleteRef(resource : string, id : string | number) : OHandler + } + + interface OFn extends OHandler { + (options ?: string | Options) : OHandler + } + + var o : OFn<{}>; + + export = o +} \ No newline at end of file diff --git a/types/odata/odata-tests.ts b/types/odata/odata-tests.ts new file mode 100644 index 0000000000..522dc3d529 --- /dev/null +++ b/types/odata/odata-tests.ts @@ -0,0 +1,151 @@ +import * as o from 'odata'; +import * as Q from "q"; + +interface Product { + ID : number; + Name : string; + Description : string; + ReleaseDate : string; + DiscontinuedDate : Date; + Rating: number; + Price: number; +} +interface Category { + ID : number; + Name : string; +} + +// copy pasta all the examples from the readme! + +o('http://services.odata.org/V4/OData/OData.svc/Products') + .get(function(data) { + console.log(data); //returns an array of Product data + }); + + + +o('http://services.odata.org/V4/OData/OData.svc/Products') + .take(5) + .skip(2) + .get(function(data) { + console.log(data); //An array of 5 products skiped by 2 + }); + + + +o('http://services.odata.org/V4/OData/OData.svc/Products') + .find(':0') + .route('Product/Detail/:0/:1',function(data) { + console.log('Route Product/Detail/'+this.param[0]+'/'+this.param[1]+' triggered. Result:'); + console.log(data); + }); + + + +var oHandler = o('http://services.odata.org/V4/OData/OData.svc/Products'); +//do somehtting +oHandler.find(1); +// do some more................ +//get the data +oHandler.get(function(data) { + console.log(data); + //or the saved var also contains the data: + console.log(oHandler.data); +}); + + + +Q.all([ + o('http://services.odata.org/V4/OData/OData.svc/Products(4)').get(), + o('http://services.odata.org/V4/OData/OData.svc/Categories').take(2).get() +]).then(function(oHandlerArray) { + //The oHandler array contains the Product oHandler and the Group oHandler: + console.log(oHandlerArray[0].data); // 1 Product with id 4 + console.log(oHandlerArray[1].data.length); // 2 Categories +}); + + + +o('http://services.odata.org/V4/OData/OData.svc/Products(2)') + .get() + .then(function(oHandler) { + console.log(oHandler.data); + }).fail(function(ex) { + console.log(ex); + }); + + + +o('http://services.odata.org/V4/OData/OData.svc/Products') + .post({Name:'Example 1',Description:'a'}) + .post({Name:'Example 2',Description:'b'}) + .save(function(data) { + console.log("Two Products added"); + }); + + + +o('http://services.odata.org/V4/OData/OData.svc/Products(1)') + .patch({Name:'NewName'}) + .save(function(data) { + console.log("Product Name changed"); + }); + + + +o('http://services.odata.org/V4/OData/OData.svc/Products(1)') + .remove() + .save(function(data) { + console.log("Product deleted"); + }); + + + +o('http://services.odata.org/V4/OData/OData.svc/Products(1)') + .ref('Categories', 2) + .save(function(data) { + console.log("Product(1) associated with Categories(2)"); + }); + + + +o('http://services.odata.org/V4/OData/OData.svc/Products') + .find(2) + .get() + .then(function(oHandler) { + oHandler.data.Name="NewName"; + return(o.save()); + }).then(function(oHandler) { + console.log(oHandler.data.Name); //NewName + }).fail(function(ex) { + console.log("error"); + }); + + + +// set an endpoint +o().config({ + endpoint:'http://services.odata.org/V4/OData/OData.svc' +}); +// after you have set an endpoint, you can shorten your queries: +o('Products').get(function(data) { + //same result like the first example on this page +}); + + + +//basic config +o().config({ + endpoint:null, // your odata endpoint for the service + format: 'json', + autoFormat:false, // currently only json is supported + version:4, // oData version (currently supported version 4. However most also work with version 3.) + strictMode:true, // strict mode throws exception, non strict mode only logs them + start:null, // a function which is executed on loading + ready:null, // a function which is executed on ready + error:null, // a function which is executed on error + headers:[{name: '', value: ''}], // a array of additional headers e.g.: [{name:'headername',value:'headervalue'}] + username:null, // a basic auth username + password:null, // a basic auth password + isAsync:true //set this to false to make synced (a)jax calls. (dosn't work with basic auth!) +}); \ No newline at end of file diff --git a/types/odata/tsconfig.json b/types/odata/tsconfig.json new file mode 100644 index 0000000000..6aac2e60a7 --- /dev/null +++ b/types/odata/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "q": [ "q/v0" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "odata-tests.ts" + ] +} \ No newline at end of file From b86997197f305d8985242c66a1fe69eb19d42a52 Mon Sep 17 00:00:00 2001 From: pilagod Date: Thu, 8 Jun 2017 00:28:12 +0800 Subject: [PATCH 50/98] refine getSync definition --- types/stacktrace-js/index.d.ts | 2 +- types/stacktrace-js/stacktrace-js-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/stacktrace-js/index.d.ts b/types/stacktrace-js/index.d.ts index 7f3c972508..96be8bfbf5 100644 --- a/types/stacktrace-js/index.d.ts +++ b/types/stacktrace-js/index.d.ts @@ -52,7 +52,7 @@ declare namespace StackTrace { * @param options Options Object * @return Array[StackFrame] */ - export function getSync(options?: { filter?: (stackFrame: StackFrame) => boolean }): StackFrame[] + export function getSync(options?: StackTraceOptions): StackFrame[]; /** * Given an error object, parse it. diff --git a/types/stacktrace-js/stacktrace-js-tests.ts b/types/stacktrace-js/stacktrace-js-tests.ts index 1de6abb185..6fac703c7f 100644 --- a/types/stacktrace-js/stacktrace-js-tests.ts +++ b/types/stacktrace-js/stacktrace-js-tests.ts @@ -29,7 +29,7 @@ const options: StackTrace.StackTraceOptions = { const error = new Error('BOOM!'); StackTrace.get(options).then(logger); -logger(StackTrace.getSync({ filter: options.filter })) +logger(StackTrace.getSync(options)) StackTrace.fromError(error, options).then(logger); StackTrace.generateArtificially(options).then(logger); From 7ea548f1fac2fd82e3e5d65c014a2e3c30d77a01 Mon Sep 17 00:00:00 2001 From: Alexander James Phillips Date: Wed, 7 Jun 2017 17:37:40 +0100 Subject: [PATCH 51/98] [Boom] Add data type to BoomError #16956 (#17022) * [Boom] Add data type to BoomError #16956 * [Boom] Update TypeScript version to 2.3 in packages that import Boom --- types/boom/boom-tests.ts | 151 +++++++++++++++++++++++++++++---------- types/boom/index.d.ts | 77 +++++++++++--------- types/catbox/index.d.ts | 2 +- 3 files changed, 160 insertions(+), 70 deletions(-) diff --git a/types/boom/boom-tests.ts b/types/boom/boom-tests.ts index b25607c4b4..e64ac44922 100644 --- a/types/boom/boom-tests.ts +++ b/types/boom/boom-tests.ts @@ -1,45 +1,124 @@ - import Boom = require('boom'); -var bo = Boom.wrap(new Error('test'), 400, 'some message'); -var a: string = bo.output.headers['some header']; +// 4xx and data type -Boom.create(500, 'Internal server error', { timestamp: Date.now() }); +const badRequestError = Boom.badRequest('message', {some: 'data'}); +badRequestError.data.some; -Boom.badRequest('message', {some: 'data'}); -Boom.unauthorized('message', 'scheme', {some: 'data'}); -Boom.unauthorized(null, 'scheme', 'data'); -Boom.paymentRequired('message', {some: 'data'}); -Boom.forbidden('message', {some: 'data'}); -Boom.notFound('message', {some: 'data'}); -Boom.methodNotAllowed('message', {some: 'data'}); -Boom.notAcceptable('message', {some: 'data'}); -Boom.proxyAuthRequired('message', {some: 'data'}); -Boom.clientTimeout('message', {some: 'data'}); -Boom.conflict('message', {some: 'data'}); -Boom.resourceGone('message', {some: 'data'}); -Boom.lengthRequired('message', {some: 'data'}); -Boom.preconditionFailed('message', {some: 'data'}); -Boom.entityTooLarge('message', {some: 'data'}); -Boom.uriTooLong('message', {some: 'data'}); -Boom.unsupportedMediaType('message', {some: 'data'}); -Boom.rangeNotSatisfiable('message', {some: 'data'}); -Boom.expectationFailed('message', {some: 'data'}); -Boom.teapot('message', {some: 'data'}); -Boom.badData('message', {some: 'data'}); -Boom.locked('message', {some: 'data'}); -Boom.preconditionRequired('message', {some: 'data'}); -Boom.tooManyRequests('message', {some: 'data'}); -Boom.illegal('message', {some: 'data'}); +const unauthorizedError1 = Boom.unauthorized('message', 'scheme', {some: 'attribute'}); +unauthorizedError1.output.payload.attributes === { some: 'attribute', error: 'message' }; +unauthorizedError1.output.headers === { 'WWW-Authenticate': 'scheme some="attribute", error="message"' }; -Boom.badImplementation('message', {some: 'data'}); -Boom.internal('message', {some: 'data'}); -Boom.notImplemented('message', {some: 'data'}); -Boom.badGateway('message', {some: 'data'}); -Boom.serverUnavailable('message', {some: 'data'}); -Boom.gatewayTimeout('message', {some: 'data'}); +const unauthorizedError2 = Boom.unauthorized('message', ['scheme']); +unauthorizedError2.output.payload.attributes === undefined; +unauthorizedError2.output.headers === { 'WWW-Authenticate': 'scheme' }; -Boom.unauthorized() as Error; +const unauthorizedError3 = Boom.unauthorized(null, 'scheme', 'attribute'); +unauthorizedError3.output.payload.attributes === 'attribute'; +unauthorizedError3.output.headers === { 'WWW-Authenticate': 'scheme attribute' }; + +const unauthorizedError4 = Boom.unauthorized(null, 'scheme', {some: 'attribute'}); +unauthorizedError4.output.payload.attributes === { some: 'attribute' }; +unauthorizedError4.output.headers === { 'WWW-Authenticate': 'scheme some="attribute"' }; + +const paymentRequiredError = Boom.paymentRequired('message', {some: 'data'}); +paymentRequiredError.data.some; + +const forbiddenError = Boom.forbidden('message', {some: 'data'}); +forbiddenError.data.some; + +const notFoundError = Boom.notFound('message', {some: 'data'}); +notFoundError.data.some; + +const methodNotAllowedError = Boom.methodNotAllowed('message', {some: 'data'}); +methodNotAllowedError.data.some; + +const notAcceptableError = Boom.notAcceptable('message', {some: 'data'}); +notAcceptableError.data.some; + +const proxyAuthRequiredError = Boom.proxyAuthRequired('message', {some: 'data'}); +proxyAuthRequiredError.data.some; + +const clientTimeoutError = Boom.clientTimeout('message', {some: 'data'}); +clientTimeoutError.data.some; + +const conflictError = Boom.conflict('message', {some: 'data'}); +conflictError.data.some; + +const resourceGoneError = Boom.resourceGone('message', {some: 'data'}); +resourceGoneError.data.some; + +const lengthRequiredError = Boom.lengthRequired('message', {some: 'data'}); +lengthRequiredError.data.some; + +const preconditionFailedError = Boom.preconditionFailed('message', {some: 'data'}); +preconditionFailedError.data.some; + +const entityTooLargeError = Boom.entityTooLarge('message', {some: 'data'}); +entityTooLargeError.data.some; + +const uriTooLongError = Boom.uriTooLong('message', {some: 'data'}); +uriTooLongError.data.some; + +const unsupportedMediaTypeError = Boom.unsupportedMediaType('message', {some: 'data'}); +unsupportedMediaTypeError.data.some; + +const rangeNotSatisfiableError = Boom.rangeNotSatisfiable('message', {some: 'data'}); +rangeNotSatisfiableError.data.some; + +const expectationFailedError = Boom.expectationFailed('message', {some: 'data'}); +expectationFailedError.data.some; + +const teapotError = Boom.teapot('message', {some: 'data'}); +teapotError.data.some; + +const badDataError = Boom.badData('message', {some: 'data'}); +badDataError.data.some; + +const lockedError = Boom.locked('message', {some: 'data'}); +lockedError.data.some; + +const preconditionRequiredError = Boom.preconditionRequired('message', {some: 'data'}); +preconditionRequiredError.data.some; + +const tooManyRequestsError = Boom.tooManyRequests('message', {some: 'data'}); +tooManyRequestsError.data.some; + +const illegalError = Boom.illegal('message', {some: 'data'}); +illegalError.data.some; + +// 5xx and data type + +const badImplementationError = Boom.badImplementation('message', {some: 'data'}); +badImplementationError.data.some; + +const internalError = Boom.internal('message', {some: 'data'}); +internalError.data.some; + +const notImplementedError = Boom.notImplemented('message', {some: 'data'}); +notImplementedError.data.some; + +const badGatewayError = Boom.badGateway('message', {some: 'data'}); +badGatewayError.data.some; + +const serverUnavailableError = Boom.serverUnavailable('message', {some: 'data'}); +serverUnavailableError.data.some; + +const gatewayTimeoutError = Boom.gatewayTimeout('message', {some: 'data'}); +gatewayTimeoutError.data.some; + +// wrap and create + +const wrappedError = Boom.wrap(new Error('test'), 400, 'some message'); + +const error1 = Boom.create(500, 'Internal server error', { timestamp: Date.now() }); +error1.data.timestamp; + +// type widden asserting + +const unauthorizedError = Boom.unauthorized() as Error; + +// status code and reformat const error = Boom.badRequest('Cannot feed after midnight'); error.output.statusCode = 499; // Assign a custom error code diff --git a/types/boom/index.d.ts b/types/boom/index.d.ts index 80a1827886..02cf60c6b8 100644 --- a/types/boom/index.d.ts +++ b/types/boom/index.d.ts @@ -2,6 +2,7 @@ // Project: http://github.com/hapijs/boom // Definitions by: Igor Rogatty , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export = Boom; @@ -11,7 +12,7 @@ declare namespace Boom { * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: * @see {@link https://github.com/hapijs/boom#boom} */ - export interface BoomError extends Error { + export interface BoomError extends Error { /** isBoom - if true, indicates this is a Boom object instance. */ isBoom: boolean; /** isServer - convenience bool indicating status code >= 500. */ @@ -24,6 +25,8 @@ declare namespace Boom { reformat: () => string; /** "If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object." mentioned in @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes} */ isMissing?: boolean; + /** https://github.com/hapijs/boom#createstatuscode-message-data */ + data: Data; } export interface Output { @@ -34,6 +37,7 @@ declare namespace Boom { /** payload - the formatted object used as the response payload (stringified). Can be directly manipulated but any changes will be lost if reformat() is called. Any content allowed and by default includes the following content: */ payload: Payload; } + export interface Payload { /** statusCode - the HTTP status code, derived from error.output.statusCode. */ statusCode: number; @@ -41,6 +45,11 @@ declare namespace Boom { error: string; /** message - the error message derived from error.message. */ message: string; + /** + * "Every key/value pair will be included ... in the response payload under the attributes key." + * [see docs](https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes) + */ + attributes?: any; // Excluded this to aid typing of the other values. See tests for example casting to a custom interface to manipulate the payload // [anyContent: string]: any; } @@ -61,7 +70,7 @@ declare namespace Boom { * @param data additional error data set to error.data property. * @see {@link https://github.com/hapijs/boom#createstatuscode-message-data} */ - export function create(statusCode: number, message?: string, data?: any): BoomError; + export function create(statusCode: number, message?: string, data?: Data): BoomError; // 4xx /** @@ -70,7 +79,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadrequestmessage-data} */ - export function badRequest(message?: string, data?: any): BoomError; + export function badRequest(message?: string, data?: Data): BoomError; /** * Returns a 401 Unauthorized error @@ -81,8 +90,10 @@ declare namespace Boom { * @param attributes an object of values to use while setting the 'WWW-Authenticate' header. This value is only used when scheme is a string, otherwise it is ignored. Every key/value pair will be included in the 'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the attributes key. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. null and undefined will be replaced with an empty string. If attributes is set, message will be used as the 'error' segment of the 'WWW-Authenticate' header. If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object. * @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes} */ - export function unauthorized(message?: string, scheme?: string | string[], attributes?: {[index: string]: string}): BoomError; - export function unauthorized(message?: null, scheme?: string | string[], attributes?: string): BoomError; + export function unauthorized(message?: string, scheme?: string, attributes?: {[index: string]: string}): BoomError; + export function unauthorized(message?: string, scheme?: string[]): BoomError; + export function unauthorized(message?: null, scheme?: string, attributes?: {[index: string]: string} | string): BoomError; + export function unauthorized(message?: null, scheme?: string[]): BoomError; /** * Returns a 402 Payment Required error @@ -90,7 +101,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompaymentrequiredmessage-data} */ - export function paymentRequired(message?: string, data?: any): BoomError; + export function paymentRequired(message?: string, data?: Data): BoomError; /** * Returns a 403 Forbidden error @@ -98,7 +109,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomforbiddenmessage-data} */ - export function forbidden(message?: string, data?: any): BoomError; + export function forbidden(message?: string, data?: Data): BoomError; /** * Returns a 404 Not Found error @@ -106,7 +117,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotfoundmessage-data} */ - export function notFound(message?: string, data?: any): BoomError; + export function notFound(message?: string, data?: Data): BoomError; /** * Returns a 405 Method Not Allowed error @@ -115,7 +126,7 @@ declare namespace Boom { * @param allow optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header. * @see {@link https://github.com/hapijs/boom#boommethodnotallowedmessage-data-allow} */ - export function methodNotAllowed(message?: string, data?: any, allow?: string | string[]): BoomError; + export function methodNotAllowed(message?: string, data?: Data, allow?: string | string[]): BoomError; /** * Returns a 406 Not Acceptable error @@ -123,7 +134,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotacceptablemessage-data} */ - export function notAcceptable(message?: string, data?: any): BoomError; + export function notAcceptable(message?: string, data?: Data): BoomError; /** * Returns a 407 Proxy Authentication Required error @@ -131,7 +142,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomproxyauthrequiredmessage-data} */ - export function proxyAuthRequired(message?: string, data?: any): BoomError; + export function proxyAuthRequired(message?: string, data?: Data): BoomError; /** * Returns a 408 Request Time-out error @@ -139,7 +150,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomclienttimeoutmessage-data} */ - export function clientTimeout(message?: string, data?: any): BoomError; + export function clientTimeout(message?: string, data?: Data): BoomError; /** * Returns a 409 Conflict error @@ -147,7 +158,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomconflictmessage-data} */ - export function conflict(message?: string, data?: any): BoomError; + export function conflict(message?: string, data?: Data): BoomError; /** * Returns a 410 Gone error @@ -155,7 +166,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomresourcegonemessage-data} */ - export function resourceGone(message?: string, data?: any): BoomError; + export function resourceGone(message?: string, data?: Data): BoomError; /** * Returns a 411 Length Required error @@ -163,7 +174,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomlengthrequiredmessage-data} */ - export function lengthRequired(message?: string, data?: any): BoomError; + export function lengthRequired(message?: string, data?: Data): BoomError; /** * Returns a 412 Precondition Failed error @@ -171,7 +182,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompreconditionfailedmessage-data} */ - export function preconditionFailed(message?: string, data?: any): BoomError; + export function preconditionFailed(message?: string, data?: Data): BoomError; /** * Returns a 413 Request Entity Too Large error @@ -179,7 +190,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomentitytoolargemessage-data} */ - export function entityTooLarge(message?: string, data?: any): BoomError; + export function entityTooLarge(message?: string, data?: Data): BoomError; /** * Returns a 414 Request-URI Too Large error @@ -187,7 +198,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomuritoolongmessage-data} */ - export function uriTooLong(message?: string, data?: any): BoomError; + export function uriTooLong(message?: string, data?: Data): BoomError; /** * Returns a 415 Unsupported Media Type error @@ -195,7 +206,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomunsupportedmediatypemessage-data} */ - export function unsupportedMediaType(message?: string, data?: any): BoomError; + export function unsupportedMediaType(message?: string, data?: Data): BoomError; /** * Returns a 416 Requested Range Not Satisfiable error @@ -203,7 +214,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomrangenotsatisfiablemessage-data} */ - export function rangeNotSatisfiable(message?: string, data?: any): BoomError; + export function rangeNotSatisfiable(message?: string, data?: Data): BoomError; /** * Returns a 417 Expectation Failed error @@ -211,7 +222,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomexpectationfailedmessage-data} */ - export function expectationFailed(message?: string, data?: any): BoomError; + export function expectationFailed(message?: string, data?: Data): BoomError; /** * Returns a 418 I'm a Teapot error @@ -219,7 +230,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomteapotmessage-data} */ - export function teapot(message?: string, data?: any): BoomError; + export function teapot(message?: string, data?: Data): BoomError; /** * Returns a 422 Unprocessable Entity error @@ -227,7 +238,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombaddatamessage-data} */ - export function badData(message?: string, data?: any): BoomError; + export function badData(message?: string, data?: Data): BoomError; /** * Returns a 423 Locked error @@ -235,7 +246,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomlockedmessage-data} */ - export function locked(message?: string, data?: any): BoomError; + export function locked(message?: string, data?: Data): BoomError; /** * Returns a 428 Precondition Required error @@ -243,7 +254,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompreconditionrequiredmessage-data} */ - export function preconditionRequired(message?: string, data?: any): BoomError; + export function preconditionRequired(message?: string, data?: Data): BoomError; /** * Returns a 429 Too Many Requests error @@ -251,7 +262,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomtoomanyrequestsmessage-data} */ - export function tooManyRequests(message?: string, data?: any): BoomError; + export function tooManyRequests(message?: string, data?: Data): BoomError; /** * Returns a 451 Unavailable For Legal Reasons error @@ -259,7 +270,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomillegalmessage-data} */ - export function illegal(message?: string, data?: any): BoomError; + export function illegal(message?: string, data?: Data): BoomError; // 5xx /** @@ -269,7 +280,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal} */ - export function badImplementation(message?: string, data?: any): BoomError; + export function badImplementation(message?: string, data?: Data): BoomError; /** * Returns a 500 Internal Server Error error @@ -278,7 +289,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal} */ - export function internal(message?: string, data?: any): BoomError; + export function internal(message?: string, data?: Data): BoomError; /** * Returns a 501 Not Implemented error with your error message to the user @@ -286,7 +297,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotimplementedmessage-data} */ - export function notImplemented(message?: string, data?: any): BoomError; + export function notImplemented(message?: string, data?: Data): BoomError; /** * Returns a 502 Bad Gateway error with your error message to the user @@ -294,7 +305,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadgatewaymessage-data} */ - export function badGateway(message?: string, data?: any): BoomError; + export function badGateway(message?: string, data?: Data): BoomError; /** * Returns a 503 Service Unavailable error with your error message to the user @@ -302,7 +313,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomserverunavailablemessage-data} */ - export function serverUnavailable(message?: string, data?: any): BoomError; + export function serverUnavailable(message?: string, data?: Data): BoomError; /** * Returns a 504 Gateway Time-out error with your error message to the user @@ -310,5 +321,5 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomgatewaytimeoutmessage-data} */ - export function gatewayTimeout(message?: string, data?: any): BoomError; + export function gatewayTimeout(message?: string, data?: Data): BoomError; } diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index e832f58446..5dad5af29a 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hapijs/catbox // Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import * as Boom from 'boom'; From 30a54db2bfa81aefece96b2306a0ca419d37f65a Mon Sep 17 00:00:00 2001 From: Jan Hommes Date: Wed, 7 Jun 2017 18:48:25 +0200 Subject: [PATCH 52/98] Fixed options interface. --- types/odata/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/odata/index.d.ts b/types/odata/index.d.ts index 9419dd0ba4..3f436667f9 100644 --- a/types/odata/index.d.ts +++ b/types/odata/index.d.ts @@ -8,8 +8,8 @@ declare module 'odata' { interface Options { endpoint : string - format ?: boolean - autoFormat ?: string + format ?: string + autoFormat ?: boolean version ?: number strictMode ?: boolean start ?: () => any From 7fc16440808f188c89e58fe47ba433e6ef3337bd Mon Sep 17 00:00:00 2001 From: Federico Caselli Date: Wed, 7 Jun 2017 19:41:33 +0200 Subject: [PATCH 53/98] [mongodb] Added support for default generic types (#16198) * Added support for ts2.3 default generic types * Updated find and findOne * Capitalized TypeScript Version * Added missing TypeScript Version: 2.3 * Added TypeScript Version: 2.3 to express-brute-mongo; removed easy-jsend test dependency on mongoose --- types/acl/index.d.ts | 1 + types/agenda/index.d.ts | 1 + types/connect-mongo/index.d.ts | 1 + types/easy-jsend/easy-jsend-tests.ts | 11 +++++----- types/express-brute-mongo/index.d.ts | 6 +++--- types/gridfs-stream/index.d.ts | 1 + types/mongodb/index.d.ts | 26 +++++++++++++----------- types/mongodb/mongodb-tests.ts | 8 +++++--- types/mongoose-auto-increment/index.d.ts | 2 +- types/mongoose-deep-populate/index.d.ts | 2 +- types/mongoose-mock/index.d.ts | 2 +- types/mongoose-paginate/index.d.ts | 1 + types/mongoose-promise/index.d.ts | 1 + types/mongoose-sequence/index.d.ts | 1 + types/mongoose/index.d.ts | 2 +- types/passport-local-mongoose/index.d.ts | 1 + 16 files changed, 40 insertions(+), 27 deletions(-) diff --git a/types/acl/index.d.ts b/types/acl/index.d.ts index 069631d2e0..3aa81de8e3 100644 --- a/types/acl/index.d.ts +++ b/types/acl/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/optimalbits/node_acl // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index e859de3188..fe8ecc45a6 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rschmukler/agenda // Definitions by: Meir Gottlieb // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/connect-mongo/index.d.ts b/types/connect-mongo/index.d.ts index b469d08d00..0b7443f7e1 100644 --- a/types/connect-mongo/index.d.ts +++ b/types/connect-mongo/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/kcbanner/connect-mongo // Definitions by: Mizuki Yamamoto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/easy-jsend/easy-jsend-tests.ts b/types/easy-jsend/easy-jsend-tests.ts index 705fe5b7e1..0ea41f4418 100644 --- a/types/easy-jsend/easy-jsend-tests.ts +++ b/types/easy-jsend/easy-jsend-tests.ts @@ -1,14 +1,15 @@ -import mongoose = require('mongoose'); +// import mongoose = require('mongoose'); import express = require('express'); import jSend = require('easy-jsend'); -var schema = new mongoose.Schema({ - name: {type: String} -}); +// var schema = new mongoose.Schema({ +// name: {type: String} +// }); -var Model = mongoose.model('model', schema); +// var Model = mongoose.model('model', schema); +var Model = {}; jSend.init({partial: true}); diff --git a/types/express-brute-mongo/index.d.ts b/types/express-brute-mongo/index.d.ts index cf248f8883..9714fedd5d 100644 --- a/types/express-brute-mongo/index.d.ts +++ b/types/express-brute-mongo/index.d.ts @@ -2,9 +2,9 @@ // Project: https://github.com/auth0/express-brute-mongo // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 - - +import { Collection } from "mongodb"; /** * @summary MongoDB store adapter. @@ -17,5 +17,5 @@ export = class MongoStore { * @param {Function} getCollection The collection. * @param {Object} options The otpions. */ - constructor(getCollection: (collection: any) => void, options?: Object); + constructor(getCollection: (collection: (c: Collection) => void) => void, options?: Object); } diff --git a/types/gridfs-stream/index.d.ts b/types/gridfs-stream/index.d.ts index 1c803348ad..80f87bb6c5 100644 --- a/types/gridfs-stream/index.d.ts +++ b/types/gridfs-stream/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/aheckmann/gridfs-stream // Definitions by: Lior Mualem // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index d83df18cf5..e115aa0666 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mongodb/node-mongodb-native/tree/2.2 // Definitions by: Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 // Documentation : http://mongodb.github.io/node-mongodb-native/2.2/api/ @@ -496,14 +497,13 @@ export interface Collection { dropIndexes(): Promise; dropIndexes(callback?: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find - find(query?: Object): Cursor; - find(query?: Object): Cursor; + find(query?: Object): Cursor; /** @deprecated */ - find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; + find(query: Object, fields?: Object, skip?: number, limit?: number, timeout?: number): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne - findOne(filter: Object, callback: MongoCallback): void; - findOne(filter: Object, options?: FindOneOptions): Promise; - findOne(filter: Object, options: FindOneOptions, callback: MongoCallback): void; + findOne(filter: Object, callback: MongoCallback): void; + findOne(filter: Object, options?: FindOneOptions): Promise; + findOne(filter: Object, options: FindOneOptions, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOneAndDelete findOneAndDelete(filter: Object, callback: MongoCallback): void; findOneAndDelete(filter: Object, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise; @@ -996,8 +996,10 @@ export interface WriteOpResult { //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#~resultCallback export type CursorResult = any | void | boolean; +type Default = { [key: string]: any }; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html -export class Cursor extends Readable { +export class Cursor extends Readable { sortValue: string; timeout: boolean; @@ -1048,8 +1050,8 @@ export class Cursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#min min(min: number): Cursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#next - next(): Promise; - next(callback: MongoCallback): void; + next(): Promise; + next(callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#project project(value: Object): Cursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#read @@ -1101,7 +1103,7 @@ export interface EndCallback { //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#~resultCallback export type AggregationCursorResult = any | void; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html -export class AggregationCursor extends Readable { +export class AggregationCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#batchSize batchSize(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#clone @@ -1127,8 +1129,8 @@ export class AggregationCursor extends Readable { // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#maxTimeMS maxTimeMS(value: number): AggregationCursor; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#next - next(): Promise; - next(callback: MongoCallback): void; + next(): Promise; + next(callback: MongoCallback): void; // http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#out out(destination: string): AggregationCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/AggregationCursor.html#project diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index a41fd4ba7e..e4c7f3bd8a 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -53,7 +53,7 @@ let options = { }); { - let cursor: mongodb.Cursor ; + let cursor: mongodb.Cursor; cursor = collection.find(); cursor = cursor.addCursorFlag('',true); cursor = cursor.addQueryModifier('',true); @@ -81,14 +81,16 @@ let options = { // Collection .findM() & .agggregate() generic tests { let bag : {cost: number, color: string}; - type bag = typeof bag; + type bag = typeof bag; let cursor: mongodb.Cursor = collection.find({color: 'black'}) cursor.toArray(function (err,r) { r[0].cost} ); cursor.forEach(function (bag ) { bag.color }, () => {}); + collection.findOne({ color: 'white' }).then(() => { }) + collection.findOne({ color: 'white' }).then(b => { b.cost; }) } { let payment: {total: number}; - type payment = typeof payment; + type payment = typeof payment; let cursor: mongodb.AggregationCursor = collection.aggregate([{}]) } }) diff --git a/types/mongoose-auto-increment/index.d.ts b/types/mongoose-auto-increment/index.d.ts index 3604b2feaa..fc8813cba7 100644 --- a/types/mongoose-auto-increment/index.d.ts +++ b/types/mongoose-auto-increment/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/codetunnel/mongoose-auto-increment // Definitions by: Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 import { Connection, Schema, Mongoose } from 'mongoose'; diff --git a/types/mongoose-deep-populate/index.d.ts b/types/mongoose-deep-populate/index.d.ts index 9c2de04b49..db01549d67 100644 --- a/types/mongoose-deep-populate/index.d.ts +++ b/types/mongoose-deep-populate/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/buunguyen/mongoose-deep-populate // Definitions by: Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 import { Mongoose, Schema } from 'mongoose'; diff --git a/types/mongoose-mock/index.d.ts b/types/mongoose-mock/index.d.ts index d5adb581d0..0358620566 100644 --- a/types/mongoose-mock/index.d.ts +++ b/types/mongoose-mock/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/JohanObrink/mongoose-mock // Definitions by: jt000 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.3 import mongoose = require('mongoose'); diff --git a/types/mongoose-paginate/index.d.ts b/types/mongoose-paginate/index.d.ts index 6b06c65ac5..2b27c30ad5 100644 --- a/types/mongoose-paginate/index.d.ts +++ b/types/mongoose-paginate/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/edwardhotchkiss/mongoose-paginate // Definitions by: Linus Brolin , simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/mongoose-promise/index.d.ts b/types/mongoose-promise/index.d.ts index d730876e9f..a5e75ea4ab 100644 --- a/types/mongoose-promise/index.d.ts +++ b/types/mongoose-promise/index.d.ts @@ -2,6 +2,7 @@ // Project: http://mongoosejs.com/ // Definitions by: simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/mongoose-sequence/index.d.ts b/types/mongoose-sequence/index.d.ts index b01081944c..f4a4e77f1d 100644 --- a/types/mongoose-sequence/index.d.ts +++ b/types/mongoose-sequence/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/ramiel/mongoose-sequence // Definitions by: Linus Brolin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 8f5d6bdad6..25cf1eb49d 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -2,7 +2,7 @@ // Project: http://mongoosejs.com/ // Definitions by: simonxca , horiuchi , sindrenm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 /// /// diff --git a/types/passport-local-mongoose/index.d.ts b/types/passport-local-mongoose/index.d.ts index acc61d0217..8a2d036c9f 100644 --- a/types/passport-local-mongoose/index.d.ts +++ b/types/passport-local-mongoose/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/saintedlama/passport-local-mongoose // Definitions by: Linus Brolin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// From 1f3527ba51b6b58d06ea4202a42134876f93e4f5 Mon Sep 17 00:00:00 2001 From: beary Date: Thu, 8 Jun 2017 10:58:40 +0800 Subject: [PATCH 54/98] Add default type argument to Collection interface --- types/mongodb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index a84fc60a40..a7c73e0799 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -443,7 +443,7 @@ export interface FSyncOptions { } // Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html -export interface Collection { +export interface Collection { // Get the collection name. collectionName: string; // Get the full collection namespace. From 046b7d5ff9a7f8754628595153c783f231a0bb11 Mon Sep 17 00:00:00 2001 From: Niklas Wulf Date: Thu, 8 Jun 2017 15:33:24 +0200 Subject: [PATCH 55/98] [Boom, Hapi] Add default generic type to all error creation functions (#17048) * [Boom] Add default generic type to all error creation functions * [Boom] Change default generic Data type to any instead of null * [Boom] Add tests for error creation without custom data * [Boom, Hapi] Move tests for passing Boom errors to Hapi continuation functions into hapi package * [boom] add wrap and unauthorized return BoomError with data as null --- types/boom/boom-tests.ts | 59 +++++++++++++++++++- types/boom/index.d.ts | 74 +++++++++++++------------- types/hapi/test/continuation/errors.ts | 57 ++++++++++++++++++++ types/hapi/tsconfig.json | 1 + 4 files changed, 153 insertions(+), 38 deletions(-) create mode 100644 types/hapi/test/continuation/errors.ts diff --git a/types/boom/boom-tests.ts b/types/boom/boom-tests.ts index e64ac44922..38dc39058f 100644 --- a/types/boom/boom-tests.ts +++ b/types/boom/boom-tests.ts @@ -1,9 +1,11 @@ import Boom = require('boom'); +import * as Hapi from 'hapi'; // 4xx and data type const badRequestError = Boom.badRequest('message', {some: 'data'}); badRequestError.data.some; +const badRequestError2: Boom.BoomError = Boom.badImplementation('message'); const unauthorizedError1 = Boom.unauthorized('message', 'scheme', {some: 'attribute'}); unauthorizedError1.output.payload.attributes === { some: 'attribute', error: 'message' }; @@ -23,89 +25,116 @@ unauthorizedError4.output.headers === { 'WWW-Authenticate': 'scheme some="attrib const paymentRequiredError = Boom.paymentRequired('message', {some: 'data'}); paymentRequiredError.data.some; +const paymentRequiredError2: Boom.BoomError = Boom.paymentRequired('message'); const forbiddenError = Boom.forbidden('message', {some: 'data'}); forbiddenError.data.some; +const forbiddenError2: Boom.BoomError = Boom.forbidden('message'); const notFoundError = Boom.notFound('message', {some: 'data'}); notFoundError.data.some; +const notFoundError2: Boom.BoomError = Boom.notFound('message'); const methodNotAllowedError = Boom.methodNotAllowed('message', {some: 'data'}); methodNotAllowedError.data.some; +const methodNotAllowedError2: Boom.BoomError = Boom.methodNotAllowed('message'); const notAcceptableError = Boom.notAcceptable('message', {some: 'data'}); notAcceptableError.data.some; +const notAcceptableError2: Boom.BoomError = Boom.notAcceptable('message'); const proxyAuthRequiredError = Boom.proxyAuthRequired('message', {some: 'data'}); proxyAuthRequiredError.data.some; +const proxyAuthRequiredError2: Boom.BoomError = Boom.proxyAuthRequired('message'); const clientTimeoutError = Boom.clientTimeout('message', {some: 'data'}); clientTimeoutError.data.some; +const clientTimeoutError2: Boom.BoomError = Boom.clientTimeout('message'); const conflictError = Boom.conflict('message', {some: 'data'}); conflictError.data.some; const resourceGoneError = Boom.resourceGone('message', {some: 'data'}); resourceGoneError.data.some; +const resourceGoneError2: Boom.BoomError = Boom.resourceGone('message'); const lengthRequiredError = Boom.lengthRequired('message', {some: 'data'}); lengthRequiredError.data.some; +const lengthRequiredError2: Boom.BoomError = Boom.lengthRequired('message'); const preconditionFailedError = Boom.preconditionFailed('message', {some: 'data'}); preconditionFailedError.data.some; +const preconditionFailedError2: Boom.BoomError = Boom.preconditionFailed('message'); const entityTooLargeError = Boom.entityTooLarge('message', {some: 'data'}); entityTooLargeError.data.some; +const entityTooLargeError2: Boom.BoomError = Boom.lengthRequired('message'); const uriTooLongError = Boom.uriTooLong('message', {some: 'data'}); uriTooLongError.data.some; +const uriTooLongError2: Boom.BoomError = Boom.uriTooLong('message'); const unsupportedMediaTypeError = Boom.unsupportedMediaType('message', {some: 'data'}); unsupportedMediaTypeError.data.some; +const unsupportedMediaTypeError2: Boom.BoomError = Boom.unsupportedMediaType('message'); const rangeNotSatisfiableError = Boom.rangeNotSatisfiable('message', {some: 'data'}); rangeNotSatisfiableError.data.some; +const rangeNotSatisfiableError2: Boom.BoomError = Boom.rangeNotSatisfiable('message'); const expectationFailedError = Boom.expectationFailed('message', {some: 'data'}); expectationFailedError.data.some; +const expectationFailedError2: Boom.BoomError = Boom.expectationFailed('message'); const teapotError = Boom.teapot('message', {some: 'data'}); teapotError.data.some; +const teapotError2: Boom.BoomError = Boom.teapot('message'); const badDataError = Boom.badData('message', {some: 'data'}); badDataError.data.some; +const badDataError2: Boom.BoomError = Boom.badData('message'); const lockedError = Boom.locked('message', {some: 'data'}); lockedError.data.some; +const lockedError2: Boom.BoomError = Boom.locked('message'); const preconditionRequiredError = Boom.preconditionRequired('message', {some: 'data'}); preconditionRequiredError.data.some; +const preconditionRequiredError2: Boom.BoomError = Boom.preconditionRequired('message'); const tooManyRequestsError = Boom.tooManyRequests('message', {some: 'data'}); tooManyRequestsError.data.some; +const tooManyRequestsError2: Boom.BoomError = Boom.tooManyRequests('message'); const illegalError = Boom.illegal('message', {some: 'data'}); illegalError.data.some; +const illegalError2: Boom.BoomError = Boom.illegal('message'); // 5xx and data type const badImplementationError = Boom.badImplementation('message', {some: 'data'}); badImplementationError.data.some; +const badImplementationError2: Boom.BoomError = Boom.badImplementation('message'); const internalError = Boom.internal('message', {some: 'data'}); internalError.data.some; +const internalError2: Boom.BoomError = Boom.internal('message'); const notImplementedError = Boom.notImplemented('message', {some: 'data'}); notImplementedError.data.some; +const notImplementedError2: Boom.BoomError = Boom.notImplemented('message'); const badGatewayError = Boom.badGateway('message', {some: 'data'}); badGatewayError.data.some; +const badGatewayError2: Boom.BoomError = Boom.badGateway('message'); const serverUnavailableError = Boom.serverUnavailable('message', {some: 'data'}); serverUnavailableError.data.some; +const serverUnavailableError2: Boom.BoomError = Boom.serverUnavailable('message'); const gatewayTimeoutError = Boom.gatewayTimeout('message', {some: 'data'}); gatewayTimeoutError.data.some; +const gatewayTimeoutError2: Boom.BoomError = Boom.gatewayTimeout('message'); // wrap and create @@ -113,8 +142,9 @@ const wrappedError = Boom.wrap(new Error('test'), 400, 'some message'); const error1 = Boom.create(500, 'Internal server error', { timestamp: Date.now() }); error1.data.timestamp; +const error2: Boom.BoomError = Boom.create(500, 'Internal server error'); -// type widden asserting +// type widen asserting const unauthorizedError = Boom.unauthorized() as Error; @@ -133,3 +163,30 @@ interface CustomPayload extends Boom.Payload { } (error.output.payload as CustomPayload).custom = 'abc_123'; + +/** + * Test assignment of custom error data: + */ +const errorWithData = Boom.badImplementation('', { custom1: 'test', customType: 'Custom1', isCustom: true } as CustomData1); +const errorWithNoExplicitDataType: Boom.BoomError = errorWithData; // can assign to error without explicit data type +const errorWithExplicitType: Boom.BoomError = errorWithData; // can assign to union data type +const errorWithConcreteCustomData: Boom.BoomError = errorWithData; // can assign to concrete data type +// assignment to CustomData2 would not be possible +// const errorWithConcreteCustomData2: Boom.BoomError = errorWithData; + +// Some complex error data types for testing purposes: +interface CustomDataBase { + isCustom: true; +} + +interface CustomData1 extends CustomDataBase { + customType: 'Custom1'; + custom1: string; +} + +interface CustomData2 extends CustomDataBase { + customType: 'Custom2'; + custom2: string; +} + +type CustomData = CustomData1 | CustomData2; diff --git a/types/boom/index.d.ts b/types/boom/index.d.ts index 02cf60c6b8..b8f41a85be 100644 --- a/types/boom/index.d.ts +++ b/types/boom/index.d.ts @@ -12,7 +12,7 @@ declare namespace Boom { * boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: * @see {@link https://github.com/hapijs/boom#boom} */ - export interface BoomError extends Error { + export interface BoomError extends Error { /** isBoom - if true, indicates this is a Boom object instance. */ isBoom: boolean; /** isServer - convenience bool indicating status code >= 500. */ @@ -25,7 +25,7 @@ declare namespace Boom { reformat: () => string; /** "If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object." mentioned in @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes} */ isMissing?: boolean; - /** https://github.com/hapijs/boom#createstatuscode-message-data */ + /** https://github.com/hapijs/boom#createstatuscode-message-data and https://github.com/hapijs/boom/blob/v4.3.0/lib/index.js#L99 */ data: Data; } @@ -61,7 +61,7 @@ declare namespace Boom { * @param message optional message string. If the error already has a message, it adds the message as a prefix. Defaults to no message. * @see {@link https://github.com/hapijs/boom#wraperror-statuscode-message} */ - export function wrap(error: Error, statusCode?: number, message?: string): BoomError; + export function wrap(error: Error, statusCode?: number, message?: string): BoomError; /** * Generates an Error object with the boom decorations @@ -70,7 +70,7 @@ declare namespace Boom { * @param data additional error data set to error.data property. * @see {@link https://github.com/hapijs/boom#createstatuscode-message-data} */ - export function create(statusCode: number, message?: string, data?: Data): BoomError; + export function create(statusCode: number, message?: string, data?: Data): BoomError; // 4xx /** @@ -79,7 +79,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadrequestmessage-data} */ - export function badRequest(message?: string, data?: Data): BoomError; + export function badRequest(message?: string, data?: Data): BoomError; /** * Returns a 401 Unauthorized error @@ -90,10 +90,10 @@ declare namespace Boom { * @param attributes an object of values to use while setting the 'WWW-Authenticate' header. This value is only used when scheme is a string, otherwise it is ignored. Every key/value pair will be included in the 'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the attributes key. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. null and undefined will be replaced with an empty string. If attributes is set, message will be used as the 'error' segment of the 'WWW-Authenticate' header. If message is unset, the 'error' segment of the header will not be present and isMissing will be true on the error object. * @see {@link https://github.com/hapijs/boom#boomunauthorizedmessage-scheme-attributes} */ - export function unauthorized(message?: string, scheme?: string, attributes?: {[index: string]: string}): BoomError; - export function unauthorized(message?: string, scheme?: string[]): BoomError; - export function unauthorized(message?: null, scheme?: string, attributes?: {[index: string]: string} | string): BoomError; - export function unauthorized(message?: null, scheme?: string[]): BoomError; + export function unauthorized(message?: string, scheme?: string, attributes?: {[index: string]: string}): BoomError; + export function unauthorized(message?: string, scheme?: string[]): BoomError; + export function unauthorized(message?: null, scheme?: string, attributes?: {[index: string]: string} | string): BoomError; + export function unauthorized(message?: null, scheme?: string[]): BoomError; /** * Returns a 402 Payment Required error @@ -101,7 +101,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompaymentrequiredmessage-data} */ - export function paymentRequired(message?: string, data?: Data): BoomError; + export function paymentRequired(message?: string, data?: Data): BoomError; /** * Returns a 403 Forbidden error @@ -109,7 +109,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomforbiddenmessage-data} */ - export function forbidden(message?: string, data?: Data): BoomError; + export function forbidden(message?: string, data?: Data): BoomError; /** * Returns a 404 Not Found error @@ -117,7 +117,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotfoundmessage-data} */ - export function notFound(message?: string, data?: Data): BoomError; + export function notFound(message?: string, data?: Data): BoomError; /** * Returns a 405 Method Not Allowed error @@ -126,7 +126,7 @@ declare namespace Boom { * @param allow optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header. * @see {@link https://github.com/hapijs/boom#boommethodnotallowedmessage-data-allow} */ - export function methodNotAllowed(message?: string, data?: Data, allow?: string | string[]): BoomError; + export function methodNotAllowed(message?: string, data?: Data, allow?: string | string[]): BoomError; /** * Returns a 406 Not Acceptable error @@ -134,7 +134,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotacceptablemessage-data} */ - export function notAcceptable(message?: string, data?: Data): BoomError; + export function notAcceptable(message?: string, data?: Data): BoomError; /** * Returns a 407 Proxy Authentication Required error @@ -142,7 +142,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomproxyauthrequiredmessage-data} */ - export function proxyAuthRequired(message?: string, data?: Data): BoomError; + export function proxyAuthRequired(message?: string, data?: Data): BoomError; /** * Returns a 408 Request Time-out error @@ -150,7 +150,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomclienttimeoutmessage-data} */ - export function clientTimeout(message?: string, data?: Data): BoomError; + export function clientTimeout(message?: string, data?: Data): BoomError; /** * Returns a 409 Conflict error @@ -158,7 +158,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomconflictmessage-data} */ - export function conflict(message?: string, data?: Data): BoomError; + export function conflict(message?: string, data?: Data): BoomError; /** * Returns a 410 Gone error @@ -166,7 +166,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomresourcegonemessage-data} */ - export function resourceGone(message?: string, data?: Data): BoomError; + export function resourceGone(message?: string, data?: Data): BoomError; /** * Returns a 411 Length Required error @@ -174,7 +174,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomlengthrequiredmessage-data} */ - export function lengthRequired(message?: string, data?: Data): BoomError; + export function lengthRequired(message?: string, data?: Data): BoomError; /** * Returns a 412 Precondition Failed error @@ -182,7 +182,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompreconditionfailedmessage-data} */ - export function preconditionFailed(message?: string, data?: Data): BoomError; + export function preconditionFailed(message?: string, data?: Data): BoomError; /** * Returns a 413 Request Entity Too Large error @@ -190,7 +190,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomentitytoolargemessage-data} */ - export function entityTooLarge(message?: string, data?: Data): BoomError; + export function entityTooLarge(message?: string, data?: Data): BoomError; /** * Returns a 414 Request-URI Too Large error @@ -198,7 +198,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomuritoolongmessage-data} */ - export function uriTooLong(message?: string, data?: Data): BoomError; + export function uriTooLong(message?: string, data?: Data): BoomError; /** * Returns a 415 Unsupported Media Type error @@ -206,7 +206,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomunsupportedmediatypemessage-data} */ - export function unsupportedMediaType(message?: string, data?: Data): BoomError; + export function unsupportedMediaType(message?: string, data?: Data): BoomError; /** * Returns a 416 Requested Range Not Satisfiable error @@ -214,7 +214,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomrangenotsatisfiablemessage-data} */ - export function rangeNotSatisfiable(message?: string, data?: Data): BoomError; + export function rangeNotSatisfiable(message?: string, data?: Data): BoomError; /** * Returns a 417 Expectation Failed error @@ -222,7 +222,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomexpectationfailedmessage-data} */ - export function expectationFailed(message?: string, data?: Data): BoomError; + export function expectationFailed(message?: string, data?: Data): BoomError; /** * Returns a 418 I'm a Teapot error @@ -230,7 +230,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomteapotmessage-data} */ - export function teapot(message?: string, data?: Data): BoomError; + export function teapot(message?: string, data?: Data): BoomError; /** * Returns a 422 Unprocessable Entity error @@ -238,7 +238,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombaddatamessage-data} */ - export function badData(message?: string, data?: Data): BoomError; + export function badData(message?: string, data?: Data): BoomError; /** * Returns a 423 Locked error @@ -246,7 +246,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomlockedmessage-data} */ - export function locked(message?: string, data?: Data): BoomError; + export function locked(message?: string, data?: Data): BoomError; /** * Returns a 428 Precondition Required error @@ -254,7 +254,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boompreconditionrequiredmessage-data} */ - export function preconditionRequired(message?: string, data?: Data): BoomError; + export function preconditionRequired(message?: string, data?: Data): BoomError; /** * Returns a 429 Too Many Requests error @@ -262,7 +262,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomtoomanyrequestsmessage-data} */ - export function tooManyRequests(message?: string, data?: Data): BoomError; + export function tooManyRequests(message?: string, data?: Data): BoomError; /** * Returns a 451 Unavailable For Legal Reasons error @@ -270,7 +270,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomillegalmessage-data} */ - export function illegal(message?: string, data?: Data): BoomError; + export function illegal(message?: string, data?: Data): BoomError; // 5xx /** @@ -280,7 +280,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal} */ - export function badImplementation(message?: string, data?: Data): BoomError; + export function badImplementation(message?: string, data?: Data): BoomError; /** * Returns a 500 Internal Server Error error @@ -289,7 +289,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadimplementationmessage-data---alias-internal} */ - export function internal(message?: string, data?: Data): BoomError; + export function internal(message?: string, data?: Data): BoomError; /** * Returns a 501 Not Implemented error with your error message to the user @@ -297,7 +297,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomnotimplementedmessage-data} */ - export function notImplemented(message?: string, data?: Data): BoomError; + export function notImplemented(message?: string, data?: Data): BoomError; /** * Returns a 502 Bad Gateway error with your error message to the user @@ -305,7 +305,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boombadgatewaymessage-data} */ - export function badGateway(message?: string, data?: Data): BoomError; + export function badGateway(message?: string, data?: Data): BoomError; /** * Returns a 503 Service Unavailable error with your error message to the user @@ -313,7 +313,7 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomserverunavailablemessage-data} */ - export function serverUnavailable(message?: string, data?: Data): BoomError; + export function serverUnavailable(message?: string, data?: Data): BoomError; /** * Returns a 504 Gateway Time-out error with your error message to the user @@ -321,5 +321,5 @@ declare namespace Boom { * @param data optional additional error data. * @see {@link https://github.com/hapijs/boom#boomgatewaytimeoutmessage-data} */ - export function gatewayTimeout(message?: string, data?: Data): BoomError; + export function gatewayTimeout(message?: string, data?: Data): BoomError; } diff --git a/types/hapi/test/continuation/errors.ts b/types/hapi/test/continuation/errors.ts new file mode 100644 index 0000000000..165e5214df --- /dev/null +++ b/types/hapi/test/continuation/errors.ts @@ -0,0 +1,57 @@ + +import * as Hapi from 'hapi'; +import * as Boom from 'boom'; + +// Assignment of a typical function to ContinuationValueFunction is possible +const handleError: Hapi.ContinuationValueFunction = (err?: Boom.BoomError | null, value?: any) => { + if (!err || !err.data.isCustom === true) { + return; + } + + // assignment is possible due to default generic Data = any + const customError: Boom.BoomError = err; + + // Discriminated union type works: + switch (customError.data.customType) { + case 'Custom1': + customError.data.custom1; + break; + case 'Custom2': + customError.data.custom2; + break; + } +}; + +// Accepts a simple Boom error +handleError(Boom.badData()); + +// Accepts an error with custom data +const errorWithData = Boom.badImplementation('', { custom1: 'test', customType: <'Custom1'>'Custom1', isCustom: true }); +handleError(errorWithData); + +// Accepts an error with a more explicit type +const errorWithExplicitType: Boom.BoomError = errorWithData; +handleError(errorWithExplicitType); + +// Accepts an error with an even more explicit type +const errorWithConcreteCustomData: Boom.BoomError = errorWithData; // assignment to CustomData2 would not be possible +handleError(errorWithConcreteCustomData); + +/** + * Some complex error data types: + */ +interface CustomDataBase { + isCustom: true; +} + +interface CustomData1 extends CustomDataBase { + customType: 'Custom1'; + custom1: string; +} + +interface CustomData2 extends CustomDataBase { + customType: 'Custom2'; + custom2: string; +} + +type CustomData = CustomData1 | CustomData2; diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index ef8e454667..01c5a12c89 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -18,6 +18,7 @@ "files": [ "index.d.ts", "test/connection/table.ts", + "test/continuation/errors.ts", "test/getting-started/01-creating-a-server.ts", "test/getting-started/02-adding-routes.ts", "test/getting-started/03-serving-static-content.ts", From 35f275c0812af7ff70cd5d044bc5370e242adb4f Mon Sep 17 00:00:00 2001 From: York Yao Date: Thu, 8 Jun 2017 21:39:20 +0800 Subject: [PATCH 56/98] [electron]remove electron because the it bundles one now (#16928) * remove electron because the it bundles one now * update asOfVersion * fix asOfVersion --- notNeededPackages.json | 6 + types/electron/.editorconfig | 2 - types/electron/index.d.ts | 6147 ------------------------------- types/electron/test/index.ts | 5 - types/electron/test/main.ts | 1138 ------ types/electron/test/renderer.ts | 311 -- types/electron/tsconfig.json | 25 - 7 files changed, 6 insertions(+), 7628 deletions(-) delete mode 100644 types/electron/.editorconfig delete mode 100644 types/electron/index.d.ts delete mode 100644 types/electron/test/index.ts delete mode 100644 types/electron/test/main.ts delete mode 100644 types/electron/test/renderer.ts delete mode 100644 types/electron/tsconfig.json diff --git a/notNeededPackages.json b/notNeededPackages.json index b251774ee9..d6e99fbf9b 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -126,6 +126,12 @@ "sourceRepoURL": "https://github.com/bterlson/ecmarkup", "asOfVersion": "3.4.0" }, + { + "libraryName": "electron", + "typingsPackageName": "electron", + "sourceRepoURL": "https://github.com/electron/electron", + "asOfVersion": "1.6.10" + }, { "libraryName": "electron-builder", "typingsPackageName": "electron-builder", diff --git a/types/electron/.editorconfig b/types/electron/.editorconfig deleted file mode 100644 index 2d98d905de..0000000000 --- a/types/electron/.editorconfig +++ /dev/null @@ -1,2 +0,0 @@ -[*.ts] -indent_style = tab diff --git a/types/electron/index.d.ts b/types/electron/index.d.ts deleted file mode 100644 index 6905671344..0000000000 --- a/types/electron/index.d.ts +++ /dev/null @@ -1,6147 +0,0 @@ -// Type definitions for Electron v1.4.8 -// Project: http://electron.atom.io/ -// Definitions by: jedmao , rhysd , Milan Burda , aliib , Daniel Perez Alvarez , Markus Olsson -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Electron { - - interface Event { - preventDefault: Function; - sender: NodeJS.EventEmitter; - } - - type Point = { - x: number; - y: number; - } - - type Size = { - width: number; - height: number; - } - - type Rectangle = { - x: number; - y: number; - width: number; - height: number; - } - - interface Destroyable { - /** - * Destroys the object. - */ - destroy(): void; - /** - * @returns Whether the object is destroyed. - */ - isDestroyed(): boolean; - } - - // https://github.com/electron/electron/blob/master/docs/api/app.md - - type VibrancyType = 'appearance-based' | 'light' | 'dark' | 'titlebar' | 'selection' | 'menu' | 'popover' | 'sidebar' | 'medium-light' | 'ultra-dark'; - - /** - * The app module is responsible for controlling the application's lifecycle. - */ - interface App extends NodeJS.EventEmitter { - /** - * Emitted when the application has finished basic startup. - * On Windows and Linux, the will-finish-launching event - * is the same as the ready event; on macOS, this event represents - * the applicationWillFinishLaunching notification of NSApplication. - * You would usually set up listeners for the open-file and open-url events here, - * and start the crash reporter and auto updater. - * - * In most cases, you should just do everything in the ready event handler. - */ - on(event: 'will-finish-launching', listener: Function): this; - /** - * Emitted when Electron has finished initialization. - */ - on(event: 'ready', listener: (event: Event, launchInfo: Object) => void): this; - /** - * Emitted when all windows have been closed. - * - * If you do not subscribe to this event and all windows are closed, - * the default behavior is to quit the app; however, if you subscribe, - * you control whether the app quits or not. - * If the user pressed Cmd + Q, or the developer called app.quit(), - * Electron will first try to close all the windows and then emit the will-quit event, - * and in this case the window-all-closed event would not be emitted. - */ - on(event: 'window-all-closed', listener: Function): this; - /** - * Emitted before the application starts closing its windows. - * Calling event.preventDefault() will prevent the default behaviour, which is terminating the application. - */ - on(event: 'before-quit', listener: (event: Event) => void): this; - /** - * Emitted when all windows have been closed and the application will quit. - * Calling event.preventDefault() will prevent the default behaviour, which is terminating the application. - */ - on(event: 'will-quit', listener: (event: Event) => void): this; - /** - * Emitted when the application is quitting. - */ - on(event: 'quit', listener: (event: Event, exitCode: number) => void): this; - /** - * Emitted when the user wants to open a file with the application. - * The open-file event is usually emitted when the application is already open - * and the OS wants to reuse the application to open the file. - * open-file is also emitted when a file is dropped onto the dock and the application - * is not yet running. Make sure to listen for the open-file event very early - * in your application startup to handle this case (even before the ready event is emitted). - * - * You should call event.preventDefault() if you want to handle this event. - * - * Note: This is only implemented on macOS. - */ - on(event: 'open-file', listener: (event: Event, url: string) => void): this; - /** - * Emitted when the user wants to open a URL with the application. - * The URL scheme must be registered to be opened by your application. - * - * You should call event.preventDefault() if you want to handle this event. - * - * Note: This is only implemented on macOS. - */ - on(event: 'open-url', listener: (event: Event, url: string) => void): this; - /** - * Emitted when the application is activated, which usually happens when clicks on the applications’s dock icon. - * Note: This is only implemented on macOS. - */ - on(event: 'activate', listener: Function): this; - /** - * Emitted during Handoff when an activity from a different device wants to be resumed. - * You should call event.preventDefault() if you want to handle this event. - */ - on(event: 'continue-activity', listener: (event: Event, type: string, userInfo: Object) => void): this; - /** - * Emitted when a browserWindow gets blurred. - */ - on(event: 'browser-window-blur', listener: (event: Event, browserWindow: BrowserWindow) => void): this; - /** - * Emitted when a browserWindow gets focused. - */ - on(event: 'browser-window-focus', listener: (event: Event, browserWindow: BrowserWindow) => void): this; - /** - * Emitted when a new browserWindow is created. - */ - on(event: 'browser-window-created', listener: (event: Event, browserWindow: BrowserWindow) => void): this; - /** - * Emitted when a new webContents is created. - */ - on(event: 'web-contents-created', listener: (event: Event, webContents: WebContents) => void): this; - /** - * Emitted when failed to verify the certificate for url, to trust the certificate - * you should prevent the default behavior with event.preventDefault() and call callback(true). - */ - on(event: 'certificate-error', listener: (event: Event, - webContents: WebContents, - url: string, - error: string, - certificate: Certificate, - callback: (trust: boolean) => void - ) => void): this; - /** - * Emitted when a client certificate is requested. - * - * The url corresponds to the navigation entry requesting the client certificate - * and callback needs to be called with an entry filtered from the list. - * Using event.preventDefault() prevents the application from using the first certificate from the store. - */ - on(event: 'select-client-certificate', listener: (event: Event, - webContents: WebContents, - url: string, - certificateList: Certificate[], - callback: (certificate: Certificate) => void - ) => void): this; - /** - * Emitted when webContents wants to do basic auth. - * - * The default behavior is to cancel all authentications, to override this - * you should prevent the default behavior with event.preventDefault() - * and call callback(username, password) with the credentials. - */ - on(event: 'login', listener: (event: Event, - webContents: WebContents, - request: LoginRequest, - authInfo: LoginAuthInfo, - callback: (username: string, password: string) => void - ) => void): this; - /** - * Emitted when the gpu process crashes. - */ - on(event: 'gpu-process-crashed', listener: (event: Event, killed: boolean) => void): this; - /** - * Emitted when Chrome's accessibility support changes. - * - * Note: This API is only available on macOS and Windows. - */ - on(event: 'accessibility-support-changed', listener: (event: Event, accessibilitySupportEnabled: boolean) => void): this; - on(event: string, listener: Function): this; - /** - * Try to close all windows. The before-quit event will first be emitted. - * If all windows are successfully closed, the will-quit event will be emitted - * and by default the application would be terminated. - * - * This method guarantees all beforeunload and unload handlers are correctly - * executed. It is possible that a window cancels the quitting by returning - * false in beforeunload handler. - */ - quit(): void; - /** - * Exits immediately with exitCode. - * All windows will be closed immediately without asking user - * and the before-quit and will-quit events will not be emitted. - */ - exit(exitCode?: number): void; - /** - * Relaunches the app when current instance exits. - * - * By default the new instance will use the same working directory - * and command line arguments with current instance. - * When args is specified, the args will be passed as command line arguments instead. - * When execPath is specified, the execPath will be executed for relaunch instead of current app. - * - * Note that this method does not quit the app when executed, you have to call app.quit - * or app.exit after calling app.relaunch to make the app restart. - * - * When app.relaunch is called for multiple times, multiple instances - * will be started after current instance exited. - */ - relaunch(options?: { - args?: string[], - execPath?: string - }): void; - /** - * @returns Whether Electron has finished initializing. - */ - isReady(): boolean; - /** - * On Linux, focuses on the first visible window. - * On macOS, makes the application the active app. - * On Windows, focuses on the application’s first window. - */ - focus(): void; - /** - * Hides all application windows without minimizing them. - * Note: This is only implemented on macOS. - */ - hide(): void; - /** - * Shows application windows after they were hidden. Does not automatically focus them. - * Note: This is only implemented on macOS. - */ - show(): void; - /** - * Returns the current application directory. - */ - getAppPath(): string; - /** - * @returns The path to a special directory or file associated with name. - * On failure an Error would throw. - */ - getPath(name: AppPathName): string; - /** - * Overrides the path to a special directory or file associated with name. - * If the path specifies a directory that does not exist, the directory will - * be created by this method. On failure an Error would throw. - * - * You can only override paths of names defined in app.getPath. - * - * By default web pages' cookies and caches will be stored under userData - * directory, if you want to change this location, you have to override the - * userData path before the ready event of app module gets emitted. - */ - setPath(name: AppPathName, path: string): void; - /** - * @returns The version of loaded application, if no version is found in - * application's package.json, the version of current bundle or executable. - */ - getVersion(): string; - /** - * @returns The current application's name, the name in package.json would be used. - * Usually the name field of package.json is a short lowercased name, according to - * the spec of npm modules. So usually you should also specify a productName field, - * which is your application's full capitalized name, and it will be preferred over - * name by Electron. - */ - getName(): string; - /** - * Overrides the current application's name. - */ - setName(name: string): void; - /** - * @returns The current application locale. - */ - getLocale(): string; - /** - * Adds path to recent documents list. - * - * This list is managed by the system, on Windows you can visit the list from - * task bar, and on macOS you can visit it from dock menu. - * - * Note: This is only implemented on macOS and Windows. - */ - addRecentDocument(path: string): void; - /** - * Clears the recent documents list. - * - * Note: This is only implemented on macOS and Windows. - */ - clearRecentDocuments(): void; - /** - * Sets the current executable as the default handler for a protocol (aka URI scheme). - * Once registered, all links with your-protocol:// will be opened with the current executable. - * The whole link, including protocol, will be passed to your application as a parameter. - * - * On Windows you can provide optional parameters path, the path to your executable, - * and args, an array of arguments to be passed to your executable when it launches. - * - * @param protocol The name of your protocol, without ://. - * @param path Defaults to process.execPath. - * @param args Defaults to an empty array. - * - * Note: This is only implemented on macOS and Windows. - * On macOS, you can only register protocols that have been added to your app's info.plist. - */ - setAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; - /** - * Removes the current executable as the default handler for a protocol (aka URI scheme). - * - * @param protocol The name of your protocol, without ://. - * @param path Defaults to process.execPath. - * @param args Defaults to an empty array. - * - * Note: This is only implemented on macOS and Windows. - */ - removeAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; - /** - * @param protocol The name of your protocol, without ://. - * @param path Defaults to process.execPath. - * @param args Defaults to an empty array. - * - * @returns Whether the current executable is the default handler for a protocol (aka URI scheme). - * - * Note: This is only implemented on macOS and Windows. - */ - isDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean; - /** - * Adds tasks to the Tasks category of JumpList on Windows. - * - * Note: This API is only available on Windows. - */ - setUserTasks(tasks: Task[]): boolean; - /** - * Note: This API is only available on Windows. - */ - getJumpListSettings(): JumpListSettings; - /** - * Sets or removes a custom Jump List for the application. - * - * If categories is null the previously set custom Jump List (if any) will be replaced - * by the standard Jump List for the app (managed by Windows). - * - * Note: This API is only available on Windows. - */ - setJumpList(categories: JumpListCategory[]): SetJumpListResult; - /** - * This method makes your application a Single Instance Application instead of allowing - * multiple instances of your app to run, this will ensure that only a single instance - * of your app is running, and other instances signal this instance and exit. - */ - makeSingleInstance(callback: (args: string[], workingDirectory: string) => void): boolean; - /** - * Releases all locks that were created by makeSingleInstance. This will allow - * multiple instances of the application to once again run side by side. - */ - releaseSingleInstance(): void; - /** - * Creates an NSUserActivity and sets it as the current activity. - * The activity is eligible for Handoff to another device afterward. - * - * @param type Uniquely identifies the activity. Maps to NSUserActivity.activityType. - * @param userInfo App-specific state to store for use by another device. - * @param webpageURL The webpage to load in a browser if no suitable app is - * installed on the resuming device. The scheme must be http or https. - * - * Note: This API is only available on macOS. - */ - setUserActivity(type: string, userInfo: Object, webpageURL?: string): void; - /** - * @returns The type of the currently running activity. - * - * Note: This API is only available on macOS. - */ - getCurrentActivityType(): string; - /** - * Changes the Application User Model ID to id. - * - * Note: This is only implemented on Windows. - */ - setAppUserModelId(id: string): void; - /** - * Imports the certificate in pkcs12 format into the platform certificate store. - * @param callback Called with the result of import operation, a value of 0 indicates success - * while any other value indicates failure according to chromium net_error_list. - * - * Note: This API is only available on Linux. - */ - importCertificate(options: ImportCertificateOptions, callback: (result: number) => void): void; - /** - * Disables hardware acceleration for current app. - * This method can only be called before app is ready. - */ - disableHardwareAcceleration(): void; - /** - * Sets the counter badge for current app. Setting the count to 0 will hide the badge. - * - * @returns True when the call succeeded, otherwise returns false. - * - * Note: This API is only available on macOS and Linux. - */ - setBadgeCount(count: number): boolean; - /** - * @returns The current value displayed in the counter badge. - * - * Note: This API is only available on macOS and Linux. - */ - getBadgeCount(): number; - /** - * @returns whether current desktop environment is Unity launcher. (Linux) - * - * Note: This API is only available on Linux. - */ - isUnityRunning(): boolean; - /** - * Returns a Boolean, true if Chrome's accessibility support is enabled, false otherwise. - * This API will return true if the use of assistive technologies, such as screen readers, - * has been detected. - * See https://www.chromium.org/developers/design-documents/accessibility for more details. - * - * Note: This API is only available on macOS and Windows. - */ - isAccessibilitySupportEnabled(): boolean; - /** - * @returns an Object with the login item settings of the app. - * - * Note: This API is only available on macOS and Windows. - */ - getLoginItemSettings(): LoginItemSettings; - /** - * Set the app's login item settings. - * - * Note: This API is only available on macOS and Windows. - */ - setLoginItemSettings(settings: LoginItemSettings): void; - /** - * Set the about panel options. This will override the values defined in the app's .plist file. - * See the Apple docs for more details. - * - * Note: This API is only available on macOS. - */ - setAboutPanelOptions(options: AboutPanelOptions): void; - commandLine: CommandLine; - /** - * Note: This API is only available on macOS. - */ - dock: Dock; - } - - type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'|'pepperFlashSystemPlugin'; - - interface ImportCertificateOptions { - /** - * Path for the pkcs12 file. - */ - certificate: string; - /** - * Passphrase for the certificate. - */ - password: string; - } - - interface CommandLine { - /** - * Append a switch [with optional value] to Chromium's command line. - * - * Note: This will not affect process.argv, and is mainly used by developers - * to control some low-level Chromium behaviors. - */ - appendSwitch(_switch: string, value?: string): void; - /** - * Append an argument to Chromium's command line. The argument will quoted properly. - * - * Note: This will not affect process.argv. - */ - appendArgument(value: string): void; - } - - interface Dock { - /** - * When critical is passed, the dock icon will bounce until either the - * application becomes active or the request is canceled. - * - * When informational is passed, the dock icon will bounce for one second. - * However, the request remains active until either the application becomes - * active or the request is canceled. - * - * @param type The default is informational. - * @returns An ID representing the request. - */ - bounce(type?: 'critical' | 'informational'): number; - /** - * Cancel the bounce of id. - * - * Note: This API is only available on macOS. - */ - cancelBounce(id: number): void; - /** - * Bounces the Downloads stack if the filePath is inside the Downloads folder. - * - * Note: This API is only available on macOS. - */ - downloadFinished(filePath: string): void; - /** - * Sets the string to be displayed in the dock’s badging area. - * - * Note: This API is only available on macOS. - */ - setBadge(text: string): void; - /** - * Returns the badge string of the dock. - * - * Note: This API is only available on macOS. - */ - getBadge(): string; - /** - * Hides the dock icon. - * - * Note: This API is only available on macOS. - */ - hide(): void; - /** - * Shows the dock icon. - * - * Note: This API is only available on macOS. - */ - show(): void; - /** - * @returns Whether the dock icon is visible. - * The app.dock.show() call is asynchronous so this method might not return true immediately after that call. - * - * Note: This API is only available on macOS. - */ - isVisible(): boolean; - /** - * Sets the application dock menu. - * - * Note: This API is only available on macOS. - */ - setMenu(menu: Menu): void; - /** - * Sets the image associated with this dock icon. - * - * Note: This API is only available on macOS. - */ - setIcon(icon: NativeImage | string): void; - } - - interface Task { - /** - * Path of the program to execute, usually you should specify process.execPath - * which opens current program. - */ - program: string; - /** - * The arguments of command line when program is executed. - */ - arguments: string; - /** - * The string to be displayed in a JumpList. - */ - title: string; - /** - * Description of this task. - */ - description?: string; - /** - * The absolute path to an icon to be displayed in a JumpList, it can be - * arbitrary resource file that contains an icon, usually you can specify - * process.execPath to show the icon of the program. - */ - iconPath: string; - /** - * The icon index in the icon file. If an icon file consists of two or more - * icons, set this value to identify the icon. If an icon file consists of - * one icon, this value is 0. - */ - iconIndex?: number; - } - - /** - * ok - Nothing went wrong. - * error - One or more errors occured, enable runtime logging to figure out the likely cause. - * invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List. - * Separators are only allowed in the standard Tasks category. - * fileTypeRegistrationError - An attempt was made to add a file link to the Jump List - * for a file type the app isn't registered to handle. - * customCategoryAccessDeniedError - Custom categories can't be added to the Jump List - * due to user privacy or group policy settings. - */ - type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; - - interface JumpListSettings { - /** - * The minimum number of items that will be shown in the Jump List. - */ - minItems: number; - /** - * Items that the user has explicitly removed from custom categories in the Jump List. - */ - removedItems: JumpListItem[]; - } - - interface JumpListCategory { - /** - * tasks - Items in this category will be placed into the standard Tasks category. - * frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows. - * recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows. - * custom - Displays tasks or file links, name must be set by the app. - */ - type?: 'tasks' | 'frequent' | 'recent' | 'custom'; - /** - * Must be set if type is custom, otherwise it should be omitted. - */ - name?: string; - /** - * Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted. - */ - items?: JumpListItem[]; - } - - interface JumpListItem { - /** - * task - A task will launch an app with specific arguments. - * separator - Can be used to separate items in the standard Tasks category. - * file - A file link will open a file using the app that created the Jump List. - */ - type: 'task' | 'separator' | 'file'; - /** - * Path of the file to open, should only be set if type is file. - */ - path?: string; - /** - * Path of the program to execute, usually you should specify process.execPath which opens the current program. - * Should only be set if type is task. - */ - program?: string; - /** - * The command line arguments when program is executed. Should only be set if type is task. - */ - args?: string; - /** - * The text to be displayed for the item in the Jump List. Should only be set if type is task. - */ - title?: string; - /** - * Description of the task (displayed in a tooltip). Should only be set if type is task. - */ - description?: string; - /** - * The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary - * resource file that contains an icon (e.g. .ico, .exe, .dll). - * You can usually specify process.execPath to show the program icon. - */ - iconPath?: string; - /** - * The index of the icon in the resource file. If a resource file contains multiple icons - * this value can be used to specify the zero-based index of the icon that should be displayed - * for this task. If a resource file contains only one icon, this property should be set to zero. - */ - iconIndex?: number; - } - - interface LoginItemSettings { - /** - * True if the app is set to open at login. - */ - openAtLogin: boolean; - /** - * True if the app is set to open as hidden at login. This setting is only supported on macOS. - */ - openAsHidden: boolean; - /** - * True if the app was opened at login automatically. This setting is only supported on macOS. - */ - wasOpenedAtLogin?: boolean; - /** - * True if the app was opened as a hidden login item. This indicates that the app should not - * open any windows at startup. This setting is only supported on macOS. - */ - wasOpenedAsHidden?: boolean; - /** - * True if the app was opened as a login item that should restore the state from the previous session. - * This indicates that the app should restore the windows that were open the last time the app was closed. - * This setting is only supported on macOS. - */ - restoreState?: boolean; - } - - interface AboutPanelOptions { - /** - * The app's name. - */ - applicationName?: string; - /** - * The app's version. - */ - applicationVersion?: string; - /** - * Copyright information. - */ - copyright?: string; - /** - * Credit information. - */ - credits?: string; - /** - * The app's build version number. - */ - version?: string; - } - - // https://github.com/electron/electron/blob/master/docs/api/auto-updater.md - - /** - * This module provides an interface for the Squirrel auto-updater framework. - */ - interface AutoUpdater extends NodeJS.EventEmitter { - /** - * Emitted when there is an error while updating. - */ - on(event: 'error', listener: (error: Error) => void): this; - /** - * Emitted when checking if an update has started. - */ - on(event: 'checking-for-update', listener: Function): this; - /** - * Emitted when there is an available update. The update is downloaded automatically. - */ - on(event: 'update-available', listener: Function): this; - /** - * Emitted when there is no available update. - */ - on(event: 'update-not-available', listener: Function): this; - /** - * Emitted when an update has been downloaded. - * Note: On Windows only releaseName is available. - */ - on(event: 'update-downloaded', listener: (event: Event, releaseNotes: string, releaseName: string, releaseDate: Date, updateURL: string) => void): this; - on(event: string, listener: Function): this; - /** - * Set the url and initialize the auto updater. - */ - setFeedURL(url: string, requestHeaders?: Headers): void; - /** - * @returns The current update feed URL. - */ - getFeedURL(): string; - /** - * Ask the server whether there is an update, you have to call setFeedURL - * before using this API - */ - checkForUpdates(): void; - /** - * Restarts the app and installs the update after it has been downloaded. - * It should only be called after update-downloaded has been emitted. - */ - quitAndInstall(): void; - } - - // https://github.com/electron/electron/blob/master/docs/api/browser-window.md - - /** - * The BrowserWindow class gives you ability to create a browser window. - * You can also create a window without chrome by using Frameless Window API. - */ - class BrowserWindow extends NodeJS.EventEmitter implements Destroyable { - /** - * Emitted when the document changed its title, - * calling event.preventDefault() would prevent the native window’s title to change. - */ - on(event: 'page-title-updated', listener: (event: Event, title: string) => void): this; - /** - * Emitted when the window is going to be closed. It’s emitted before the beforeunload - * and unload event of the DOM. Calling event.preventDefault() will cancel the close. - */ - on(event: 'close', listener: (event: Event) => void): this; - /** - * Emitted when the window is closed. After you have received this event - * you should remove the reference to the window and avoid using it anymore. - */ - on(event: 'closed', listener: Function): this; - /** - * Emitted when the web page becomes unresponsive. - */ - on(event: 'unresponsive', listener: Function): this; - /** - * Emitted when the unresponsive web page becomes responsive again. - */ - on(event: 'responsive', listener: Function): this; - /** - * Emitted when the window loses focus. - */ - on(event: 'blur', listener: Function): this; - /** - * Emitted when the window gains focus. - */ - on(event: 'focus', listener: Function): this; - /** - * Emitted when the window is shown. - */ - on(event: 'show', listener: Function): this; - /** - * Emitted when the window is hidden. - */ - on(event: 'hide', listener: Function): this; - /** - * Emitted when the web page has been rendered and window can be displayed without visual flash. - */ - on(event: 'ready-to-show', listener: Function): this; - /** - * Emitted when window is maximized. - */ - on(event: 'maximize', listener: Function): this; - /** - * Emitted when the window exits from maximized state. - */ - on(event: 'unmaximize', listener: Function): this; - /** - * Emitted when the window is minimized. - */ - on(event: 'minimize', listener: Function): this; - /** - * Emitted when the window is restored from minimized state. - */ - on(event: 'restore', listener: Function): this; - /** - * Emitted when the window is getting resized. - */ - on(event: 'resize', listener: Function): this; - /** - * Emitted when the window is getting moved to a new position. - */ - on(event: 'move', listener: Function): this; - /** - * Emitted when the window enters full screen state. - */ - on(event: 'enter-full-screen', listener: Function): this; - /** - * Emitted when the window leaves full screen state. - */ - on(event: 'leave-full-screen', listener: Function): this; - /** - * Emitted when the window enters full screen state triggered by HTML API. - */ - on(event: 'enter-html-full-screen', listener: Function): this; - /** - * Emitted when the window leaves full screen state triggered by HTML API. - */ - on(event: 'leave-html-full-screen', listener: Function): this; - /** - * Emitted when an App Command is invoked. These are typically related - * to keyboard media keys or browser commands, as well as the "Back" / - * "Forward" buttons built into some mice on Windows. - * Note: This is only implemented on Windows. - */ - on(event: 'app-command', listener: (event: Event, command: string) => void): this; - /** - * Emitted when scroll wheel event phase has begun. - * Note: This is only implemented on macOS. - */ - on(event: 'scroll-touch-begin', listener: Function): this; - /** - * Emitted when scroll wheel event phase has ended. - * Note: This is only implemented on macOS. - */ - on(event: 'scroll-touch-end', listener: Function): this; - /** - * Emitted when scroll wheel event phase filed upon reaching the edge of element. - * Note: This is only implemented on macOS. - */ - on(event: 'scroll-touch-edge', listener: Function): this; - /** - * Emitted on 3-finger swipe. - * Note: This is only implemented on macOS. - */ - on(event: 'swipe', listener: (event: Event, direction: SwipeDirection) => void): this; - on(event: string, listener: Function): this; - /** - * Creates a new BrowserWindow with native properties as set by the options. - */ - constructor(options?: BrowserWindowOptions); - /** - * @returns All opened browser windows. - */ - static getAllWindows(): BrowserWindow[]; - /** - * @returns The window that is focused in this application. - */ - static getFocusedWindow(): BrowserWindow; - /** - * Find a window according to the webContents it owns. - */ - static fromWebContents(webContents: WebContents): BrowserWindow; - /** - * Find a window according to its ID. - */ - static fromId(id: number): BrowserWindow; - /** - * Adds devtools extension located at path. The extension will be remembered - * so you only need to call this API once, this API is not for programming use. - * @returns The extension's name. - * - * Note: This API cannot be called before the ready event of the app module is emitted. - */ - static addDevToolsExtension(path: string): string; - /** - * Remove a devtools extension. - * @param name The name of the devtools extension to remove. - * - * Note: This API cannot be called before the ready event of the app module is emitted. - */ - static removeDevToolsExtension(name: string): void; - /** - * @returns devtools extensions. - * - * Note: This API cannot be called before the ready event of the app module is emitted. - */ - static getDevToolsExtensions(): DevToolsExtensions; - /** - * The WebContents object this window owns, all web page related events and - * operations would be done via it. - * Note: Users should never store this object because it may become null when - * the renderer process (web page) has crashed. - */ - webContents: WebContents; - /** - * Get the unique ID of this window. - */ - id: number; - /** - * Force closing the window, the unload and beforeunload event won't be emitted - * for the web page, and close event would also not be emitted for this window, - * but it would guarantee the closed event to be emitted. - * You should only use this method when the renderer process (web page) has crashed. - */ - destroy(): void; - /** - * Try to close the window, this has the same effect with user manually clicking - * the close button of the window. The web page may cancel the close though, - * see the close event. - */ - close(): void; - /** - * Focus on the window. - */ - focus(): void; - /** - * Remove focus on the window. - */ - blur(): void; - /** - * @returns Whether the window is focused. - */ - isFocused(): boolean; - /** - * @returns Whether the window is destroyed. - */ - isDestroyed(): boolean; - /** - * Shows and gives focus to the window. - */ - show(): void; - /** - * Shows the window but doesn't focus on it. - */ - showInactive(): void; - /** - * Hides the window. - */ - hide(): void; - /** - * @returns Whether the window is visible to the user. - */ - isVisible(): boolean; - /** - * @returns Whether the window is a modal window. - */ - isModal(): boolean; - /** - * Maximizes the window. - */ - maximize(): void; - /** - * Unmaximizes the window. - */ - unmaximize(): void; - /** - * @returns Whether the window is maximized. - */ - isMaximized(): boolean; - /** - * Minimizes the window. On some platforms the minimized window will be - * shown in the Dock. - */ - minimize(): void; - /** - * Restores the window from minimized state to its previous state. - */ - restore(): void; - /** - * @returns Whether the window is minimized. - */ - isMinimized(): boolean; - /** - * Sets whether the window should be in fullscreen mode. - */ - setFullScreen(flag: boolean): void; - /** - * @returns Whether the window is in fullscreen mode. - */ - isFullScreen(): boolean; - /** - * This will have a window maintain an aspect ratio. - * The extra size allows a developer to have space, specified in pixels, - * not included within the aspect ratio calculations. - * This API already takes into account the difference between a window’s size and its content size. - * - * Note: This API is available only on macOS. - */ - setAspectRatio(aspectRatio: number, extraSize?: Size): void; - /** - * Uses Quick Look to preview a file at a given path. - * - * @param path The absolute path to the file to preview with QuickLook. - * @param displayName The name of the file to display on the Quick Look modal view. - * Note: This API is available only on macOS. - */ - previewFile(path: string, displayName?: string): void; - /** - * Resizes and moves the window to width, height, x, y. - */ - setBounds(options: Rectangle, animate?: boolean): void; - /** - * @returns The window's width, height, x and y values. - */ - getBounds(): Rectangle; - /** - * Resizes and moves the window's client area (e.g. the web page) to width, height, x, y. - */ - setContentBounds(options: Rectangle, animate?: boolean): void; - /** - * @returns The window's client area (e.g. the web page) width, height, x and y values. - */ - getContentBounds(): Rectangle; - /** - * Resizes the window to width and height. - */ - setSize(width: number, height: number, animate?: boolean): void; - /** - * @returns The window's width and height. - */ - getSize(): number[]; - /** - * Resizes the window's client area (e.g. the web page) to width and height. - */ - setContentSize(width: number, height: number, animate?: boolean): void; - /** - * @returns The window's client area's width and height. - */ - getContentSize(): number[]; - /** - * Sets the minimum size of window to width and height. - */ - setMinimumSize(width: number, height: number): void; - /** - * @returns The window's minimum width and height. - */ - getMinimumSize(): number[]; - /** - * Sets the maximum size of window to width and height. - */ - setMaximumSize(width: number, height: number): void; - /** - * @returns The window's maximum width and height. - */ - getMaximumSize(): number[]; - /** - * Sets whether the window can be manually resized by user. - */ - setResizable(resizable: boolean): void; - /** - * @returns Whether the window can be manually resized by user. - */ - isResizable(): boolean; - /** - * Sets whether the window can be moved by user. On Linux does nothing. - * Note: This API is available only on macOS and Windows. - */ - setMovable(movable: boolean): void; - /** - * Note: This API is available only on macOS and Windows. - * @returns Whether the window can be moved by user. On Linux always returns true. - */ - isMovable(): boolean; - /** - * Sets whether the window can be manually minimized by user. On Linux does nothing. - * Note: This API is available only on macOS and Windows. - */ - setMinimizable(minimizable: boolean): void; - /** - * Note: This API is available only on macOS and Windows. - * @returns Whether the window can be manually minimized by user. On Linux always returns true. - */ - isMinimizable(): boolean; - /** - * Sets whether the window can be manually maximized by user. On Linux does nothing. - * Note: This API is available only on macOS and Windows. - */ - setMaximizable(maximizable: boolean): void; - /** - * Note: This API is available only on macOS and Windows. - * @returns Whether the window can be manually maximized by user. On Linux always returns true. - */ - isMaximizable(): boolean; - /** - * Sets whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. - */ - setFullScreenable(fullscreenable: boolean): void; - /** - * @returns Whether the maximize/zoom window button toggles fullscreen mode or maximizes the window. - */ - isFullScreenable(): boolean; - /** - * Sets whether the window can be manually closed by user. On Linux does nothing. - * Note: This API is available only on macOS and Windows. - */ - setClosable(closable: boolean): void; - /** - * Note: This API is available only on macOS and Windows. - * @returns Whether the window can be manually closed by user. On Linux always returns true. - */ - isClosable(): boolean; - /** - * Sets whether the window should show always on top of other windows. After - * setting this, the window is still a normal window, not a toolbox window - * which can not be focused on. - */ - setAlwaysOnTop(flag: boolean, level?: WindowLevel): void; - /** - * @returns Whether the window is always on top of other windows. - */ - isAlwaysOnTop(): boolean; - /** - * Moves window to the center of the screen. - */ - center(): void; - /** - * Moves window to x and y. - */ - setPosition(x: number, y: number, animate?: boolean): void; - /** - * @returns The window's current position. - */ - getPosition(): number[]; - /** - * Changes the title of native window to title. - */ - setTitle(title: string): void; - /** - * Note: The title of web page can be different from the title of the native window. - * @returns The title of the native window. - */ - getTitle(): string; - /** - * Changes the attachment point for sheets on macOS. - * Note: This API is available only on macOS. - */ - setSheetOffset(offsetY: number, offsetX?: number): void; - /** - * Starts or stops flashing the window to attract user's attention. - */ - flashFrame(flag: boolean): void; - /** - * Makes the window do not show in Taskbar. - */ - setSkipTaskbar(skip: boolean): void; - /** - * Enters or leaves the kiosk mode. - */ - setKiosk(flag: boolean): void; - /** - * @returns Whether the window is in kiosk mode. - */ - isKiosk(): boolean; - /** - * The native type of the handle is HWND on Windows, NSView* on macOS, - * and Window (unsigned long) on Linux. - * @returns The platform-specific handle of the window as Buffer. - */ - getNativeWindowHandle(): Buffer; - /** - * Hooks a windows message. The callback is called when the message is received in the WndProc. - * Note: This API is available only on Windows. - */ - hookWindowMessage(message: number, callback: Function): void; - /** - * @returns Whether the message is hooked. - */ - isWindowMessageHooked(message: number): boolean; - /** - * Unhook the window message. - */ - unhookWindowMessage(message: number): void; - /** - * Unhooks all of the window messages. - */ - unhookAllWindowMessages(): void; - /** - * Sets the pathname of the file the window represents, and the icon of the - * file will show in window's title bar. - * Note: This API is available only on macOS. - */ - setRepresentedFilename(filename: string): void; - /** - * Note: This API is available only on macOS. - * @returns The pathname of the file the window represents. - */ - getRepresentedFilename(): string; - /** - * Specifies whether the window’s document has been edited, and the icon in - * title bar will become grey when set to true. - * Note: This API is available only on macOS. - */ - setDocumentEdited(edited: boolean): void; - /** - * Note: This API is available only on macOS. - * @returns Whether the window's document has been edited. - */ - isDocumentEdited(): boolean; - focusOnWebView(): void; - blurWebView(): void; - /** - * Captures the snapshot of page within rect, upon completion the callback - * will be called. Omitting the rect would capture the whole visible page. - * Note: Be sure to read documents on remote buffer in remote if you are going - * to use this API in renderer process. - * @param callback Supplies the image that stores data of the snapshot. - */ - capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; - /** - * Captures the snapshot of page within rect, upon completion the callback - * will be called. Omitting the rect would capture the whole visible page. - * Note: Be sure to read documents on remote buffer in remote if you are going - * to use this API in renderer process. - * @param callback Supplies the image that stores data of the snapshot. - */ - capturePage(callback: (image: NativeImage) => void): void; - /** - * Same as webContents.loadURL(url). - */ - loadURL(url: string, options?: LoadURLOptions): void; - /** - * Same as webContents.reload. - */ - reload(): void; - /** - * Sets the menu as the window top menu. - * Note: This API is not available on macOS. - */ - setMenu(menu: Menu | null): void; - /** - * Sets the progress value in the progress bar. - * On Linux platform, only supports Unity desktop environment, you need to - * specify the *.desktop file name to desktopName field in package.json. - * By default, it will assume app.getName().desktop. - * @param progress Valid range is [0, 1.0]. If < 0, the progress bar is removed. - * If greater than 0, it becomes indeterminate. - */ - setProgressBar(progress: number, options?: { - /** - * Mode for the progress bar. - * Note: This is only implemented on Windows. - */ - mode: 'none' | 'normal' | 'indeterminate' | 'error' | 'paused' - }): void; - /** - * Sets a 16px overlay onto the current Taskbar icon, usually used to convey - * some sort of application status or to passively notify the user. - * Note: This API is only available on Windows 7 or above. - * @param overlay The icon to display on the bottom right corner of the Taskbar - * icon. If this parameter is null, the overlay is cleared - * @param description Provided to Accessibility screen readers. - */ - setOverlayIcon(overlay: NativeImage, description: string): void; - /** - * Sets whether the window should have a shadow. On Windows and Linux does nothing. - * Note: This API is available only on macOS. - */ - setHasShadow(hasShadow: boolean): void; - /** - * Note: This API is available only on macOS. - * @returns whether the window has a shadow. On Windows and Linux always returns true. - */ - hasShadow(): boolean; - /** - * Add a thumbnail toolbar with a specified set of buttons to the thumbnail image - * of a window in a taskbar button layout. - * @returns Whether the thumbnail has been added successfully. - * - * Note: This API is available only on Windows. - */ - setThumbarButtons(buttons: ThumbarButton[]): boolean; - /** - * Sets the region of the window to show as the thumbnail image displayed when hovering - * over the window in the taskbar. You can reset the thumbnail to be the entire window - * by specifying an empty region: {x: 0, y: 0, width: 0, height: 0}. - * - * Note: This API is available only on Windows. - */ - setThumbnailClip(region: Rectangle): boolean; - /** - * Sets the toolTip that is displayed when hovering over the window thumbnail in the taskbar. - * Note: This API is available only on Windows. - */ - setThumbnailToolTip(toolTip: string): boolean; - /** - * Same as webContents.showDefinitionForSelection(). - * Note: This API is available only on macOS. - */ - showDefinitionForSelection(): void; - /** - * Changes window icon. - * Note: This API is not available on macOS. - */ - setIcon(icon: NativeImage): void; - /** - * Sets whether the window menu bar should hide itself automatically. Once set - * the menu bar will only show when users press the single Alt key. - * If the menu bar is already visible, calling setAutoHideMenuBar(true) won't - * hide it immediately. - */ - setAutoHideMenuBar(hide: boolean): void; - /** - * @returns Whether menu bar automatically hides itself. - */ - isMenuBarAutoHide(): boolean; - /** - * Sets whether the menu bar should be visible. If the menu bar is auto-hide, - * users can still bring up the menu bar by pressing the single Alt key. - */ - setMenuBarVisibility(visibile: boolean): void; - /** - * @returns Whether the menu bar is visible. - */ - isMenuBarVisible(): boolean; - /** - * Sets whether the window should be visible on all workspaces. - * Note: This API does nothing on Windows. - */ - setVisibleOnAllWorkspaces(visible: boolean): void; - /** - * Note: This API always returns false on Windows. - * @returns Whether the window is visible on all workspaces. - */ - isVisibleOnAllWorkspaces(): boolean; - /** - * Makes the window ignore all mouse events. - * - * All mouse events happened in this window will be passed to the window below this window, - * but if this window has focus, it will still receive keyboard events. - */ - setIgnoreMouseEvents(ignore: boolean): void; - /** - * Prevents the window contents from being captured by other apps. - * - * On macOS it sets the NSWindow's sharingType to NSWindowSharingNone. - * On Windows it calls SetWindowDisplayAffinity with WDA_MONITOR. - */ - setContentProtection(enable: boolean): void; - /** - * Changes whether the window can be focused. - * Note: This API is available only on Windows. - */ - setFocusable(focusable: boolean): void; - /** - * Sets parent as current window's parent window, - * passing null will turn current window into a top-level window. - * Note: This API is not available on Windows. - */ - setParentWindow(parent: BrowserWindow): void; - /** - * @returns The parent window. - */ - getParentWindow(): BrowserWindow; - /** - * @returns All child windows. - */ - getChildWindows(): BrowserWindow[]; - /** - * Adds a vibrancy effect to the browser window. Passing null or - * an empty string will remove the vibrancy effect on the window. - * - * Note: This API is available only on macOS. - */ - setVibrancy(type: VibrancyType): void; - } - - type WindowLevel = 'normal' | 'floating' | 'torn-off-menu' | 'modal-panel' | 'main-menu' | 'status' | 'pop-up-menu' | 'screen-saver' | 'dock'; - type SwipeDirection = 'up' | 'right' | 'down' | 'left'; - type ThumbarButtonFlags = 'enabled' | 'disabled' | 'dismissonclick' | 'nobackground' | 'hidden' | 'noninteractive'; - - interface ThumbarButton { - icon: NativeImage | string; - click: Function; - tooltip?: string; - flags?: ThumbarButtonFlags[]; - } - - interface DevToolsExtensions { - [name: string]: { - name: string; - value: string; - } - } - - interface WebPreferences { - /** - * Whether to enable DevTools. - * If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools. - * Default: true. - */ - devTools?: boolean; - /** - * Whether node integration is enabled. - * Default: true. - */ - nodeIntegration?: boolean; - /** - * Specifies a script that will be loaded before other scripts run in the page. - * This script will always have access to node APIs no matter whether node integration is turned on or off. - * The value should be the absolute file path to the script. - * When node integration is turned off, the preload script can reintroduce - * Node global symbols back to the global scope. - */ - preload?: string; - /** - * Sets the session used by the page. Instead of passing the Session object directly, - * you can also choose to use the partition option instead, which accepts a partition string. - * When both session and partition are provided, session would be preferred. - * Default: the default session. - */ - session?: Session; - /** - * Sets the session used by the page according to the session’s partition string. - * If partition starts with persist:, the page will use a persistent session available - * to all pages in the app with the same partition. if there is no persist: prefix, - * the page will use an in-memory session. By assigning the same partition, - * multiple pages can share the same session. - * Default: the default session. - */ - partition?: string; - /** - * The default zoom factor of the page, 3.0 represents 300%. - * Default: 1.0. - */ - zoomFactor?: number; - /** - * Enables JavaScript support. - * Default: true. - */ - javascript?: boolean; - /** - * When setting false, it will disable the same-origin policy (Usually using testing - * websites by people), and set allowDisplayingInsecureContent and allowRunningInsecureContent - * to true if these two options are not set by user. - * Default: true. - */ - webSecurity?: boolean; - /** - * Allow an https page to display content like images from http URLs. - * Default: false. - */ - allowDisplayingInsecureContent?: boolean; - /** - * Allow a https page to run JavaScript, CSS or plugins from http URLs. - * Default: false. - */ - allowRunningInsecureContent?: boolean; - /** - * Enables image support. - * Default: true. - */ - images?: boolean; - /** - * Make TextArea elements resizable. - * Default: true. - */ - textAreasAreResizable?: boolean; - /** - * Enables WebGL support. - * Default: true. - */ - webgl?: boolean; - /** - * Enables WebAudio support. - * Default: true. - */ - webaudio?: boolean; - /** - * Whether plugins should be enabled. - * Default: false. - */ - plugins?: boolean; - /** - * Enables Chromium’s experimental features. - * Default: false. - */ - experimentalFeatures?: boolean; - /** - * Enables Chromium’s experimental canvas features. - * Default: false. - */ - experimentalCanvasFeatures?: boolean; - /** - * Enables DirectWrite font rendering system on Windows. - * Default: true. - */ - directWrite?: boolean; - /** - * Enables scroll bounce (rubber banding) effect on macOS. - * Default: false. - */ - scrollBounce?: boolean; - /** - * A list of feature strings separated by ",", like CSSVariables,KeyboardEventKey to enable. - */ - blinkFeatures?: string; - /** - * A list of feature strings separated by ",", like CSSVariables,KeyboardEventKey to disable. - */ - disableBlinkFeatures?: string; - /** - * Sets the default font for the font-family. - */ - defaultFontFamily?: { - /** - * Default: Times New Roman. - */ - standard?: string; - /** - * Default: Times New Roman. - */ - serif?: string; - /** - * Default: Arial. - */ - sansSerif?: string; - /** - * Default: Courier New. - */ - monospace?: string; - }; - /** - * Default: 16. - */ - defaultFontSize?: number; - /** - * Default: 13. - */ - defaultMonospaceFontSize?: number; - /** - * Default: 0. - */ - minimumFontSize?: number; - /** - * Default: ISO-8859-1. - */ - defaultEncoding?: string; - /** - * Whether to throttle animations and timers when the page becomes background. - * Default: true. - */ - backgroundThrottling?: boolean; - /** - * Whether to enable offscreen rendering for the browser window. - * Default: false. - */ - offscreen?: boolean; - /** - * Whether to enable Chromium OS-level sandbox. - * Default: false. - */ - sandbox?: boolean; - } - - interface BrowserWindowOptions { - /** - * Window’s width in pixels. - * Default: 800. - */ - width?: number; - /** - * Window’s height in pixels. - * Default: 600. - */ - height?: number; - /** - * Window’s left offset from screen. - * Default: center the window. - */ - x?: number; - /** - * Window’s top offset from screen. - * Default: center the window. - */ - y?: number; - /** - * The width and height would be used as web page’s size, which means - * the actual window’s size will include window frame’s size and be slightly larger. - * Default: false. - */ - useContentSize?: boolean; - /** - * Show window in the center of the screen. - * Default: true - */ - center?: boolean; - /** - * Window’s minimum width. - * Default: 0. - */ - minWidth?: number; - /** - * Window’s minimum height. - * Default: 0. - */ - minHeight?: number; - /** - * Window’s maximum width. - * Default: no limit. - */ - maxWidth?: number; - /** - * Window’s maximum height. - * Default: no limit. - */ - maxHeight?: number; - /** - * Whether window is resizable. - * Default: true. - */ - resizable?: boolean; - /** - * Whether window is movable. - * Note: This is not implemented on Linux. - * Default: true. - */ - movable?: boolean; - /** - * Whether window is minimizable. - * Note: This is not implemented on Linux. - * Default: true. - */ - minimizable?: boolean; - /** - * Whether window is maximizable. - * Note: This is not implemented on Linux. - * Default: true. - */ - maximizable?: boolean; - /** - * Whether window is closable. - * Note: This is not implemented on Linux. - * Default: true. - */ - closable?: boolean; - /** - * Whether the window can be focused. - * On Windows setting focusable: false also implies setting skipTaskbar: true. - * On Linux setting focusable: false makes the window stop interacting with wm, - * so the window will always stay on top in all workspaces. - * Default: true. - */ - focusable?: boolean; - /** - * Whether the window should always stay on top of other windows. - * Default: false. - */ - alwaysOnTop?: boolean; - /** - * Whether the window should show in fullscreen. - * When explicitly set to false the fullscreen button will be hidden or disabled on macOS. - * Default: false. - */ - fullscreen?: boolean; - /** - * Whether the window can be put into fullscreen mode. - * On macOS, also whether the maximize/zoom button should toggle full screen mode or maximize window. - * Default: true. - */ - fullscreenable?: boolean; - /** - * Whether to show the window in taskbar. - * Default: false. - */ - skipTaskbar?: boolean; - /** - * The kiosk mode. - * Default: false. - */ - kiosk?: boolean; - /** - * Default window title. - * Default: "Electron". - */ - title?: string; - /** - * The window icon, when omitted on Windows the executable’s icon would be used as window icon. - */ - icon?: NativeImage|string; - /** - * Whether window should be shown when created. - * Default: true. - */ - show?: boolean; - /** - * Specify false to create a Frameless Window. - * Default: true. - */ - frame?: boolean; - /** - * Specify parent window. - * Default: null. - */ - parent?: BrowserWindow; - /** - * Whether this is a modal window. This only works when the window is a child window. - * Default: false. - */ - modal?: boolean; - /** - * Whether the web view accepts a single mouse-down event that simultaneously activates the window. - * Default: false. - */ - acceptFirstMouse?: boolean; - /** - * Whether to hide cursor when typing. - * Default: false. - */ - disableAutoHideCursor?: boolean; - /** - * Auto hide the menu bar unless the Alt key is pressed. - * Default: true. - */ - autoHideMenuBar?: boolean; - /** - * Enable the window to be resized larger than screen. - * Default: false. - */ - enableLargerThanScreen?: boolean; - /** - * Window’s background color as Hexadecimal value, like #66CD00 or #FFF or #80FFFFFF (alpha is supported). - * Default: #FFF (white). - */ - backgroundColor?: string; - /** - * Whether window should have a shadow. - * Note: This is only implemented on macOS. - * Default: true. - */ - hasShadow?: boolean; - /** - * Forces using dark theme for the window. - * Note: Only works on some GTK+3 desktop environments. - * Default: false. - */ - darkTheme?: boolean; - /** - * Makes the window transparent. - * Default: false. - */ - transparent?: boolean; - /** - * The type of window, default is normal window. - */ - type?: BrowserWindowType; - /** - * The style of window title bar. - */ - titleBarStyle?: 'default' | 'hidden' | 'hidden-inset'; - /** - * Use WS_THICKFRAME style for frameless windows on Windows - */ - thickFrame?: boolean; - /** - * Add a type of vibrancy effect to the window, only on macOS - */ - vibrancy?: VibrancyType; - /** - * Settings of web page’s features. - */ - webPreferences?: WebPreferences; - } - - type BrowserWindowType = BrowserWindowTypeLinux | BrowserWindowTypeMac | BrowserWindowTypeWindows; - type BrowserWindowTypeLinux = 'desktop' | 'dock' | 'toolbar' | 'splash' | 'notification'; - type BrowserWindowTypeMac = 'desktop' | 'textured'; - type BrowserWindowTypeWindows = 'toolbar'; - - // https://github.com/electron/electron/blob/master/docs/api/clipboard.md - - /** - * The clipboard module provides methods to perform copy and paste operations. - */ - interface Clipboard { - /** - * @returns The contents of the clipboard as plain text. - */ - readText(type?: ClipboardType): string; - /** - * Writes the text into the clipboard as plain text. - */ - writeText(text: string, type?: ClipboardType): void; - /** - * @returns The contents of the clipboard as markup. - */ - readHTML(type?: ClipboardType): string; - /** - * Writes markup to the clipboard. - */ - writeHTML(markup: string, type?: ClipboardType): void; - /** - * @returns The contents of the clipboard as a NativeImage. - */ - readImage(type?: ClipboardType): NativeImage; - /** - * Writes the image into the clipboard. - */ - writeImage(image: NativeImage, type?: ClipboardType): void; - /** - * @returns The contents of the clipboard as RTF. - */ - readRTF(type?: ClipboardType): string; - /** - * Writes the text into the clipboard in RTF. - */ - writeRTF(text: string, type?: ClipboardType): void; - /** - * Clears everything in clipboard. - */ - clear(type?: ClipboardType): void; - /** - * @returns Array available formats for the clipboard type. - */ - availableFormats(type?: ClipboardType): string[]; - /** - * Returns whether the clipboard supports the format of specified data. - * Note: This API is experimental and could be removed in future. - * @returns Whether the clipboard has data in the specified format. - */ - has(format: string, type?: ClipboardType): boolean; - /** - * Reads the data in the clipboard of the specified format. - * Note: This API is experimental and could be removed in future. - */ - read(format: string, type?: ClipboardType): string | NativeImage; - /** - * Writes data to the clipboard. - */ - write(data: { text: string; bookmark?: string; } | { rtf: string; } | { html: string; } | { image: NativeImage; }, type?: ClipboardType): void; - /** - * @returns An Object containing title and url keys representing the bookmark in the clipboard. - * - * Note: This API is available on macOS and Windows. - */ - readBookmark(): Bookmark; - /** - * Writes the title and url into the clipboard as a bookmark. - * - * Note: This API is available on macOS and Windows. - */ - writeBookmark(title: string, url: string, type?: ClipboardType): void; - /** - * The text on the find pasteboard. This method uses synchronous IPC when called from the renderer process. - * The cached value is reread from the find pasteboard whenever the application is activated. - * - * Note: This API is available on macOS. - */ - readFindText(): string; - /** - * Writes the text into the find pasteboard as plain text. - * This method uses synchronous IPC when called from the renderer process. - * - * Note: This API is available on macOS. - */ - writeFindText(text: string): void; - } - - type ClipboardType = '' | 'selection'; - - interface Bookmark { - title: string; - url: string; - } - - // https://github.com/electron/electron/blob/master/docs/api/content-tracing.md - - /** - * The content-tracing module is used to collect tracing data generated by the underlying Chromium content module. - * This module does not include a web interface so you need to open chrome://tracing/ - * in a Chrome browser and load the generated file to view the result. - */ - interface ContentTracing { - /** - * Get a set of category groups. The category groups can change as new code paths are reached. - * - * @param callback Called once all child processes have acknowledged the getCategories request. - */ - getCategories(callback: (categoryGroups: string[]) => void): void; - /** - * Start recording on all processes. Recording begins immediately locally and asynchronously - * on child processes as soon as they receive the EnableRecording request. - * - * @param callback Called once all child processes have acknowledged the startRecording request. - */ - startRecording(options: ContentTracingOptions, callback: Function): void; - /** - * Stop recording on all processes. Child processes typically are caching trace data and - * only rarely flush and send trace data back to the main process. That is because it may - * be an expensive operation to send the trace data over IPC, and we would like to avoid - * much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all - * child processes to flush any pending trace data. - * - * @param resultFilePath Trace data will be written into this file if it is not empty, - * or into a temporary file. - * @param callback Called once all child processes have acknowledged the stopRecording request. - */ - stopRecording(resultFilePath: string, callback: (filePath: string) => void): void; - /** - * Start monitoring on all processes. Monitoring begins immediately locally and asynchronously - * on child processes as soon as they receive the startMonitoring request. - * - * @param callback Called once all child processes have acked to the startMonitoring request. - */ - startMonitoring(options: ContentTracingOptions, callback: Function): void; - /** - * Stop monitoring on all processes. - * - * @param callback Called once all child processes have acknowledged the stopMonitoring request. - */ - stopMonitoring(callback: Function): void; - /** - * Get the current monitoring traced data. Child processes typically are caching trace data - * and only rarely flush and send trace data back to the main process. That is because it may - * be an expensive operation to send the trace data over IPC, and we would like to avoid much - * runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child - * processes to flush any pending trace data. - * - * @param callback Called once all child processes have acknowledged the captureMonitoringSnapshot request. - */ - captureMonitoringSnapshot(resultFilePath: string, callback: (filePath: string) => void): void; - /** - * Get the maximum usage across processes of trace buffer as a percentage of the full state. - * - * @param callback Called when the TraceBufferUsage value is determined. - */ - getTraceBufferUsage(callback: Function): void; - /** - * @param callback Called every time the given event occurs on any process. - */ - setWatchEvent(categoryName: string, eventName: string, callback: Function): void; - /** - * Cancel the watch event. This may lead to a race condition with the watch event callback if tracing is enabled. - */ - cancelWatchEvent(): void; - } - - interface ContentTracingOptions { - /** - * Filter to control what category groups should be traced. - * A filter can have an optional - prefix to exclude category groups - * that contain a matching category. Having both included and excluded - * category patterns in the same list is not supported. - * - * Examples: - * test_MyTest* - * test_MyTest*,test_OtherStuff - * -excluded_category1,-excluded_category2 - */ - categoryFilter: string; - /** - * Controls what kind of tracing is enabled, it is a comma-delimited list. - * - * Possible options are: - * record-until-full - * record-continuously - * trace-to-console - * enable-sampling - * enable-systrace - * - * The first 3 options are trace recoding modes and hence mutually exclusive. - * If more than one trace recording modes appear in the traceOptions string, - * the last one takes precedence. If none of the trace recording modes are specified, - * recording mode is record-until-full. - * - * The trace option will first be reset to the default option (record_mode set - * to record-until-full, enable_sampling and enable_systrace set to false) - * before options parsed from traceOptions are applied on it. - */ - traceOptions: string; - } - - // https://github.com/electron/electron/blob/master/docs/api/crash-reporter.md - - /** - * The crash-reporter module enables sending your app's crash reports. - */ - interface CrashReporter { - /** - * You are required to call this method before using other crashReporter APIs. - * - * Note: On macOS, Electron uses a new crashpad client, which is different from breakpad - * on Windows and Linux. To enable the crash collection feature, you are required to call - * the crashReporter.start API to initialize crashpad in the main process and in each - * renderer process from which you wish to collect crash reports. - */ - start(options: CrashReporterStartOptions): void; - /** - * @returns The crash report. When there was no crash report - * sent or the crash reporter is not started, null will be returned. - */ - getLastCrashReport(): CrashReport; - /** - * @returns All uploaded crash reports. - */ - getUploadedReports(): CrashReport[]; - } - - interface CrashReporterStartOptions { - /** - * Default: app.getName() - */ - productName?: string; - companyName: string; - /** - * URL that crash reports would be sent to as POST. - */ - submitURL: string; - /** - * Send the crash report without user interaction. - * Default: true. - */ - autoSubmit?: boolean; - /** - * Default: false. - */ - ignoreSystemCrashHandler?: boolean; - /** - * An object you can define that will be sent along with the report. - * Only string properties are sent correctly, nested objects are not supported. - */ - extra?: {[prop: string]: string}; - } - - interface CrashReport { - id: string; - date: Date; - } - - // https://github.com/electron/electron/blob/master/docs/api/desktop-capturer.md - - /** - * The desktopCapturer module can be used to get available sources - * that can be used to be captured with getUserMedia. - */ - interface DesktopCapturer { - /** - * Starts a request to get all desktop sources. - * - * Note: There is no guarantee that the size of source.thumbnail is always - * the same as the thumnbailSize in options. It also depends on the scale of the screen or window. - */ - getSources(options: DesktopCapturerOptions, callback: (error: Error, sources: DesktopCapturerSource[]) => any): void; - } - - interface DesktopCapturerOptions { - /** - * The types of desktop sources to be captured. - */ - types?: ('screen' | 'window')[]; - /** - * The suggested size that thumbnail should be scaled. - * Default: {width: 150, height: 150} - */ - thumbnailSize?: Size; - } - - interface DesktopCapturerSource { - /** - * The id of the captured window or screen used in navigator.webkitGetUserMedia. - * The format looks like window:XX or screen:XX where XX is a random generated number. - */ - id: string; - /** - * The described name of the capturing screen or window. - * If the source is a screen, the name will be Entire Screen or Screen ; - * if it is a window, the name will be the window’s title. - */ - name: string; - /** - * A thumbnail image. - */ - thumbnail: NativeImage; - } - - // https://github.com/electron/electron/blob/master/docs/api/dialog.md - - /** - * The dialog module provides APIs to show native system dialogs, such as opening files or alerting, - * so web applications can deliver the same user experience as native applications. - */ - interface Dialog { - /** - * Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, - * so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown. - * - * @param callback If supplied, the API call will be asynchronous. - * @returns On success, returns an array of file paths chosen by the user, - * otherwise returns undefined. - */ - showOpenDialog(browserWindow: BrowserWindow, options: OpenDialogOptions, callback?: (fileNames: string[]) => void): string[]; - /** - * Note: On Windows and Linux an open dialog can not be both a file selector and a directory selector, - * so if you set properties to ['openFile', 'openDirectory'] on these platforms, a directory selector will be shown. - * - * @param callback If supplied, the API call will be asynchronous. - * @returns On success, returns an array of file paths chosen by the user, - * otherwise returns undefined. - */ - showOpenDialog(options: OpenDialogOptions, callback?: (fileNames: string[]) => void): string[]; - /** - * @param callback If supplied, the API call will be asynchronous. - * @returns On success, returns the path of file chosen by the user, otherwise - * returns undefined. - */ - showSaveDialog(browserWindow: BrowserWindow, options: SaveDialogOptions, callback?: (fileName: string) => void): string; - /** - * @param callback If supplied, the API call will be asynchronous. - * @returns On success, returns the path of file chosen by the user, otherwise - * returns undefined. - */ - showSaveDialog(options: SaveDialogOptions, callback?: (fileName: string) => void): string; - /** - * Shows a message box. It will block until the message box is closed. - * @param callback If supplied, the API call will be asynchronous. - * @returns The index of the clicked button. - */ - showMessageBox(browserWindow: BrowserWindow, options: ShowMessageBoxOptions, callback?: (response: number) => void): number; - /** - * Shows a message box. It will block until the message box is closed. - * @param callback If supplied, the API call will be asynchronous. - * @returns The index of the clicked button. - */ - showMessageBox(options: ShowMessageBoxOptions, callback?: (response: number) => void): number; - /** - * Displays a modal dialog that shows an error message. - * - * This API can be called safely before the ready event the app module emits, - * it is usually used to report errors in early stage of startup. - * If called before the app readyevent on Linux, the message will be emitted to stderr, - * and no GUI dialog will appear. - */ - showErrorBox(title: string, content: string): void; - } - - interface OpenDialogOptions { - title?: string; - defaultPath?: string; - /** - * Custom label for the confirmation button, when left empty the default label will be used. - */ - buttonLabel?: string; - /** - * File types that can be displayed or selected. - */ - filters?: { - name: string; - /** - * Extensions without wildcards or dots (e.g. 'png' is good but '.png' and '*.png' are bad). - * To show all files, use the '*' wildcard (no other wildcard is supported). - */ - extensions: string[]; - }[]; - /** - * Contains which features the dialog should use. - */ - properties?: ('openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory' | 'showHiddenFiles' | 'promptToCreate' | 'noResolveAliases')[]; - /** - * Normalize the keyboard access keys across platforms. - */ - normalizeAccessKeys?: boolean; - /** - * Message to display above input boxes. - */ - message?: string; - } - - interface SaveDialogOptions { - title?: string; - defaultPath?: string; - /** - * Custom label for the confirmation button, when left empty the default label will be used. - */ - buttonLabel?: string; - /** - * File types that can be displayed, see dialog.showOpenDialog for an example. - */ - filters?: { - name: string; - extensions: string[]; - }[]; - /** - * macOS - Message to display above text fields. - */ - message?: string; - /** - * macOS - Custom label for the text displayed in front of the filename text field. - */ - nameFieldLabel?: string; - /** - * macOS - Show the tags input box, defaults to true. - */ - showsTagField?: boolean; - } - - interface ShowMessageBoxOptions { - /** - * On Windows, "question" displays the same icon as "info", unless you set an icon using the "icon" option. - */ - type?: 'none' | 'info' | 'error' | 'question' | 'warning'; - /** - * Texts for buttons. On Windows, an empty array will result in one button labeled "OK". - */ - buttons?: string[]; - /** - * Index of the button in the buttons array which will be selected by default when the message box opens. - */ - defaultId?: number; - /** - * Title of the message box (some platforms will not show it). - */ - title?: string; - /** - * Contents of the message box. - */ - message?: string; - /** - * Extra information of the message. - */ - detail?: string; - icon?: NativeImage; - /** - * The value will be returned when user cancels the dialog instead of clicking the buttons of the dialog. - * By default it is the index of the buttons that have "cancel" or "no" as label, - * or 0 if there is no such buttons. On macOS and Windows the index of "Cancel" button - * will always be used as cancelId, not matter whether it is already specified. - */ - cancelId?: number; - /** - * On Windows Electron will try to figure out which one of the buttons are common buttons - * (like "Cancel" or "Yes"), and show the others as command links in the dialog. - * This can make the dialog appear in the style of modern Windows apps. - * If you don’t like this behavior, you can set noLink to true. - */ - noLink?: boolean; - } - - // https://github.com/electron/electron/blob/master/docs/api/download-item.md - - /** - * DownloadItem represents a download item in Electron. - */ - interface DownloadItem extends NodeJS.EventEmitter { - /** - * Emitted when the download has been updated and is not done. - */ - on(event: 'updated', listener: (event: Event, state: 'progressing' | 'interrupted') => void): this; - /** - * Emits when the download is in a terminal state. This includes a completed download, - * a cancelled download (via downloadItem.cancel()), and interrupted download that can’t be resumed. - */ - on(event: 'done', listener: (event: Event, state: 'completed' | 'cancelled' | 'interrupted') => void): this; - on(event: string, listener: Function): this; - /** - * Set the save file path of the download item. - * Note: The API is only available in session’s will-download callback function. - * If user doesn’t set the save path via the API, Electron will use the original - * routine to determine the save path (Usually prompts a save dialog). - */ - setSavePath(path: string): void; - /** - * @returns The save path of the download item. - * This will be either the path set via downloadItem.setSavePath(path) or the path selected from the shown save dialog. - */ - getSavePath(): string; - /** - * Pauses the download. - */ - pause(): void; - /** - * @returns Whether the download is paused. - */ - isPaused(): boolean; - /** - * Resumes the download that has been paused. - */ - resume(): void; - /** - * @returns Whether the download can resume. - */ - canResume(): boolean; - /** - * Cancels the download operation. - */ - cancel(): void; - /** - * @returns The origin url where the item is downloaded from. - */ - getURL(): string; - /** - * @returns The mime type. - */ - getMimeType(): string; - /** - * @returns Whether the download has user gesture. - */ - hasUserGesture(): boolean; - /** - * @returns The file name of the download item. - * Note: The file name is not always the same as the actual one saved in local disk. - * If user changes the file name in a prompted download saving dialog, - * the actual name of saved file will be different. - */ - getFilename(): string; - /** - * @returns The total size in bytes of the download item. If the size is unknown, it returns 0. - */ - getTotalBytes(): number; - /** - * @returns The received bytes of the download item. - */ - getReceivedBytes(): number; - /** - * @returns The Content-Disposition field from the response header. - */ - getContentDisposition(): string; - /** - * @returns The current state. - */ - getState(): 'progressing' | 'completed' | 'cancelled' | 'interrupted'; - } - - // https://github.com/electron/electron/blob/master/docs/api/global-shortcut.md - - /** - * The globalShortcut module can register/unregister a global keyboard shortcut - * with the operating system so that you can customize the operations for various shortcuts. - * Note: The shortcut is global; it will work even if the app does not have the keyboard focus. - * You should not use this module until the ready event of the app module is emitted. - */ - interface GlobalShortcut { - /** - * Registers a global shortcut of accelerator. - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - * @param callback Called when the registered shortcut is pressed by the user. - */ - register(accelerator: string, callback: Function): void; - /** - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - * @returns Whether the accelerator is registered. - */ - isRegistered(accelerator: string): boolean; - /** - * Unregisters the global shortcut of keycode. - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - */ - unregister(accelerator: string): void; - /** - * Unregisters all the global shortcuts. - */ - unregisterAll(): void; - } - - // https://github.com/electron/electron/blob/master/docs/api/ipc-main.md - - /** - * The ipcMain module handles asynchronous and synchronous messages - * sent from a renderer process (web page). - * Messages sent from a renderer will be emitted to this module. - */ - interface IpcMain extends NodeJS.EventEmitter { - addListener(channel: string, listener: IpcMainEventListener): this; - on(channel: string, listener: IpcMainEventListener): this; - once(channel: string, listener: IpcMainEventListener): this; - removeListener(channel: string, listener: IpcMainEventListener): this; - removeAllListeners(channel?: string): this; - } - - type IpcMainEventListener = (event: IpcMainEvent, ...args: any[]) => void; - - interface IpcMainEvent { - /** - * Set this to the value to be returned in a synchronous message. - */ - returnValue?: any; - /** - * Returns the webContents that sent the message, you can call sender.send - * to reply to the asynchronous message. - */ - sender: WebContents; - } - - // https://github.com/electron/electron/blob/master/docs/api/ipc-renderer.md - - /** - * The ipcRenderer module provides a few methods so you can send synchronous - * and asynchronous messages from the render process (web page) to the main process. - * You can also receive replies from the main process. - */ - interface IpcRenderer extends NodeJS.EventEmitter { - addListener(channel: string, listener: IpcRendererEventListener): this; - on(channel: string, listener: IpcRendererEventListener): this; - once(channel: string, listener: IpcRendererEventListener): this; - removeListener(channel: string, listener: IpcRendererEventListener): this; - removeAllListeners(channel?: string): this; - /** - * Send ...args to the renderer via channel in asynchronous message, the main - * process can handle it by listening to the channel event of ipc module. - */ - send(channel: string, ...args: any[]): void; - /** - * Send ...args to the renderer via channel in synchronous message, and returns - * the result sent from main process. The main process can handle it by listening - * to the channel event of ipc module, and returns by setting event.returnValue. - * Note: Usually developers should never use this API, since sending synchronous - * message would block the whole renderer process. - * @returns The result sent from the main process. - */ - sendSync(channel: string, ...args: any[]): any; - /** - * Like ipc.send but the message will be sent to the host page instead of the main process. - * This is mainly used by the page in to communicate with host page. - */ - sendToHost(channel: string, ...args: any[]): void; - } - - type IpcRendererEventListener = (event: IpcRendererEvent, ...args: any[]) => void; - - interface IpcRendererEvent { - /** - * You can call sender.send to reply to the asynchronous message. - */ - sender: IpcRenderer; - } - - // https://github.com/electron/electron/blob/master/docs/api/menu-item.md - // https://github.com/electron/electron/blob/master/docs/api/accelerator.md - - /** - * The MenuItem allows you to add items to an application or context menu. - */ - class MenuItem { - /** - * Create a new menu item. - */ - constructor(options: MenuItemOptions); - - /** - * A function that is fired when the MenuItem receives a click event - */ - click: (event: Event, browserWindow: BrowserWindow, webContents: WebContents) => void; - - /** - * Read-only property. - */ - type: MenuItemType; - /** - * Read-only property. - */ - role: MenuItemRole | MenuItemRoleMac; - /** - * Read-only property. - */ - accelerator: string; - /** - * Read-only property. - */ - icon: NativeImage | string; - /** - * Read-only property. - */ - submenu: Menu | MenuItemOptions[]; - - label: string; - sublabel: string; - enabled: boolean; - visible: boolean; - checked: boolean; - } - - type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; - type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close' | 'quit' | 'togglefullscreen' | 'resetzoom' | 'zoomin' | 'zoomout' | 'editMenu' | 'windowMenu' | 'reload' | 'forcereload' | 'toggledevtools'; - type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'startspeaking' | 'stopspeaking' | 'front' | 'zoom' | 'window' | 'help' | 'services'; - - interface MenuItemOptions { - /** - * Callback when the menu item is clicked. - */ - click?: (menuItem: MenuItem, browserWindow: BrowserWindow, event: Event) => void; - /** - * Can be normal, separator, submenu, checkbox or radio. - */ - type?: MenuItemType; - label?: string; - sublabel?: string; - /** - * An accelerator is string that represents a keyboard shortcut, it can contain - * multiple modifiers and key codes, combined by the + character. - * - * Examples: - * CommandOrControl+A - * CommandOrControl+Shift+Z - * - * Platform notice: - * On Linux and Windows, the Command key would not have any effect, - * you can use CommandOrControl which represents Command on macOS and Control on - * Linux and Windows to define some accelerators. - * - * Use Alt instead of Option. The Option key only exists on macOS, whereas - * the Alt key is available on all platforms. - * - * The Super key is mapped to the Windows key on Windows and Linux and Cmd on macOS. - * - * Available modifiers: - * Command (or Cmd for short) - * Control (or Ctrl for short) - * CommandOrControl (or CmdOrCtrl for short) - * Alt - * Option - * AltGr - * Shift - * Super - * - * Available key codes: - * 0 to 9 - * A to Z - * F1 to F24 - * Punctuations like ~, !, @, #, $, etc. - * Plus - * Space - * Tab - * Backspace - * Delete - * Insert - * Return (or Enter as alias) - * Up, Down, Left and Right - * Home and End - * PageUp and PageDown - * Escape (or Esc for short) - * VolumeUp, VolumeDown and VolumeMute - * MediaNextTrack, MediaPreviousTrack, MediaStop and MediaPlayPause - * PrintScreen - */ - accelerator?: string; - /** - * In Electron for the APIs that take images, you can pass either file paths - * or NativeImage instances. When passing null, an empty image will be used. - */ - icon?: NativeImage|string; - /** - * If false, the menu item will be greyed out and unclickable. - */ - enabled?: boolean; - /** - * If false, the menu item will be entirely hidden. - */ - visible?: boolean; - /** - * Should only be specified for 'checkbox' or 'radio' type menu items. - */ - checked?: boolean; - /** - * Should be specified for submenu type menu item, when it's specified the - * type: 'submenu' can be omitted for the menu item - */ - submenu?: Menu|MenuItemOptions[]; - /** - * Unique within a single menu. If defined then it can be used as a reference - * to this item by the position attribute. - */ - id?: string; - /** - * This field allows fine-grained definition of the specific location within - * a given menu. - */ - position?: string; - /** - * Define the action of the menu item, when specified the click property will be ignored - */ - role?: MenuItemRole | MenuItemRoleMac; - } - - // https://github.com/electron/electron/blob/master/docs/api/menu.md - - /** - * The Menu class is used to create native menus that can be used as application - * menus and context menus. This module is a main process module which can be used - * in a render process via the remote module. - * - * Each menu consists of multiple menu items, and each menu item can have a submenu. - */ - class Menu extends NodeJS.EventEmitter { - /** - * Creates a new menu. - */ - constructor(); - /** - * Sets menu as the application menu on macOS. On Windows and Linux, the - * menu will be set as each window's top menu. - * - * Passing null will remove the menu bar on Windows and Linux but has no - * effect on macOS. - */ - static setApplicationMenu(menu: Menu | null): void; - /** - * @returns The application menu if set, or null if not set. - */ - static getApplicationMenu(): Menu | null; - /** - * Sends the action to the first responder of application. - * This is used for emulating default Cocoa menu behaviors, - * usually you would just use the role property of MenuItem. - * - * Note: This method is macOS only. - */ - static sendActionToFirstResponder(action: string): void; - /** - * @param template Generally, just an array of options for constructing MenuItem. - * You can also attach other fields to element of the template, and they will - * become properties of the constructed menu items. - */ - static buildFromTemplate(template: MenuItemOptions[]): Menu; - /** - * Pops up this menu as a context menu in the browserWindow. You can optionally - * provide a (x,y) coordinate to place the menu at, otherwise it will be placed - * at the current mouse cursor position. - * @param x Horizontal coordinate where the menu will be placed. - * @param y Vertical coordinate where the menu will be placed. - */ - popup(browserWindow?: BrowserWindow, x?: number, y?: number): void; - /** - * Appends the menuItem to the menu. - */ - append(menuItem: MenuItem): void; - /** - * Inserts the menuItem to the pos position of the menu. - */ - insert(position: number, menuItem: MenuItem): void; - /** - * @returns an array containing the menu’s items. - */ - items: MenuItem[]; - } - - // https://github.com/electron/electron/blob/master/docs/api/native-image.md - - /** - * This class is used to represent an image. - */ - class NativeImage { - /** - * Creates an empty NativeImage instance. - */ - static createEmpty(): NativeImage; - /** - * Creates a new NativeImage instance from file located at path. - * This method returns an empty image if the path does not exist, cannot be read, or is not a valid image. - */ - static createFromPath(path: string): NativeImage; - /** - * Creates a new NativeImage instance from buffer. - * @param scaleFactor 1.0 by default. - */ - static createFromBuffer(buffer: Buffer, scaleFactor?: number): NativeImage; - /** - * Creates a new NativeImage instance from dataURL - */ - static createFromDataURL(dataURL: string): NativeImage; - /** - * @returns Buffer that contains the image's PNG encoded data. - */ - toPNG(): Buffer; - /** - * @returns Buffer that contains the image's JPEG encoded data. - */ - toJPEG(quality: number): Buffer; - /** - * @returns Buffer that contains a copy of the image's raw bitmap pixel data. - */ - toBitmap(): Buffer; - /** - * @returns Buffer that contains the image's raw bitmap pixel data. - * - * The difference between getBitmap() and toBitmap() is, getBitmap() does not copy the bitmap data, - * so you have to use the returned Buffer immediately in current event loop tick, - * otherwise the data might be changed or destroyed. - */ - getBitmap(): Buffer; - /** - * @returns The data URL of the image. - */ - toDataURL(): string; - /** - * The native type of the handle is NSImage* on macOS. - * Note: This is only implemented on macOS. - * @returns The platform-specific handle of the image as Buffer. - */ - getNativeHandle(): Buffer; - /** - * @returns Whether the image is empty. - */ - isEmpty(): boolean; - /** - * @returns The size of the image. - */ - getSize(): Size; - /** - * Marks the image as template image. - */ - setTemplateImage(option: boolean): void; - /** - * Returns a boolean whether the image is a template image. - */ - isTemplateImage(): boolean; - } - - // https://github.com/electron/electron/blob/master/docs/api/net.md - - /** - * The net module is a client-side API for issuing HTTP(S) requests. - * It is similar to the HTTP and HTTPS modules of Node.js but uses Chromium’s native - * networking library instead of the Node.js implementation, offering better support - * for web proxies. - * The following is a non-exhaustive list of why you may consider using the net module - * instead of the native Node.js modules: - * - Automatic management of system proxy configuration, support of the wpad protocol - * and proxy pac configuration files. - * - Automatic tunneling of HTTPS requests. - * - Support for authenticating proxies using basic, digest, NTLM, Kerberos or negotiate - * authentication schemes. - * - Support for traffic monitoring proxies: Fiddler-like proxies used for access control - * and monitoring. - * - * The net module API has been specifically designed to mimic, as closely as possible, - * the familiar Node.js API. The API components including classes, methods, - * properties and event names are similar to those commonly used in Node.js. - * - * The net API can be used only after the application emits the ready event. - * Trying to use the module before the ready event will throw an error. - */ - interface Net extends NodeJS.EventEmitter { - /** - * @param options The ClientRequest constructor options. - * @param callback A one time listener for the response event. - * - * @returns a ClientRequest instance using the provided options which are directly - * forwarded to the ClientRequest constructor. - */ - request(options: string | RequestOptions, callback?: (response: IncomingMessage) => void): ClientRequest; - } - - /** - * The RequestOptions interface allows to define various options for an HTTP request. - */ - interface RequestOptions { - /** - * The HTTP request method. Defaults to the GET method. - */ - method?: string; - /** - * The request URL. Must be provided in the absolute form with the protocol - * scheme specified as http or https. - */ - url?: string; - /** - * The Session instance with which the request is associated. - */ - session?: Session; - /** - * The name of the partition with which the request is associated. - * Defaults to the empty string. The session option prevails on partition. - * Thus if a session is explicitly specified, partition is ignored. - */ - partition?: string; - /** - * The protocol scheme in the form ‘scheme:’. Currently supported values are ‘http:’ or ‘https:’. - * Defaults to ‘http:’. - */ - protocol?: 'http:' | 'https:'; - /** - * The server host provided as a concatenation of the hostname and the port number ‘hostname:port’. - */ - host?: string; - /** - * The server host name. - */ - hostname?: string; - /** - * The server’s listening port number. - */ - port?: number; - /** - * The path part of the request URL. - */ - path?: string; - /** - * A map specifying extra HTTP header name/value. - */ - headers?: { [key: string]: any }; - } - - /** - * The ClientRequest class represents an HTTP request. - */ - class ClientRequest extends NodeJS.EventEmitter { - /** - * Emitted when an HTTP response is received for the request. - */ - on(event: 'response', listener: (response: IncomingMessage) => void): this; - /** - * Emitted when an authenticating proxy is asking for user credentials. - * The callback function is expected to be called back with user credentials. - * Providing empty credentials will cancel the request and report an authentication - * error on the response object. - */ - on(event: 'login', listener: (authInfo: LoginAuthInfo, callback: (username?: string, password?: string) => void) => void): this; - /** - * Emitted just after the last chunk of the request’s data has been written into - * the request object. - */ - on(event: 'finish', listener: () => void): this; - /** - * Emitted when the request is aborted. The abort event will not be fired if the - * request is already closed. - */ - on(event: 'abort', listener: () => void): this; - /** - * Emitted when the net module fails to issue a network request. - * Typically when the request object emits an error event, a close event will - * subsequently follow and no response object will be provided. - */ - on(event: 'error', listener: (error: Error) => void): this; - /** - * Emitted as the last event in the HTTP request-response transaction. - * The close event indicates that no more events will be emitted on either the - * request or response objects. - */ - on(event: 'close', listener: () => void): this; - on(event: string, listener: Function): this; - /** - * A Boolean specifying whether the request will use HTTP chunked transfer encoding or not. - * Defaults to false. The property is readable and writable, however it can be set only before - * the first write operation as the HTTP headers are not yet put on the wire. - * Trying to set the chunkedEncoding property after the first write will throw an error. - * - * Using chunked encoding is strongly recommended if you need to send a large request - * body as data will be streamed in small chunks instead of being internally buffered - * inside Electron process memory. - */ - chunkedEncoding: boolean; - /** - * @param options If options is a String, it is interpreted as the request URL. - * If it is an object, it is expected to be a RequestOptions. - * @param callback A one time listener for the response event. - */ - constructor(options: string | RequestOptions, callback?: (response: IncomingMessage) => void); - /** - * Adds an extra HTTP header. The header name will issued as it is without lowercasing. - * It can be called only before first write. Calling this method after the first write - * will throw an error. - * @param name An extra HTTP header name. - * @param value An extra HTTP header value. - */ - setHeader(name: string, value: string): void; - /** - * @param name Specify an extra header name. - * @returns The value of a previously set extra header name. - */ - getHeader(name: string): string; - /** - * Removes a previously set extra header name. This method can be called only before first write. - * Trying to call it after the first write will throw an error. - * @param name Specify an extra header name. - */ - removeHeader(name: string): void; - /** - * Adds a chunk of data to the request body. The first write operation may cause the - * request headers to be issued on the wire. - * After the first write operation, it is not allowed to add or remove a custom header. - * @param chunk A chunk of the request body’s data. If it is a string, it is converted - * into a Buffer using the specified encoding. - * @param encoding Used to convert string chunks into Buffer objects. Defaults to ‘utf-8’. - * @param callback Called after the write operation ends. - */ - write(chunk: string | Buffer, encoding?: string, callback?: Function): boolean; - /** - * Sends the last chunk of the request data. Subsequent write or end operations will not be allowed. - * The finish event is emitted just after the end operation. - * @param chunk A chunk of the request body’s data. If it is a string, it is converted into - * a Buffer using the specified encoding. - * @param encoding Used to convert string chunks into Buffer objects. Defaults to ‘utf-8’. - * @param callback Called after the write operation ends. - * - */ - end(chunk?: string | Buffer, encoding?: string, callback?: Function): boolean; - /** - * Cancels an ongoing HTTP transaction. If the request has already emitted the close event, - * the abort operation will have no effect. - * Otherwise an ongoing event will emit abort and close events. - * Additionally, if there is an ongoing response object,it will emit the aborted event. - */ - abort(): void - } - - /** - * An IncomingMessage represents an HTTP response. - */ - interface IncomingMessage extends NodeJS.ReadableStream { - /** - * The data event is the usual method of transferring response data into applicative code. - */ - on(event: 'data', listener: (chunk: Buffer) => void): this; - /** - * Indicates that response body has ended. - */ - on(event: 'end', listener: () => void): this; - /** - * Emitted when a request has been canceled during an ongoing HTTP transaction. - */ - on(event: 'aborted', listener: () => void): this; - /** - * Emitted when an error was encountered while streaming response data events. - * For instance, if the server closes the underlying while the response is still - * streaming, an error event will be emitted on the response object and a close - * event will subsequently follow on the request object. - */ - on(event: 'error', listener: (error: Error) => void): this; - on(event: string, listener: Function): this; - /** - * An Integer indicating the HTTP response status code. - */ - statusCode: number; - /** - * A String representing the HTTP status message. - */ - statusMessage: string; - /** - * An object representing the response HTTP headers. The headers object is formatted as follows: - * - All header names are lowercased. - * - Each header name produces an array-valued property on the headers object. - * - Each header value is pushed into the array associated with its header name. - */ - headers: { - [key: string]: string[] - }; - /** - * A string indicating the HTTP protocol version number. Typical values are ‘1.0’ or ‘1.1’. - */ - httpVersion: string; - /** - * An integer-valued read-only property that returns the HTTP major version number. - */ - httpVersionMajor: number; - /** - * An integer-valued read-only property that returns the HTTP minor version number. - */ - httpVersionMinor: number; - } - - // https://github.com/electron/electron/blob/master/docs/api/power-monitor.md - - /** - * The power-monitor module is used to monitor power state changes. - * You should not use this module until the ready event of the app module is emitted. - */ - interface PowerMonitor extends NodeJS.EventEmitter { - /** - * Emitted when the system is suspending. - */ - on(event: 'suspend', listener: Function): this; - /** - * Emitted when system is resuming. - */ - on(event: 'resume', listener: Function): this; - /** - * Emitted when the system changes to AC power. - */ - on(event: 'on-ac', listener: Function): this; - /** - * Emitted when system changes to battery power. - */ - on(event: 'on-battery', listener: Function): this; - on(event: string, listener: Function): this; - } - - // https://github.com/electron/electron/blob/master/docs/api/power-save-blocker.md - - /** - * The powerSaveBlocker module is used to block the system from entering - * low-power (sleep) mode and thus allowing the app to keep the system and screen active. - */ - interface PowerSaveBlocker { - /** - * Starts preventing the system from entering lower-power mode. - * @returns The blocker ID that is assigned to this power blocker. - * Note: prevent-display-sleep has higher has precedence over prevent-app-suspension. - */ - start(type: 'prevent-app-suspension' | 'prevent-display-sleep'): number; - /** - * @param id The power save blocker id returned by powerSaveBlocker.start. - * Stops the specified power save blocker. - */ - stop(id: number): void; - /** - * @param id The power save blocker id returned by powerSaveBlocker.start. - * @returns Whether the corresponding powerSaveBlocker has started. - */ - isStarted(id: number): boolean; - } - - // https://github.com/electron/electron/blob/master/docs/api/protocol.md - - /** - * The protocol module can register a custom protocol or intercept an existing protocol. - */ - interface Protocol { - /** - * Registers custom schemes as standard schemes. - */ - registerStandardSchemes(schemes: string[]): void; - /** - * Registers custom schemes to handle service workers. - */ - registerServiceWorkerSchemes(schemes: string[]): void; - /** - * Registers a protocol of scheme that will send the file as a response. - */ - registerFileProtocol(scheme: string, handler: FileProtocolHandler, completion?: (error: Error) => void): void; - /** - * Registers a protocol of scheme that will send a Buffer as a response. - */ - registerBufferProtocol(scheme: string, handler: BufferProtocolHandler, completion?: (error: Error) => void): void; - /** - * Registers a protocol of scheme that will send a String as a response. - */ - registerStringProtocol(scheme: string, handler: StringProtocolHandler, completion?: (error: Error) => void): void; - /** - * Registers a protocol of scheme that will send an HTTP request as a response. - */ - registerHttpProtocol(scheme: string, handler: HttpProtocolHandler, completion?: (error: Error) => void): void; - /** - * Unregisters the custom protocol of scheme. - */ - unregisterProtocol(scheme: string, completion?: (error: Error) => void): void; - /** - * The callback will be called with a boolean that indicates whether there is already a handler for scheme. - */ - isProtocolHandled(scheme: string, callback: (handled: boolean) => void): void; - /** - * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a file as a response. - */ - interceptFileProtocol(scheme: string, handler: FileProtocolHandler, completion?: (error: Error) => void): void; - /** - * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a Buffer as a response. - */ - interceptBufferProtocol(scheme: string, handler: BufferProtocolHandler, completion?: (error: Error) => void): void; - /** - * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a String as a response. - */ - interceptStringProtocol(scheme: string, handler: StringProtocolHandler, completion?: (error: Error) => void): void; - /** - * Intercepts scheme protocol and uses handler as the protocol’s new handler which sends a new HTTP request as a response. - */ - interceptHttpProtocol(scheme: string, handler: HttpProtocolHandler, completion?: (error: Error) => void): void; - /** - * Remove the interceptor installed for scheme and restore its original handler. - */ - uninterceptProtocol(scheme: string, completion?: (error: Error) => void): void; - } - - type FileProtocolHandler = (request: ProtocolRequest, callback: FileProtocolCallback) => void; - type BufferProtocolHandler = (request: ProtocolRequest, callback: BufferProtocolCallback) => void; - type StringProtocolHandler = (request: ProtocolRequest, callback: StringProtocolCallback) => void; - type HttpProtocolHandler = (request: ProtocolRequest, callback: HttpProtocolCallback) => void; - - interface ProtocolRequest { - url: string; - referrer: string; - method: string; - uploadData?: { - /** - * Content being sent. - */ - bytes: Buffer, - /** - * Path of file being uploaded. - */ - file: string, - /** - * UUID of blob data. Use session.getBlobData method to retrieve the data. - */ - blobUUID: string; - }[]; - } - - interface ProtocolCallback { - (error: number): void; - (obj: { - error: number - }): void; - (): void; - } - - interface FileProtocolCallback extends ProtocolCallback { - (filePath: string): void; - (obj: { - path: string - }): void; - } - - interface BufferProtocolCallback extends ProtocolCallback { - (buffer: Buffer): void; - (obj: { - data: Buffer, - mimeType: string, - charset?: string - }): void; - } - - interface StringProtocolCallback extends ProtocolCallback { - (str: string): void; - (obj: { - data: string, - mimeType: string, - charset?: string - }): void; - } - - interface HttpProtocolCallback extends ProtocolCallback { - (redirectRequest: { - url: string; - method: string; - session?: Object; - uploadData?: { - contentType: string; - data: string; - }; - }): void; - } - - // https://github.com/electron/electron/blob/master/docs/api/remote.md - - /** - * The remote module provides a simple way to do inter-process communication (IPC) - * between the renderer process (web page) and the main process. - */ - interface Remote extends CommonElectron { - /** - * @returns The object returned by require(module) in the main process. - */ - require(module: string): any; - /** - * @returns The BrowserWindow object which this web page belongs to. - */ - getCurrentWindow(): BrowserWindow; - /** - * @returns The WebContents object of this web page. - */ - getCurrentWebContents(): WebContents; - /** - * @returns The global variable of name (e.g. global[name]) in the main process. - */ - getGlobal(name: string): any; - /** - * Returns the process object in the main process. This is the same as - * remote.getGlobal('process'), but gets cached. - */ - process: NodeJS.Process; - } - - // https://github.com/electron/electron/blob/master/docs/api/screen.md - - /** - * The Display object represents a physical display connected to the system. - * A fake Display may exist on a headless system, or a Display may correspond to a remote, virtual display. - */ - interface Display { - /** - * Unique identifier associated with the display. - */ - id: number; - bounds: Rectangle; - workArea: Rectangle; - size: Size; - workAreaSize: Size; - /** - * Output device’s pixel scale factor. - */ - scaleFactor: number; - /** - * Can be 0, 90, 180, 270, represents screen rotation in clock-wise degrees. - */ - rotation: number; - touchSupport: 'available' | 'unavailable' | 'unknown'; - } - - type DisplayMetrics = 'bounds' | 'workArea' | 'scaleFactor' | 'rotation'; - - /** - * The screen module retrieves information about screen size, displays, cursor position, etc. - * You can not use this module until the ready event of the app module is emitted. - */ - interface Screen extends NodeJS.EventEmitter { - /** - * Emitted when newDisplay has been added. - */ - on(event: 'display-added', listener: (event: Event, newDisplay: Display) => void): this; - /** - * Emitted when oldDisplay has been removed. - */ - on(event: 'display-removed', listener: (event: Event, oldDisplay: Display) => void): this; - /** - * Emitted when one or more metrics change in a display. - */ - on(event: 'display-metrics-changed', listener: (event: Event, display: Display, changedMetrics: DisplayMetrics[]) => void): this; - on(event: string, listener: Function): this; - /** - * @returns The current absolute position of the mouse pointer. - */ - getCursorScreenPoint(): Point; - /** - * @returns The primary display. - */ - getPrimaryDisplay(): Display; - /** - * @returns An array of displays that are currently available. - */ - getAllDisplays(): Display[]; - /** - * @returns The display nearest the specified point. - */ - getDisplayNearestPoint(point: Point): Display; - /** - * @returns The display that most closely intersects the provided bounds. - */ - getDisplayMatching(rect: Rectangle): Display; - } - - // https://github.com/electron/electron/blob/master/docs/api/session.md - - /** - * The session module can be used to create new Session objects. - * You can also access the session of existing pages by using - * the session property of webContents which is a property of BrowserWindow. - */ - class Session extends NodeJS.EventEmitter { - /** - * @returns a new Session instance from partition string. - */ - static fromPartition(partition: string, options?: FromPartitionOptions): Session; - /** - * @returns the default session object of the app. - */ - static defaultSession: Session; - /** - * Emitted when Electron is about to download item in webContents. - * Calling event.preventDefault() will cancel the download - * and item will not be available from next tick of the process. - */ - on(event: 'will-download', listener: (event: Event, item: DownloadItem, webContents: WebContents) => void): this; - on(event: string, listener: Function): this; - /** - * The cookies gives you ability to query and modify cookies. - */ - cookies: SessionCookies; - /** - * @returns the session’s current cache size. - */ - getCacheSize(callback: (size: number) => void): void; - /** - * Clears the session’s HTTP cache. - */ - clearCache(callback: Function): void; - /** - * Clears the data of web storages. - */ - clearStorageData(callback: Function): void; - /** - * Clears the data of web storages. - */ - clearStorageData(options: ClearStorageDataOptions, callback: Function): void; - /** - * Writes any unwritten DOMStorage data to disk. - */ - flushStorageData(): void; - /** - * Sets the proxy settings. - */ - setProxy(config: ProxyConfig, callback: Function): void; - /** - * Resolves the proxy information for url. - */ - resolveProxy(url: URL, callback: (proxy: string) => void): void; - /** - * Sets download saving directory. - * By default, the download directory will be the Downloads under the respective app folder. - */ - setDownloadPath(path: string): void; - /** - * Emulates network with the given configuration for the session. - */ - enableNetworkEmulation(options: NetworkEmulationOptions): void; - /** - * Disables any network emulation already active for the session. - * Resets to the original network configuration. - */ - disableNetworkEmulation(): void; - /** - * Sets the certificate verify proc for session, the proc will be called - * whenever a server certificate verification is requested. - * - * Calling setCertificateVerifyProc(null) will revert back to default certificate verify proc. - */ - setCertificateVerifyProc(proc: ((hostname: string, cert: Certificate, callback: (accepted: boolean) => void) => void) | null): void; - /** - * Sets the handler which can be used to respond to permission requests for the session. - */ - setPermissionRequestHandler(handler: (webContents: WebContents, permission: Permission, callback: (allow: boolean) => void) => void): void; - /** - * Clears the host resolver cache. - */ - clearHostResolverCache(callback: Function): void; - /** - * Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. - * @param domains Comma-seperated list of servers for which integrated authentication is enabled. - */ - allowNTLMCredentialsForDomains(domains: string): void; - /** - * Overrides the userAgent and acceptLanguages for this session. - * The acceptLanguages must a comma separated ordered list of language codes, for example "en-US,fr,de,ko,zh-CN,ja". - * This doesn't affect existing WebContents, and each WebContents can use webContents.setUserAgent to override the session-wide user agent. - */ - setUserAgent(userAgent: string, acceptLanguages?: string): void; - /** - * @returns The user agent for this session. - */ - getUserAgent(): string; - /** - * Returns the blob data associated with the identifier. - */ - getBlobData(identifier: string, callback: (result: Buffer) => void): void; - /** - * The webRequest API set allows to intercept and modify contents of a request at various stages of its lifetime. - */ - webRequest: WebRequest; - /** - * @returns An instance of protocol module for this session. - */ - protocol: Protocol; - } - - type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal'; - - interface FromPartitionOptions { - /** - * Whether to enable cache. - */ - cache?: boolean; - } - - interface ClearStorageDataOptions { - /** - * Should follow window.location.origin’s representation scheme://host:port. - */ - origin?: string; - /** - * The types of storages to clear. - */ - storages?: ('appcache' | 'cookies' | 'filesystem' | 'indexdb' | 'localstorage' | 'shadercache' | 'websql' | 'serviceworkers')[]; - /** - * The types of quotas to clear. - */ - quotas?: ('temporary' | 'persistent' | 'syncable')[]; - } - - interface ProxyConfig { - /** - * The URL associated with the PAC file. - */ - pacScript: string; - /** - * Rules indicating which proxies to use. - */ - proxyRules: string; - /** - * Rules indicating which URLs should bypass the proxy settings. - */ - proxyBypassRules: string; - } - - interface NetworkEmulationOptions { - /** - * Whether to emulate network outage. - * Default: false. - */ - offline?: boolean; - /** - * RTT in ms. - * Default: 0, which will disable latency throttling. - */ - latency?: number; - /** - * Download rate in Bps. - * Default: 0, which will disable download throttling. - */ - downloadThroughput?: number; - /** - * Upload rate in Bps. - * Default: 0, which will disable upload throttling. - */ - uploadThroughput?: number; - } - - interface CookieFilter { - /** - * Retrieves cookies which are associated with url. Empty implies retrieving cookies of all urls. - */ - url?: string; - /** - * Filters cookies by name. - */ - name?: string; - /** - * Retrieves cookies whose domains match or are subdomains of domains. - */ - domain?: string; - /** - * Retrieves cookies whose path matches path. - */ - path?: string; - /** - * Filters cookies by their Secure property. - */ - secure?: boolean; - /** - * Filters out session or persistent cookies. - */ - session?: boolean; - } - - interface Cookie { - /** - * Emitted when a cookie is changed because it was added, edited, removed, or expired. - */ - on(event: 'changed', listener: (event: Event, cookie: Cookie, cause: CookieChangedCause) => void): this; - on(event: string, listener: Function): this; - /** - * The name of the cookie. - */ - name: string; - /** - * The value of the cookie. - */ - value: string; - /** - * The domain of the cookie. - */ - domain: string; - /** - * Whether the cookie is a host-only cookie. - */ - hostOnly: string; - /** - * The path of the cookie. - */ - path: string; - /** - * Whether the cookie is marked as secure. - */ - secure: boolean; - /** - * Whether the cookie is marked as HTTP only. - */ - httpOnly: boolean; - /** - * Whether the cookie is a session cookie or a persistent cookie with an expiration date. - */ - session: boolean; - /** - * The expiration date of the cookie as the number of seconds since the UNIX epoch. - * Not provided for session cookies. - */ - expirationDate?: number; - } - - type CookieChangedCause = 'explicit' | 'overwrite' | 'expired' | 'evicted' | 'expired-overwrite'; - - interface CookieDetails { - /** - * The URL associated with the cookie. - */ - url: string; - /** - * The name of the cookie. - * Default: empty. - */ - name?: string; - /** - * The value of the cookie. - * Default: empty. - */ - value?: string; - /** - * The domain of the cookie. - * Default: empty. - */ - domain?: string; - /** - * The path of the cookie. - * Default: empty. - */ - path?: string; - /** - * Whether the cookie should be marked as secure. - * Default: false. - */ - secure?: boolean; - /** - * Whether the cookie should be marked as HTTP only. - * Default: false. - */ - httpOnly?: boolean; - /** - * The expiration date of the cookie as the number of seconds since the UNIX epoch. - * If omitted, the cookie becomes a session cookie. - */ - expirationDate?: number; - } - - interface SessionCookies { - /** - * Sends a request to get all cookies matching filter. - */ - get(filter: CookieFilter, callback: (error: Error, cookies: Cookie[]) => void): void; - /** - * Sets the cookie with details. - */ - set(details: CookieDetails, callback: (error: Error) => void): void; - /** - * Removes the cookies matching url and name. - */ - remove(url: string, name: string, callback: (error: Error) => void): void; - } - - /** - * Each API accepts an optional filter and a listener, the listener will be called when the API's event has happened. - * Passing null as listener will unsubscribe from the event. - * - * The filter will be used to filter out the requests that do not match the URL patterns. - * If the filter is omitted then all requests will be matched. - * - * For certain events the listener is passed with a callback, - * which should be called with an response object when listener has done its work. - */ - interface WebRequest { - /** - * The listener will be called when a request is about to occur. - */ - onBeforeRequest(listener: (details: WebRequest.BeforeRequestDetails, callback: WebRequest.BeforeRequestCallback) => void): void; - /** - * The listener will be called when a request is about to occur. - */ - onBeforeRequest(filter: WebRequest.Filter, listener: (details: WebRequest.BeforeRequestDetails, callback: WebRequest.BeforeRequestCallback) => void): void; - /** - * The listener will be called before sending an HTTP request, once the request headers are available. - * This may occur after a TCP connection is made to the server, but before any http data is sent. - */ - onBeforeSendHeaders(listener: (details: WebRequest.BeforeSendHeadersDetails, callback: WebRequest.BeforeSendHeadersCallback) => void): void; - /** - * The listener will be called before sending an HTTP request, once the request headers are available. - * This may occur after a TCP connection is made to the server, but before any http data is sent. - */ - onBeforeSendHeaders(filter: WebRequest.Filter, listener: (details: WebRequest.BeforeSendHeadersDetails, callback: WebRequest.BeforeSendHeadersCallback) => void): void; - /** - * The listener will be called just before a request is going to be sent to the server, - * modifications of previous onBeforeSendHeaders response are visible by the time this listener is fired. - */ - onSendHeaders(listener: (details: WebRequest.SendHeadersDetails) => void): void; - /** - * The listener will be called just before a request is going to be sent to the server, - * modifications of previous onBeforeSendHeaders response are visible by the time this listener is fired. - */ - onSendHeaders(filter: WebRequest.Filter, listener: (details: WebRequest.SendHeadersDetails) => void): void; - /** - * The listener will be called when HTTP response headers of a request have been received. - */ - onHeadersReceived(listener: (details: WebRequest.HeadersReceivedDetails, callback: WebRequest.HeadersReceivedCallback) => void): void; - /** - * The listener will be called when HTTP response headers of a request have been received. - */ - onHeadersReceived(filter: WebRequest.Filter, listener: (details: WebRequest.HeadersReceivedDetails, callback: WebRequest.HeadersReceivedCallback) => void): void; - /** - * The listener will be called when first byte of the response body is received. - * For HTTP requests, this means that the status line and response headers are available. - */ - onResponseStarted(listener: (details: WebRequest.ResponseStartedDetails) => void): void; - /** - * The listener will be called when first byte of the response body is received. - * For HTTP requests, this means that the status line and response headers are available. - */ - onResponseStarted(filter: WebRequest.Filter, listener: (details: WebRequest.ResponseStartedDetails) => void): void; - /** - * The listener will be called when a server initiated redirect is about to occur. - */ - onBeforeRedirect(listener: (details: WebRequest.BeforeRedirectDetails) => void): void; - /** - * The listener will be called when a server initiated redirect is about to occur. - */ - onBeforeRedirect(filter: WebRequest.Filter, listener: (details: WebRequest.BeforeRedirectDetails) => void): void; - /** - * The listener will be called when a request is completed. - */ - onCompleted(listener: (details: WebRequest.CompletedDetails) => void): void; - /** - * The listener will be called when a request is completed. - */ - onCompleted(filter: WebRequest.Filter, listener: (details: WebRequest.CompletedDetails) => void): void; - /** - * The listener will be called when an error occurs. - */ - onErrorOccurred(listener: (details: WebRequest.ErrorOccurredDetails) => void): void; - /** - * The listener will be called when an error occurs. - */ - onErrorOccurred(filter: WebRequest.Filter, listener: (details: WebRequest.ErrorOccurredDetails) => void): void; - } - - namespace WebRequest { - interface Filter { - urls: string[]; - } - - interface Details { - id: number; - url: string; - method: string; - resourceType: string; - timestamp: number; - } - - interface UploadData { - /** - * Content being sent. - */ - bytes: Buffer; - /** - * Path of file being uploaded. - */ - file: string; - /** - * UUID of blob data. Use session.getBlobData method to retrieve the data. - */ - blobUUID: string; - } - - interface BeforeRequestDetails extends Details { - uploadData?: UploadData[]; - } - - type BeforeRequestCallback = (response: { - cancel?: boolean; - /** - * The original request is prevented from being sent or completed, and is instead redirected to the given URL. - */ - redirectURL?: string; - }) => void; - - interface BeforeSendHeadersDetails extends Details { - requestHeaders: Headers; - } - - type BeforeSendHeadersCallback = (response: { - cancel?: boolean; - /** - * When provided, request will be made with these headers. - */ - requestHeaders?: Headers; - }) => void; - - interface SendHeadersDetails extends Details { - requestHeaders: Headers; - } - - interface HeadersReceivedDetails extends Details { - statusLine: string; - statusCode: number; - responseHeaders: Headers; - } - - type HeadersReceivedCallback = (response: { - cancel?: boolean; - /** - * When provided, the server is assumed to have responded with these headers. - */ - responseHeaders?: Headers; - /** - * Should be provided when overriding responseHeaders to change header status - * otherwise original response header's status will be used. - */ - statusLine?: string; - }) => void; - - interface ResponseStartedDetails extends Details { - responseHeaders: Headers; - fromCache: boolean; - statusCode: number; - statusLine: string; - } - - interface BeforeRedirectDetails extends Details { - redirectURL: string; - statusCode: number; - ip?: string; - fromCache: boolean; - responseHeaders: Headers; - } - - interface CompletedDetails extends Details { - responseHeaders: Headers; - fromCache: boolean; - statusCode: number; - statusLine: string; - } - - interface ErrorOccurredDetails extends Details { - fromCache: boolean; - error: string; - } - } - - // https://github.com/electron/electron/blob/master/docs/api/shell.md - - /** - * The shell module provides functions related to desktop integration. - */ - interface Shell { - /** - * Show the given file in a file manager. If possible, select the file. - * @returns Whether the item was successfully shown. - */ - showItemInFolder(fullPath: string): boolean; - /** - * Open the given file in the desktop's default manner. - * @returns Whether the item was successfully shown. - */ - openItem(fullPath: string): boolean; - /** - * Open the given external protocol URL in the desktop's default manner - * (e.g., mailto: URLs in the default mail user agent). - * @returns Whether an application was available to open the URL. - */ - openExternal(url: string, options?: { - /** - * Bring the opened application to the foreground. - * Default: true. - */ - activate: boolean; - }): boolean; - /** - * Move the given file to trash. - * @returns Whether the item was successfully moved to the trash. - */ - moveItemToTrash(fullPath: string): boolean; - /** - * Play the beep sound. - */ - beep(): void; - /** - * Creates or updates a shortcut link at shortcutPath. - * - * Note: This API is available only on Windows. - */ - writeShortcutLink(shortcutPath: string, options: ShortcutLinkOptions): boolean; - /** - * Creates or updates a shortcut link at shortcutPath. - * - * Note: This API is available only on Windows. - */ - writeShortcutLink(shortcutPath: string, operation: 'create' | 'update' | 'replace', options: ShortcutLinkOptions): boolean; - /** - * Resolves the shortcut link at shortcutPath. - * An exception will be thrown when any error happens. - * - * Note: This API is available only on Windows. - */ - readShortcutLink(shortcutPath: string): ShortcutLinkOptions; - } - - interface ShortcutLinkOptions { - /** - * The target to launch from this shortcut. - */ - target: string; - /** - * The working directory. - * Default: empty. - */ - cwd?: string; - /** - * The arguments to be applied to target when launching from this shortcut. - * Default: empty. - */ - args?: string; - /** - * The description of the shortcut. - * Default: empty. - */ - description?: string; - /** - * The path to the icon, can be a DLL or EXE. icon and iconIndex have to be set together. - * Default: empty, which uses the target's icon. - */ - icon?: string; - /** - * The resource ID of icon when icon is a DLL or EXE. - * Default: 0. - */ - iconIndex?: number; - /** - * The Application User Model ID. - * Default: empty. - */ - appUserModelId?: string; - } - - // https://github.com/electron/electron/blob/master/docs/api/system-preferences.md - - type SystemColor = - '3d-dark-shadow' | // Dark shadow for three-dimensional display elements. - '3d-face' | // Face color for three-dimensional display elements and for dialog box backgrounds. - '3d-highlight' | // Highlight color for three-dimensional display elements. - '3d-light' | // Light color for three-dimensional display elements. - '3d-shadow' | // Shadow color for three-dimensional display elements. - 'active-border' | // Active window border. - 'active-caption' | // Active window title bar. Specifies the left side color in the color gradient of an active window's title bar if the gradient effect is enabled. - 'active-caption-gradient' | // Right side color in the color gradient of an active window's title bar. - 'app-workspace' | // Background color of multiple document interface (MDI) applications. - 'button-text' | // Text on push buttons. - 'caption-text' | // Text in caption, size box, and scroll bar arrow box. - 'desktop' | // Desktop background color. - 'disabled-text' | // Grayed (disabled) text. - 'highlight' | // Item(s) selected in a control. - 'highlight-text' | // Text of item(s) selected in a control. - 'hotlight' | // Color for a hyperlink or hot-tracked item. - 'inactive-border' | // Inactive window border. - 'inactive-caption' | // Inactive window caption. Specifies the left side color in the color gradient of an inactive window's title bar if the gradient effect is enabled. - 'inactive-caption-gradient' | // Right side color in the color gradient of an inactive window's title bar. - 'inactive-caption-text' | // Color of text in an inactive caption. - 'info-background' | // Background color for tooltip controls. - 'info-text' | // Text color for tooltip controls. - 'menu' | // Menu background. - 'menu-highlight' | // The color used to highlight menu items when the menu appears as a flat menu. - 'menubar' | // The background color for the menu bar when menus appear as flat menus. - 'menu-text' | // Text in menus. - 'scrollbar' | // Scroll bar gray area. - 'window' | // Window background. - 'window-frame' | // Window frame. - 'window-text'; // Text in windows. - - /** - * Get system preferences. - */ - interface SystemPreferences { - /** - * Note: This is only implemented on Windows. - */ - on(event: 'accent-color-changed', listener: (event: Event, newColor: string) => void): this; - /** - * Note: This is only implemented on Windows. - */ - on(event: 'color-changed', listener: (event: Event) => void): this; - /** - * Note: This is only implemented on Windows. - */ - on(event: 'inverted-color-scheme-changed', listener: ( - event: Event, - /** - * @param invertedColorScheme true if an inverted color scheme, such as a high contrast theme, is being used, false otherwise. - */ - invertedColorScheme: boolean - ) => void): this; - on(event: string, listener: Function): this; - /** - * @returns Whether the system is in Dark Mode. - * - * Note: This is only implemented on macOS. - */ - isDarkMode(): boolean; - /** - * @returns Whether the Swipe between pages setting is on. - * - * Note: This is only implemented on macOS. - */ - isSwipeTrackingFromScrollEventsEnabled(): boolean; - /** - * Posts event as native notifications of macOS. - * The userInfo contains the user information dictionary sent along with the notification. - * - * Note: This is only implemented on macOS. - */ - postNotification(event: string, userInfo: Object): void; - /** - * Posts event as native notifications of macOS. - * The userInfo contains the user information dictionary sent along with the notification. - * - * Note: This is only implemented on macOS. - */ - postLocalNotification(event: string, userInfo: Object): void; - /** - * Subscribes to native notifications of macOS, callback will be called when the corresponding event happens. - * The id of the subscriber is returned, which can be used to unsubscribe the event. - * - * Note: This is only implemented on macOS. - */ - subscribeNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; - /** - * Removes the subscriber with id. - * - * Note: This is only implemented on macOS. - */ - unsubscribeNotification(id: number): void; - /** - * Same as subscribeNotification, but uses NSNotificationCenter for local defaults. - */ - subscribeLocalNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; - /** - * Same as unsubscribeNotification, but removes the subscriber from NSNotificationCenter. - */ - unsubscribeLocalNotification(id: number): void; - /** - * Get the value of key in system preferences. - * - * Note: This is only implemented on macOS. - */ - getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url' | 'array' | 'dictionary'): any; - /** - * @returns Whether DWM composition (Aero Glass) is enabled. - * - * Note: This is only implemented on Windows. - */ - isAeroGlassEnabled(): boolean; - /** - * @returns The users current system wide color preference in the form of an RGBA hexadecimal string. - * - * Note: This is only implemented on Windows. - */ - getAccentColor(): string; - /** - * @returns true if an inverted color scheme, such as a high contrast theme, is active, false otherwise. - * - * Note: This is only implemented on Windows. - */ - isInvertedColorScheme(): boolean; - /** - * @returns The system color setting in RGB hexadecimal form (#ABCDEF). See the Windows docs for more details. - * - * Note: This is only implemented on Windows. - */ - getColor(color: SystemColor): string; - } - - // https://github.com/electron/electron/blob/master/docs/api/tray.md - - /** - * A Tray represents an icon in an operating system's notification area. - */ - class Tray extends NodeJS.EventEmitter implements Destroyable { - /** - * Emitted when the tray icon is clicked. - * Note: The bounds payload is only implemented on macOS and Windows. - */ - on(event: 'click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; - /** - * Emitted when the tray icon is right clicked. - * Note: This is only implemented on macOS and Windows. - */ - on(event: 'right-click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; - /** - * Emitted when the tray icon is double clicked. - * Note: This is only implemented on macOS and Windows. - */ - on(event: 'double-click', listener: (modifiers: Modifiers, bounds: Rectangle) => void): this; - /** - * Emitted when the tray balloon shows. - * Note: This is only implemented on Windows. - */ - on(event: 'balloon-show', listener: Function): this; - /** - * Emitted when the tray balloon is clicked. - * Note: This is only implemented on Windows. - */ - on(event: 'balloon-click', listener: Function): this; - /** - * Emitted when the tray balloon is closed because of timeout or user manually closes it. - * Note: This is only implemented on Windows. - */ - on(event: 'balloon-closed', listener: Function): this; - /** - * Emitted when any dragged items are dropped on the tray icon. - * Note: This is only implemented on macOS. - */ - on(event: 'drop', listener: Function): this; - /** - * Emitted when dragged files are dropped in the tray icon. - * Note: This is only implemented on macOS - */ - on(event: 'drop-files', listener: (event: Event, files: string[]) => void): this; - /** - * Emitted when dragged text is dropped in the tray icon. - * Note: This is only implemented on macOS - */ - on(event: 'drop-text', listener: (event: Event, text: string) => void): this; - /** - * Emitted when a drag operation enters the tray icon. - * Note: This is only implemented on macOS - */ - on(event: 'drag-enter', listener: Function): this; - /** - * Emitted when a drag operation exits the tray icon. - * Note: This is only implemented on macOS - */ - on(event: 'drag-leave', listener: Function): this; - /** - * Emitted when a drag operation ends on the tray or ends at another location. - * Note: This is only implemented on macOS - */ - on(event: 'drag-end', listener: Function): this; - on(event: string, listener: Function): this; - /** - * Creates a new tray icon associated with the image. - */ - constructor(image: NativeImage|string); - /** - * Destroys the tray icon immediately. - */ - destroy(): void; - /** - * Sets the image associated with this tray icon. - */ - setImage(image: NativeImage|string): void; - /** - * Sets the image associated with this tray icon when pressed. - */ - setPressedImage(image: NativeImage): void; - /** - * Sets the hover text for this tray icon. - */ - setToolTip(toolTip: string): void; - /** - * Sets the title displayed aside of the tray icon in the status bar. - * Note: This is only implemented on macOS. - */ - setTitle(title: string): void; - /** - * Sets when the tray's icon background becomes highlighted. - * Note: This is only implemented on macOS. - */ - setHighlightMode(mode: 'selection' | 'always' | 'never'): void; - /** - * Displays a tray balloon. - * Note: This is only implemented on Windows. - */ - displayBalloon(options?: { - icon?: NativeImage; - title?: string; - content?: string; - }): void; - /** - * Pops up the context menu of tray icon. When menu is passed, - * the menu will showed instead of the tray's context menu. - * The position is only available on Windows, and it is (0, 0) by default. - * Note: This is only implemented on macOS and Windows. - */ - popUpContextMenu(menu?: Menu, position?: Point): void; - /** - * Sets the context menu for this icon. - */ - setContextMenu(menu: Menu): void; - /** - * @returns The bounds of this tray icon. - */ - getBounds(): Rectangle; - /** - * @returns Whether the tray icon is destroyed. - */ - isDestroyed(): boolean; - } - - interface Modifiers { - altKey: boolean; - shiftKey: boolean; - ctrlKey: boolean; - metaKey: boolean; - } - - interface DragItem { - /** - * The absolute path of the file to be dragged - */ - file: string; - /** - * The image showing under the cursor when dragging. - */ - icon: NativeImage; - } - - // https://github.com/electron/electron/blob/master/docs/api/web-contents.md - - interface WebContentsStatic { - /** - * @returns An array of all WebContents instances. This will contain web contents for all windows, - * webviews, opened devtools, and devtools extension background pages. - */ - getAllWebContents(): WebContents[]; - /** - * @returns The web contents that is focused in this application, otherwise returns null. - */ - getFocusedWebContents(): WebContents; - /** - * Find a WebContents instance according to its ID. - */ - fromId(id: number): WebContents; - } - - /** - * A WebContents is responsible for rendering and controlling a web page. - */ - interface WebContents extends NodeJS.EventEmitter { - /** - * Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, - * and the onload event was dispatched. - */ - on(event: 'did-finish-load', listener: Function): this; - /** - * This event is like did-finish-load but emitted when the load failed or was cancelled, - * e.g. window.stop() is invoked. - */ - on(event: 'did-fail-load', listener: (event: Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => void): this; - /** - * Emitted when a frame has done navigation. - */ - on(event: 'did-frame-finish-load', listener: (event: Event, isMainFrame: boolean) => void): this; - /** - * Corresponds to the points in time when the spinner of the tab started spinning. - */ - on(event: 'did-start-loading', listener: Function): this; - /** - * Corresponds to the points in time when the spinner of the tab stopped spinning. - */ - on(event: 'did-stop-loading', listener: Function): this; - /** - * Emitted when details regarding a requested resource are available. - * status indicates the socket connection to download the resource. - */ - on(event: 'did-get-response-details', listener: (event: Event, - status: boolean, - newURL: string, - originalURL: string, - httpResponseCode: number, - requestMethod: string, - referrer: string, - headers: Headers, - resourceType: string - ) => void): this; - /** - * Emitted when a redirect is received while requesting a resource. - */ - on(event: 'did-get-redirect-request', listener: (event: Event, - oldURL: string, - newURL: string, - isMainFrame: boolean, - httpResponseCode: number, - requestMethod: string, - referrer: string, - headers: Headers - ) => void): this; - /** - * Emitted when the document in the given frame is loaded. - */ - on(event: 'dom-ready', listener: (event: Event) => void): this; - /** - * Emitted when page receives favicon URLs. - */ - on(event: 'page-favicon-updated', listener: (event: Event, favicons: string[]) => void): this; - /** - * Emitted when the page requests to open a new window for a url. - * It could be requested by window.open or an external link like . - * - * By default a new BrowserWindow will be created for the url. - * - * Calling event.preventDefault() will prevent creating new windows. - */ - on(event: 'new-window', listener: (event: Event, - url: string, - frameName: string, - disposition: NewWindowDisposition, - options: BrowserWindowOptions - ) => void): this; - /** - * Emitted when a user or the page wants to start navigation. - * It can happen when the window.location object is changed or a user clicks a link in the page. - * - * This event will not emit when the navigation is started programmatically with APIs like - * webContents.loadURL and webContents.back. - * - * It is also not emitted for in-page navigations, such as clicking anchor links - * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. - * - * Calling event.preventDefault() will prevent the navigation. - */ - on(event: 'will-navigate', listener: (event: Event, url: string) => void): this; - /** - * Emitted when a navigation is done. - * - * This event is not emitted for in-page navigations, such as clicking anchor links - * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. - */ - on(event: 'did-navigate', listener: (event: Event, url: string) => void): this; - /** - * Emitted when an in-page navigation happened. - * - * When in-page navigation happens, the page URL changes but does not cause - * navigation outside of the page. Examples of this occurring are when anchor links - * are clicked or when the DOM hashchange event is triggered. - */ - on(event: 'did-navigate-in-page', listener: (event: Event, url: string, isMainFrame: boolean) => void): this; - /** - * Emitted when the renderer process has crashed. - */ - on(event: 'crashed', listener: (event: Event, killed: boolean) => void): this; - /** - * Emitted when a plugin process has crashed. - */ - on(event: 'plugin-crashed', listener: (event: Event, name: string, version: string) => void): this; - /** - * Emitted when webContents is destroyed. - */ - on(event: 'destroyed', listener: Function): this; - /** - * Emitted when DevTools is opened. - */ - on(event: 'devtools-opened', listener: Function): this; - /** - * Emitted when DevTools is closed. - */ - on(event: 'devtools-closed', listener: Function): this; - /** - * Emitted when DevTools is focused / opened. - */ - on(event: 'devtools-focused', listener: Function): this; - /** - * Emitted when failed to verify the certificate for url. - * The usage is the same with the "certificate-error" event of app. - */ - on(event: 'certificate-error', listener: (event: Event, - url: string, - error: string, - certificate: Certificate, - callback: (trust: boolean) => void - ) => void): this; - /** - * Emitted when a client certificate is requested. - * The usage is the same with the "select-client-certificate" event of app. - */ - on(event: 'select-client-certificate', listener: (event: Event, - url: string, - certificateList: Certificate[], - callback: (certificate: Certificate) => void - ) => void): this; - /** - * Emitted when webContents wants to do basic auth. - * The usage is the same with the "login" event of app. - */ - on(event: 'login', listener: (event: Event, - request: LoginRequest, - authInfo: LoginAuthInfo, - callback: (username: string, password: string) => void - ) => void): this; - /** - * Emitted when a result is available for webContents.findInPage request. - */ - on(event: 'found-in-page', listener: (event: Event, result: FoundInPageResult) => void): this; - /** - * Emitted when media starts playing. - */ - on(event: 'media-started-playing', listener: Function): this; - /** - * Emitted when media is paused or done playing. - */ - on(event: 'media-paused', listener: Function): this; - /** - * Emitted when a page’s theme color changes. This is usually due to encountering a meta tag: - * - */ - on(event: 'did-change-theme-color', listener: Function): this; - /** - * Emitted when mouse moves over a link or the keyboard moves the focus to a link. - */ - on(event: 'update-target-url', listener: (event: Event, url: string) => void): this; - /** - * Emitted when the cursor’s type changes. - * If the type parameter is custom, the image parameter will hold the custom cursor image - * in a NativeImage, and scale, size and hotspot will hold additional information about the custom cursor. - */ - on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number, size?: Size, hotspot?: Point) => void): this; - /** - * Emitted when there is a new context menu that needs to be handled. - */ - on(event: 'context-menu', listener: (event: Event, params: ContextMenuParams) => void): this; - /** - * Emitted when bluetooth device needs to be selected on call to navigator.bluetooth.requestDevice. - * To use navigator.bluetooth api webBluetooth should be enabled. - * If event.preventDefault is not called, first available device will be selected. - * callback should be called with deviceId to be selected, - * passing empty string to callback will cancel the request. - */ - on(event: 'select-bluetooth-device', listener: (event: Event, deviceList: BluetoothDevice[], callback: (deviceId: string) => void) => void): this; - /** - * Emitted when a new frame is generated. Only the dirty area is passed in the buffer. - */ - on(event: 'paint', listener: (event: Event, dirtyRect: Rectangle, image: NativeImage) => void): this; - on(event: string, listener: Function): this; - /** - * Loads the url in the window. - * @param url Must contain the protocol prefix (e.g., the http:// or file://). - */ - loadURL(url: string, options?: LoadURLOptions): void; - /** - * Initiates a download of the resource at url without navigating. - * The will-download event of session will be triggered. - */ - downloadURL(url: string): void; - /** - * @returns The URL of current web page. - */ - getURL(): string; - /** - * @returns The title of web page. - */ - getTitle(): string; - /** - * @returns Whether the web page is destroyed. - */ - isDestroyed(): boolean; - /** - * @returns Whether the web page is focused. - */ - isFocused(): boolean; - /** - * @returns Whether web page is still loading resources. - */ - isLoading(): boolean; - /** - * @returns Whether the main frame (and not just iframes or frames within it) is still loading. - */ - isLoadingMainFrame(): boolean; - /** - * @returns Whether web page is waiting for a first-response for the main - * resource of the page. - */ - isWaitingForResponse(): boolean; - /** - * Stops any pending navigation. - */ - stop(): void; - /** - * Reloads current page. - */ - reload(): void; - /** - * Reloads current page and ignores cache. - */ - reloadIgnoringCache(): void; - /** - * @returns Whether the web page can go back. - */ - canGoBack(): boolean; - /** - * @returns Whether the web page can go forward. - */ - canGoForward(): boolean; - /** - * @returns Whether the web page can go to offset. - */ - canGoToOffset(offset: number): boolean; - /** - * Clears the navigation history. - */ - clearHistory(): void; - /** - * Makes the web page go back. - */ - goBack(): void; - /** - * Makes the web page go forward. - */ - goForward(): void; - /** - * Navigates to the specified absolute index. - */ - goToIndex(index: number): void; - /** - * Navigates to the specified offset from the "current entry". - */ - goToOffset(offset: number): void; - /** - * @returns Whether the renderer process has crashed. - */ - isCrashed(): boolean; - /** - * Overrides the user agent for this page. - */ - setUserAgent(userAgent: string): void; - /** - * @returns The user agent for this web page. - */ - getUserAgent(): string; - /** - * Injects CSS into this page. - */ - insertCSS(css: string): void; - /** - * Evaluates code in page. - * @param code Code to evaluate. - * - * @returns Promise - */ - executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any) => void): Promise; - /** - * Mute the audio on the current web page. - */ - setAudioMuted(muted: boolean): void; - /** - * @returns Whether this page has been muted. - */ - isAudioMuted(): boolean; - /** - * Changes the zoom factor to the specified factor. - * Zoom factor is zoom percent divided by 100, so 300% = 3.0. - */ - setZoomFactor(factor: number): void; - /** - * Sends a request to get current zoom factor. - */ - getZoomFactor(callback: (zoomFactor: number) => void): void; - /** - * Changes the zoom level to the specified level. - * The original size is 0 and each increment above or below represents - * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. - */ - setZoomLevel(level: number): void; - /** - * Sends a request to get current zoom level. - */ - getZoomLevel(callback: (zoomLevel: number) => void): void; - /** - * Sets the maximum and minimum zoom level. - */ - setVisualZoomLevelLimits(minimumLevel: number, maximumLevel: number): void; - /** - * Sets the maximum and minimum layout-based (i.e. non-visual) zoom level. - */ - setLayoutZoomLevelLimits(minimumLevel: number, maximumLevel: number): void; - /** - * Executes the editing command undo in web page. - */ - undo(): void; - /** - * Executes the editing command redo in web page. - */ - redo(): void; - /** - * Executes the editing command cut in web page. - */ - cut(): void; - /** - * Executes the editing command copy in web page. - */ - copy(): void; - /** - * Copy the image at the given position to the clipboard. - */ - copyImageAt(x: number, y: number): void; - /** - * Executes the editing command paste in web page. - */ - paste(): void; - /** - * Executes the editing command pasteAndMatchStyle in web page. - */ - pasteAndMatchStyle(): void; - /** - * Executes the editing command delete in web page. - */ - delete(): void; - /** - * Executes the editing command selectAll in web page. - */ - selectAll(): void; - /** - * Executes the editing command unselect in web page. - */ - unselect(): void; - /** - * Executes the editing command replace in web page. - */ - replace(text: string): void; - /** - * Executes the editing command replaceMisspelling in web page. - */ - replaceMisspelling(text: string): void; - /** - * Inserts text to the focused element. - */ - insertText(text: string): void; - /** - * Starts a request to find all matches for the text in the web page. - * The result of the request can be obtained by subscribing to found-in-page event. - * @returns The request id used for the request. - */ - findInPage(text: string, options?: FindInPageOptions): number; - /** - * Stops any findInPage request for the webContents with the provided action. - */ - stopFindInPage(action: StopFindInPageAtion): void; - /** - * Checks if any serviceworker is registered. - */ - hasServiceWorker(callback: (hasServiceWorker: boolean) => void): void; - /** - * Unregisters any serviceworker if present. - */ - unregisterServiceWorker(callback: (isFulfilled: boolean) => void): void; - /** - * Prints window's web page. When silent is set to false, Electron will pick up system's default printer and default settings for printing. - * Calling window.print() in web page is equivalent to call WebContents.print({silent: false, printBackground: false}). - * Note: On Windows, the print API relies on pdf.dll. If your application doesn't need print feature, you can safely remove pdf.dll in saving binary size. - */ - print(options?: PrintOptions): void; - /** - * Prints windows' web page as PDF with Chromium's preview printing custom settings. - */ - printToPDF(options: PrintToPDFOptions, callback: (error: Error, data: Buffer) => void): void; - /** - * Adds the specified path to DevTools workspace. - */ - addWorkSpace(path: string): void; - /** - * Removes the specified path from DevTools workspace. - */ - removeWorkSpace(path: string): void; - /** - * Opens the developer tools. - */ - openDevTools(options?: { - /** - * Opens the devtools with specified dock state. Defaults to last used dock state. - */ - mode?: 'right' | 'bottom' | 'undocked' | 'detach' - }): void; - /** - * Closes the developer tools. - */ - closeDevTools(): void; - /** - * Returns whether the developer tools are opened. - */ - isDevToolsOpened(): boolean; - /** - * Returns whether the developer tools are focussed. - */ - isDevToolsFocused(): boolean; - /** - * Toggle the developer tools. - */ - toggleDevTools(): void; - /** - * Starts inspecting element at position (x, y). - */ - inspectElement(x: number, y: number): void; - /** - * Opens the developer tools for the service worker context. - */ - inspectServiceWorker(): void; - /** - * Send args.. to the web page via channel in asynchronous message, the web page - * can handle it by listening to the channel event of ipc module. - * Note: - * 1. The IPC message handler in web pages do not have a event parameter, - * which is different from the handlers on the main process. - * 2. There is no way to send synchronous messages from the main process - * to a renderer process, because it would be very easy to cause dead locks. - */ - send(channel: string, ...args: any[]): void; - /** - * Enable device emulation with the given parameters. - */ - enableDeviceEmulation(parameters: DeviceEmulationParameters): void; - /** - * Disable device emulation. - */ - disableDeviceEmulation(): void; - /** - * Sends an input event to the page. - */ - sendInputEvent(event: SendInputEvent): void; - /** - * Begin subscribing for presentation events and captured frames, - * The callback will be called when there is a presentation event. - */ - beginFrameSubscription(onlyDirty: boolean, callback: BeginFrameSubscriptionCallback): void; - /** - * Begin subscribing for presentation events and captured frames, - * The callback will be called when there is a presentation event. - */ - beginFrameSubscription(callback: BeginFrameSubscriptionCallback): void; - /** - * End subscribing for frame presentation events. - */ - endFrameSubscription(): void; - /** - * @returns If the process of saving page has been initiated successfully. - */ - savePage(fullPath: string, saveType: 'HTMLOnly' | 'HTMLComplete' | 'MHTML', callback?: (eror: Error) => void): boolean; - /** - * Shows pop-up dictionary that searches the selected word on the page. - * Note: This API is available only on macOS. - */ - showDefinitionForSelection(): void; - /** - * @returns Whether offscreen rendering is enabled. - */ - isOffscreen(): boolean; - /** - * If offscreen rendering is enabled and not painting, start painting. - */ - startPainting(): void; - /** - * If offscreen rendering is enabled and painting, stop painting. - */ - stopPainting(): void; - /** - * If offscreen rendering is enabled returns whether it is currently painting. - */ - isPainting(): boolean; - /** - * If offscreen rendering is enabled sets the frame rate to the specified number. - * Only values between 1 and 60 are accepted. - */ - setFrameRate(fps: number): void; - /** - * If offscreen rendering is enabled returns the current frame rate. - */ - getFrameRate(): number; - /** - * If offscreen rendering is enabled invalidates the frame and generates a new one through the 'paint' event. - */ - invalidate(): void; - /** - * Sets the item as dragging item for current drag-drop operation. - */ - startDrag(item: DragItem): void; - /** - * Captures a snapshot of the page within rect. - */ - capturePage(callback: (image: NativeImage) => void): void; - /** - * Captures a snapshot of the page within rect. - */ - capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; - /** - * @returns The unique ID of this WebContents. - */ - id: number; - /** - * @returns The session object used by this webContents. - */ - session: Session; - /** - * @returns The WebContents that might own this WebContents. - */ - hostWebContents: WebContents; - /** - * @returns The WebContents of DevTools for this WebContents. - * Note: Users should never store this object because it may become null - * when the DevTools has been closed. - */ - devToolsWebContents: WebContents; - /** - * @returns Debugger API - */ - debugger: Debugger; - } - - interface BeginFrameSubscriptionCallback { - ( - /** - * The frameBuffer is a Buffer that contains raw pixel data. - * On most machines, the pixel data is effectively stored in 32bit BGRA format, - * but the actual representation depends on the endianness of the processor - * (most modern processors are little-endian, on machines with big-endian - * processors the data is in 32bit ARGB format). - */ - frameBuffer: Buffer, - /** - * The dirtyRect is an object with x, y, width, height properties that describes which part of the page was repainted. - * If onlyDirty is set to true, frameBuffer will only contain the repainted area. onlyDirty defaults to false. - */ - dirtyRect?: Rectangle - ): void - } - - interface ContextMenuParams { - /** - * x coordinate - */ - x: number; - /** - * y coordinate - */ - y: number; - /** - * URL of the link that encloses the node the context menu was invoked on. - */ - linkURL: string; - /** - * Text associated with the link. May be an empty string if the contents of the link are an image. - */ - linkText: string; - /** - * URL of the top level page that the context menu was invoked on. - */ - pageURL: string; - /** - * URL of the subframe that the context menu was invoked on. - */ - frameURL: string; - /** - * Source URL for the element that the context menu was invoked on. - * Elements with source URLs are images, audio and video. - */ - srcURL: string; - /** - * Type of the node the context menu was invoked on. - */ - mediaType: 'none' | 'image' | 'audio' | 'video' | 'canvas' | 'file' | 'plugin'; - /** - * Parameters for the media element the context menu was invoked on. - */ - mediaFlags: { - /** - * Whether the media element has crashed. - */ - inError: boolean; - /** - * Whether the media element is paused. - */ - isPaused: boolean; - /** - * Whether the media element is muted. - */ - isMuted: boolean; - /** - * Whether the media element has audio. - */ - hasAudio: boolean; - /** - * Whether the media element is looping. - */ - isLooping: boolean; - /** - * Whether the media element's controls are visible. - */ - isControlsVisible: boolean; - /** - * Whether the media element's controls are toggleable. - */ - canToggleControls: boolean; - /** - * Whether the media element can be rotated. - */ - canRotate: boolean; - } - /** - * Whether the context menu was invoked on an image which has non-empty contents. - */ - hasImageContents: boolean; - /** - * Whether the context is editable. - */ - isEditable: boolean; - /** - * These flags indicate whether the renderer believes it is able to perform the corresponding action. - */ - editFlags: { - /** - * Whether the renderer believes it can undo. - */ - canUndo: boolean; - /** - * Whether the renderer believes it can redo. - */ - canRedo: boolean; - /** - * Whether the renderer believes it can cut. - */ - canCut: boolean; - /** - * Whether the renderer believes it can copy - */ - canCopy: boolean; - /** - * Whether the renderer believes it can paste. - */ - canPaste: boolean; - /** - * Whether the renderer believes it can delete. - */ - canDelete: boolean; - /** - * Whether the renderer believes it can select all. - */ - canSelectAll: boolean; - } - /** - * Text of the selection that the context menu was invoked on. - */ - selectionText: string; - /** - * Title or alt text of the selection that the context was invoked on. - */ - titleText: string; - /** - * The misspelled word under the cursor, if any. - */ - misspelledWord: string; - /** - * The character encoding of the frame on which the menu was invoked. - */ - frameCharset: string; - /** - * If the context menu was invoked on an input field, the type of that field. - */ - inputFieldType: 'none' | 'plainText' | 'password' | 'other'; - /** - * Input source that invoked the context menu. - */ - menuSourceType: 'none' | 'mouse' | 'keyboard' | 'touch' | 'touchMenu'; - } - - interface BluetoothDevice { - deviceName: string; - deviceId: string; - } - - interface Headers { - [key: string]: string; - } - - type NewWindowDisposition = 'default' | 'foreground-tab' | 'background-tab' | 'new-window' | 'save-to-disk' | 'other'; - - /** - * Specifies the action to take place when ending webContents.findInPage request. - * 'clearSelection' - Clear the selection. - * 'keepSelection' - Translate the selection into a normal selection. - * 'activateSelection' - Focus and click the selection node. - */ - type StopFindInPageAtion = 'clearSelection' | 'keepSelection' | 'activateSelection'; - - type CursorType = 'default' | 'crosshair' | 'pointer' | 'text' | 'wait' | 'help' | 'e-resize' | 'n-resize' | 'ne-resize' | 'nw-resize' | 's-resize' | 'se-resize' | 'sw-resize' | 'w-resize' | 'ns-resize' | 'ew-resize' | 'nesw-resize' | 'nwse-resize' | 'col-resize' | 'row-resize' | 'm-panning' | 'e-panning' | 'n-panning' | 'ne-panning' | 'nw-panning' | 's-panning' | 'se-panning' |'sw-panning' | 'w-panning' | 'move' | 'vertical-text' | 'cell' | 'context-menu' | 'alias' | 'progress' | 'nodrop' | 'copy' | 'none' | 'not-allowed' | 'zoom-in' | 'zoom-out' | 'grab' | 'grabbing' | 'custom'; - - interface LoadURLOptions { - /** - * HTTP Referrer URL. - */ - httpReferrer?: string; - /** - * User agent originating the request. - */ - userAgent?: string; - /** - * Extra headers separated by "\n" - */ - extraHeaders?: string; - /** - * POST data - */ - postData?: (UploadRawData | UploadFileSystem | UploadBlob)[]; - } - - interface UploadRawData { - /** - * rawData - */ - type: 'rawData'; - /** - * Data to be uploaded. - */ - bytes: Buffer; - } - - interface UploadFileSystem { - /** - * fileSystem - */ - type: 'fileSystem'; - /** - * FileSystem url to read data for upload. - */ - fileSystemURL: string; - /** - * Defaults to 0. - */ - offset: number; - /** - * Number of bytes to read from offset. Defaults to 0. - */ - length: number; - /** - * Last Modification time in number of seconds sine the UNIX epoch. - */ - modificationTime: number; - } - - interface UploadBlob { - /** - * blob - */ - type: 'blob'; - /** - * UUID of blob data to upload. - */ - blobUUID: string; - } - - interface PrintOptions { - /** - * Don't ask user for print settings. - * Defaults: false. - */ - silent?: boolean; - /** - * Also prints the background color and image of the web page. - * Defaults: false. - */ - printBackground?: boolean; - } - - interface PrintToPDFOptions { - /** - * Specify the type of margins to use. - * 0 - default - * 1 - none - * 2 - minimum - * Default: 0 - */ - marginsType?: number; - /** - * Specify page size of the generated PDF. - * Default: A4. - */ - pageSize?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid' | Size; - /** - * Whether to print CSS backgrounds. - * Default: false. - */ - printBackground?: boolean; - /** - * Whether to print selection only. - * Default: false. - */ - printSelectionOnly?: boolean; - /** - * true for landscape, false for portrait. - * Default: false. - */ - landscape?: boolean; - } - - interface Certificate { - /** - * PEM encoded data. - */ - data: string; - /** - * Issuer principal - */ - issuer: CertificatePrincipal; - /** - * Issuer's Common Name. - */ - issuerName: string; - /** - * Issuer certificate (if not self-signed) - */ - issuerCert: Certificate; - /** - * Subject principal - */ - subject: CertificatePrincipal; - /** - * Subject's Common Name. - */ - subjectName: string; - /** - * Hex value represented string. - */ - serialNumber: string; - /** - * Start date of the certificate being valid in seconds. - */ - validStart: number; - /** - * End date of the certificate being valid in seconds. - */ - validExpiry: number; - /** - * Fingerprint of the certificate. - */ - fingerprint: string; - } - - interface CertificatePrincipal { - /** - * Common Name - */ - commonName: string; - /** - * Organization names - */ - organizations: string[]; - /** - * Organization Unit names - */ - organizationUnits: string[]; - /** - * Locality - */ - locality: string; - /** - * State or province - */ - state: string; - /** - * Country or region - */ - country: string; - } - - interface LoginRequest { - method: string; - url: string; - referrer: string; - } - - interface LoginAuthInfo { - isProxy: boolean; - scheme: string; - host: string; - port: number; - realm: string; - } - - interface FindInPageOptions { - /** - * Whether to search forward or backward, defaults to true - */ - forward?: boolean; - /** - * Whether the operation is first request or a follow up, defaults to false. - */ - findNext?: boolean; - /** - * Whether search should be case-sensitive, defaults to false. - */ - matchCase?: boolean; - /** - * Whether to look only at the start of words. defaults to false. - */ - wordStart?: boolean; - /** - * When combined with wordStart, accepts a match in the middle of a word - * if the match begins with an uppercase letter followed by a lowercase - * or non-letter. Accepts several other intra-word matches, defaults to false. - */ - medialCapitalAsWordStart?: boolean; - } - - interface FoundInPageResult { - requestId: number; - /** - * Indicates if more responses are to follow. - */ - finalUpdate: boolean; - /** - * Position of the active match. - */ - activeMatchOrdinal?: number; - /** - * Number of Matches. - */ - matches?: number; - /** - * Coordinates of first match region. - */ - selectionArea?: Rectangle; - } - - interface DeviceEmulationParameters { - /** - * Specify the screen type to emulated - * Default: desktop - */ - screenPosition?: 'desktop' | 'mobile'; - /** - * Set the emulated screen size (screenPosition == mobile) - */ - screenSize?: Size; - /** - * Position the view on the screen (screenPosition == mobile) - * Default: {x: 0, y: 0} - */ - viewPosition?: Point; - /** - * Set the device scale factor (if zero defaults to original device scale factor) - * Default: 0 - */ - deviceScaleFactor: number; - /** - * Set the emulated view size (empty means no override). - */ - viewSize?: Size; - /** - * Whether emulated view should be scaled down if necessary to fit into available space - * Default: false - */ - fitToView?: boolean; - /** - * Offset of the emulated view inside available space (not in fit to view mode) - * Default: {x: 0, y: 0} - */ - offset?: Point; - /** - * Scale of emulated view inside available space (not in fit to view mode) - * Default: 1 - */ - scale: number; - } - - interface SendInputEvent { - type: 'mouseDown' | 'mouseUp' | 'mouseEnter' | 'mouseLeave' | 'contextMenu' | 'mouseWheel' | 'mouseMove' | 'keyDown' | 'keyUp' | 'char'; - modifiers: ('shift' | 'control' | 'alt' | 'meta' | 'isKeypad' | 'isAutoRepeat' | 'leftButtonDown' | 'middleButtonDown' | 'rightButtonDown' | 'capsLock' | 'numLock' | 'left' | 'right')[]; - } - - interface SendInputKeyboardEvent extends SendInputEvent { - keyCode: string; - } - - interface SendInputMouseEvent extends SendInputEvent { - x: number; - y: number; - button?: 'left' | 'middle' | 'right'; - globalX?: number; - globalY?: number; - movementX?: number; - movementY?: number; - clickCount?: number; - } - - interface SendInputMouseWheelEvent extends SendInputEvent { - deltaX?: number; - deltaY?: number; - wheelTicksX?: number; - wheelTicksY?: number; - accelerationRatioX?: number; - accelerationRatioY?: number; - hasPreciseScrollingDeltas?: boolean; - canScroll?: boolean; - } - - /** - * Debugger API serves as an alternate transport for remote debugging protocol. - */ - interface Debugger extends NodeJS.EventEmitter { - /** - * Attaches the debugger to the webContents. - * @param protocolVersion Requested debugging protocol version. - */ - attach(protocolVersion?: string): void; - /** - * @returns Whether a debugger is attached to the webContents. - */ - isAttached(): boolean; - /** - * Detaches the debugger from the webContents. - */ - detach(): void; - /** - * Send given command to the debugging target. - * @param method Method name, should be one of the methods defined by the remote debugging protocol. - * @param commandParams JSON object with request parameters. - * @param callback Response defined by the ‘returns’ attribute of the command description in the remote debugging protocol. - */ - sendCommand(method: string, commandParams?: any, callback?: (error: Error, result: any) => void): void; - /** - * Emitted when debugging session is terminated. This happens either when - * webContents is closed or devtools is invoked for the attached webContents. - */ - on(event: 'detach', listener: (event: Event, reason: string) => void): this; - /** - * Emitted whenever debugging target issues instrumentation event. - * Event parameters defined by the ‘parameters’ attribute in the remote debugging protocol. - */ - on(event: 'message', listener: (event: Event, method: string, params: any) => void): this; - on(event: string, listener: Function): this; - } - - // https://github.com/electron/electron/blob/master/docs/api/web-frame.md - - /** - * The web-frame module allows you to customize the rendering of the current web page. - */ - interface WebFrame { - /** - * Changes the zoom factor to the specified factor, zoom factor is - * zoom percent / 100, so 300% = 3.0. - */ - setZoomFactor(factor: number): void; - /** - * @returns The current zoom factor. - */ - getZoomFactor(): number; - /** - * Changes the zoom level to the specified level, 0 is "original size", and each - * increment above or below represents zooming 20% larger or smaller to default - * limits of 300% and 50% of original size, respectively. - */ - setZoomLevel(level: number): void; - /** - * @returns The current zoom level. - */ - getZoomLevel(): number; - /** - * Sets the maximum and minimum zoom level. - */ - setVisualZoomLevelLimits(minimumLevel: number, maximumLevel: number): void; - /** - * Sets the maximum and minimum layout-based (i.e. non-visual) zoom level. - */ - setLayoutZoomLevelLimits(minimumLevel: number, maximumLevel: number): void; - /** - * Sets a provider for spell checking in input fields and text areas. - */ - setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: { - /** - * @returns Whether the word passed is correctly spelled. - */ - spellCheck: (text: string) => boolean; - }): void; - /** - * Sets the scheme as secure scheme. Secure schemes do not trigger mixed content - * warnings. For example, https and data are secure schemes because they cannot be - * corrupted by active network attackers. - */ - registerURLSchemeAsSecure(scheme: string): void; - /** - * Resources will be loaded from this scheme regardless of the current page’s Content Security Policy. - */ - registerURLSchemeAsBypassingCSP(scheme: string): void; - /** - * Registers the scheme as secure, bypasses content security policy for resources, - * allows registering ServiceWorker and supports fetch API. - */ - registerURLSchemeAsPrivileged(scheme: string, options?: RegisterURLSchemeOptions): void; - /** - * Inserts text to the focused element. - */ - insertText(text: string): void; - /** - * Evaluates `code` in page. - * In the browser window some HTML APIs like `requestFullScreen` can only be - * invoked by a gesture from the user. Setting `userGesture` to `true` will remove - * this limitation. - * - * @returns Promise - */ - executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any) => void): Promise; - /** - * @returns Object describing usage information of Blink’s internal memory caches. - */ - getResourceUsage(): ResourceUsages; - /** - * Attempts to free memory that is no longer being used (like images from a previous navigation). - */ - clearCache(): void; - } - - interface ResourceUsages { - fonts: ResourceUsage; - images: ResourceUsage; - cssStyleSheets: ResourceUsage; - xslStyleSheets: ResourceUsage; - scripts: ResourceUsage; - other: ResourceUsage; - } - - interface ResourceUsage { - count: number; - decodedSize: number; - liveSize: number; - purgeableSize: number; - purgedSize: number; - size: number; - } - - interface RegisterURLSchemeOptions { - secure?: boolean; - bypassCSP?: boolean; - allowServiceWorkers?: boolean; - supportFetchAPI?: boolean; - corsEnabled?: boolean; - } - - // https://github.com/electron/electron/blob/master/docs/api/web-view-tag.md - - /** - * Use the webview tag to embed 'guest' content (such as web pages) in your Electron app. - * The guest content is contained within the webview container. - * An embedded page within your app controls how the guest content is laid out and rendered. - * - * Unlike an iframe, the webview runs in a separate process than your app. - * It doesn't have the same permissions as your web page and all interactions between your app - * and embedded content will be asynchronous. This keeps your app safe from the embedded content. - */ - interface WebViewElement extends HTMLElement { - /** - * Returns the visible URL. Writing to this attribute initiates top-level navigation. - * Assigning src its own value will reload the current page. - * The src attribute can also accept data URLs, such as data:text/plain,Hello, world!. - */ - src: string; - /** - * If "on", the webview container will automatically resize within the bounds specified - * by the attributes minwidth, minheight, maxwidth, and maxheight. - * These constraints do not impact the webview unless autosize is enabled. - * When autosize is enabled, the webview container size cannot be less than - * the minimum values or greater than the maximum. - */ - autosize: string; - /** - * If "on", the guest page in webview will have node integration and can use node APIs - * like require and process to access low level system resources. - */ - nodeintegration: string; - /** - * If "on", the guest page in webview will be able to use browser plugins. - */ - plugins: string; - /** - * Specifies a script that will be loaded before other scripts run in the guest page. - * The protocol of script's URL must be either file: or asar:, - * because it will be loaded by require in guest page under the hood. - * - * When the guest page doesn't have node integration this script will still have access to all Node APIs, - * but global objects injected by Node will be deleted after this script has finished executing. - */ - preload: string; - /** - * Sets the referrer URL for the guest page. - */ - httpreferrer: string; - /** - * Sets the user agent for the guest page before the page is navigated to. - * Once the page is loaded, use the setUserAgent method to change the user agent. - */ - useragent: string; - /** - * If "on", the guest page will have web security disabled. - */ - disablewebsecurity: string; - /** - * Sets the session used by the page. If partition starts with persist:, - * the page will use a persistent session available to all pages in the app with the same partition. - * If there is no persist: prefix, the page will use an in-memory session. - * By assigning the same partition, multiple pages can share the same session. - * If the partition is unset then default session of the app will be used. - * - * This value can only be modified before the first navigation, - * since the session of an active renderer process cannot change. - * Subsequent attempts to modify the value will fail with a DOM exception. - */ - partition: string; - /** - * If "on", the guest page will be allowed to open new windows. - */ - allowpopups: string; - /** - * A list of strings which specifies the web preferences to be set on the webview, separated by ,. - */ - webpreferences: string; - /** - * A list of strings which specifies the blink features to be enabled separated by ,. - */ - blinkfeatures: string; - /** - * A list of strings which specifies the blink features to be disabled separated by ,. - */ - disableblinkfeatures: string; - /** - * A value that links the webview to a specific webContents. - * When a webview first loads a new webContents is created and this attribute is set - * to its instance identifier. Setting this attribute on a new or existing webview connects - * it to the existing webContents that currently renders in a different webview. - * - * The existing webview will see the destroy event and will then create a new webContents when a new url is loaded. - */ - guestinstance: string; - /** - * Loads the url in the webview, the url must contain the protocol prefix, e.g. the http:// or file://. - */ - loadURL(url: string, options?: LoadURLOptions): void; - /** - * @returns URL of guest page. - */ - getURL(): string; - /** - * @returns The title of guest page. - */ - getTitle(): string; - /** - * @returns Whether the web page is destroyed. - */ - isDestroyed(): boolean; - /** - * @returns Whether the web page is focused. - */ - isFocused(): boolean; - /** - * @returns Whether guest page is still loading resources. - */ - isLoading(): boolean; - /** - * Returns a boolean whether the guest page is waiting for a first-response for the main resource of the page. - */ - isWaitingForResponse(): boolean; - /** - * Stops any pending navigation. - */ - stop(): void; - /** - * Reloads the guest page. - */ - reload(): void; - /** - * Reloads the guest page and ignores cache. - */ - reloadIgnoringCache(): void; - /** - * @returns Whether the guest page can go back. - */ - canGoBack(): boolean; - /** - * @returns Whether the guest page can go forward. - */ - canGoForward(): boolean; - /** - * @returns Whether the guest page can go to offset. - */ - canGoToOffset(offset: number): boolean; - /** - * Clears the navigation history. - */ - clearHistory(): void; - /** - * Makes the guest page go back. - */ - goBack(): void; - /** - * Makes the guest page go forward. - */ - goForward(): void; - /** - * Navigates to the specified absolute index. - */ - goToIndex(index: number): void; - /** - * Navigates to the specified offset from the "current entry". - */ - goToOffset(offset: number): void; - /** - * @returns Whether the renderer process has crashed. - */ - isCrashed(): boolean; - /** - * Overrides the user agent for the guest page. - */ - setUserAgent(userAgent: string): void; - /** - * @returns The user agent for guest page. - */ - getUserAgent(): string; - /** - * Injects CSS into the guest page. - */ - insertCSS(css: string): void; - /** - * Evaluates code in page. If userGesture is set, it will create the user gesture context in the page. - * HTML APIs like requestFullScreen, which require user action, can take advantage of this option for automation. - * - * @returns Promise - */ - executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any) => void): Promise; - /** - * Opens a DevTools window for guest page. - */ - openDevTools(): void; - /** - * Closes the DevTools window of guest page. - */ - closeDevTools(): void; - /** - * @returns Whether guest page has a DevTools window attached. - */ - isDevToolsOpened(): boolean; - /** - * @returns Whether DevTools window of guest page is focused. - */ - isDevToolsFocused(): boolean; - /** - * Starts inspecting element at position (x, y) of guest page. - */ - inspectElement(x: number, y: number): void; - /** - * Opens the DevTools for the service worker context present in the guest page. - */ - inspectServiceWorker(): void; - /** - * Set guest page muted. - */ - setAudioMuted(muted: boolean): void; - /** - * @returns Whether guest page has been muted. - */ - isAudioMuted(): boolean; - /** - * Executes editing command undo in page. - */ - undo(): void; - /** - * Executes editing command redo in page. - */ - redo(): void; - /** - * Executes editing command cut in page. - */ - cut(): void; - /** - * Executes editing command copy in page. - */ - copy(): void; - /** - * Executes editing command paste in page. - */ - paste(): void; - /** - * Executes editing command pasteAndMatchStyle in page. - */ - pasteAndMatchStyle(): void; - /** - * Executes editing command delete in page. - */ - delete(): void; - /** - * Executes editing command selectAll in page. - */ - selectAll(): void; - /** - * Executes editing command unselect in page. - */ - unselect(): void; - /** - * Executes editing command replace in page. - */ - replace(text: string): void; - /** - * Executes editing command replaceMisspelling in page. - */ - replaceMisspelling(text: string): void; - /** - * Inserts text to the focused element. - */ - insertText(text: string): void; - /** - * Starts a request to find all matches for the text in the web page. - * The result of the request can be obtained by subscribing to found-in-page event. - * @returns The request id used for the request. - */ - findInPage(text: string, options?: FindInPageOptions): number; - /** - * Stops any findInPage request for the webview with the provided action. - */ - stopFindInPage(action: StopFindInPageAtion): void; - /** - * Prints webview's web page. Same with webContents.print([options]). - */ - print(options?: PrintOptions): void; - /** - * Prints webview's web page as PDF, Same with webContents.printToPDF(options, callback) - */ - printToPDF(options: PrintToPDFOptions, callback: (error: Error, data: Buffer) => void): void; - /** - * Send an asynchronous message to renderer process via channel, you can also send arbitrary arguments. - * The renderer process can handle the message by listening to the channel event with the ipcRenderer module. - * See webContents.send for examples. - */ - send(channel: string, ...args: any[]): void; - /** - * Sends an input event to the page. - * See webContents.sendInputEvent for detailed description of event object. - */ - sendInputEvent(event: SendInputEvent): void - /** - * Changes the zoom factor to the specified factor. - * Zoom factor is zoom percent divided by 100, so 300% = 3.0. - */ - setZoomFactor(factor: number): void; - /** - * Changes the zoom level to the specified level. - * The original size is 0 and each increment above or below represents - * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. - */ - setZoomLevel(level: number): void; - /** - * Shows pop-up dictionary that searches the selected word on the page. - * Note: This API is available only on macOS. - */ - showDefinitionForSelection(): void; - /** - * @returns The WebContents associated with this webview. - */ - getWebContents(): WebContents; - /** - * Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback). - */ - capturePage(callback: (image: NativeImage) => void): void; - /** - * Captures a snapshot of the webview's page. Same as webContents.capturePage([rect, ]callback). - */ - capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; - /** - * Fired when a load has committed. This includes navigation within the current document - * as well as subframe document-level loads, but does not include asynchronous resource loads. - */ - addEventListener(type: 'load-commit', listener: (event: WebViewElement.LoadCommitEvent) => void, useCapture?: boolean): void; - /** - * Fired when the navigation is done, i.e. the spinner of the tab will stop spinning, and the onload event is dispatched. - */ - addEventListener(type: 'did-finish-load', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * This event is like did-finish-load, but fired when the load failed or was cancelled, e.g. window.stop() is invoked. - */ - addEventListener(type: 'did-fail-load', listener: (event: WebViewElement.DidFailLoadEvent) => void, useCapture?: boolean): void; - /** - * Fired when a frame has done navigation. - */ - addEventListener(type: 'did-frame-finish-load', listener: (event: WebViewElement.DidFrameFinishLoadEvent) => void, useCapture?: boolean): void; - /** - * Corresponds to the points in time when the spinner of the tab starts spinning. - */ - addEventListener(type: 'did-start-loading', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Corresponds to the points in time when the spinner of the tab stops spinning. - */ - addEventListener(type: 'did-stop-loading', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Fired when details regarding a requested resource is available. - * status indicates socket connection to download the resource. - */ - addEventListener(type: 'did-get-response-details', listener: (event: WebViewElement.DidGetResponseDetails) => void, useCapture?: boolean): void; - /** - * Fired when a redirect was received while requesting a resource. - */ - addEventListener(type: 'did-get-redirect-request', listener: (event: WebViewElement.DidGetRedirectRequestEvent) => void, useCapture?: boolean): void; - /** - * Fired when document in the given frame is loaded. - */ - addEventListener(type: 'dom-ready', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Fired when page title is set during navigation. explicitSet is false when title is synthesized from file URL. - */ - addEventListener(type: 'page-title-updated', listener: (event: WebViewElement.PageTitleUpdatedEvent) => void, useCapture?: boolean): void; - /** - * Fired when page receives favicon URLs. - */ - addEventListener(type: 'page-favicon-updated', listener: (event: WebViewElement.PageFaviconUpdatedEvent) => void, useCapture?: boolean): void; - /** - * Fired when page enters fullscreen triggered by HTML API. - */ - addEventListener(type: 'enter-html-full-screen', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Fired when page leaves fullscreen triggered by HTML API. - */ - addEventListener(type: 'leave-html-full-screen', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Fired when the guest window logs a console message. - */ - addEventListener(type: 'console-message', listener: (event: WebViewElement.ConsoleMessageEvent) => void, useCapture?: boolean): void; - /** - * Fired when a result is available for webview.findInPage request. - */ - addEventListener(type: 'found-in-page', listener: (event: WebViewElement.FoundInPageEvent) => void, useCapture?: boolean): void; - /** - * Fired when the guest page attempts to open a new browser window. - */ - addEventListener(type: 'new-window', listener: (event: WebViewElement.NewWindowEvent) => void, useCapture?: boolean): void; - /** - * Emitted when a user or the page wants to start navigation. - * It can happen when the window.location object is changed or a user clicks a link in the page. - * - * This event will not emit when the navigation is started programmatically with APIs - * like .loadURL and .back. - * - * It is also not emitted during in-page navigation, such as clicking anchor links - * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. - * - * Calling event.preventDefault() does NOT have any effect. - */ - addEventListener(type: 'will-navigate', listener: (event: WebViewElement.WillNavigateEvent) => void, useCapture?: boolean): void; - /** - * Emitted when a navigation is done. - * - * This event is not emitted for in-page navigations, such as clicking anchor links - * or updating the window.location.hash. Use did-navigate-in-page event for this purpose. - */ - addEventListener(type: 'did-navigate', listener: (event: WebViewElement.DidNavigateEvent) => void, useCapture?: boolean): void; - /** - * Emitted when an in-page navigation happened. - * - * When in-page navigation happens, the page URL changes but does not cause - * navigation outside of the page. Examples of this occurring are when anchor links - * are clicked or when the DOM hashchange event is triggered. - */ - addEventListener(type: 'did-navigate-in-page', listener: (event: WebViewElement.DidNavigateInPageEvent) => void, useCapture?: boolean): void; - /** - * Fired when the guest page attempts to close itself. - */ - addEventListener(type: 'close', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Fired when the guest page has sent an asynchronous message to embedder page. - */ - addEventListener(type: 'ipc-message', listener: (event: WebViewElement.IpcMessageEvent) => void, useCapture?: boolean): void; - /** - * Fired when the renderer process is crashed. - */ - addEventListener(type: 'crashed', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Fired when the gpu process is crashed. - */ - addEventListener(type: 'gpu-crashed', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Fired when a plugin process is crashed. - */ - addEventListener(type: 'plugin-crashed', listener: (event: WebViewElement.PluginCrashedEvent) => void, useCapture?: boolean): void; - /** - * Fired when the WebContents is destroyed. - */ - addEventListener(type: 'destroyed', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Emitted when media starts playing. - */ - addEventListener(type: 'media-started-playing', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Emitted when media is paused or done playing. - */ - addEventListener(type: 'media-paused', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Emitted when a page's theme color changes. This is usually due to encountering a meta tag: - * - */ - addEventListener(type: 'did-change-theme-color', listener: (event: WebViewElement.DidChangeThemeColorEvent) => void, useCapture?: boolean): void; - /** - * Emitted when mouse moves over a link or the keyboard moves the focus to a link. - */ - addEventListener(type: 'update-target-url', listener: (event: WebViewElement.UpdateTargetUrlEvent) => void, useCapture?: boolean): void; - /** - * Emitted when DevTools is opened. - */ - addEventListener(type: 'devtools-opened', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Emitted when DevTools is closed. - */ - addEventListener(type: 'devtools-closed', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - /** - * Emitted when DevTools is focused / opened. - */ - addEventListener(type: 'devtools-focused', listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - addEventListener(type: string, listener: (event: WebViewElement.Event) => void, useCapture?: boolean): void; - } - - namespace WebViewElement { - type Event = ElectronPrivate.GlobalEvent; - - interface LoadCommitEvent extends Event { - url: string; - isMainFrame: boolean; - } - - interface DidFailLoadEvent extends Event { - errorCode: number; - errorDescription: string; - validatedURL: string; - isMainFrame: boolean; - } - - interface DidFrameFinishLoadEvent extends Event { - isMainFrame: boolean; - } - - interface DidGetResponseDetails extends Event { - status: boolean; - newURL: string; - originalURL: string; - httpResponseCode: number; - requestMethod: string; - referrer: string; - headers: Headers; - resourceType: string; - } - - interface DidGetRedirectRequestEvent extends Event { - oldURL: string; - newURL: string; - isMainFrame: boolean; - httpResponseCode: number; - requestMethod: string; - referrer: string; - headers: Headers; - } - - interface PageTitleUpdatedEvent extends Event { - title: string; - explicitSet: string; - } - - interface PageFaviconUpdatedEvent extends Event { - favicons: string[]; - } - - interface ConsoleMessageEvent extends Event { - level: number; - message: string; - line: number; - sourceId: string; - } - - interface FoundInPageEvent extends Event { - result: FoundInPageResult; - } - - interface NewWindowEvent extends Event { - url: string; - frameName: string; - disposition: NewWindowDisposition; - options: BrowserWindowOptions; - } - - interface WillNavigateEvent extends Event { - url: string; - } - - interface DidNavigateEvent extends Event { - url: string; - } - - interface DidNavigateInPageEvent extends Event { - url: string; - isMainFrame: boolean; - } - - interface IpcMessageEvent extends Event { - channel: string; - args: any[]; - } - - interface PluginCrashedEvent extends Event { - name: string; - version: string; - } - - interface DidChangeThemeColorEvent extends Event { - themeColor: string; - } - - interface UpdateTargetUrlEvent extends Event { - url: string; - } - } - - /** - * The BrowserWindowProxy object is returned from window.open and provides limited functionality with the child window. - */ - interface BrowserWindowProxy { - /** - * Removes focus from the child window. - */ - blur(): void; - /** - * Forcefully closes the child window without calling its unload event. - */ - close(): void; - /** - * Set to true after the child window gets closed. - */ - closed: boolean; - /** - * Evaluates the code in the child window. - */ - eval(code: string): void; - /** - * Focuses the child window (brings the window to front). - */ - focus(): void; - /** - * Sends a message to the child window with the specified origin or * for no origin preference. - * In addition to these methods, the child window implements window.opener object with no - * properties and a single method. - */ - postMessage(message: string, targetOrigin: string): void; - /** - * Invokes the print dialog on the child window. - */ - print(): void; - } - - // https://github.com/electron/electron/blob/master/docs/api/synopsis.md - - interface CommonElectron { - clipboard: Electron.Clipboard; - crashReporter: Electron.CrashReporter; - nativeImage: typeof Electron.NativeImage; - shell: Electron.Shell; - - app: Electron.App; - autoUpdater: Electron.AutoUpdater; - BrowserWindow: typeof Electron.BrowserWindow; - contentTracing: Electron.ContentTracing; - dialog: Electron.Dialog; - ipcMain: Electron.IpcMain; - globalShortcut: Electron.GlobalShortcut; - Menu: typeof Electron.Menu; - MenuItem: typeof Electron.MenuItem; - net: Electron.Net; - powerMonitor: Electron.PowerMonitor; - powerSaveBlocker: Electron.PowerSaveBlocker; - protocol: Electron.Protocol; - screen: Electron.Screen; - session: typeof Electron.Session; - systemPreferences: Electron.SystemPreferences; - Tray: typeof Electron.Tray; - webContents: Electron.WebContentsStatic; - } - - interface ElectronMainAndRenderer extends CommonElectron { - desktopCapturer: Electron.DesktopCapturer; - ipcRenderer: Electron.IpcRenderer; - remote: Electron.Remote; - webFrame: Electron.WebFrame; - } -} - -declare namespace ElectronPrivate { - type GlobalEvent = Event; -} - -interface Document { - createElement(tagName: 'webview'): Electron.WebViewElement; -} - -// https://github.com/electron/electron/blob/master/docs/api/window-open.md - -interface Window { - /** - * Creates a new window. - */ - open(url: string, frameName?: string, features?: string): Electron.BrowserWindowProxy; -} - -// https://github.com/electron/electron/blob/master/docs/api/file-object.md - -interface File { - /** - * Exposes the real path of the filesystem. - */ - path: string; -} - -// https://github.com/electron/electron/blob/master/docs/api/process.md - -declare namespace NodeJS { - - interface ProcessVersions { - /** - * Electron's version string. - */ - electron: string; - /** - * Chrome's version string. - */ - chrome: string; - } - - interface Process { - /** - * Setting this to true can disable the support for asar archives in Node's built-in modules. - */ - noAsar?: boolean; - /** - * Process's type - */ - type: 'browser' | 'renderer'; - /** - * Path to JavaScript source code. - */ - resourcesPath: string; - /** - * For Mac App Store build, this value is true, for other builds it is undefined. - */ - mas?: boolean; - /** - * If the app is running as a Windows Store app (appx), this value is true, for other builds it is undefined. - */ - windowsStore?: boolean; - /** - * When app is started by being passed as parameter to the default app, - * this value is true in the main process, otherwise it is undefined. - */ - defaultApp?: boolean; - /** - * Emitted when Electron has loaded its internal initialization script - * and is beginning to load the web page or the main script. - */ - on(event: 'loaded', listener: Function): this; - on(event: string, listener: Function): this; - /** - * Causes the main thread of the current process crash; - */ - crash(): void; - /** - * Causes the main thread of the current process hang. - */ - hang(): void; - /** - * Sets the file descriptor soft limit to maxDescriptors or the OS hard limit, - * whichever is lower for the current process. - * - * Note: This API is only available on macOS and Linux. - */ - setFdLimit(maxDescriptors: number): void; - /** - * @returns Object giving memory usage statistics about the current process. - * Note: All statistics are reported in Kilobytes. - */ - getProcessMemoryInfo(): ProcessMemoryInfo; - /** - * @returns Object giving memory usage statistics about the entire system. - * Note: All statistics are reported in Kilobytes. - */ - getSystemMemoryInfo(): SystemMemoryInfo; - } - - interface ProcessMemoryInfo { - /** - * The amount of memory currently pinned to actual physical RAM. - */ - workingSetSize: number; - /** - * The maximum amount of memory that has ever been pinned to actual physical RAM. - */ - peakWorkingSetSize: number; - /** - * The amount of memory not shared by other processes, such as JS heap or HTML content. - */ - privateBytes: number; - /** - * The amount of memory shared between processes, typically memory consumed by the Electron code itself. - */ - sharedBytes: number; - } - - interface SystemMemoryInfo { - /** - * The total amount of physical memory available to the system. - */ - total: number; - /** - * The total amount of memory not being used by applications or disk cache. - */ - free: number; - /** - * The total amount of swap memory available to the system. - */ - swapTotal: number; - /** - * The free amount of swap memory available to the system. - */ - swapFree: number; - } -} - -declare module 'electron' { - var electron: Electron.ElectronMainAndRenderer; - export = electron; -} - -interface NodeRequireFunction { - (moduleName: 'electron'): Electron.ElectronMainAndRenderer; -} diff --git a/types/electron/test/index.ts b/types/electron/test/index.ts deleted file mode 100644 index 8ae462139a..0000000000 --- a/types/electron/test/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -import electron = require('electron'); -import child_process = require('child_process'); - -// TODO -child_process.spawn(electron as any); diff --git a/types/electron/test/main.ts b/types/electron/test/main.ts deleted file mode 100644 index 0f3f17ca33..0000000000 --- a/types/electron/test/main.ts +++ /dev/null @@ -1,1138 +0,0 @@ - -import { - app, - autoUpdater, - BrowserWindow, - contentTracing, - dialog, - globalShortcut, - ipcMain, - Menu, - MenuItem, - net, - powerMonitor, - powerSaveBlocker, - protocol, - Tray, - clipboard, - crashReporter, - nativeImage, - screen, - shell, - session, - systemPreferences, - webContents -} from 'electron'; - -import * as path from 'path'; - -// Quick start -// https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md - -// Keep a global reference of the window object, if you don't, the window will -// be closed automatically when the javascript object is GCed. -var mainWindow: Electron.BrowserWindow = null; - -// Quit when all windows are closed. -app.on('window-all-closed', () => { - if (process.platform !== 'darwin') - app.quit(); -}); - -// Check single instance app -var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) { - // Someone tried to run a second instance, we should focus our window - if (mainWindow) { - if (mainWindow.isMinimized()) mainWindow.restore(); - mainWindow.focus(); - } -}); - -if (shouldQuit) { - app.quit(); - process.exit(0); -} - -// This method will be called when Electron has done everything -// initialization and ready for creating browser windows. -app.on('ready', () => { - // Create the browser window. - mainWindow = new BrowserWindow({ width: 800, height: 600 }); - - // and load the index.html of the app. - mainWindow.loadURL(`file://${__dirname}/index.html`); - mainWindow.loadURL('file://foo/bar', {userAgent: 'cool-agent', httpReferrer: 'greateRefferer'}); - mainWindow.webContents.loadURL('file://foo/bar', {userAgent: 'cool-agent', httpReferrer: 'greateRefferer'}); - mainWindow.webContents.loadURL('file://foo/bar', {userAgent: 'cool-agent', httpReferrer: 'greateRefferer', postData: [{type: 'blob', blobUUID: 'hogefuga'}]}); - - mainWindow.webContents.openDevTools(); - mainWindow.webContents.toggleDevTools(); - mainWindow.webContents.openDevTools({mode: 'detach'}); - mainWindow.webContents.closeDevTools(); - mainWindow.webContents.addWorkSpace('/path/to/workspace'); - mainWindow.webContents.removeWorkSpace('/path/to/workspace'); - var opened: boolean = mainWindow.webContents.isDevToolsOpened() - var focused = mainWindow.webContents.isDevToolsFocused(); - // Emitted when the window is closed. - mainWindow.on('closed', () => { - // Dereference the window object, usually you would store windows - // in an array if your app supports multi windows, this is the time - // when you should delete the corresponding element. - mainWindow = null; - }); - - mainWindow.webContents.setVisualZoomLevelLimits(50, 200); - mainWindow.webContents.setLayoutZoomLevelLimits(50, 200); - - mainWindow.webContents.print({silent: true, printBackground: false}); - mainWindow.webContents.print(); - - mainWindow.webContents.printToPDF({ - marginsType: 1, - pageSize: 'A3', - printBackground: true, - printSelectionOnly: true, - landscape: true, - }, (error: Error, data: Buffer) => {}); - - mainWindow.webContents.printToPDF({}, (err, data) => {}); - - mainWindow.webContents.executeJavaScript('return true;').then((v: boolean) => console.log(v)); - mainWindow.webContents.executeJavaScript('return true;', true); - mainWindow.webContents.executeJavaScript('return true;', true, (result: boolean) => console.log(result)); - mainWindow.webContents.insertText('blah, blah, blah'); - mainWindow.webContents.startDrag({file: '/path/to/img.png', icon: nativeImage.createFromPath('/path/to/icon.png')}); - mainWindow.webContents.findInPage('blah'); - mainWindow.webContents.findInPage('blah', { - forward: true, - matchCase: false, - }); - mainWindow.webContents.stopFindInPage('clearSelection'); - mainWindow.webContents.stopFindInPage('keepSelection'); - mainWindow.webContents.stopFindInPage('activateSelection'); - - mainWindow.loadURL('https://github.com'); - - mainWindow.webContents.on('did-finish-load', function() { - mainWindow.webContents.savePage('/tmp/test.html', 'HTMLComplete', function(error) { - if (!error) - console.log("Save page successfully"); - }); - }); - - try { - mainWindow.webContents.debugger.attach("1.1"); - } catch(err) { - console.log("Debugger attach failed : ", err); - }; - - mainWindow.webContents.debugger.on('detach', function(event, reason) { - console.log("Debugger detached due to : ", reason); - }); - - mainWindow.webContents.debugger.on('message', function(event, method, params) { - if (method == "Network.requestWillBeSent") { - if (params.request.url == "https://www.github.com") { - win.webContents.debugger.detach(); - } - } - }); - - mainWindow.webContents.debugger.sendCommand("Network.enable"); - mainWindow.webContents.capturePage(image => { - console.log(image.toDataURL()); - }); - mainWindow.webContents.capturePage({x: 0, y: 0, width: 100, height: 200}, image => { - console.log(image.toPNG()); - }); - - mainWindow.setMenu(null); - mainWindow.setMenu(Menu.buildFromTemplate([])); -}); - -app.commandLine.appendSwitch('enable-web-bluetooth'); - -app.on('ready', () => { - mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { - event.preventDefault(); - - let result = (() => { - for (let device of deviceList) { - if (device.deviceName === 'test') { - return device; - } - } - return null; - })(); - - if (!result) { - callback(''); - } else { - callback(result.deviceId); - } - }); -}); - -// Locale -app.getLocale(); - -// Desktop environment integration -// https://github.com/atom/electron/blob/master/docs/tutorial/desktop-environment-integration.md - -app.addRecentDocument('/Users/USERNAME/Desktop/work.type'); -app.clearRecentDocuments(); -var dockMenu = Menu.buildFromTemplate([ - { - label: 'New Window', - click: () => { - console.log('New Window'); - } - }, - { - label: 'New Window with Settings', - submenu: [ - { label: 'Basic' }, - { label: 'Pro' } - ] - }, - { label: 'New Command...' }, - { - label: 'Edit', - submenu: [ - { - label: 'Undo', - accelerator: 'CmdOrCtrl+Z', - role: 'undo' - }, - { - label: 'Redo', - accelerator: 'Shift+CmdOrCtrl+Z', - role: 'redo' - }, - { - type: 'separator' - }, - { - label: 'Cut', - accelerator: 'CmdOrCtrl+X', - role: 'cut' - }, - { - label: 'Copy', - accelerator: 'CmdOrCtrl+C', - role: 'copy' - }, - { - label: 'Paste', - accelerator: 'CmdOrCtrl+V', - role: 'paste' - }, - ] - }, -]); -app.dock.setMenu(dockMenu); -app.dock.setBadge('foo'); -var id = app.dock.bounce('informational'); -app.dock.cancelBounce(id); -app.dock.setIcon('/path/to/icon.png'); - -app.setBadgeCount(app.getBadgeCount() + 1); - -app.setUserTasks([ - { - program: process.execPath, - arguments: '--new-window', - iconPath: process.execPath, - iconIndex: 0, - title: 'New Window', - description: 'Create a new window' - } -]); -app.setUserTasks([]); - -app.setJumpList([ - { - type: 'custom', - name: 'Recent Projects', - items: [ - { type: 'file', path: 'C:\\Projects\\project1.proj' }, - { type: 'file', path: 'C:\\Projects\\project2.proj' } - ] - }, - { // has a name so type is assumed to be "custom" - name: 'Tools', - items: [ - { - type: 'task', - title: 'Tool A', - program: process.execPath, - args: '--run-tool-a', - iconPath: process.execPath, - iconIndex: 0, - description: 'Runs Tool A' - }, - { - type: 'task', - title: 'Tool B', - program: process.execPath, - args: '--run-tool-b', - iconPath: process.execPath, - iconIndex: 0, - description: 'Runs Tool B' - }] - }, - { - type: 'frequent' - }, - { // has no name and no type so type is assumed to be "tasks" - items: [ - { - type: 'task', - title: 'New Project', - program: process.execPath, - args: '--new-project', - description: 'Create a new project.' - }, - { - type: 'separator' - }, - { - type: 'task', - title: 'Recover Project', - program: process.execPath, - args: '--recover-project', - description: 'Recover Project' - }] - } -]); - -if (app.isUnityRunning()) { -} -if (app.isAccessibilitySupportEnabled()) { -} -app.setLoginItemSettings({openAtLogin: true, openAsHidden: false}); -console.log(app.getLoginItemSettings().wasOpenedAtLogin); -app.setAboutPanelOptions({ - applicationName: 'Test', - version: '1.2.3' -}); - -var window = new BrowserWindow(); -window.setProgressBar(0.5); -window.setRepresentedFilename('/etc/passwd'); -window.setDocumentEdited(true); -window.previewFile('/path/to/file'); -window.previewFile('/path/to/file', 'Displayed Name'); -window.setVibrancy('light'); -window.setVibrancy('titlebar'); - -// Online/Offline Event Detection -// https://github.com/atom/electron/blob/master/docs/tutorial/online-offline-events.md - -var onlineStatusWindow: Electron.BrowserWindow; - -app.on('ready', () => { - onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false, vibrancy: 'sidebar' }); - onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`); -}); -app.on('accessibility-support-changed', (_, enabled) => console.log('accessibility: ' + enabled)); - -ipcMain.on('online-status-changed', (event: any, status: any) => { - console.log(status); -}); - -// Synopsis -// https://github.com/atom/electron/blob/master/docs/api/synopsis.md - -app.on('ready', () => { - window = new BrowserWindow({ - width: 800, - height: 600, - titleBarStyle: 'hidden-inset', - }); - window.loadURL('https://github.com'); -}); - -// Supported Chrome command line switches -// https://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md - -app.commandLine.appendSwitch('remote-debugging-port', '8315'); -app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); -app.commandLine.appendSwitch('vmodule', 'console=0'); - -// systemPreferences -// https://github.com/electron/electron/blob/master/docs/api/system-preferences.md - -var browserOptions = { - width: 1000, - height: 800, - transparent: false, - frame: true -}; - -// Make the window transparent only if the platform supports it. -if (process.platform !== 'win32' || systemPreferences.isAeroGlassEnabled()) { - browserOptions.transparent = true; - browserOptions.frame = false; -} - -if (process.platform === 'win32') { - systemPreferences.on('color-changed', () => { console.log('color changed'); }); - systemPreferences.on('inverted-color-scheme-changed', (_, inverted) => console.log(inverted ? 'inverted' : 'not inverted')); - console.log('Color for menu is', systemPreferences.getColor('menu')); -} - -// Create the window. -var win = new BrowserWindow(browserOptions); - -// Navigate. -if (browserOptions.transparent) { - win.loadURL('file://' + __dirname + '/index.html'); -} else { - // No transparency, so we load a fallback that uses basic styles. - win.loadURL('file://' + __dirname + '/fallback.html'); -} - -// app -// https://github.com/atom/electron/blob/master/docs/api/app.md - -app.on('certificate-error', function(event, webContents, url, error, certificate, callback) { - if (url == "https://github.com") { - // Verification logic. - event.preventDefault(); - callback(true); - } else { - callback(false); - } -}); - -app.on('select-client-certificate', function(event, webContents, url, list, callback) { - event.preventDefault(); - callback(list[0]); -}); - -app.on('login', function(event, webContents, request, authInfo, callback) { - event.preventDefault(); - callback('username', 'secret'); -}); - -var win = new BrowserWindow({show: false}) -win.once('ready-to-show', () => { - win.show(); -}); - -app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])}); -app.exit(0); - -// auto-updater -// https://github.com/atom/electron/blob/master/docs/api/auto-updater.md - -autoUpdater.setFeedURL('http://mycompany.com/myapp/latest?version=' + app.getVersion()); -autoUpdater.checkForUpdates(); -autoUpdater.quitAndInstall(); - -autoUpdater.on('error', (error) => { - console.log('error', error); -}); - -autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName, releaseDate, updateURL) => { - console.log('update-downloaded', releaseNotes, releaseName, releaseDate, updateURL); -}); - -// browser-window -// https://github.com/atom/electron/blob/master/docs/api/browser-window.md - -var win = new BrowserWindow({ width: 800, height: 600, show: false }); -win.on('closed', () => { - win = null; -}); - -win.loadURL('https://github.com'); -win.show(); - -var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); -win.setSheetOffset(toolbarRect.height); - -var installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron'); - -// content-tracing -// https://github.com/atom/electron/blob/master/docs/api/content-tracing.md - -const options = { - categoryFilter: '*', - traceOptions: 'record-until-full,enable-sampling' -} - -contentTracing.startRecording(options, function() { - console.log('Tracing started'); - setTimeout(function() { - contentTracing.stopRecording('', function(path) { - console.log('Tracing data recorded to ' + path); - }); - }, 5000); -}); - -// dialog -// https://github.com/atom/electron/blob/master/docs/api/dialog.md - -// variant without browserWindow -var openDialogResult: string[] = dialog.showOpenDialog({ - title: 'Testing showOpenDialog', - defaultPath: '/var/log/syslog', - filters: [{name: '', extensions: ['']}], - properties: ['openFile', 'openDirectory', 'multiSelections'] -}); - -// variant with browserWindow -openDialogResult = dialog.showOpenDialog(win, { - title: 'Testing showOpenDialog', - defaultPath: '/var/log/syslog', - filters: [{name: '', extensions: ['']}], - properties: ['openFile', 'openDirectory', 'multiSelections'] -}); - -// global-shortcut -// https://github.com/atom/electron/blob/master/docs/api/global-shortcut.md - -// Register a 'ctrl+x' shortcut listener. -var ret = globalShortcut.register('ctrl+x', () => { - console.log('ctrl+x is pressed'); -}); -if (!ret) - console.log('registerion fails'); - -// Check whether a shortcut is registered. -console.log(globalShortcut.isRegistered('ctrl+x')); - -// Unregister a shortcut. -globalShortcut.unregister('ctrl+x'); - -// Unregister all shortcuts. -globalShortcut.unregisterAll(); - -// ipcMain -// https://github.com/atom/electron/blob/master/docs/api/ipc-main-process.md - -ipcMain.on('asynchronous-message', (event: Electron.IpcMainEvent, arg: any) => { - console.log(arg); // prints "ping" - event.sender.send('asynchronous-reply', 'pong'); -}); - -ipcMain.on('synchronous-message', (event: Electron.IpcMainEvent, arg: any) => { - console.log(arg); // prints "ping" - event.returnValue = 'pong'; -}); - -var winWindows = new BrowserWindow({ - width: 800, - height: 600, - show: false, - thickFrame: false, - type: 'toolbar', -}); - -// menu-item -// https://github.com/atom/electron/blob/master/docs/api/menu-item.md - -var menuItem = new MenuItem({ - click: (menuItem: Electron.MenuItem, browserWindow: Electron.BrowserWindow, event: Electron.Event) => { - console.log('click', menuItem, browserWindow, event); - } -}); - -const fakeEvent: Electron.Event = { - preventDefault: () => { }, - sender: winWindows.webContents, -} - -menuItem.label = 'Hello World!'; -menuItem.click(fakeEvent, winWindows, winWindows.webContents) - -// menu -// https://github.com/atom/electron/blob/master/docs/api/menu.md - -var menu = new Menu(); -menu.append(new MenuItem({ label: 'MenuItem1', click: () => { console.log('item 1 clicked'); } })); -menu.append(new MenuItem({ type: 'separator' })); -menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true })); -menu.insert(0, menuItem); - -console.log(menu.items); - -var pos = screen.getCursorScreenPoint(); -menu.popup(null, pos.x, pos.y); - -// main.js -var template = [ - { - label: 'Electron', - submenu: [ - { - label: 'About Electron', - role: 'about' - }, - { - type: 'separator' - }, - { - label: 'Services', - role: 'services', - submenu: [] - }, - { - type: 'separator' - }, - { - label: 'Hide Electron', - accelerator: 'Command+H', - role: 'hide' - }, - { - label: 'Hide Others', - accelerator: 'Command+Shift+H', - role: 'hideothers' - }, - { - label: 'Show All', - role: 'unhide' - }, - { - type: 'separator' - }, - { - label: 'Quit', - accelerator: 'Command+Q', - click: () => { app.quit(); } - } - ] - }, - { - label: 'Edit', - submenu: [ - { - label: 'Undo', - accelerator: 'Command+Z', - role: 'undo' - }, - { - label: 'Redo', - accelerator: 'Shift+Command+Z', - role: 'redo' - }, - { - type: 'separator' - }, - { - label: 'Cut', - accelerator: 'Command+X', - role: 'cut' - }, - { - label: 'Copy', - accelerator: 'Command+C', - role: 'copy' - }, - { - label: 'Paste', - accelerator: 'Command+V', - role: 'paste' - }, - { - label: 'Select All', - accelerator: 'Command+A', - role: 'selectall' - } - ] - }, - { - label: 'View', - submenu: [ - { - label: 'Reload', - accelerator: 'Command+R', - click: (item, focusedWindow) => { - if (focusedWindow) { - focusedWindow.webContents.reloadIgnoringCache(); - } - } - }, - { - label: 'Toggle DevTools', - accelerator: 'Alt+Command+I', - click: (item, focusedWindow) => { - if (focusedWindow) { - focusedWindow.webContents.toggleDevTools(); - } - } - }, - { - type: 'separator' - }, - { - label: 'Actual Size', - accelerator: 'CmdOrCtrl+0', - click: (item, focusedWindow) => { - if (focusedWindow) { - focusedWindow.webContents.setZoomLevel(0) - } - } - }, - { - label: 'Zoom In', - accelerator: 'CmdOrCtrl+Plus', - click: (item, focusedWindow) => { - if (focusedWindow) { - const { webContents } = focusedWindow; - webContents.getZoomLevel((zoomLevel) => { - webContents.setZoomLevel(zoomLevel + 0.5) - }); - } - } - }, - { - label: 'Zoom Out', - accelerator: 'CmdOrCtrl+-', - click: (item, focusedWindow) => { - if (focusedWindow) { - const { webContents } = focusedWindow; - webContents.getZoomLevel((zoomLevel) => { - webContents.setZoomLevel(zoomLevel - 0.5) - }); - } - } - } - ] - }, - { - label: 'Window', - submenu: [ - { - label: 'Minimize', - accelerator: 'Command+M', - role: 'minimize' - }, - { - label: 'Close', - accelerator: 'Command+W', - role: 'close' - }, - { - type: 'separator' - }, - { - label: 'Bring All to Front', - role: 'front' - } - ] - }, - { - label: 'Help', - submenu: [] - } -]; - -menu = Menu.buildFromTemplate(template); - -Menu.setApplicationMenu(menu); // Must be called within app.on('ready', function(){ ... }); -Menu.setApplicationMenu(null); - -Menu.buildFromTemplate([ - { label: '4', id: '4' }, - { label: '5', id: '5' }, - { label: '1', id: '1', position: 'before=4' }, - { label: '2', id: '2' }, - { label: '3', id: '3' } -]); - -Menu.buildFromTemplate([ - { label: 'a', position: 'endof=letters' }, - { label: '1', position: 'endof=numbers' }, - { label: 'b', position: 'endof=letters' }, - { label: '2', position: 'endof=numbers' }, - { label: 'c', position: 'endof=letters' }, - { label: '3', position: 'endof=numbers' } -]); - -// net -// https://github.com/electron/electron/blob/master/docs/api/net.md - -app.on('ready', () => { - const request = net.request('https://github.com') - request.setHeader('Some-Custom-Header-Name', 'Some-Custom-Header-Value'); - let header = request.getHeader('Some-Custom-Header-Name'); - request.removeHeader('Some-Custom-Header-Name'); - request.on('response', (response) => { - console.log(`Status code: ${response.statusCode}`); - console.log(`Status message: ${response.statusMessage}`); - console.log(`Headers: ${JSON.stringify(response.headers)}`); - console.log(`Http version: ${response.httpVersion}`); - console.log(`Major Http version: ${response.httpVersionMajor}`); - console.log(`Minor Http version: ${response.httpVersionMinor}`); - response.on('data', (chunk) => { - console.log(`BODY: ${chunk}`); - }) - response.on('end', () => { - console.log('No more data in response.'); - }) - response.on('error', () => { - console.log('"error" event emitted'); - }); - response.on('aborted', () => { - console.log('"aborted" event emitted'); - }); - }) - request.on('login', (authInfo, callback) => { - callback('username', 'password'); - }); - request.on('finish', () => { - console.log('"finish" event emitted'); - }); - request.on('abort', () => { - console.log('"abort" event emitted'); - }); - request.on('error', () => { - console.log('"error" event emitted'); - }); - request.write('Hello World!', 'utf-8', () => { }); - request.end('Hello World!', 'utf-8', () => { }); - request.abort(); -}) - -// power-monitor -// https://github.com/atom/electron/blob/master/docs/api/power-monitor.md - -app.on('ready', () => { - powerMonitor.on('suspend', () => { - console.log('The system is going to sleep'); - }); - powerMonitor.on('resume', () => { - console.log('The system has resumed from sleep'); - }); - powerMonitor.on('on-ac', () => { - console.log('The system changed to AC power') - }); - powerMonitor.on('on-battery', () => { - console.log('The system changed to battery power'); - }); -}); - -// power-save-blocker -// https://github.com/atom/electron/blob/master/docs/api/power-save-blocker.md - -var id = powerSaveBlocker.start('prevent-display-sleep'); -console.log(powerSaveBlocker.isStarted(id)); - -powerSaveBlocker.stop(id); - -// protocol -// https://github.com/atom/electron/blob/master/docs/api/protocol.md - -app.on('ready', () => { - protocol.registerStandardSchemes(['https']); - protocol.registerServiceWorkerSchemes(['https']); - - protocol.registerFileProtocol('atom', (request, callback) => { - callback(`${__dirname}/${request.url}`); - }); - - protocol.registerBufferProtocol('atom', (request, callback) => { - callback({mimeType: 'text/html', data: new Buffer('
Response
')}); - }); - - protocol.registerStringProtocol('atom', (request, callback) => { - callback('Hello World!'); - }); - - protocol.registerHttpProtocol('atom', (request, callback) => { - callback({url: request.url, method: request.method}); - }); - - protocol.unregisterProtocol('atom', (error) => { - console.log(error ? error.message : 'ok'); - }); - - protocol.isProtocolHandled('atom', (handled) => { - console.log(handled); - }); -}); - -// tray -// https://github.com/atom/electron/blob/master/docs/api/tray.md - -var appIcon: Electron.Tray = null; -app.on('ready', () => { - appIcon = new Tray('/path/to/my/icon'); - var contextMenu = Menu.buildFromTemplate([ - { label: 'Item1', type: 'radio' }, - { label: 'Item2', type: 'radio' }, - { label: 'Item3', type: 'radio', checked: true }, - { label: 'Item4', type: 'radio' }, - ]); - appIcon.setToolTip('This is my application.'); - appIcon.setContextMenu(contextMenu); - appIcon.setImage('/path/to/new/icon'); - appIcon.popUpContextMenu(contextMenu, {x: 100, y: 100}); - - appIcon.on('click', (event, bounds) => { - console.log('click', event, bounds); - }); - - appIcon.on('ballon-show', () => { - console.log('ballon-show'); - }); - - appIcon.displayBalloon({ - title: 'Hello World!' - }); -}); - -// clipboard -// https://github.com/atom/electron/blob/master/docs/api/clipboard.md - -{ - let str: string; - clipboard.writeText('Example String'); - clipboard.writeText('Example String', 'selection'); - clipboard.writeBookmark('foo', 'http://example.com'); - clipboard.writeBookmark('foo', 'http://example.com', 'selection'); - clipboard.writeFindText('foo'); - str = clipboard.readText('selection'); - str = clipboard.readFindText(); - console.log(clipboard.availableFormats()); - console.log(clipboard.readBookmark().title); - clipboard.clear(); - - clipboard.write({ - html: '', - text: 'Hello World!', - image: clipboard.readImage() - }); -} - -// crash-reporter -// https://github.com/atom/electron/blob/master/docs/api/crash-reporter.md - -crashReporter.start({ - productName: 'YourName', - companyName: 'YourCompany', - submitURL: 'https://your-domain.com/url-to-submit', - autoSubmit: true, - extra: { - someKey: "value" - } -}); - -console.log(crashReporter.getLastCrashReport()); -console.log(crashReporter.getUploadedReports()); - -// nativeImage -// https://github.com/atom/electron/blob/master/docs/api/native-image.md - -var appIcon2 = new Tray('/Users/somebody/images/icon.png'); -var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); -var image = clipboard.readImage(); -var appIcon3 = new Tray(image); -var appIcon4 = new Tray('/Users/somebody/images/icon.png'); - -let image2 = nativeImage.createFromPath('/Users/somebody/images/icon.png'); - -// process -// https://github.com/electron/electron/blob/master/docs/api/process.md - -console.log(process.versions.electron); -console.log(process.versions.chrome); -console.log(process.type); -console.log(process.resourcesPath); -console.log(process.mas); -console.log(process.windowsStore); -process.noAsar = true; -process.crash(); -process.hang(); -process.setFdLimit(8192); - -// screen -// https://github.com/atom/electron/blob/master/docs/api/screen.md - -app.on('ready', () => { - var size = screen.getPrimaryDisplay().workAreaSize; - mainWindow = new BrowserWindow({ width: size.width, height: size.height }); -}); - -app.on('ready', () => { - var displays = screen.getAllDisplays(); - var externalDisplay: any = null; - for (var i in displays) { - if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) { - externalDisplay = displays[i]; - break; - } - } - - if (externalDisplay) { - mainWindow = new BrowserWindow({ - x: externalDisplay.bounds.x + 50, - y: externalDisplay.bounds.y + 50, - }); - } - - screen.on('display-added', (event, display) => { - console.log('display-added', display); - }); - - screen.on('display-removed', (event, display) => { - console.log('display-removed', display); - }); - - screen.on('display-metrics-changed', (event, display, changes) => { - console.log('display-metrics-changed', display, changes); - }); -}); - -// shell -// https://github.com/atom/electron/blob/master/docs/api/shell.md - -shell.showItemInFolder('/home/user/Desktop/test.txt'); -shell.openItem('/home/user/Desktop/test.txt'); -shell.moveItemToTrash('/home/user/Desktop/test.txt'); - -shell.openExternal('https://github.com', { - activate: false -}); - -shell.beep(); - -shell.writeShortcutLink('/home/user/Desktop/shortcut.lnk', 'update', shell.readShortcutLink('/home/user/Desktop/shortcut.lnk')); - -// session -// https://github.com/atom/electron/blob/master/docs/api/session.md - -session.defaultSession.on('will-download', (event, item, webContents) => { - event.preventDefault(); - require('request')(item.getURL(), (data: any) => { - require('fs').writeFileSync('/somewhere', data); - }); -}); - -// Query all cookies. -session.defaultSession.cookies.get({}, (error, cookies) => { - console.log(cookies); -}); - -// Query all cookies associated with a specific url. -session.defaultSession.cookies.get({ url : "http://www.github.com" }, (error, cookies) => { - console.log(cookies); -}); - -// Set a cookie with the given cookie data; -// may overwrite equivalent cookies if they exist. -var cookie = { url : "http://www.github.com", name : "dummy_name", value : "dummy" }; -session.defaultSession.cookies.set(cookie, (error) => { - if (error) { - console.error(error); - } -}); - -// In the main process. -session.defaultSession.on('will-download', (event, item, webContents) => { - // Set the save path, making Electron not to prompt a save dialog. - item.setSavePath('/tmp/save.pdf'); - console.log(item.getSavePath()); - console.log(item.getMimeType()); - console.log(item.getFilename()); - console.log(item.getTotalBytes()); - - item.on('updated', (event, state) => { - if (state === 'interrupted') { - console.log('Download is interrupted but can be resumed'); - } else if (state === 'progressing') { - if (item.isPaused()) { - console.log('Download is paused'); - } else { - console.log(`Received bytes: ${item.getReceivedBytes()}`); - } - } - }); - - item.on('done', function(e, state) { - if (state == "completed") { - console.log("Download successfully"); - } else { - console.log(`Download failed: ${state}`) - } - }); -}); - -// To emulate a GPRS connection with 50kbps throughput and 500 ms latency. -session.defaultSession.enableNetworkEmulation({ - latency: 500, - downloadThroughput: 6400, - uploadThroughput: 6400 -}); - -// To emulate a network outage. -session.defaultSession.enableNetworkEmulation({ - offline: true -}); - -session.defaultSession.setCertificateVerifyProc((hostname, cert, callback) => { - callback((hostname === 'github.com') ? true : false); - console.log(cert.issuer.commonName); -}); - -session.defaultSession.setPermissionRequestHandler(function(webContents, permission, callback) { - if (webContents.getURL() === 'github.com') { - if (permission == "notifications") { - callback(false); - return; - } - } - - callback(true); -}); - -// consider any url ending with `example.com`, `foobar.com`, `baz` -// for integrated authentication. -session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') - -// consider all urls for integrated authentication. -session.defaultSession.allowNTLMCredentialsForDomains('*') - -// Modify the user agent for all requests to the following urls. -var filter = { - urls: ["https://*.github.com/*", "*://electron.github.io"] -}; - -session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, callback) { - details.requestHeaders['User-Agent'] = "MyAgent"; - callback({cancel: false, requestHeaders: details.requestHeaders}); -}); - -app.on('ready', function () { - const protocol = session.defaultSession.protocol - protocol.registerFileProtocol('atom', function (request, callback) { - var url = request.url.substr(7); - callback({path: path.normalize(__dirname + '/' + url)}); - }, function (error) { - if (error) { - console.error('Failed to register protocol'); - } - }) -}); - -// webContents -// https://github.com/electron/electron/blob/master/docs/api/web-contents.md - -console.log(webContents.getAllWebContents()); -console.log(webContents.getFocusedWebContents()); - -var win = new BrowserWindow({ - webPreferences: { - offscreen: true - } -}); - -win.webContents.on('paint', (event, dirty, image) => { - console.log(dirty, image.getBitmap()); -}); - -win.loadURL('http://github.com'); diff --git a/types/electron/test/renderer.ts b/types/electron/test/renderer.ts deleted file mode 100644 index 9779765e6f..0000000000 --- a/types/electron/test/renderer.ts +++ /dev/null @@ -1,311 +0,0 @@ - -import { - ipcRenderer, - remote, - webFrame, - clipboard, - crashReporter, - nativeImage, - screen, - shell -} from 'electron'; - -import * as fs from 'fs'; - -// In renderer process (web page). -// https://github.com/atom/electron/blob/master/docs/api/ipc-renderer.md -console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong" - -ipcRenderer.on('asynchronous-reply', (event: Electron.IpcRendererEvent, arg: any) => { - console.log(arg); // prints "pong" - event.sender.send('another-message', 'Hello World!'); -}); - -ipcRenderer.send('asynchronous-message', 'ping'); - -// remote -// https://github.com/atom/electron/blob/master/docs/api/remote.md - -var BrowserWindow = remote.BrowserWindow; -var win = new BrowserWindow({ width: 800, height: 600 }); -win.loadURL('https://github.com'); - -remote.getCurrentWindow().on('close', () => { - // blabla... -}); - -remote.getCurrentWindow().capturePage(buf => { - fs.writeFile('/tmp/screenshot.png', buf, err => { - console.log(err); - }); -}); - -remote.getCurrentWebContents().print(); - -remote.getCurrentWindow().capturePage(buf => { - remote.require('fs').writeFile('/tmp/screenshot.png', buf, (err: Error) => { - console.log(err); - }); -}); - -// web-frame -// https://github.com/atom/electron/blob/master/docs/api/web-frame.md - -webFrame.setZoomFactor(2); -console.log(webFrame.getZoomFactor()); - -webFrame.setZoomLevel(200); -console.log(webFrame.getZoomLevel()); - -webFrame.setVisualZoomLevelLimits(50, 200); -webFrame.setLayoutZoomLevelLimits(50, 200); - -webFrame.setSpellCheckProvider('en-US', true, { - spellCheck: text => { - return !(require('spellchecker').isMisspelled(text)); - } -}); - -webFrame.registerURLSchemeAsSecure('app'); -webFrame.registerURLSchemeAsBypassingCSP('app'); -webFrame.registerURLSchemeAsPrivileged('app'); -webFrame.registerURLSchemeAsPrivileged('app', { - secure: true, - supportFetchAPI: true, -}); - -webFrame.insertText('text'); - -webFrame.executeJavaScript('JSON.stringify({})', false, (result) => { - console.log(result); -}).then((result: string) => console.log('OK:' + result)); - -console.log(webFrame.getResourceUsage()); -webFrame.clearCache(); - -// clipboard -// https://github.com/atom/electron/blob/master/docs/api/clipboard.md - -clipboard.writeText('Example String'); -clipboard.writeText('Example String', 'selection'); -console.log(clipboard.readText('selection')); -console.log(clipboard.availableFormats()); -clipboard.clear(); - -clipboard.write({ - html: '', - text: 'Hello World!', - bookmark: "Bookmark name", - image: clipboard.readImage() -}); - -// crash-reporter -// https://github.com/atom/electron/blob/master/docs/api/crash-reporter.md - -crashReporter.start({ - productName: 'YourName', - companyName: 'YourCompany', - submitURL: 'https://your-domain.com/url-to-submit', - autoSubmit: true -}); - -// desktopCapturer -// https://github.com/atom/electron/blob/master/docs/api/desktop-capturer.md - -var desktopCapturer = require('electron').desktopCapturer; - -desktopCapturer.getSources({types: ['window', 'screen']}, function(error, sources) { - if (error) throw error; - for (var i = 0; i < sources.length; ++i) { - if (sources[i].name == "Electron") { - (navigator as any).webkitGetUserMedia({ - audio: false, - video: { - mandatory: { - chromeMediaSource: 'desktop', - chromeMediaSourceId: sources[i].id, - minWidth: 1280, - maxWidth: 1280, - minHeight: 720, - maxHeight: 720 - } - } - }, gotStream, getUserMediaError); - return; - } - } -}); - -function gotStream(stream: any) { - (document.querySelector('video') as HTMLVideoElement).src = URL.createObjectURL(stream); -} - -function getUserMediaError(error: Error) { - console.log('getUserMediaError', error); -} - -// File object -// https://github.com/atom/electron/blob/master/docs/api/file-object.md - -/* -
- Drag your file here -
-*/ - -var holder = document.getElementById('holder'); - -holder.ondragover = function () { - return false; -}; - -holder.ondragleave = holder.ondragend = function () { - return false; -}; - -holder.ondrop = function (e) { - e.preventDefault(); - var file = e.dataTransfer.files[0]; - console.log('File you dragged here is', file.path); - return false; -}; - -// nativeImage -// https://github.com/atom/electron/blob/master/docs/api/native-image.md - -var Tray = remote.Tray; -var appIcon2 = new Tray('/Users/somebody/images/icon.png'); -var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); -var image = clipboard.readImage(); -var appIcon3 = new Tray(image); -var appIcon4 = new Tray('/Users/somebody/images/icon.png'); - -// https://github.com/electron/electron/blob/master/docs/api/process.md - -// preload.js -var _setImmediate = setImmediate; -var _clearImmediate = clearImmediate; -process.once('loaded', function() { - global.setImmediate = _setImmediate; - global.clearImmediate = _clearImmediate; -}); - -// screen -// https://github.com/atom/electron/blob/master/docs/api/screen.md - -var app = remote.app; - -var mainWindow: Electron.BrowserWindow = null; - -app.on('ready', () => { - var size = screen.getPrimaryDisplay().workAreaSize; - mainWindow = new BrowserWindow({ width: size.width, height: size.height }); -}); - -app.on('ready', () => { - var displays = screen.getAllDisplays(); - var externalDisplay: any = null; - for (var i in displays) { - if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) { - externalDisplay = displays[i]; - break; - } - } - - if (externalDisplay) { - mainWindow = new BrowserWindow({ - x: externalDisplay.bounds.x + 50, - y: externalDisplay.bounds.y + 50, - }); - } -}); - -// shell -// https://github.com/atom/electron/blob/master/docs/api/shell.md - -shell.openExternal('https://github.com'); - -// -// https://github.com/atom/electron/blob/master/docs/api/web-view-tag.md - -var webview = document.createElement('webview'); -webview.loadURL('https://github.com'); - -webview.addEventListener('console-message', function(e) { - console.log('Guest page logged a message:', e.message); -}); - -webview.addEventListener('found-in-page', function(e) { - if (e.result.finalUpdate) { - webview.stopFindInPage("keepSelection"); - } -}); - -var requestId = webview.findInPage("test"); - -webview.addEventListener('new-window', function(e) { - require('electron').shell.openExternal(e.url); -}); - -webview.addEventListener('close', function() { - webview.src = 'about:blank'; -}); - -// In embedder page. -webview.addEventListener('ipc-message', function(event) { - console.log(event.channel); // Prints "pong" -}); -webview.send('ping'); -webview.capturePage((image) => { console.log(image); }); - -{ - const opened: boolean = webview.isDevToolsOpened(); - const focused: boolean = webview.isDevToolsFocused(); - const focused2: boolean = webview.getWebContents().isFocused(); -} - -// In guest page. -ipcRenderer.on('ping', function() { - ipcRenderer.sendToHost('pong'); -}); - - -// showOpenDialog -// https://electron.atom.io/docs/api/dialog/#dialogshowopendialogbrowserwindow-options-callback - -remote.dialog.showOpenDialog({ title: 'foo' }); -remote.dialog.showOpenDialog(win, {}, fileNames => fileNames); -remote.dialog.showOpenDialog(win, { - title: 'foo', - defaultPath: '/bar', - buttonLabel: 'foo bar', - filters: [ - {name: 'Images', extensions: ['jpg', 'png', 'gif']}, - {name: 'Movies', extensions: ['mkv', 'avi', 'mp4']}, - {name: 'Custom File Type', extensions: ['as']}, - {name: 'All Files', extensions: ['*']} - ], - properties: ['openFile', 'openDirectory', 'multiSelections', 'showHiddenFiles', 'createDirectory', 'promptToCreate', 'noResolveAliases'], - normalizeAccessKeys: true, - message: 'foo message', -}); - -// showSaveDialog -// https://electron.atom.io/docs/api/dialog/#dialogshowsavedialogbrowserwindow-options-callback - -remote.dialog.showSaveDialog({ title: 'foo' }); -remote.dialog.showSaveDialog(win, {}, fileNames => fileNames); -remote.dialog.showSaveDialog(win, { - title: 'foo', - defaultPath: '/bar', - buttonLabel: 'foo bar', - filters: [ - {name: 'Images', extensions: ['jpg', 'png', 'gif']}, - {name: 'Movies', extensions: ['mkv', 'avi', 'mp4']}, - {name: 'Custom File Type', extensions: ['as']}, - {name: 'All Files', extensions: ['*']} - ], - message: 'foo message', - nameFieldLabel: 'foo name', - showsTagField: true -}); diff --git a/types/electron/tsconfig.json b/types/electron/tsconfig.json deleted file mode 100644 index bf2299ea31..0000000000 --- a/types/electron/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "test/index.ts", - "test/main.ts", - "test/renderer.ts" - ] -} \ No newline at end of file From dba4a0f69f771621ac0349bb37765b7b91c63003 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 09:10:20 -0700 Subject: [PATCH 57/98] material-ui: Fix error in typescript@next (#17054) --- types/material-ui/material-ui-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/material-ui/material-ui-tests.tsx b/types/material-ui/material-ui-tests.tsx index 77a0445fb2..9a0eddd0b9 100644 --- a/types/material-ui/material-ui-tests.tsx +++ b/types/material-ui/material-ui-tests.tsx @@ -319,8 +319,8 @@ class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}, {}> { } } - -const MuiThemeableFunction = muiThemeable()((props: {label: string, muiTheme?: MuiTheme}) => { +type Props = { label: string, muiTheme?: MuiTheme }; +const MuiThemeableFunction = muiThemeable(), Props>(props => { return ( Applied the Theme to functional component: {props.label}. From 248eba251a06d3a635ef46ae59253c306c3399b1 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 09:19:48 -0700 Subject: [PATCH 58/98] parse: Fix error in typescript@next (#17057) --- types/parse/parse-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index 79d583f3be..282913d17e 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -198,7 +198,7 @@ function test_file() { // The file either could n ot be read, or could not be saved to Parse. }); - Parse.Cloud.httpRequest({ url: file.url() }).then((response: Parse.Promise) => { + Parse.Cloud.httpRequest({ url: file.url() }).then((response: Parse.Cloud.HttpResponse) => { // result }); From 3aaf7db373afa972cebab532dc6443c657dec28f Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 09:43:41 -0700 Subject: [PATCH 59/98] verror: Fix lint (#17064) --- types/verror/verror-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/verror/verror-tests.ts b/types/verror/verror-tests.ts index c3b560bfb2..17f7fe1bd7 100644 --- a/types/verror/verror-tests.ts +++ b/types/verror/verror-tests.ts @@ -12,7 +12,7 @@ const verror3 = new VError({ name: "fooError", cause: error, info: { - "info0": "baz" + info0: "baz" } }, "bar"); From dc27c3788c00d279ae5ff61e8e2dfd568aae5e8e Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 12:27:20 -0700 Subject: [PATCH 60/98] d3-zoom: Add needed type arguments (#17053) --- types/d3-zoom/d3-zoom-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index de213d5149..185b9fd45a 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -104,7 +104,7 @@ function zoomedCanvas(this: HTMLCanvasElement, d: CanvasDatum) { let canvasZoom: d3Zoom.ZoomBehavior; -canvasZoom = d3Zoom.zoom() +canvasZoom = d3Zoom.zoom() .scaleExtent([1 / 2, 4]) .on('zoom', zoomedCanvas); From f342368cd4daf837e26571b2f2b9049c1859fe9c Mon Sep 17 00:00:00 2001 From: Jeremi Stadler Date: Thu, 8 Jun 2017 22:24:16 +0200 Subject: [PATCH 61/98] [React-Native] Add dark-content as statusbar option https://facebook.github.io/react-native/docs/statusbar.html#statusbarstyle --- types/react-native/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 22930ea00c..01942e2267 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -7273,9 +7273,9 @@ export interface SettingsStatic { /** - * @enum('default', 'light-content') + * @enum('default', 'light-content', 'dark-content') */ -export type StatusBarStyle = "default" | "light-content" +export type StatusBarStyle = "default" | "light-content" | "dark-content" /** * @enum('fade', 'slide') From 9e9bee141249c1b0430f94d5d1e79cbbf0dc4273 Mon Sep 17 00:00:00 2001 From: Eli Young Date: Thu, 8 Jun 2017 14:33:19 -0700 Subject: [PATCH 62/98] [convict] Fix header (#17046) The DefinitelyTyped header needs to have the name of the library as it is published on npm and must not have a patch number in the version. --- types/convict/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/convict/index.d.ts b/types/convict/index.d.ts index 395d540875..82b22ba2db 100644 --- a/types/convict/index.d.ts +++ b/types/convict/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-convict v3.0.0 +// Type definitions for convict 3.0 // Project: https://github.com/mozilla/node-convict // Definitions by: Wim Looman , Vesa Poikajärvi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 0c42afa21ab4549367f07f18d8d0c0c22a7498df Mon Sep 17 00:00:00 2001 From: StefanSchoof Date: Thu, 8 Jun 2017 23:35:02 +0200 Subject: [PATCH 63/98] [SharePoint] Add _spFriendlyUrlPageContextInfo (#17052) --- types/sharepoint/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/sharepoint/index.d.ts b/types/sharepoint/index.d.ts index 3520e12f06..b4e4e4cb9d 100644 --- a/types/sharepoint/index.d.ts +++ b/types/sharepoint/index.d.ts @@ -179,6 +179,13 @@ declare class _spPageContextInfo { static webUIVersion: number; // 15 } +declare class _spFriendlyUrlPageContextInfo { + static termId: string; + static termSetId: string; + static termStoreId: string; + static title: string; +} + declare function STSHtmlEncode(value: string): string; declare function STSHtmlDecode(value: string): string; From 47e7bba277f09ce790de00c4db44f24e74b01376 Mon Sep 17 00:00:00 2001 From: Simon Pfeifer Date: Thu, 8 Jun 2017 23:46:23 +0200 Subject: [PATCH 64/98] Chartist: added candle stick chart support (#16745) * Chartist: added candle stick chart support to. This PR is depending on: https://github.com/gionkunz/chartist-js/pull/956 * Increased type definition version for Chartist from v0.9.5 to v0.9.6 --- types/chartist/chartist-tests.ts | 26 +++++++ types/chartist/index.d.ts | 127 ++++++++++++++++++++++++++++++- 2 files changed, 151 insertions(+), 2 deletions(-) diff --git a/types/chartist/chartist-tests.ts b/types/chartist/chartist-tests.ts index 2a4a362e7e..13a7c7dd1c 100644 --- a/types/chartist/chartist-tests.ts +++ b/types/chartist/chartist-tests.ts @@ -401,3 +401,29 @@ var overlappingBarsResponsiveOptions: Array +// Definitions by: Matt Gibbs , Simon Pfeifer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Chartist { @@ -20,6 +20,7 @@ declare namespace Chartist { Pie: IChartistPieChart; Bar: IChartistBarChart; Line: IChartistLineChart; + Candle: IChartistCandleChart; FixedScaleAxis: IFixedScaleAxisStatic; AutoScaleAxis: IAutoScaleAxisStatic; @@ -138,6 +139,10 @@ declare namespace Chartist { new (target: any, data: IChartistData, options?: IBarChartOptions, responsiveOptions?: Array>): IChartistBarChart; } + interface IChartistCandleChart extends IChartistBase { + new (target: any, data: IChartistData, options?: ICandleChartOptions, responsiveOptions?: Array>): IChartistCandleChart; + } + interface IChartOptions { /** * If true the whole data is reversed including labels, the series order as well as the whole series data arrays. @@ -352,6 +357,124 @@ declare namespace Chartist { end?: string; } + interface ICandleChartOptions extends IChartOptions { + + /** + * Options for X-Axis + */ + axisX?: ICandleChartAxis; + + /** + * Options for Y-Axis + */ + axisY?: ICandleChartAxis; + + /** + * Specify a fixed width for the chart as a string (i.e. '100px' or '50%') + */ + width?: number | string; + + /** + * Specify a fixed height for the chart as a string (i.e. '100px' or '50%') + */ + height?: number | string; + + /** + * Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value + */ + hight?: number | string; + + /** + * Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value + */ + low?: number | string; + + /** + * Width of candle body in pixel (IMO is 2 px best minimum value) + */ + candleWidth?: number | string; + + /** + * Width of candle wick in pixel (IMO is 1 px best minimum value) + */ + candleWickWidth?: number | string; + + /** + * Use calculated x-axis step length, depending on the number of quotes to display, as candle width. Otherwise the candleWidth is being used. + */ + useStepLengthAsCandleWidth?: boolean | string; + + /** + * Use 1/3 of candle body width as width for the candle wick, otherwise the candleWickWidth is being used. + */ + useOneThirdAsCandleWickWidth?: boolean | string; + + /** + * Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5} + */ + chartPadding?: IChartPadding | number; + + /** + * When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler. + */ + fullWidth?: boolean | string; + + /** + * Override the class names that get used to generate the SVG structure of the chart + */ + classNames?: ICandleChartClasses; + } + + interface ICandleChartAxis { + /** + * The offset of the chart drawing area to the border of the container + */ + offset?: number; + /** + * Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis. + */ + position?: string; + /** + * Allows you to correct label positioning on this axis by positive or negative x and y offset. + */ + labelOffset?: { + x?: number; + y?: number; + }; + /** + * If labels should be shown or not + */ + showLabel?: boolean; + /** + * If the axis grid should be drawn or not + */ + showGrid?: boolean; + /** + * Interpolation function that allows you to intercept the value from the axis label + */ + labelInterpolationFnc?: Function; + /** + * Set the axis type to be used to project values on this axis. If not defined, Chartist.StepAxis will be used for the X-Axis, where the ticks option will be set to the labels in the data and the stretch option will be set to the global fullWidth option. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here. + */ + type?: any; + } + + interface ICandleChartClasses { + chart?: string; + label?: string; + labelGroup?: string; + series?: string; + candlePositive?: string; + candleNegative?: string, + grid?: string, + gridGroup?: string, + gridBackground?: string, + vertical?: string, + horizontal?: string, + start?: string, + end?: string, + } + interface ChartistSvgStatic { new (name: HTMLElement | string, attributes: Object, className?: string, parent?: Object, insertFirst?: boolean): IChartistSvg; From 5a7ad344d10e8fdc8fa9dcb7ef2c873e3e966e20 Mon Sep 17 00:00:00 2001 From: Anton Cholakov Date: Fri, 9 Jun 2017 00:50:41 +0300 Subject: [PATCH 65/98] Add confirm property in PNotifyOptions (#17043) Use PNotifyconfirm interface as a type for confirm property in the PNotifyOptions --- types/jquery.pnotify/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/jquery.pnotify/index.d.ts b/types/jquery.pnotify/index.d.ts index 1d222efb26..3355f889ce 100644 --- a/types/jquery.pnotify/index.d.ts +++ b/types/jquery.pnotify/index.d.ts @@ -133,6 +133,10 @@ interface PNotifyOptions { * Whether to escape the content of the text. (Not allow HTML.) */ text_escape?: boolean; + /** + * Support for PNotifyconfirm options + */ + confirm?: PNotifyconfirm /** * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", "fontawesome" or a custom style object) */ From 380c910b7470dc2fa0db17693cf18b94620f18c5 Mon Sep 17 00:00:00 2001 From: Eli Young Date: Thu, 8 Jun 2017 15:08:09 -0700 Subject: [PATCH 66/98] [bunyan] Fix automatic publishing (#17045) The DefinitelyTyped header needs to have the name of the library as it is published on npm. --- types/bunyan/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/bunyan/index.d.ts b/types/bunyan/index.d.ts index d46396023f..bc1dca298d 100644 --- a/types/bunyan/index.d.ts +++ b/types/bunyan/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-bunyan 1.8 +// Type definitions for bunyan 1.8 // Project: https://github.com/trentm/node-bunyan // Definitions by: Alex Mikhalev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 96d2d239f83f962da5144de776ec527352ba41ea Mon Sep 17 00:00:00 2001 From: Mads Madsen Date: Fri, 9 Jun 2017 00:08:28 +0200 Subject: [PATCH 67/98] Updated jwt-decode definitions to v2.2.0 (#17049) --- types/jwt-decode/index.d.ts | 6 +++--- types/jwt-decode/jwt-decode-tests.ts | 8 +++++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/types/jwt-decode/index.d.ts b/types/jwt-decode/index.d.ts index 5cf3772b68..d27cdf91e9 100644 --- a/types/jwt-decode/index.d.ts +++ b/types/jwt-decode/index.d.ts @@ -1,12 +1,12 @@ -// Type definitions for jwt-decode v1.4.0 +// Type definitions for jwt-decode v2.2.0 // Project: https://github.com/auth0/jwt-decode -// Definitions by: Giedrius Grabauskas +// Definitions by: Giedrius Grabauskas , Mads Madsen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace JwtDecode { interface JwtDecodeStatic { - (token: string): any; + (token: string, options?: { header: boolean }): any; } } diff --git a/types/jwt-decode/jwt-decode-tests.ts b/types/jwt-decode/jwt-decode-tests.ts index 4ec792fde1..7e65c2a5a4 100644 --- a/types/jwt-decode/jwt-decode-tests.ts +++ b/types/jwt-decode/jwt-decode-tests.ts @@ -9,4 +9,10 @@ interface TokenDto { iat: number; } -let decodedToken = jwtDecode(token) as TokenDto; +interface TokenHeaderDto { + typ: string; + alg: string; +} + +let decodedTokenPayload = jwtDecode(token) as TokenDto; +let decodedTokenHeader = jwtDecode(token, { header: true }) as TokenHeaderDto; \ No newline at end of file From b3dc832da43f1ea3362edfe2b78bf058c995dc89 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:10:18 -0700 Subject: [PATCH 68/98] multiplexjs: Fix error in typescript@next (#17055) --- types/multiplexjs/index.d.ts | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/types/multiplexjs/index.d.ts b/types/multiplexjs/index.d.ts index eddd801609..0cc38c8c06 100644 --- a/types/multiplexjs/index.d.ts +++ b/types/multiplexjs/index.d.ts @@ -448,9 +448,9 @@ declare namespace multiplex { /** * Performs the specified action on each element of the List. - * @param action The action function to perform on each element of the List. + * @param action The action function to perform on each element of an List; the second parameter of the function represents the index of the source element. */ - forEach(action: (item: T) => void): void + forEach(action: (item: T, index: number) => void): void /** @@ -1741,14 +1741,6 @@ declare namespace multiplex { */ firstOrDefault(predicate: (item: T) => boolean, defaultValue: T): T - - /** - * Performs the specified action on each element of an Enumerable. - * @param action The action function to perform on each element of an Enumerable. - */ - forEach(action: (item: T) => void): void - - /** * Performs the specified action on each element of an Enumerable. * @param action The action function to perform on each element of an Enumerable; the second parameter of the function represents the index of the source element. From 261cdecc96aea45d6eba9d0c5d42f317ee1d5d6e Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:10:37 -0700 Subject: [PATCH 69/98] observe-js: Fix type of ArrayObserver_instance (#17056) --- types/observe-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/observe-js/index.d.ts b/types/observe-js/index.d.ts index 4b668bec16..d3321c9a8c 100644 --- a/types/observe-js/index.d.ts +++ b/types/observe-js/index.d.ts @@ -102,7 +102,7 @@ declare namespace observejs { } interface ArrayObserver_instance extends Observable { - open(onChange:(splices:Array)=>any):void + open(onChange: (splices: Array, oldSplices: Array) => any): void } /** From 2baab8780cd73ec5f57dcb8ac53d07be439154d2 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:10:57 -0700 Subject: [PATCH 70/98] passport-local-mongoose: Fix error in typescript@next (#17058) --- .../passport-local-mongoose/passport-local-mongoose-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/passport-local-mongoose/passport-local-mongoose-tests.ts b/types/passport-local-mongoose/passport-local-mongoose-tests.ts index 7b428561fe..63c82a9913 100644 --- a/types/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/types/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -31,13 +31,13 @@ interface User extends PassportLocalDocument { last: Date; } -const UserSchema: PassportLocalSchema = new Schema({ +const UserSchema = new Schema({ username: String, hash: String, salt: String, attempts: Number, last: Date -}); +}) as PassportLocalSchema; let options: PassportLocalOptions = {}; options.iterations = 25000; From e8aac973ef3e774c3fd9c0c425525e58848a61fa Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:13:10 -0700 Subject: [PATCH 71/98] quill: Fix error in typescript@next (#17060) --- types/quill/quill-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/quill/quill-tests.ts b/types/quill/quill-tests.ts index b16c90b384..eba77f8b68 100644 --- a/types/quill/quill-tests.ts +++ b/types/quill/quill-tests.ts @@ -170,7 +170,7 @@ function test_addContainer() function test_on_EventType1(){ var quillEditor = new Quill('#editor'); - quillEditor.on('text-change', (newDelta, oldDelta, source)=>{ + quillEditor.on('text-change', (newDelta: T, oldDelta: T, source: string)=>{ // happened }); From 90ccae007e185274f5dae2e6863005ace1dc99af Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:13:41 -0700 Subject: [PATCH 72/98] restify: Fix error in typescript@next (#17061) --- types/restify/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index 5f7e0ccb21..a7781f933c 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -483,13 +483,14 @@ export interface Client { basicAuth(username: string, password: string): any; } -export interface HttpClient extends Client { +export interface HttpClient { get(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; head(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; post(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; put(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; patch(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; del(opts?: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request) => void): any; + basicAuth(username: string, password: string): any; } export interface ThrottleOptions { From cc464d95a45feb58f45fa683d4b9633b06f73e71 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:14:00 -0700 Subject: [PATCH 73/98] rx-*: Fix lint (#17062) --- types/rx-core-binding/index.d.ts | 2 +- types/rx-lite-aggregates/index.d.ts | 2 +- types/rx-lite-async/index.d.ts | 2 +- types/rx-lite-backpressure/index.d.ts | 2 +- types/rx-lite-coincidence/index.d.ts | 2 +- types/rx-lite-time/index.d.ts | 2 +- types/rx-lite-virtualtime/index.d.ts | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/types/rx-core-binding/index.d.ts b/types/rx-core-binding/index.d.ts index e8ba93bd3a..3b7cf59369 100644 --- a/types/rx-core-binding/index.d.ts +++ b/types/rx-core-binding/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { interface ISubject extends Observable, Observer, IDisposable { diff --git a/types/rx-lite-aggregates/index.d.ts b/types/rx-lite-aggregates/index.d.ts index 72c2ae402f..2b2ce8d6b7 100644 --- a/types/rx-lite-aggregates/index.d.ts +++ b/types/rx-lite-aggregates/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { interface Observable { diff --git a/types/rx-lite-async/index.d.ts b/types/rx-lite-async/index.d.ts index 94117a1562..8979b9dd36 100644 --- a/types/rx-lite-async/index.d.ts +++ b/types/rx-lite-async/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: zoetrope , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { interface ObservableStatic { diff --git a/types/rx-lite-backpressure/index.d.ts b/types/rx-lite-backpressure/index.d.ts index fa997f03c6..73e9f2e8d1 100644 --- a/types/rx-lite-backpressure/index.d.ts +++ b/types/rx-lite-backpressure/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { interface Observable { diff --git a/types/rx-lite-coincidence/index.d.ts b/types/rx-lite-coincidence/index.d.ts index 3682126071..7649b234be 100644 --- a/types/rx-lite-coincidence/index.d.ts +++ b/types/rx-lite-coincidence/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { interface Observable { diff --git a/types/rx-lite-time/index.d.ts b/types/rx-lite-time/index.d.ts index e5abaf3832..e1cf93dc07 100644 --- a/types/rx-lite-time/index.d.ts +++ b/types/rx-lite-time/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { interface Observable { diff --git a/types/rx-lite-virtualtime/index.d.ts b/types/rx-lite-virtualtime/index.d.ts index 7413ec2604..1ff855f532 100644 --- a/types/rx-lite-virtualtime/index.d.ts +++ b/types/rx-lite-virtualtime/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { interface VirtualTimeScheduler extends Scheduler { From a994ca3b6016a1a1212380b866412a21140f00df Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:14:24 -0700 Subject: [PATCH 74/98] stale-lru-cache: Fix error in typescript@next (#17063) --- types/stale-lru-cache/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/stale-lru-cache/index.d.ts b/types/stale-lru-cache/index.d.ts index f5ab3733b3..80be52905d 100644 --- a/types/stale-lru-cache/index.d.ts +++ b/types/stale-lru-cache/index.d.ts @@ -22,7 +22,7 @@ declare class Cache { } declare namespace Cache { - type OptionsCallback = (error: any, value: V, options?: string | SetOptions) => void; + type OptionsCallback = (error: any, value?: V, options?: string | SetOptions) => void; type RevalidationCallback = (key: K, callback: OptionsCallback) => void; interface CacheOptions { From b3212da01e75bd1604a1612e80320414d6bb4575 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:15:14 -0700 Subject: [PATCH 75/98] vinyl: Fix error in typescript@next (#17065) --- types/vinyl/v0/vinyl-tests.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/vinyl/v0/vinyl-tests.ts b/types/vinyl/v0/vinyl-tests.ts index 910b5b7bc7..e9017f7235 100644 --- a/types/vinyl/v0/vinyl-tests.ts +++ b/types/vinyl/v0/vinyl-tests.ts @@ -72,9 +72,9 @@ describe('File', () => { }); it('should set stat to given value', done => { - var val = {}; - var file = new File({stat: val}); - file.stat.should.equal(val); + var stat = {} as fs.Stats; + var file = new File({ stat }); + file.stat.should.equal(stat); done(); }); From be319089e5efbe5b2ddd526fe16cbf9558d85d38 Mon Sep 17 00:00:00 2001 From: Jean-Michel DECORET Date: Thu, 8 Jun 2017 22:18:37 +0000 Subject: [PATCH 76/98] Fix Materialize-css ScrollFireOptions (#17044) * Fix Materialize-css ScrollFireOptions The callback is either a strng, or a real typescript callback. * Add parens --- types/materialize-css/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index 12dbeb5aa0..2c43daf285 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -316,8 +316,9 @@ declare namespace Materialize { * The string function call that you want to make when the user scrolls to the threshold. * It will only be called once. * Example: 'console.log("hello, world!")'; + * or callback: () => { console.log('hello world'); } */ - callback?: string; + callback?: string | (() => void); } interface TabOptions { From 26ae3e5aae99621e16007809465ede468b1aa566 Mon Sep 17 00:00:00 2001 From: Joscha Feth Date: Fri, 9 Jun 2017 00:19:57 +0200 Subject: [PATCH 77/98] add jest-matchers (#17040) --- types/jest-matchers/index.d.ts | 7 +++++++ types/jest-matchers/jest-matchers-tests.ts | 3 +++ types/jest-matchers/tsconfig.json | 22 ++++++++++++++++++++++ types/jest-matchers/tslint.json | 1 + 4 files changed, 33 insertions(+) create mode 100644 types/jest-matchers/index.d.ts create mode 100644 types/jest-matchers/jest-matchers-tests.ts create mode 100644 types/jest-matchers/tsconfig.json create mode 100644 types/jest-matchers/tslint.json diff --git a/types/jest-matchers/index.d.ts b/types/jest-matchers/index.d.ts new file mode 100644 index 0000000000..27e6a5b9f0 --- /dev/null +++ b/types/jest-matchers/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for jest-matchers 20.0 +// Project: https://github.com/facebook/jest#readme +// Definitions by: Joscha Feth +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +export = expect; diff --git a/types/jest-matchers/jest-matchers-tests.ts b/types/jest-matchers/jest-matchers-tests.ts new file mode 100644 index 0000000000..7484dd5ed8 --- /dev/null +++ b/types/jest-matchers/jest-matchers-tests.ts @@ -0,0 +1,3 @@ +import * as expect from 'jest-matchers'; + +expect('x').toEqual('x'); diff --git a/types/jest-matchers/tsconfig.json b/types/jest-matchers/tsconfig.json new file mode 100644 index 0000000000..37a7e86d8d --- /dev/null +++ b/types/jest-matchers/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jest-matchers-tests.ts" + ] +} diff --git a/types/jest-matchers/tslint.json b/types/jest-matchers/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jest-matchers/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f91d29adad47ead7491da5c071d1635a3b5f670e Mon Sep 17 00:00:00 2001 From: Nick Schultz Date: Thu, 8 Jun 2017 18:27:57 -0400 Subject: [PATCH 78/98] sequelize: update BelongsToManyAssociationMixin to accept join table attributes (#17071) * update BelongsToManyAssociationMixin to accept join table attributes correctly * dont make a bunch of automatic editor changes --- types/sequelize/index.d.ts | 8 ++++---- types/sequelize/sequelize-tests.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 68c68a854f..70c637e25a 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -811,7 +811,7 @@ declare namespace sequelize { */ ( newAssociations?: Array, - options?: BelongsToManySetAssociationsMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | TJoinTableAttributes + options?: BelongsToManySetAssociationsMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } ): Promise; } @@ -860,7 +860,7 @@ declare namespace sequelize { */ ( newAssociations?: Array, - options?: BelongsToManyAddAssociationsMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | TJoinTableAttributes + options?: BelongsToManyAddAssociationsMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } ): Promise; } @@ -909,7 +909,7 @@ declare namespace sequelize { */ ( newAssociation?: TInstance | TInstancePrimaryKey, - options?: BelongsToManyAddAssociationMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | TJoinTableAttributes + options?: BelongsToManyAddAssociationMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } ): Promise; } @@ -952,7 +952,7 @@ declare namespace sequelize { */ ( values?: TAttributes, - options?: BelongsToManyCreateAssociationMixinOptions | CreateOptions | TJoinTableAttributes + options?: BelongsToManyCreateAssociationMixinOptions | CreateOptions | { through: TJoinTableAttributes } ): Promise; } diff --git a/types/sequelize/sequelize-tests.ts b/types/sequelize/sequelize-tests.ts index c5c494a454..d786dfc4a2 100644 --- a/types/sequelize/sequelize-tests.ts +++ b/types/sequelize/sequelize-tests.ts @@ -270,19 +270,19 @@ warehouse.getBranches({ where: {} }).then((branches) => branches[0].rank); warehouse.setBranches(); warehouse.setBranches([branch]); -warehouse.setBranches([branch, 2], { validate: true, distance: 1 }).then(() => { }); +warehouse.setBranches([branch, 2], { validate: true, through: { distance: 1 } }).then(() => { }); warehouse.addBranches(); warehouse.addBranches([branch]); -warehouse.addBranches([branch, 2], { validate: false, distance: 1 }).then(() => { }); +warehouse.addBranches([branch, 2], { validate: false, through: { distance: 1 } }).then(() => { }); warehouse.addBranch(); warehouse.addBranch(branch); -warehouse.addBranch(2, { validate: true, distance: 1 }).then(() => { }); +warehouse.addBranch(2, { validate: true, through: { distance: 1 } }).then(() => { }); warehouse.createBranch(); warehouse.createBranch({ id: 1, address: 'baz' }); -warehouse.createBranch({ id: 1 }, { silent: true, distance: 1 }).then((branch) => { }); +warehouse.createBranch({ id: 1 }, { silent: true, through: { distance: 1 } }).then((branch) => { }); warehouse.removeBranches(); warehouse.removeBranches([branch]); From ad756d05b3537420eac2e66baaec58fae27a0e31 Mon Sep 17 00:00:00 2001 From: Mike Woodward Date: Thu, 8 Jun 2017 17:30:24 -0500 Subject: [PATCH 79/98] className type support for Uncontrolled Dropdown (#17075) --- types/reactstrap/lib/Dropdown.d.ts | 2 +- types/reactstrap/reactstrap-tests.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/reactstrap/lib/Dropdown.d.ts b/types/reactstrap/lib/Dropdown.d.ts index 57e4532a31..c89150fd83 100644 --- a/types/reactstrap/lib/Dropdown.d.ts +++ b/types/reactstrap/lib/Dropdown.d.ts @@ -3,6 +3,7 @@ export interface UncontrolledProps { isOpen?: boolean; toggle?: () => void; + className?: string; } export interface Props extends UncontrolledProps { @@ -12,7 +13,6 @@ export interface Props extends UncontrolledProps { size?: string; tag?: React.ReactType; tether?: boolean | Tether.ITetherOptions; - className?: string; } declare var Dropdown: React.StatelessComponent; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index ba5f5e38e1..b69023e6c0 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -1051,7 +1051,7 @@ class Example43 extends React.Component { function Example44() { return ( - + Dropdown From 7019f85ea5b3d6d30cbeb3bf05babf612695790d Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 8 Jun 2017 15:46:15 -0700 Subject: [PATCH 80/98] webpack: Remove test that fails in typescript@next (#17066) --- types/webpack/webpack-tests.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/types/webpack/webpack-tests.ts b/types/webpack/webpack-tests.ts index 066bdfb740..6c7095483d 100644 --- a/types/webpack/webpack-tests.ts +++ b/types/webpack/webpack-tests.ts @@ -585,14 +585,6 @@ class TestResolvePlugin implements webpack.ResolvePlugin { } } -const resolve: webpack.Resolve = { - plugins: [ - new TestResolvePlugin() - ], - symlinks: false, - cachePredicate: 'boo' // why does this test _not_ fail!? -}; - const performance: webpack.Options.Performance = { hints: 'error', maxEntrypointSize: 400000, From eef8a774f54b920cf17216c72dd142d8db7bd7cd Mon Sep 17 00:00:00 2001 From: Yui Date: Thu, 8 Jun 2017 15:50:41 -0700 Subject: [PATCH 81/98] manually port fix from 16286 and address PR (#17003) --- types/reactstrap/lib/Row.d.ts | 4 ++-- types/reactstrap/reactstrap-tests.tsx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/reactstrap/lib/Row.d.ts b/types/reactstrap/lib/Row.d.ts index b318b6e6f5..61529c4a48 100644 --- a/types/reactstrap/lib/Row.d.ts +++ b/types/reactstrap/lib/Row.d.ts @@ -1,8 +1,8 @@ -interface Props { +interface Props extends React.HTMLProps< HTMLElement> { className?: string; tag?: React.ReactType; noGutters?: boolean; } -declare var Row: React.StatelessComponent>; +declare var Row: React.StatelessComponent; export default Row; \ No newline at end of file diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index b69023e6c0..331436760e 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -549,7 +549,7 @@ const Example26 = (props: any) => { const Example27 = (props: any) => { return ( - + Special Title Treatment From e8568770879dd7f8442331b969ae4892cb73c77d Mon Sep 17 00:00:00 2001 From: Kamil Szostak Date: Thu, 8 Jun 2017 15:51:32 -0700 Subject: [PATCH 82/98] Update application insights JS SDK types (#17076) --- .../applicationinsights-js-tests.ts | 13 ++++++++++++- types/applicationinsights-js/index.d.ts | 4 +++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/types/applicationinsights-js/applicationinsights-js-tests.ts b/types/applicationinsights-js/applicationinsights-js-tests.ts index 8967356426..ecefb6d41a 100644 --- a/types/applicationinsights-js/applicationinsights-js-tests.ts +++ b/types/applicationinsights-js/applicationinsights-js-tests.ts @@ -118,7 +118,18 @@ const envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(dat context.track(envelope); -context.addTelemetryInitializer(telemetryEnvelope => false); +context.addTelemetryInitializer(envelope => false); +context.addTelemetryInitializer(envelope => { }); + +// a sample from: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#example +context.addTelemetryInitializer(envelope => { + let telemetryItem = envelope.data.baseData; + if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType) { + telemetryItem.url = "URL CENSORED"; + } + telemetryItem.properties = telemetryItem.properties || {}; + telemetryItem.properties["globalProperty"] = "boo"; +}); // track event const eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null); diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 0a01d726a4..17137d67dd 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -572,6 +572,7 @@ declare module Microsoft.ApplicationInsights { isPerfAnalyzerEnabled?: boolean; url?: string; isStorageUseDisabled?: boolean; + isBeaconApiDisabled?: boolean; } /** @@ -611,6 +612,7 @@ declare module Microsoft.ApplicationInsights { tags: { [name: string]: any; }; + data: any; } interface ITelemetryContext { @@ -650,7 +652,7 @@ declare module Microsoft.ApplicationInsights { * Adds telemetry initializer to the collection. Telemetry initializers will be called one by one * before telemetry item is pushed for sending and in the order they were added. */ - addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean): any; + addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean | void): any; /** * Tracks telemetry object. */ From 462dfb5b3a3d15632ffe508e2bce997a6658aedc Mon Sep 17 00:00:00 2001 From: Syncfusion-JavaScript Date: Fri, 9 Jun 2017 05:40:32 +0530 Subject: [PATCH 83/98] Typing files updated (#17014) * typings updated * Lint errors with v15.2.0.43 have been resolved. --- types/ej.web.all/index.d.ts | 1747 +++++++++++++++++++++++++++++++++-- 1 file changed, 1673 insertions(+), 74 deletions(-) diff --git a/types/ej.web.all/index.d.ts b/types/ej.web.all/index.d.ts index e304a73863..61698887b8 100644 --- a/types/ej.web.all/index.d.ts +++ b/types/ej.web.all/index.d.ts @@ -7,7 +7,7 @@ /*! * filename: ej.web.all.d.ts -* version : 15.2.0.40 +* version : 15.2.0.43 * Copyright Syncfusion Inc. 2001 - 2017. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -239,6 +239,7 @@ declare namespace ej { convertToQueryString(req: any, query: ej.Query, dm: ej.DataManager): JQueryParam; processResponse(data: any, ds: any, query: ej.Query, xhr: JQueryXHR, request?: any, changes?: Changes): any; onGroup(e: any): void; + onAggregates(e: any): void; batchRequest(dm: ej.DataManager, changes: Changes, e: any): void; beforeSend(dm: ej.DataManager, request: any, settings?: any): void; insert(dm: ej.DataManager, data: any, tableName: string): { url: string; data: any }; @@ -246,14 +247,12 @@ declare namespace ej { update(dm: ej.DataManager, keyField: string, value: any, tableName: string): { type: string; url: string; data: any }; getFiltersFrom(data: any, query: ej.Query): ej.Predicate; } - class WebMethodAdaptor extends ej.UrlAdaptor { constructor(); processQuery(dm: ej.DataManager, query: ej.Query, hierarchyFilters?: any): { type: string; url: string; ejPvtData: any; contentType?: string; data?: any; }; } - class CacheAdaptor extends ej.UrlAdaptor { constructor(); init(adaptor: any, timeStamp: number, pageSize: number): void; @@ -266,7 +265,6 @@ declare namespace ej { batchRequest(dm: ej.DataManager, changes: Changes, e: any): { url: string; type: string; data: any; contentType: string }; } - class ODataAdaptor extends ej.UrlAdaptor { constructor(); options: UrlAdaptorOptions; @@ -280,6 +278,7 @@ declare namespace ej { onSortBy(e: any): string; onGroup(e: any): string; onSelect(e: any): string; + onAggregates(e: any): string; onCount(e: any): string; beforeSend(dm: ej.DataManager, request: any, settings?: any): void; processResponse(data: any, ds: any, query: ej.Query, xhr: any, request: any, changes: Changes): { @@ -313,6 +312,7 @@ declare namespace ej { changeSetContent?: string; batchChangeSetContentType?: string; } + class WebApiAdaptor extends ej.ODataAdaptor { constructor(); insert(dm: ej.DataManager, data: any, tableName?: string): { url: string; type: string; data: any; }; @@ -322,6 +322,7 @@ declare namespace ej { result: any; count: number }; } + class ODataV4Adaptor extends ej.ODataAdaptor { constructor(); options: ODataAdaptorOptions; @@ -329,9 +330,13 @@ declare namespace ej { onEachSearch(e: any): void; onSearch(e: any): string; beforeSend(dm: ej.DataManager, request: any, settings?: any): void; + processQuery(ds: any, query: ej.Query): { + type: string; url: string; ejPvtData: any; contentType?: string; data?: any; + }; processResponse(data: any, ds: any, query: ej.Query, xhr: any, request: any, changes: Changes): { result: any; count: number }; + } interface ODataAdaptorOptions { requestType?: string; @@ -359,6 +364,7 @@ declare namespace ej { processQuery(ds: any, query: ej.Query): string; batchRequest(dm: ej.DataManager, changes: Changes, e: any): Changes; onWhere(ds: any, e: any): any; + onAggregates(ds: any, e: any): any; onSearch(ds: any, e: any): any; onSortBy(ds: any, e: any, query: ej.Query): any; onGroup(ds: any, e: any, query: ej.Query): any; @@ -367,10 +373,16 @@ declare namespace ej { onTake(ds: any, e: any): any; onSkip(ds: any, e: any): any; onSelect(ds: any, e: any): any; - insert(dm: ej.DataManager, data: any): any; + insert(dm: ej.DataManager, data: any, tableName?: string): any; remove(dm: ej.DataManager, keyField: string, value: any, tableName: string): any; update(dm: ej.DataManager, keyField: string, value: any, tableName: string): any; } + class ForeignKeyAdaptor extends ej.JsonAdaptor { + constructor(); + processQuery(ds: any, query: ej.Query): any; + insert(dm: ej.DataManager, data: any, tableName: string): { url: string; data: any }; + update(dm: ej.DataManager, keyField: string, value: any, tableName: string): { url: string; type: string; data: any }; + } class remoteSaveAdaptor extends ej.UrlAdaptor { constructor(); batchRequest(dm: ej.DataManager, changes: Changes, e: any): void; @@ -740,7 +752,7 @@ declare namespace ej { /** returns the element which accepts the droppable element. */ - targetElement?: any; + target?: any; } export interface OutEventArgs { @@ -759,7 +771,7 @@ declare namespace ej { /** returns the mouse out over the element */ - targetElement?: any; + target?: any; } export interface OverEventArgs { @@ -778,7 +790,7 @@ declare namespace ej { /** returns the mouse over the element */ - targetElement?: any; + target?: any; } } @@ -3267,7 +3279,10 @@ declare namespace ej { * @Default {false} */ showRoundedCorner?: boolean; - + /** Set to sort ListBox items either by Ascending or Descending order. By default sortOrder is set as enum type of "None".You can use only below mentioned type for sorting purpose. + * @Default {ej.SortOrder.None} + */ + sortOrder?: ej.ListBox.SortOrder | string; /** The template to display the ListBox widget with customized appearance. * @Default {null} */ @@ -3864,6 +3879,14 @@ declare namespace ej { */ value?: string; } + enum SortOrder { + /// The items are not sorted. + None, + /// To sort items in Ascending order. + Ascending, + /// To sort items in Descending order. + Descending + } } class Calculate { @@ -6868,8 +6891,8 @@ declare namespace ej { export interface TimeDrillDown { - /** This is the field to show/hide the timeDrillDown in DateTimePicker. - */ + /** This is the field to show/hide the timeDrillDown in DateTimePicker. + */ enabled?: boolean; /** Sets the interval time of minutes on selected date. @@ -7342,6 +7365,10 @@ declare namespace ej { */ animation?: any; + /** To Enable or disable the scrolling for background element of the modal dialog. This will work only with modal dialog. + */ + backgroundScroll?: boolean; + /** Closes the dialog widget on pressing the ESC key when it is set to true. */ closeOnEscape?: boolean; @@ -9002,6 +9029,10 @@ declare namespace ej { */ target?: string; + /** defines Tooltip size and gap between tooltip against the target element. + */ + tip?: Tip; + /** The title text to be displayed in the Tooltip header. * @Default {null} */ @@ -9936,6 +9967,26 @@ declare namespace ej { */ width?: string | number; + /** Specifies the number of items to be fetched on each scroll. Note: This property works only with Virtual scrolling. + * @Default {5} + */ + itemRequestCount?: number; + + /** Specifies the maximum number of items to be fetched. Note: This will work only with Virtual scrolling + * @Default {null} + */ + totalItemsCount?: number; + + /** Loads the list data on demand via scrolling behavior to improve the application’s performance. There are two ways to load data which can be defined using virtualScrollMode property. + * @Default {false} + */ + allowVirtualScrolling?: boolean; + + /** Specifies the virtual scroll mode to load the list data on demand via scrolling behavior. There are two types of mode. + * @Default {ej.VirtualScrollMode.Normal} + */ + virtualScrollMode?: ej.VirtualScrollMode | string; + /** Event triggers before the AJAX request happens. */ ajaxBeforeLoad?(e: AjaxBeforeLoadEventArgs): void; @@ -10712,6 +10763,11 @@ declare namespace ej { */ contextMenuTarget?: string; + /** Specifies the container element selectors for submenu’s collision. The submenu gets displayed based on spacing available with respect to container element. + * @Default {null} + */ + container?: string; + /** Specify the CSS class to achieve custom theme. */ cssClass?: string; @@ -11990,8 +12046,8 @@ declare namespace ej { export interface MouseoverEventArgs { - /** returns the current value. - */ + /** returns the current value. + */ value?: number; /** if the event should be canceled; otherwise, false. @@ -13609,6 +13665,9 @@ declare namespace ej { /** Triggered initial load. */ load?(e: LoadEventArgs): void; + /** Triggers before swim lane expand or collapse icon is clicked. */ + swimlaneClick?(e: SwimlaneClickEventArgs): void; + /** Triggered every time a single card rendered request is made to access particular card information. */ queryCellInfo?(e: QueryCellInfoEventArgs): void; @@ -14304,6 +14363,37 @@ declare namespace ej { type?: string; } + export interface SwimlaneClickEventArgs { + + /** Current Action name while swim lane clicked. Actions are "expand" or "collapse" + */ + action?: string; + + /** Returns the kanban model. + */ + model?: any; + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the name of the event. + */ + type?: string; + + /** Returns the swim lane group data's. + */ + data?: any; + + /** Returns current swim lane row index. + */ + rowIndex?: number; + + /** Returns current target element. + */ + target?: any; + } + export interface QueryCellInfoEventArgs { /** Returns Kanban card. @@ -14330,8 +14420,8 @@ declare namespace ej { */ model?: any; - /** Returns the name of the event. - */ + /** Returns the name of the event. + */ type?: string; } @@ -15447,6 +15537,11 @@ declare namespace ej { */ autoHeight?: boolean; + /** This API holds configuration setting for paste clenaup behavior. + * @Default {{ listConversion: false, cleanCSS: false, removeStyles: false, cleanElements: false }} + */ + pasteCleanupSettings?: PasteCleanupSettings; + /** Sets the colorCode to display the color of the fontColor and backgroundColor in the font tools of the RTE. * @Default {[000000, FFFFFF, C4C4C4, ADADAD, 595959, 262626, 4f81bd, dbe5f1, b8cce4, 95b3d7, 366092, 244061, c0504d, f2dcdb, e5b9b7, d99694, 953734,632423, 9bbb59, * ebf1dd, d7e3bc, c3d69b, 76923c, 4f6128, 8064a2, e5e0ec, ccc1d9, b2a2c7, 5f497a, 3f3151, f79646, fdeada, fbd5b5, fac08f,e36c09, 974806]} @@ -15695,6 +15790,11 @@ declare namespace ej { */ toolsList?: any[]; + /** Specifies the overflow mode for RTE responsive toolbar + * @Default {Popup} + */ + toolbarOverflowMode?: ej.RTE.ToolbarOverflowMode | string; + /** Display the hints for the tools in the Toolbar. * @Default {{ associate: mouseenter, showShadow: true, position: { stem: { horizontal: left, vertical: top } }, tip: { size: { width: 5, height: 5 }, isBalloon: false }} */ @@ -15897,6 +15997,29 @@ declare namespace ej { event?: any; } + export interface PasteCleanupSettings { + + /** This API is used to convert the list elements pasted from word document to editor. + * @Default {false} + */ + listConversion?: boolean; + + /** This API is used to clean the unwanted css in the elements pasted from word document to editor. + * @Default {false} + */ + cleanCSS?: boolean; + + /** This API is used to remove all styles in the elements pasted from word document to editor. + * @Default {false} + */ + removeStyles?: boolean; + + /** This API is used to clean the unwanted elements pasted from word document to editor. + * @Default {false} + */ + cleanElements?: boolean; + } + export interface ExportToPdfSettings { /** This API is used to receive the server-side handler for export related operations. @@ -16096,6 +16219,16 @@ declare namespace ej { */ customUnorderedList?: ToolsCustomUnorderedList[]; } + + enum ToolbarOverflowMode { + + ///To display the RTE toolbar overflow items as popup + Popup, + + ///To display the RTE toolbar overflow items as inline toolbar + Inline + } + } class Slider extends ej.Widget { @@ -16125,6 +16258,7 @@ declare namespace ej { */ setValue(): void; } + export namespace Slider { export interface Model { @@ -16418,6 +16552,7 @@ declare namespace ej { cancel?: boolean; } } + namespace slider { enum sliderType { //Shows default slider @@ -17233,8 +17368,8 @@ declare namespace ej { */ activeIndex?: number; - /** returns, is it triggered by interaction or not. - */ + /** returns, is it triggered by interaction or not. + */ isInteraction?: boolean; } @@ -21193,6 +21328,12 @@ declare namespace ej { */ addIgnoreOnExport(propertyNames: any[]): void; + /** Adds a grid model property which is to be ignored upon OnServerToolbarClick. + * @param {Array} Pass the array of parameters which need to be ignored on OnServerToolbarClick + * @returns {void} + */ + addIgnoreOnToolbarServerClick(propertyNames: any[]): void; + /** Add a new record in grid control when allowAdding is set as true. * @returns {void} */ @@ -23581,6 +23722,21 @@ declare namespace ej { type?: string; } + export interface MergeHeaderCellInfoEventArgs { + + /** Method to merge the header cells. + */ + headerCellMerge?: any; + + /** Returns the column headers. + */ + columnHeaders?: any; + + /** Returns the grid model. + */ + model?: any; + } + export interface MergeCellInfoEventArgs { /** Returns grid cell. @@ -23593,7 +23749,7 @@ declare namespace ej { /** Returns current row record object (JSON). */ - data?: any; + rowData?: any; /** Returns the text value in the cell. */ @@ -23636,7 +23792,7 @@ declare namespace ej { /** Returns current row record object (JSON). */ - data?: any; + rowData?: any; /** Returns the text value in the cell. */ @@ -24068,7 +24224,7 @@ declare namespace ej { /** Returns the current row data. */ - data?: any; + rowData?: any; /** Returns the grid model. */ @@ -24630,6 +24786,10 @@ declare namespace ej { * @Default {null} */ dropMapper?: string; + /** Gets or sets a value that indicates whether to define the behavior for drag. + * @Default {ej.Grid.DragBehavior.Move} + */ + dragBehavior?: ej.Grid.DragBehavior | string; } export interface SearchSettings { @@ -24872,6 +25032,17 @@ declare namespace ej { wrapMode?: ej.Grid.WrapMode | string; } + export interface ToolbarSettingsCustomToolbarItem { + + /** Gets or sets a value that indicates whether to add custom toolbar item as a template element. + */ + templateID?: string; + + /** Gets or sets a value that indicates whether to add custom toolbar item with a custom tooltip. + */ + tooltip?: string; + } + export interface ToolbarSettings { /** Gets or sets a value that indicates whether to add custom toolbar items within the toolbar to perform any action in the grid @@ -25058,6 +25229,16 @@ declare namespace ej { } + enum DragBehavior { + + ///Moves a dragged row from one grid to another + Move, + + ///Copies a dragged row from one grid to another + Copy + } + + enum SelectionType { ///Specifies the selection type as single. @@ -25225,6 +25406,11 @@ declare namespace ej { */ rangeBandSettings?: RangeBandSettings; + /** Name of the culture based on which sparkline should be localized. + * @Default {en-US} + */ + locale?: string; + /** Name of a field in data source, where the fill color for all the data points is generated. */ palette?: string; @@ -25239,6 +25425,11 @@ declare namespace ej { */ enableCanvasRendering?: boolean; + /** Specify to convert the date object to string, using locale settings. + * @Default {false} + */ + enableGroupSeparator?: boolean; + /** Specifies the dataSource for the series. It can be an array of JSON objects or an instance of ej.DataManager. * @Default {null} */ @@ -25377,8 +25568,8 @@ declare namespace ej { */ cancel?: boolean; - /** Instance of the sparkline model object - */ + /** Instance of the sparkline model object + */ model?: any; /** Name of the event @@ -27022,6 +27213,16 @@ declare namespace ej { */ frozenHeaderSettings?: FrozenHeaderSettings; + /** Allows user to display header name in PivotGrid control. + * @Default {{}} + */ + headerSettings?: HeaderSettings; + + /** Allows user to show appropriate unique name on Pivot button. + * @Default {false} + */ + showUniqueNameOnPivotButton?: boolean; + /** Object utilized to pass additional information between client-end and service-end on operating the control in server mode. * @Default {null} */ @@ -27865,6 +28066,24 @@ declare namespace ej { * @Default {false} */ enableFrozenHeaders?: boolean; + + /** Allows user to set the size of the scrollbar (horizontal and vertical) visible in PivotGrid. + * @Default {18} + */ + scrollerSize?: number; + } + + export interface HeaderSettings { + + /** Allows user to enable/disable row header names in PivotGrid control. + * @Default {false} + */ + showRowItems?: boolean; + + /** Allows user to enable/disable column header names in PivotGrid control. + * @Default {false} + */ + showColumnItems?: boolean; } export interface HyperlinkSettings { @@ -28441,6 +28660,11 @@ declare namespace ej { */ enableRTL?: boolean; + /** Allows user to render complete PivotChart on drill operation, that is, when expanding and collapsing members which are shown in multi-level labels. + * @Default {false} + */ + enableMultiLevelLabels?: boolean; + /** Allows the user to enable PivotChart’s responsiveness in the browser layout. * @Default {false} */ @@ -29005,6 +29229,16 @@ declare namespace ej { */ displaySettings?: DisplaySettings; + /** Allows user to set visibility of icons in toolbar panel. + * @Default {{}} + */ + toolbarIconSettings?: ToolbarIconSettings; + + /** Allows user to show unique name on pivotbutton. + * @Default {false} + */ + showUniqueNameOnPivotButton?: boolean; + /** Enables the splitter option for resizing the elements inside the control. * @Default {false} */ @@ -29626,6 +29860,89 @@ declare namespace ej { mode?: ej.PivotClient.DisplayMode | string; } + export interface ToolbarIconSettings { + + /** Allows user to set the visibility of Add Report icon in toolbar panel. + * @Default {true} + */ + enableAddReport?: boolean; + + /** Allows user to set the visibility of New Report icon in toolbar panel. + * @Default {true} + */ + enableNewReport?: boolean; + + /** Allows user to set the visibility of Rename Report icon in toolbar panel. + * @Default {true} + */ + enableRenameReport?: boolean; + + /** Allows user to set the visibility of DB Manipulation icon in toolbar panel. + * @Default {true} + */ + enableDBManipulation?: boolean; + + /** Allows user to set the visibility of Word Export icon in toolbar panel. + * @Default {true} + */ + enableWordExport?: boolean; + + /** Allows user to set the visibility of Excel Export icon in toolbar panel. + * @Default {true} + */ + enableExcelExport?: boolean; + + /** Allows user to set the visibility of PDF Export icon in toolbar panel. + * @Default {true} + */ + enablePdfExport?: boolean; + + /** Allows user to set the visibility of MDX Query icon in toolbar panel. + * @Default {true} + */ + enableMDXQuery?: boolean; + + /** Allows user to set the visibility of Defer Update icon in toolbar panel. + * @Default {false} + */ + enableDeferUpdate?: boolean; + + /** Allows user to set the visibility of Full Screen icon in toolbar panel. + * @Default {false} + */ + enableFullScreen?: boolean; + + /** Allows user to set the visibility of Sort/Filter Column icon in toolbar panel. + * @Default {true} + */ + enableSortOrFilterColumn?: boolean; + + /** Allows user to set the visibility of Sort/Filter Row icon in toolbar panel. + * @Default {true} + */ + enableSortOrFilterRow?: boolean; + + /** Allows user to set the visibility of Toggle Axis icon in toolbar panel. + * @Default {true} + */ + enableToggleAxis?: boolean; + + /** Allows user to set the visibility of Chart Types icon in toolbar panel. + * @Default {true} + */ + enableChartTypes?: boolean; + + /** Allows user to set the visibility of Remove Report icon in toolbar panel. + * @Default {true} + */ + enableRemoveReport?: boolean; + + /** Allows user to set the visibility of Calculated Member icon in toolbar panel. + * @Default {false} + */ + enableCalculatedMember?: boolean; + } + export interface ServiceMethodSettings { /** Allows the user to set the custom name for the service method responsible for updating the entire report and widget, while changing the Cube. @@ -29887,9 +30204,9 @@ declare namespace ej { */ showHeaderLabel?: boolean; - /** Connects the service using the specified URL for any server updates on server mode operation. - * @Default {“”} - */ + /** Connects the service using the specified URL for any server updates on server mode operation. + * @Default {“”} + */ url?: string; /** Sets the mode for the PivotGauge widget for binding either OLAP or Relational data source. @@ -30843,6 +31160,11 @@ declare namespace ej { */ showAllDayRow?: boolean; + /** When set to false, hides the weekend days on all the Scheduler views. + * @Default {true} + */ + showWeekend?: boolean; + /** When set to true, displays the current time indicator on the Schedule. * @Default {true} */ @@ -32455,6 +32777,13 @@ declare namespace ej { */ setSplitterIndex(index: number): void; + /** To sort the column in required direction + * @param {string} Defines the column's mapping name in which sorting have to be performed + * @param {string} Defines the sort direction whether the column has to sorted in ascending/descending order. By default it is sorting in an ascending order + * @returns {void} + */ + sortColumn(mappingName: string, columnSortDirection: string): void; + /** To cancel the edited state of an item in Gantt * @returns {void} */ @@ -32486,6 +32815,14 @@ declare namespace ej { */ expandCollapseRecord(taskId: number): void; + /** Export the Gantt content to excel or PDF document. + * @param {string} Pass the controller action name corresponding to exporting + * @param {string} optionalASP server event name corresponding to exporting + * @param {boolean} optionalPass the multiple exporting value as true/false + * @returns {void} + */ + export(action: string, serverEvent?: string, multipleExport?: boolean): void; + /** To hide the column by using header text * @param {string} you can pass a header text of a column to hide * @returns {void} @@ -32594,6 +32931,14 @@ declare namespace ej { */ baselineColor?: string; + /** Specifies the mapping property path for the work field of a task in the data source. When it is mapped the end date and duration for a task will be calculated automatically. + */ + workMapping?: string; + + /** Specifies the mapping property path for the expand status of a record in data source. + */ + expandStateMapping?: string; + /** Specifies the mapping property path for baseline end date in datasource */ baselineEndDateMapping?: string; @@ -32643,6 +32988,11 @@ declare namespace ej { */ dateFormat?: string; + /** Specifies the customized working time for tasks in Gantt + * @Default {[{ from: 08:00 AM, to: 12:00 PM }, { from: 01:00 PM, to: 05:00 PM }]} + */ + dayWorkingTime?: any[]; + /** Specifies the mapping property path for duration of a task in datasource */ durationMapping?: string; @@ -32978,6 +33328,11 @@ declare namespace ej { */ taskbarEditingTooltipTemplateId?: string; + /** Specifies the height of taskBar in Gantt. + * @Default {20} + */ + taskbarHeight?: number; + /** Specifies the template for tooltip on mouse action on taskbars */ taskbarTooltipTemplate?: string; @@ -33790,6 +34145,17 @@ declare namespace ej { type?: string; } + export interface AddDialogField { + + /** Specifies mapping name to include required fields in Gantt + */ + field?: string; + + /** Specifies editType of fields to be included in the add dialog in Gantt + */ + editType?: string; + } + export interface DragTooltip { /** Specifies option to enable/disable tooltip while drag and drop a row. @@ -33808,6 +34174,17 @@ declare namespace ej { tooltipTemplate?: string; } + export interface EditDialogField { + + /** Specifies mapping name to include required fields in Gantt + */ + field?: string; + + /** Specifies editType of fields to be included in the edit dialog in Gantt + */ + editType?: string; + } + export interface SplitterSettings { /** Specifies position of the splitter in Gantt , splitter can be placed either based on percentage values or pixel values. @@ -33862,6 +34239,21 @@ declare namespace ej { rowPosition?: ej.Gantt.RowPosition | string; } + export interface Holiday { + + /** Specifies holiday date to be displayed in Gantt + */ + day?: string; + + /** Specifies the background color for holiday date in Gantt Schedule + */ + background?: string; + + /** Specifies the label to be displayed for rendered holiday in Gantt + */ + label?: string; + } + export interface ScheduleHeaderSettings { /** Specified the format for day view in schedule header @@ -33899,9 +34291,9 @@ declare namespace ej { */ weekendBackground?: string; - /** Specified the format for week view in schedule header - * @Default {ddd} - */ + /** Specified the format for week view in schedule header + * @Default {MMM dd , yyyy} + */ weekHeaderFormat?: string; /** Specified the format for year view in schedule header @@ -33945,12 +34337,61 @@ declare namespace ej { cellIndex?: number; } + export interface SortSettingsSortedColumn { + + /** Specifies the field to be sorted in Gantt + */ + field?: string; + + /** Specifies the sort direction in Gantt + */ + direction?: string; + } + export interface SortSettings { /** Specifies the sorted columns for Gantt * @Default {[]} */ - sortedColumns?: any[]; + sortedColumns?: SortSettingsSortedColumn[]; + } + + export interface StripLine { + + /** Specifies date to render striplines in Gantt + */ + day?: string; + + /** Specifies label to be displayed for striplines in Gantt + */ + label?: string; + + /** Specifies line style for rendered striplines in Gantt + */ + lineStyle?: string; + + /** Specifies the line color for rendered striplines in Gantt + */ + lineColor?: string; + + /** Specifies the width of the stripline in Gantt + */ + lineWidth?: string; + } + + export interface ToolbarSettingsCustomToolbarItem { + + /** Allows the user to insert the custom icons in toolbar using CSS class name selector. + */ + text?: string; + + /** Allows the user to insert the custom icons in toolbar using script templates. Using this property we can bind HTML elements and other EJ controls to Gantt toolbar. + */ + templateID?: string; + + /** Allows the user to display custom tooltip text for Gantt custom toolbar items. + */ + tooltipText?: string; } export interface ToolbarSettings { @@ -33964,6 +34405,10 @@ declare namespace ej { * @Default {[]} */ toolbarItems?: any[]; + + /** Allows the user to insert custom toolbar items. + */ + customToolbarItems?: ToolbarSettingsCustomToolbarItem[]; } enum DurationUnit { @@ -34856,12 +35301,6 @@ declare namespace ej { */ saveCell(): void; - /** To search an item with search string provided at the run time - * @param {string} you can pass a searchString to search the tree grid - * @returns {void} - */ - search(searchString: string): void; - /** To show the column by using header text * @param {string} you can pass a header text of a column to show. * @returns {void} @@ -34873,7 +35312,7 @@ declare namespace ej { * @param {string} you can pass a sort direction to sort the column. * @returns {void} */ - sortColumn(columnName: string, columnSortDirection: string): void; + sortColumn(fieldName: string, columnSortDirection: string): void; /** To reorder the column with field name and target index values * @param {string} you can pass a name of column to reorder. @@ -34936,6 +35375,10 @@ declare namespace ej { */ altRowTemplateID?: string; + /** Specifies the mapping property path for the expand status of a record in data source. + */ + expandStateMapping?: string; + /** Specifies the mapping property path for sub tasks in datasource */ childMapping?: string; @@ -34963,9 +35406,9 @@ declare namespace ej { dataSource?: any[]; /** Specifies whether to wrap the header text when it is overflown i.e., when it exceeds the header width. - * @Default {none} + * @Default {ej.TreeGrid.HeaderTextOverflow.None} */ - headerTextOverflow?: string; + headerTextOverflow?: ej.TreeGrid.HeaderTextOverflow | string; /** Options for displaying and customizing the tooltip. This tooltip will show the preview of the row that is being dragged. */ @@ -34999,6 +35442,11 @@ declare namespace ej { */ columnResizeSettings?: ColumnResizeSettings; + /** Defines the common width for all the columns in TreeGrid + * @Default {150} + */ + commonWidth?: number; + /** Options for filtering and customizing filter actions. */ filterSettings?: FilterSettings; @@ -35054,6 +35502,10 @@ declare namespace ej { */ selectedRowIndex?: number; + /** Specifies the selected cell information on rendering TreeGrid. + */ + selectedCellIndexes?: SelectedCellIndex[]; + /** Specifies the settings for row and cell selection. */ selectionSettings?: SelectionSettings; @@ -35172,6 +35624,15 @@ declare namespace ej { /** Triggered when TreeGrid is rendered completely */ create?(e: CreateEventArgs): void; + /** Triggered while rendering details template in TreeGrid */ + detailsDataBound?(e: DetailsDataBoundEventArgs): void; + + /** Triggered when details template pop-up is shown. */ + detailsShown?(e: DetailsShownEventArgs): void; + + /** Triggered when details template pop-up is hidden. */ + detailsHidden?(e: DetailsHiddenEventArgs): void; + /** Triggered after saved the modified cellValue in TreeGrid */ endEdit?(e: EndEditEventArgs): void; @@ -35621,6 +36082,79 @@ declare namespace ej { type?: string; } + export interface DetailsDataBoundEventArgs { + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the data collection of selected row. + */ + data?: any; + + /** Returns the details element of selected row. + */ + detailsElement?: any; + + /** Returns the rowIndex of selected row. + */ + rowIndex?: number; + + /** Returns the TreeGrid model + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; + } + + export interface DetailsShownEventArgs { + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the data collection of selected row. + */ + data?: any; + + /** Returns the details element of selected row. + */ + detailsElement?: any; + + /** Returns the rowIndex of selected row. + */ + rowIndex?: number; + + /** Returns the TreeGrid model + */ + model?: any; + + /** Returns the name of the event. + */ + type?: string; + } + + export interface DetailsHiddenEventArgs { + + /** Returns the cancel option value. + */ + cancel?: boolean; + + /** Returns the TreeGrid model + */ + model?: any; + + /** Returns the data collection of hidden details Template + */ + rowData?: any; + + /** Returns the name of the event. + */ + type?: string; + } + export interface EndEditEventArgs { /** Returns the cancel option value. @@ -36018,6 +36552,11 @@ declare namespace ej { */ allowFiltering?: boolean; + /** Enables the blanks option in ejDropDownList mapped in TreeGrid column + * @Default {true} + */ + allowFilteringBlankContent?: boolean; + /** Enables or disables the ability to sort the rows based on this column/field. * @Default {false} */ @@ -36028,15 +36567,35 @@ declare namespace ej { */ allowCellSelection?: boolean; + /** To customize the ej controls defined in TreeGrid column with their native property. + */ + editParams?: any; + /** Specifies the edit type of the column. * @Default {ej.TreeGrid.EditingType.String} */ editType?: ej.TreeGrid.EditingType | string; + /** To bind the dropdown data for TreeGrid column mapped with ejDropDownList + */ + dropdownData?: string; + /** Specifies the name of the field from the dataSource to bind with this column. */ field?: string; + /** Specifies the template string of the script element to enable column template for a column. + */ + template?: string; + + /** Specifies the template ID of the script element to enable column template for a column. + */ + templateID?: string; + + /** Specifies the template ID or the template string of the AngularJS script element to enable column template for a column. + */ + angularTemplate?: string; + /** Specifies the type of the editor control to be used to filter the rows. * @Default {ej.TreeGrid.EditingType.String} */ @@ -36050,6 +36609,11 @@ declare namespace ej { /** Enables or disables the checkbox visibility in a column to make it as a checkbox column * @Default {false} */ + displayAsCheckbox?: boolean; + + /** Enables or disables the checkbox visibility in a column for checkbox selection. + * @Default {false} + */ showCheckbox?: boolean; /** Controls the visibility of the column. @@ -36090,15 +36654,35 @@ declare namespace ej { */ textAlign?: ej.TextAlign | string; - /** Specifies the template for the TreeGrid column - */ - templateID?: string; - /** Enables or disables the ability to edit a row or cell. * @Default {false} */ allowEditing?: boolean; + /** We can include or exclude particular column from column visibility list in column menu. + * @Default {true} + */ + showInColumnChooser?: boolean; + + /** Sets the clip mode for TreeGrid cell as ellipsis or clipped content(both header and content) + * @Default {ej.TreeGrid.ClipMode.Clip} + */ + clipMode?: ej.TreeGrid.ClipMode | string; + + /** Sets the tooltip template for the specific column. + * @Default {null} + */ + tooltip?: string; + + /** Sets the tooltip template for the column header + * @Default {null} + */ + headerTooltip?: string; + + /** specifies the conditions for saving data to the database while adding or editing the fields. + */ + validationRules?: any; + /** Enables or disables the ability to freeze/unfreeze the columns * @Default {false} */ @@ -36167,14 +36751,37 @@ declare namespace ej { * @Default {top} */ rowPosition?: ej.TreeGrid.RowPosition | string; + /** Specifies the template ID for the custom dialog. + * @Default {null} + */ + dialogEditorTemplateID?: string; } export interface ColumnResizeSettings { /** Specifies the mode for column resizing - * @Default {normal} + * @Default {ej.TreeGrid.ColumnResizeMode.Normal} */ - columnResizeMode?: string; + columnResizeMode?: ej.TreeGrid.ColumnResizeMode | string; + } + + export interface FilterSettingsFilteredColumn { + + /** Specifies the value to be filtered in TreeGrid. + */ + value?: string; + + /** Specifies the field where filtering has to be performed. + */ + field?: string; + + /** Specifies the predicate(and/or) value to perform filtering. + */ + predicate?: string; + + /** Specifies the filter condition to filtered column. See operator + */ + operator?: string; } export interface FilterSettings { @@ -36185,9 +36792,9 @@ declare namespace ej { filterBarMode?: string; /** Specifies the type of column filtering. - * @Default {filterbar} + * @Default {ej.TreeGrid.FilterType.FilterBar} */ - filterType?: string; + filterType?: ej.TreeGrid.FilterType | string; /** Specifies the column collection for filtering the TreeGrid content on initial load * @Default {[]} @@ -36228,6 +36835,18 @@ declare namespace ej { template?: string; } + export interface SelectedCellIndex { + + /** Specifies the row index of the cell to be selected in TreeGrid control + */ + rowIndex?: number; + + /** Specifies the cell index to be selected in the row. + * @Default { } + */ + cellIndex?: number; + } + export interface SelectionSettings { /** Specifies the type of selection whether to select row or cell. @@ -36251,6 +36870,44 @@ declare namespace ej { enableSelectAll?: boolean; } + export interface SummaryRowsSummaryColumn { + + /** Specifies the summary type to perform calculations in a corresponding summary column. See summaryType. + */ + summaryType?: ej.TreeGrid.SummaryType | string; + + /** Specifies summary column used to perform the summary calculation. + */ + dataMember?: string; + + /** Specifies the required column to display the summary. + */ + displayColumn?: string; + + /** Specifies the text to be displayed before the summary column value. + */ + prefix?: string; + + /** Specifies the text to be displayed after the summary column value. + */ + suffix?: string; + + /** Specifies the format to be applied on the summary column value. + */ + format?: string; + } + + export interface SummaryRow { + + /** Specifies the title for summary row collection in TreeGrid + */ + title?: string; + + /** Specifies the summary columns in the summary rows. + */ + summaryColumns?: SummaryRowsSummaryColumn[]; + } + export interface SizeSettings { /** Height of the TreeGrid. @@ -36264,12 +36921,38 @@ declare namespace ej { width?: string; } + export interface SortSettingsSortedColumn { + + /** Specifies the field to be sorted in TreeGrid + */ + field?: string; + + /** Specifies the sort direction in TreeGrid + */ + direction?: string; + } + export interface SortSettings { /** Option to add columns based on which the rows have to be sorted recursively. * @Default {[]} */ - sortedColumns?: any[]; + sortedColumns?: SortSettingsSortedColumn[]; + } + + export interface ToolbarSettingsCustomToolbarItem { + + /** Allows the user to insert the custom icons in toolbar using CSS class name selector. + */ + text?: string; + + /** Allows the user to insert the custom icons in toolbar using script templates. Using this property we can bind HTML elements and other EJ controls to TreeGrid toolbar. + */ + templateID?: string; + + /** Allows the user to display custom tooltip text for TreeGrid custom toolbar items. + */ + tooltipText?: string; } export interface ToolbarSettings { @@ -36283,6 +36966,10 @@ declare namespace ej { * @Default {[]} */ toolbarItems?: any[]; + + /** Allows the user to insert custom toolbar items. + */ + customToolbarItems?: ToolbarSettingsCustomToolbarItem[]; } enum EditingType { @@ -36310,6 +36997,26 @@ declare namespace ej { } + enum ClipMode { + + ///Shows ellipsis for the overflown cell. + Ellipsis, + + ///Truncate the text in the cell. + Clip + } + + + enum HeaderTextOverflow { + + ///You can disable the word wrap + None, + + ///You can wrap the header content + Wrap + } + + enum BeginEditAction { ///you can begin the editing at double click @@ -36349,6 +37056,29 @@ declare namespace ej { } + enum ColumnResizeMode { + + ///At load time column are rendered with given width value, while resizing the column only current column width is changed + FixedColumns, + + ///At load time columns are stretched with control width,while resizing the column, current column width updated based on next column + Normal, + + ///In this mode columns are stretched with control width in load time and on resizing action. + NextColumn + } + + + enum FilterType { + + ///Enables the filterbar filtering + FilterBar, + + ///Enables the menu filtering + Menu + } + + enum PageSizeMode { ///To count all the parent and child records. @@ -36381,6 +37111,37 @@ declare namespace ej { Checkbox } + + enum SummaryType { + + ///Displays the sum of summary column + Sum, + + ///Displays the average of summary column + Average, + + ///Displays the maximum value of summary column + Maximum, + + ///Displays the minimum value of summary column + Minimum, + + ///Displays the total count of summary column + Count, + + ///Displays the minimum date value in summary column + MinimumDate, + + ///Displays the maximum date value in summary column + MaximumDate, + + ///Displays the true count value for boolean summary columns + TrueCount, + + ///Displays the false count value for boolean summary columns + FalseCount + } + } class GroupButton extends ej.Widget { @@ -38233,6 +38994,11 @@ declare namespace ej { */ gotoPage(sheetIdx: number, newSheet: boolean): void; + /** This method is used to hide the pivot table activationPanel in the Spreadsheet. + * @returns {void} + */ + hideActivationPanel(): void; + /** This method is used to hide the entire columns from the specified range (startCol, endCol) in Spreadsheet. * @param {number} Index of the start column. * @param {number} Optional. Index of the end column. @@ -38952,6 +39718,12 @@ declare namespace ej { export interface XLFormat { + /** This method is used to add the font to the Ribbon font family dropdown. + * @param {string} Font name which needs to add into the font family option. + * @returns {void} + */ + addFontFamily(fontName: string): void; + /** This method is used to convert table range to normal range. * @param {any} Pass the sheet index and table id. * @returns {void} @@ -38972,6 +39744,12 @@ declare namespace ej { */ format(formatObj: any, range: string): void; + /** This method is used to remove the font from the Ribbon font family dropdown. + * @param {string} Font name which needs to remove from the font family drop down. + * @returns {void} + */ + removeFontFamily(fontName: string): void; + /** This method is used to remove the style in the specified range. * @param {Array|string} Pass the cell range . * @param {any} Optional. Pass the options for which the style gets removed. @@ -38986,7 +39764,7 @@ declare namespace ej { removeTable(tableId: number): void; /** This method is used to update the decimal places for numeric value for the selected range of cells in the Spreadsheet. - * @param {string} Pass the decimal places type in increment/decrement. + * @param {string} Pass the decimal places type in IncreaseDecimal/DecreaseDecimal. * @param {string|Array} Pass the range. * @returns {void} */ @@ -39475,9 +40253,9 @@ declare namespace ej { */ allowFormulaBar?: boolean; - /** Gets or sets a value that indicates whether to enable or disable freeze pane support in Spreadsheet. After enabling this feature, - * you can use freeze top row, freeze first column and freeze panes options. - * @Default {false} + /** Gets or sets a value that indicates whether to enable or disable freeze pane support in Spreadsheet. By enabling this feature, you can use freeze top row, + * freeze first column and freeze panes options. + * @Default {true} */ allowFreezing?: boolean; @@ -39620,6 +40398,10 @@ declare namespace ej { */ locale?: string; + /** Gets or sets a value that indicates name manager in Spreadsheet. + */ + nameManager?: NameManager[]; + /** Gets or sets an object that indicates to customize the picture behavior in the Spreadsheet. */ pictureSettings?: PictureSettings; @@ -41012,6 +41794,17 @@ declare namespace ej { password?: string; } + export interface NameManager { + + /** Specifies the name for the cell or a range. + */ + name?: string; + + /** Specifies the address for the cell or a range. + */ + refersto?: string; + } + export interface PictureSettings { /** Gets or sets a value that indicates whether to enable or disable picture feature in Spreadsheet. By enabling this, you can add pictures in Spreadsheet. @@ -42238,6 +43031,11 @@ declare namespace ej { */ isResponsive?: boolean; + /** Gets or sets a value that indicates whether to enable the spellcheck operation on Enter/Space key-press. + * @Default {false} + */ + enableValidateOnType?: boolean; + /** It allows to spell check the multiple target HTML element's texts and correct its error words. * @Default {null} */ @@ -42802,6 +43600,7 @@ declare namespace ej { } } + declare namespace ej.datavisualization { class SymbolPalette extends ej.Widget { @@ -43401,6 +44200,16 @@ declare namespace ej.datavisualization { */ isResponsive?: boolean; + /** Used to Convert the date object to string while using the locale settings + * @Default {false} + */ + enableGroupSeparator?: boolean; + + /** Responsiveness of the linear gauge is controlled + * @Default {false} + */ + enableResize?: boolean; + /** Specify frame of linear gauge * @Default {null} */ @@ -43415,6 +44224,10 @@ declare namespace ej.datavisualization { * @Default {null} */ labelColor?: string; + /** Set the localization culture for the Linear gauge + * @Default {en-US} + */ + locale?: string; /** Specifies the maximum value of Linear gauge. * @Default {100} @@ -45412,6 +46225,16 @@ declare namespace ej.datavisualization { */ enableAnimation?: boolean; + /** Specify to convert the date object to string, using locale settings. + * @Default {false} + */ + enableGroupSeparator?: boolean; + + /** Controls whether circular gauge has to be responsive while resizing. + * @Default {false} + */ + enableResize?: boolean; + /** Specify the frame of circular gauge * @Default {Object} */ @@ -45442,6 +46265,11 @@ declare namespace ej.datavisualization { */ isResponsive?: boolean; + /** Name of the culture based on which circular gauge should be localized. + * @Default {en-US} + */ + locale?: string; + /** Specifies the maximum value of circular gauge. * @Default {100} */ @@ -45477,6 +46305,10 @@ declare namespace ej.datavisualization { */ theme?: string; + /** Options to customize the legend. + */ + legend?: Legend; + /** Specify tooltip option of circular gauge * @Default {object} */ @@ -45492,6 +46324,15 @@ declare namespace ej.datavisualization { */ width?: number; + /** Fires before rendering the legend item. This event is fired for each legend item in CircularGauge. You can use this event to customize legend item shape or add custom text to legend item. */ + legendItemRender?(e: LegendItemRenderEventArgs): void; + + /** Fires on clicking the legend item. */ + legendItemClick?(e: LegendItemClickEventArgs): void; + + /** Fires when mouse moving on ranges. */ + rangeMouseMove?(e: RangeMouseMoveEventArgs): void; + /** Triggers while the custom labels are being drawn on the gauge. */ drawCustomLabel?(e: DrawCustomLabelEventArgs): void; @@ -45529,6 +46370,63 @@ declare namespace ej.datavisualization { renderComplete?(e: RenderCompleteEventArgs): void; } + export interface LegendItemRenderEventArgs { + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the circulargauge model object + */ + model?: any; + + /** Name of the event + */ + type?: string; + + /** Instance of the legend item object that is about to be rendered + */ + data?: any; + } + + export interface LegendItemClickEventArgs { + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the circulargauge model object + */ + model?: any; + + /** Name of the event + */ + type?: string; + + /** Instance of the legend item object that is about to be rendered + */ + data?: any; + } + + export interface RangeMouseMoveEventArgs { + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the circulargauge model object + */ + model?: any; + + /** Name of the event + */ + type?: string; + + /** Region of ranges + */ + data?: any; + } + export interface DrawCustomLabelEventArgs { /** returns the object of the gauge. @@ -46171,10 +47069,20 @@ declare namespace ej.datavisualization { */ position?: ScalesCustomLabelsPosition; + /** Specify angle for the rotation of the custom labels in degrees. + * @Default {0} + */ + textAngle?: number; + /** Specify font for custom labels * @Default {Object} */ font?: ScalesCustomLabelsFont; + + /** Specifies the position of the custom labels. See CustomLabelPositionType + * @Default {inner} + */ + positionType?: ej.datavisualization.CircularGauge.CustomLabelPositionType | string; } export interface ScalesIndicatorsPosition { @@ -46540,6 +47448,11 @@ declare namespace ej.datavisualization { */ backgroundColor?: string; + /** Specify text for the ranges of circular gauge + * @Default {null} + */ + legendText?: string; + /** Specify border for ranges of circular gauge * @Default {Object} */ @@ -46798,6 +47711,144 @@ declare namespace ej.datavisualization { ticks?: ScalesTick[]; } + export interface LegendBorder { + + /** Border color of the legend. + * @Default {transparent} + */ + color?: string; + + /** Border width of the legend. + * @Default {1} + */ + width?: number; + } + + export interface LegendItemStyleBorder { + + /** Border color of the legend items. + * @Default {transparent} + */ + color?: string; + + /** Border width of the legend items. + * @Default {1} + */ + width?: number; + } + + export interface LegendItemStyle { + + /** Options for customizing the border of legend items. + */ + border?: LegendItemStyleBorder; + + /** Specifies the height of the legend item shapes. + * @Default {10} + */ + height?: number; + + /** Specifies the width of the legend item shapes. + * @Default {10} + */ + width?: number; + } + + export interface LegendSize { + + /** Specify the height of the legend. Height can be specified in pixel. + * @Default {null} + */ + height?: string; + + /** Specify the width of the legend. Width can be specified in pixel. + * @Default {null} + */ + width?: string; + } + + export interface LegendFont { + + /** Font family for legend item text. + * @Default {Segoe UI} + */ + fontFamily?: string; + + /** Font style for legend item text. + * @Default {Normal} + */ + fontStyle?: string; + + /** Font weight for legend item text. + * @Default {Regular} + */ + fontWeight?: string; + + /** Font size for legend item text. + * @Default {12px} + */ + size?: string; + + /** Font color of the text for legend items. + * @Default {null} + */ + color?: string; + } + + export interface Legend { + + /** Toggles the visibility of the legend. + * @Default {false} + */ + visible?: boolean; + + /** Specifies the alignment of the legend. + * @Default {Center. See Alignment} + */ + alignment?: ej.datavisualization.CircularGauge.LegendAlignment | string; + + /** Options for customizing the legend border. + */ + border?: LegendBorder; + + /** Fill color for the legend items. By using this property, it displays all legend item shapes in same color.Legend items representing invisible ranges is displayed in gray color. + * @Default {null} + */ + fill?: string; + + /** Gap or padding between the legend items. + * @Default {20} + */ + itemPadding?: number; + + /** Options to customize the style of legend items. + */ + itemStyle?: LegendItemStyle; + + /** Opacity of the legend. + * @Default {1} + */ + opacity?: number; + + /** Places the legend at specified position. Legend can be placed at left, right, top or bottom of the circular gauge. + * @Default {Bottom. See Position} + */ + position?: ej.datavisualization.CircularGauge.LegendPosition | string; + + /** Shape of the legend items. + * @Default {Circle. See Shape} + */ + shape?: ej.datavisualization.CircularGauge.LegendShape | string; + + /** Options to customize the size of the legend. + */ + size?: LegendSize; + + /** Options to customize the font used for legend item text. + */ + font?: LegendFont; + } + export interface Tooltip { /** enable showCustomLabelTooltip of circular gauge @@ -46955,6 +48006,53 @@ declare namespace ej.datavisualization { } } + namespace CircularGauge { + enum LegendAlignment { + //string + Center, + //string + Near, + //string + Far, + } + } + + namespace CircularGauge { + enum LegendPosition { + //string + Left, + //string + Right, + //string + Top, + //string + Bottom, + } + } + + namespace CircularGauge { + enum LegendShape { + //string + Rectangle, + //string + Circle, + //string + Triangle, + //string + Ellipse, + //string + Diamond, + //string + Pentagon, + //string + Slider, + //string + Trapezoid, + //string + Line, + } + } + class DigitalGauge extends ej.Widget { static fn: DigitalGauge; constructor(element: JQuery | Element, options?: DigitalGauge.Model); @@ -47024,6 +48122,11 @@ declare namespace ej.datavisualization { */ isResponsive?: boolean; + /** Specifies the responsiveness of the Digital gauge + * @Default {false} + */ + enableResize?: boolean; + /** Specifies the items for the DigitalGauge. * @Default {null} */ @@ -47384,6 +48487,11 @@ declare namespace ej.datavisualization { */ animate(options: any): void; + /** Prints the rendered chart. + * @returns {void} + */ + print(): void; + /** Exports chart as an image or to an excel file. Chart can be exported as an image only when exportCanvasRendering option is set to true. * @param {string} Type of the export operation to be performed. Following are the two export types that are supported now,1. 'image'2. 'excel'Example * @param {string} URL of the service, where the chart will be exported to excel.Example, @@ -47599,6 +48707,9 @@ declare namespace ej.datavisualization { /** Fires before loading the chart. */ load?(e: LoadEventArgs): void; + /** Fires while performing rectangle zooming in chart. */ + zoomed?(e: ZoomedEventArgs): void; + /** Fires after selected the data in chart. */ rangeSelected?(e: RangeSelectedEventArgs): void; @@ -47694,15 +48805,15 @@ declare namespace ej.datavisualization { /** Instance of the corresponding axis. */ - Axis?: any; + axis?: any; /** Formatted text of the respective label. You can also add custom text to the label. */ - LabelText?: string; + Text?: string; /** Actual value of the label. */ - LabelValue?: string; + Value?: string; /** Set this option to true to cancel the event. */ @@ -48056,6 +49167,42 @@ declare namespace ej.datavisualization { */ type?: string; } + export interface ZoomedEventArgs { + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the chart model object + */ + model?: any; + + /** Name of the event + */ + type?: string; + + /** Selected data collection of object + */ + data?: any; + } + export interface RangeSelectedEventArgs { + + /** Set this option to true to cancel the event + */ + cancel?: boolean; + + /** Instance of the chart model object + */ + model?: any; + + /** Name of the event + */ + type?: string; + + /** Selected data collection of object + */ + data?: any; + } export interface RangeSelectedEventArgs { @@ -49765,6 +50912,11 @@ declare namespace ej.datavisualization { */ labelPosition?: ej.datavisualization.Chart.LabelPosition | string; + /** Specifies the mode for splitting the data points in pieOfPie series. + * @Default {value. See SplitMode} + */ + splitMode?: ej.datavisualization.Chart.SplitMode | string; + /** Quartile calculation has been performed in three different formulas to render the box and whisker series. * @Default {exclusive} */ @@ -49802,6 +50954,21 @@ declare namespace ej.datavisualization { */ pieCoefficient?: number; + /** Controls the size of the second pie in pieOfPie series. Value ranges from 0 to 1. + * @Default {0.6} + */ + pieOfPieCoefficient?: number; + + /** Split Value of pieofpie series. + * @Default {null} + */ + splitValue?: string; + + /** Distance between the two pie's in pieOfPie series. + * @Default {50} + */ + gapWidth?: number; + /** Name of the property in the datasource that contains fill color for the series. * @Default {null} */ @@ -51141,6 +52308,11 @@ declare namespace ej.datavisualization { */ multiLevelLabels?: PrimaryXAxisMultiLevelLabel[]; + /** Specifies whether the axis elements need to be placed nearby the axis line, while crossing. + * @Default {true} + */ + showNextToAxisLine?: boolean; + /** Options for customizing the strip lines. * @Default {[ ]} */ @@ -51818,6 +52990,11 @@ declare namespace ej.datavisualization { */ multiLevelLabels?: AxesMultiLevelLabel[]; + /** Specifies whether the axis elements need to be placed nearby the axis line, while crossing. + * @Default {true} + */ + showNextToAxisLine?: boolean; + /** Options for customizing the strip lines. * @Default {[ ]} */ @@ -52491,6 +53668,11 @@ declare namespace ej.datavisualization { */ multiLevelLabels?: PrimaryYAxisMultiLevelLabel[]; + /** Specifies whether the axis elements need to be placed nearby the axis line, while crossing. + * @Default {true} + */ + showNextToAxisLine?: boolean; + /** Options for customizing the strip lines. * @Default {[ ]} */ @@ -53719,6 +54901,11 @@ declare namespace ej.datavisualization { */ labelPosition?: ej.datavisualization.Chart.LabelPosition | string; + /** Specifies the mode for splitting the data points in pieOfPie series. + * @Default {value. See SplitMode} + */ + splitMode?: ej.datavisualization.Chart.SplitMode | string; + /** Quartile calculation has been performed in three different formulas to render the boxplot series . * @Default {exclusive} */ @@ -53761,6 +54948,21 @@ declare namespace ej.datavisualization { */ pieCoefficient?: number; + /** Controls the size of the second pie in pieOfPie series. Value ranges from 0 to 1. + * @Default {0.6} + */ + pieOfPieCoefficient?: number; + + /** Split Value of pieofpie series. + * @Default {null} + */ + splitValue?: string; + + /** Distance between the two pie's in pieOfPie series. + * @Default {50} + */ + gapWidth?: number; + /** Options for customizing the empty point in the series. */ emptyPointSettings?: SeriesEmptyPointSettings; @@ -54223,6 +55425,19 @@ declare namespace ej.datavisualization { OutsideExtended, } } + + namespace Chart { + enum SplitMode { + //string + Position, + //string + Value, + //string + Percentage, + //string + Indexes, + } + } namespace Chart { enum boxPlotMode { //string @@ -54719,6 +55934,11 @@ declare namespace ej.datavisualization { */ enableScrollbar?: boolean; + /** Enable the resize option in the rangenavigator. + * @Default {false} + */ + enableAutoResizing?: boolean; + /** Toggles the direction of rendering the range navigator control. * @Default {false} */ @@ -54813,6 +56033,12 @@ declare namespace ej.datavisualization { /** Fires on when starting to change the scrollbar position of range navigator. */ scrollStart?(e: ScrollStartEventArgs): void; + /** Fires on when starting to change the slider position of range navigator. */ + selectedRangeStart?(e: SelectedRangeStartEventArgs): void; + + /** Fires when the selection ends in the range navigator */ + selectedRangeEnd?(e: SelectedRangeEndEventArgs): void; + /** Fires on changes ending the scrollbar position of range navigator. */ scrollEnd?(e: ScrollEndEventArgs): void; } @@ -54928,6 +56154,19 @@ declare namespace ej.datavisualization { type?: string; } + export interface SelectedRangeStartEventArgs { + + /** if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + } + + export interface SelectedRangeEndEventArgs { + + /** if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + } export interface ScrollEndEventArgs { /** parameters from RangeNavigator @@ -55644,6 +56883,24 @@ declare namespace ej.datavisualization { width?: number; } + export interface ValueAxisSettingsRange { + + /** Default Value + * @Default {null} + */ + min?: number; + + /** Default Value + * @Default {null} + */ + max?: number; + + /** Default Value + * @Default {null} + */ + interval?: number; + } + export interface ValueAxisSettings { /** Options for customizing the axis line. @@ -55662,6 +56919,10 @@ declare namespace ej.datavisualization { */ majorTickLines?: ValueAxisSettingsMajorTickLines; + /** You can customize the range of the axis by setting minimum , maximum and interval. + */ + range?: ValueAxisSettingsRange; + /** If the range is not given explicitly, range will be calculated automatically. You can customize the automatic range calculation using rangePadding. * @Default {none} */ @@ -55827,6 +57088,11 @@ declare namespace ej.datavisualization { */ enableAnimation?: boolean; + /** Controls whether bullet graph has to be responsive while resizing. + * @Default {true} + */ + enableResizing?: boolean; + /** Specifies the direction of flow in bullet graph. Neither it may be backward nor forward. * @Default {forward} */ @@ -55842,6 +57108,16 @@ declare namespace ej.datavisualization { */ isResponsive?: boolean; + /** Specifies to convert the date object to string, using locale settings. + * @Default {false} + */ + enableGroupSeparator?: boolean; + + /** Name of the culture based on which bulletgraph should be localized. + * @Default {en-US} + */ + locale?: string; + /** Bullet graph will render in the specified orientation. * @Default {horizontal} */ @@ -55902,6 +57178,9 @@ declare namespace ej.datavisualization { /** Fires on rendering the labels. */ drawLabels?(e: DrawLabelsEventArgs): void; + /** Fires on rendering the ticks. */ + drawTicks?(e: DrawTicksEventArgs): void; + /** Fires on rendering the qualitative ranges. */ drawQualitativeRanges?(e: DrawQualitativeRangesEventArgs): void; @@ -56023,6 +57302,11 @@ declare namespace ej.datavisualization { labelType?: string; } + export interface DrawTicksEventArgs { + /** Returns the cancel option value. + */ + cancel?: boolean; + } export interface DrawQualitativeRangesEventArgs { /** returns the object of the bullet graph. @@ -57952,6 +59236,15 @@ declare namespace ej.datavisualization { /** Triggers on treemap item selected. */ treeMapItemSelected?(e: TreeMapItemSelectedEventArgs): void; + + /** Triggers when drilldown is started */ + drillStarted?(e: DrillStartedEventArgs): void; + + /** Triggers on treemap drilldown item selected. */ + drillDownItemSelected?(e: DrillDownItemSelectedEventArgs): void; + + /** Triggers after refreshing the treemap items. */ + refreshed?(e: RefreshedEventArgs): void; } export interface TreeMapItemSelectedEventArgs { @@ -57961,6 +59254,27 @@ declare namespace ej.datavisualization { originalEvent?: any; } + export interface DrillStartedEventArgs { + + /** Returns selected drilled treeMap object. + */ + originalEvent?: any; + } + + export interface DrillDownItemSelectedEventArgs { + + /** Returns selected drilldown treeMap object. + */ + originalEvent?: any; + } + + export interface RefreshedEventArgs { + + /** Refresh and load the treemap. + */ + originalEvent?: any; + } + export interface UniColorMapping { /** Specifies the uniform color mapping of the treemap @@ -58085,6 +59399,11 @@ declare namespace ej.datavisualization { */ borderThickness?: number; + /** Specifies the space between the leaf items. + * @Default {0} + */ + gap?: number; + /** Specifies the label template of the leaf item. * @Default {null} */ @@ -58392,13 +59711,13 @@ declare namespace ej.datavisualization { */ findNode(name: string): any; - /** Fit the diagram content into diagram viewport - * @param {string} to set the mode of fit to command. See [Fit Mode](/api/js/global#fitmode) - * @param {string} to set whether the region to be fit will be based on diagram elements or page settings [Region](/api/js/global#region) - * @param {any} to set the required margin - * @returns {void} - */ - fitToPage(mode?: string, region?: string, margin?: any): void; + /** Fit the diagram content into diagram viewport + * @param {ej.datavisualization.Diagram.FitMode} to set the mode of fit to command. + * @param {ej.datavisualization.Diagram.Region} to set whether the region to be fit will be based on diagram elements or page settings. + * @param {any} to set the required margin + * @returns {void} + */ + fitToPage(mode?: ej.datavisualization.Diagram.FitMode, region?: ej.datavisualization.Diagram.Region, margin?: any): void; /** Group the selected nodes and connectors * @returns {void} @@ -58617,17 +59936,17 @@ declare namespace ej.datavisualization { */ fileName?: string; - /** format of the exported file/data. See [File Formats](/api/js/global#fileformats). + /** format of the exported file/data. */ - format?: string; + format?: ej.datavisualization.Diagram.FileFormats; - /** to set whether to export diagram as a file or as raw data. See [Export Modes](/api/js/global#exportmodes). + /** to set whether to export diagram as a file or as raw data. */ - mode?: string; + mode?: ej.datavisualization.Diagram.ExportModes; - /** to set the region of the diagram to be exported. See [Region](/api/js/global#region). + /** to set the region of the diagram to be exported. */ - region?: string; + region?: ej.datavisualization.Diagram.Region; /** to export any custom region of diagram. */ @@ -58637,9 +59956,9 @@ declare namespace ej.datavisualization { */ margin?: any; - /** to set stretch to the exported data. + /** to resize the diagram content to fill its allocated space. */ - stretch?: string; + stretch?: ej.datavisualization.Diagram.Stretch; } export interface Zoom { @@ -58925,6 +60244,10 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter to specify whether or not to cancel the event + */ + cancel?: boolean; } export interface ConnectionChangeEventArgs { @@ -59052,6 +60375,17 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + /** parameter returns whether or not to cancel the dragOver event + */ + cancel?: boolean; + + /** parameter returns the actual click event arguments that explains which button is clicked + */ + model?: any; + + /** parameter returns the type of the event triggered + */ + type?: string; } export interface ContextMenuClickEventArgs { @@ -59083,6 +60417,22 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter to specify whether or not to cancel the event + */ + cancel?: boolean; + + /** parameter returns the elementof the object that was clicked + */ + element?: any; + + /** parameter returns the object that is selected + */ + selectedItem?: any; + + /** parameter returns the model of the diagram + */ + events?: any; } export interface DoubleClickEventArgs { @@ -59098,6 +60448,10 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter to specify whether or not to cancel the event + */ + cancel?: boolean; } export interface DragEventArgs { @@ -59125,6 +60479,10 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter returns the offset of the selecteditems + */ + offset?: any; } export interface DragEnterEventArgs { @@ -59148,6 +60506,10 @@ declare namespace ej.datavisualization { */ element?: any; + /** parameter returns whether or not to cancel the dragOver event + */ + cancel?: boolean; + /** parameter returns the id of the diagram */ diagramId?: string; @@ -59204,7 +60566,7 @@ declare namespace ej.datavisualization { /** parameter returns the enum which defines the type of the source */ - sourceType?: string; + objectType?: string; /** parameter returns the id of the diagram */ @@ -59212,7 +60574,7 @@ declare namespace ej.datavisualization { } export interface EditorFocusChangeEventArgs { - /** Returns the cancel option value. + /** parameter to specify whether or not to cancel the event */ cancel?: boolean; } @@ -59253,6 +60615,14 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter to specify whether or not to cancel the event + */ + cancel?: boolean; + + /** parameter returns the model of the diagram + */ + cause?: boolean; } export interface ItemClickEventArgs { @@ -59269,7 +60639,7 @@ declare namespace ej.datavisualization { */ cancel?: boolean; - /** parameter returns the actual click event arguments that explains which button is clicked + /** parameter returns the model of the diagram */ event?: any; @@ -59295,6 +60665,10 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter returns whether or not to cancel the dragOver event + */ + cancel?: boolean; } export interface MouseLeaveEventArgs { @@ -59311,6 +60685,10 @@ declare namespace ej.datavisualization { */ target?: any; + /** parameter returns whether or not to cancel the dragOver event + */ + cancel?: boolean; + /** parameter returns the id of the diagram */ diagramId?: string; @@ -59330,6 +60708,10 @@ declare namespace ej.datavisualization { */ target?: any; + /** parameter returns whether or not to cancel the dragOver event + */ + cancel?: boolean; + /** parameter returns the id of the diagram */ diagramId?: string; @@ -59383,6 +60765,10 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter defines whether to cancel the property change or not + */ + cancel?: boolean; } export interface RotationChangeEventArgs { @@ -59406,6 +60792,10 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter returns the actual click event arguments that explains which button is clicked + */ + cause?: string; } export interface ScrollChangeEventArgs { @@ -59418,9 +60808,17 @@ declare namespace ej.datavisualization { */ oldValues?: any; + /** parameter returns whether or not to cancel the dragOver event + */ + cancel?: boolean; + /** parameter returns the id of the diagram */ diagramId?: string; + + /** Parameter returns the new zoom value, horizontal and vertical scroll offsets. + */ + cause?: string; } export interface SegmentChangeEventArgs { @@ -59472,14 +60870,18 @@ declare namespace ej.datavisualization { */ cancel?: boolean; - /** triggers before and after adding the selection to the object in the diagram which can be differentiated through `state` argument. - * We can cancel the event only before the selection of the object. + /** triggers before and after adding the selection to the object in the diagram which can be differentiated through `state` argument. We can cancel the event only + * before the selection of the object. */ state?: string; /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter returns the actual cause of the event + */ + cause?: string; } export interface SizeChangeEventArgs { @@ -59511,6 +60913,10 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter returns the direction of the node is resized + */ + direction?: string; } export interface TextChangeEventArgs { @@ -59530,6 +60936,10 @@ declare namespace ej.datavisualization { /** parameter returns the id of the diagram */ diagramId?: string; + + /** parameter to specify whether or not to cancel the event + */ + cancel?: boolean; } export interface CreateEventArgs { @@ -60173,6 +61583,105 @@ declare namespace ej.datavisualization { showCustomMenuItemsOnly?: boolean; } + export interface DataSourceSettingsCrudAction { + + /** Specifies the create method which is used to get the nodes to be added from client side to the server side + * @Default {null} + */ + create?: string; + + /** Specifies the update method which is used to get the updated data from client side to the server side + * @Default {null} + */ + update?: string; + + /** Specifies the destroy method which is used to get the deleted items data from client side to the server side + * @Default {null} + */ + destroy?: string; + + /** Specifies the read method to get the created nodes from client side to the server side + * @Default {null} + */ + read?: string; + } + + export interface DataSourceSettingsConnectionDataSourceCrudAction { + + /** Specifies the create method which is used to get the connectors to be added from client side to the server side + * @Default {null} + */ + create?: string; + + /** Specifies the update method which is used to get the updated connectors from client side to the server side + * @Default {null} + */ + update?: string; + + /** Specifies the destroy method which is used to get the deleted items data from client side to the server side + * @Default {null} + */ + destroy?: string; + + /** Specifies the read method which is used to get the data from client side to the server side + * @Default {null} + */ + read?: string; + } + + export interface DataSourceSettingsConnectionDataSource { + + /** Sets the datasource for the connection datasource settings items. + * @Default {null} + */ + dataSource?: string; + + /** Sets the unique id of the connection data source item + * @Default {null} + */ + id?: string; + + /** Sets the sourcenode of the connection data source item + * @Default {null} + */ + sourceNode?: string; + + /** Sets the targetnode of the connection data source item + * @Default {null} + */ + targetNode?: string; + + /** Sets the sourcepoint-x value of the connection data source item + * @Default {null} + */ + sourcePointX?: string; + + /** Sets the sourcePoint-y value of the connection data source item + * @Default {null} + */ + sourcePointY?: string; + + /** Sets the targetPoint-x value of the connection data source item + * @Default {null} + */ + targetPointX?: string; + + /** Sets the targetPoint-y value of the connection data source item + * @Default {null} + */ + targetPointY?: string; + + /** Specifies the method name which is used to get updated connectors from client side to the server side + * @Default {null} + */ + crudAction?: DataSourceSettingsConnectionDataSourceCrudAction; + + /** Specifies the customfields to get the updated data from client side to the server side + * @Default {[]} + */ + customFields?: any[]; + } + export interface DataSourceSettings { /** Defines the data source either as a collection of objects or as an instance of ej.DataManager @@ -60202,6 +61711,21 @@ declare namespace ej.datavisualization { * @Default {null} */ tableName?: string; + + /** Specifies the method name which is used to get the updated data from client side to the server side + * @Default {null} + */ + crudAction?: DataSourceSettingsCrudAction; + + /** Specifies the customfields to get the updated data from client side to the server side + * @Default {[]} + */ + customFields?: any[]; + + /** Defines the data source either as a collection of objects or as an instance of ej.DataManager + * @Default {null} + */ + connectionDataSource?: DataSourceSettingsConnectionDataSource; } export interface DefaultSettings { @@ -60285,6 +61809,11 @@ declare namespace ej.datavisualization { */ getLayoutInfo?: any; + /** Defines a method to customize the segments based on source and target nodes. + * @Default {null} + */ + getConnectorSegments?: any; + /** Sets the space to be horizontally left between nodes * @Default {30} */ @@ -61534,6 +63063,10 @@ declare namespace ej.datavisualization { export interface SelectedItemsUserHandle { + /** Defines the name of the user handle + */ + name?: string; + /** Defines the background color of the user handle * @Default {#2382c3} */ @@ -62691,6 +64224,57 @@ declare namespace ej.datavisualization { Mouse, } } + namespace Diagram { + enum FileFormats { + //Used to export the diagram into JPG format. + JPG, + //Used to export the diagram into PNG format. + PNG, + //Used to export the diagram into BMP format. + BMP, + //Used to export the diagram into SVG format. + SVG, + } + } + namespace Diagram { + enum ExportModes { + //Used to export the diagram as a file. + Download, + //Used to export the diagram as raw data. + Data, + } + } + namespace Diagram { + enum Region { + //Used to export the content of the diagram only. + Content, + //Used to export the page region of the diagram. + PageSettings, + } + } + namespace Diagram { + enum Stretch { + //The diagram content preserves its original size. + None, + //The diagram content is resized to fill the destination dimensions. The aspect ratio is not preserved. + Fill, + //The diagram content is resized to fit in the destination dimensions while it preserves its native aspect ratio. + Uniform, + //The diagram content is resized to fill the destination dimensions while it preserves its native aspect ratio. If the aspect ratio of the destination rectangle differs from the source, + //the source content is clipped to fit in the destination dimensions. + UniformToFill, + } + } + namespace Diagram { + enum FitMode { + //Used to fit the diagram content based on page size. + Page, + //Used to fit the diagram content based on diagram width. + Width, + //Used to fit the diagram content based on diagram height. + Height, + } + } namespace Diagram { enum ZoomCommand { //Used to zoom in the Diagram @@ -63378,6 +64962,11 @@ declare namespace ej.datavisualization { */ rangeBandSettings?: RangeBandSettings; + /** Name of the culture based on which sparkline should be localized. + * @Default {en-US} + */ + locale?: string; + /** Name of a field in data source, where the fill color for all the data points is generated. */ palette?: string; @@ -63392,6 +64981,11 @@ declare namespace ej.datavisualization { */ enableCanvasRendering?: boolean; + /** Specify to convert the date object to string, using locale settings. + * @Default {false} + */ + enableGroupSeparator?: boolean; + /** Specifies the dataSource for the series. It can be an array of JSON objects or an instance of ej.DataManager. * @Default {null} */ @@ -65079,6 +66673,7 @@ declare namespace ej.datavisualization { } + interface JQueryXHR { /** * Returns the cancel option value. @@ -65243,6 +66838,9 @@ interface JQuery { ejPivotTreeMap(options?: ej.PivotTreeMap.Model): JQuery; ejPivotTreeMap(memberName: any, value?: any, param?: any): any; + ejPrint(options?: ej.Print.Model): JQuery; + ejPrint(memberName: any, value?: any, param?: any): any; + ejProgressBar(options?: ej.ProgressBar.Model): JQuery; ejProgressBar(memberName: any, value?: any, param?: any): any; @@ -65401,6 +66999,7 @@ interface JQuery { data(key: "ejPivotPager"): ej.PivotPager; data(key: "ejPivotSchemaDesigner"): ej.PivotSchemaDesigner; data(key: "ejPivotTreeMap"): ej.PivotTreeMap; + data(key: "ejPrint"): ej.Print; data(key: "ejProgressBar"): ej.ProgressBar; data(key: "ejRadialMenu"): ej.RadialMenu; data(key: "ejRadialSlider"): ej.RadialSlider; From a2415a9ba3f08ec1bb81d2c1d8895f82152485b7 Mon Sep 17 00:00:00 2001 From: Walter Rumsby Date: Fri, 9 Jun 2017 13:16:04 +1200 Subject: [PATCH 84/98] [react-select] Update types for loadOptions to support Async options with Promises (#16664) * Update types for loadOptions to support Async options with Promises As per https://github.com/JedWatson/react-select#async-options-with-promises * Add test * Updates based on PR comments --- types/react-select/index.d.ts | 4 +- types/react-select/react-select-tests.tsx | 46 +++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index 361dcfecc2..a3c2cf7881 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -434,7 +434,9 @@ declare namespace ReactSelectClass { /** * function to call to load options asynchronously */ - loadOptions: (input: string, callback: (err: any, result: AutocompleteResult) => any) => any; + loadOptions: + | ((input: string) => Promise) + | ((input: string, callback: (err: any, result: AutocompleteResult) => void) => void); /** * replaces the placeholder while options are loading diff --git a/types/react-select/react-select-tests.tsx b/types/react-select/react-select-tests.tsx index 972a1dacdc..5d603c9259 100644 --- a/types/react-select/react-select-tests.tsx +++ b/types/react-select/react-select-tests.tsx @@ -209,6 +209,52 @@ class SelectAsyncTest extends React.Component, {}> { } +class SelectAsyncPromiseTest extends React.Component, {}> { + + render() { + const getOptions = (input: string): Promise => { + return new Promise(resolve => { + setTimeout(function() { + return resolve({ + options: options, + complete: true + }); + }, 500); + }); + }; + const options: Option[] = [{ label: "Foo", value: "bar" }]; + const onChange = (value: any) => console.log(value); + + const asyncSelectProps: ReactAsyncSelectProps = { + name: "test-select-async-promise", + className: "test-select", + key: "1", + matchPos: "any", + matchProp: "any", + multi: true, + onValueClick: onChange, + valueKey: "github", + labelKey: "name", + onChange: onChange, + simpleValue: undefined, + value: options, + loadOptions: getOptions, + cache: {}, + ignoreAccents: false, + ignoreCase: true, + isLoading: false, + minimumInput: 5, + searchPromptText: "search...", + searchingText: "searching...", + }; + + return
+ +
; + } + +} + class SelectCreatableTest extends React.Component, {}> { render() { From 424873bdfaa0bb226d5525538ff6482d4bebb139 Mon Sep 17 00:00:00 2001 From: beary Date: Fri, 9 Jun 2017 09:37:32 +0800 Subject: [PATCH 85/98] Add default generic to FindAndModify... interface --- types/mongodb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index a7c73e0799..ebe427a427 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -741,7 +741,7 @@ export interface DeleteWriteOpResultObject { } //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#~findAndModifyWriteOpResult -export interface FindAndModifyWriteOpResultObject { +export interface FindAndModifyWriteOpResultObject { //Document returned from findAndModify command. value?: TSchema; //The raw lastErrorObject returned from the command. From b937fd61dc391cbae5469538af4b8c0e54aa856d Mon Sep 17 00:00:00 2001 From: Maximilian Heinz Date: Fri, 9 Jun 2017 11:26:58 +0200 Subject: [PATCH 86/98] fix(reduxMockStore): mock store should return Redux.Store instead of own IStore --- types/redux-mock-store/index.d.ts | 15 ++++++--------- types/redux-mock-store/package.json | 5 +++-- types/redux-mock-store/redux-mock-store-tests.ts | 7 +++---- 3 files changed, 12 insertions(+), 15 deletions(-) diff --git a/types/redux-mock-store/index.d.ts b/types/redux-mock-store/index.d.ts index 9183423bfd..46846cd248 100644 --- a/types/redux-mock-store/index.d.ts +++ b/types/redux-mock-store/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Redux Mock Store v0.0.6 +// Type definitions for Redux Mock Store v0.0.7 // Project: https://github.com/arnaudbenard/redux-mock-store // Definitions by: Marian Palkus , Cap3 // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -6,19 +6,16 @@ /// declare module 'redux-mock-store' { - import * as Redux from 'redux' + import * as Redux from 'redux'; function createMockStore(middlewares?: Redux.Middleware[]): mockStore; - export type mockStore = (state?: T) => IStore; - - export interface IStore { - dispatch(action: any): any; - getState(): T; + interface MockStore { getActions(): any[]; clearActions(): void; - subscribe(listener: Function): Function; } - export default createMockStore + export type mockStore = (state?: T) => Redux.Store & MockStore; + + export default createMockStore; } diff --git a/types/redux-mock-store/package.json b/types/redux-mock-store/package.json index e52256ea90..1c5803bcd8 100644 --- a/types/redux-mock-store/package.json +++ b/types/redux-mock-store/package.json @@ -1,5 +1,6 @@ { "dependencies": { - "redux": "^3.6.0" + "redux": "^3.6.0", + "redux-mock-store": "^1.2.3" } -} \ No newline at end of file +} diff --git a/types/redux-mock-store/redux-mock-store-tests.ts b/types/redux-mock-store/redux-mock-store-tests.ts index 15d51d1f23..0937e70654 100644 --- a/types/redux-mock-store/redux-mock-store-tests.ts +++ b/types/redux-mock-store/redux-mock-store-tests.ts @@ -1,5 +1,5 @@ import * as Redux from 'redux'; -import configureStore, {IStore} from 'redux-mock-store'; +import configureStore from 'redux-mock-store'; // Redux store API tests // The following test are taken from ../redux/redux-tests.ts @@ -26,9 +26,8 @@ function loggingMiddleware() { const storeMock = configureStore([loggingMiddleware]); const initialState = 0 -let store: IStore; -store = storeMock(initialState); +const store = storeMock(initialState); store.subscribe(() => { // ... @@ -44,4 +43,4 @@ store.clearActions(); // actions access without the need to cast var actions2 = store.getActions(); -actions2[10].payload.id; \ No newline at end of file +actions2[10].payload.id; From 9dace9e9bd693a541d6f109159624b47df599738 Mon Sep 17 00:00:00 2001 From: Maximilian Heinz Date: Fri, 9 Jun 2017 12:06:02 +0200 Subject: [PATCH 87/98] refactor(redux-mock-store): extend Redux.Store instead of using intersection --- types/redux-mock-store/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/redux-mock-store/index.d.ts b/types/redux-mock-store/index.d.ts index 46846cd248..e8d4cced5e 100644 --- a/types/redux-mock-store/index.d.ts +++ b/types/redux-mock-store/index.d.ts @@ -10,12 +10,12 @@ declare module 'redux-mock-store' { function createMockStore(middlewares?: Redux.Middleware[]): mockStore; - interface MockStore { + interface MockStore extends Redux.Store { getActions(): any[]; clearActions(): void; } - export type mockStore = (state?: T) => Redux.Store & MockStore; + export type mockStore = (state?: T) => MockStore; export default createMockStore; } From 08f784aa8dbbb611aa6ef8d08869f1f2e3f6606f Mon Sep 17 00:00:00 2001 From: Kacper Polak Date: Fri, 9 Jun 2017 12:59:04 +0200 Subject: [PATCH 88/98] Deprecated res.status ``res.send(status, body)`` is deprecated. Use ``res.status(status).send(body)`` instead --- types/express-serve-static-core/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index 8e1f075f03..a24e96d144 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -475,7 +475,6 @@ interface MediaType { } interface Send { - (status: number, body?: any): Response; (body?: any): Response; } From 0a705ea0462c897568685575669b6cfcf7a038de Mon Sep 17 00:00:00 2001 From: Kacper Polak Date: Fri, 9 Jun 2017 13:14:08 +0200 Subject: [PATCH 89/98] Update contributors I just want to review code next time --- types/express-serve-static-core/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index a24e96d144..dd012cab4e 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Express 4.x // Project: http://expressjs.com -// Definitions by: Boris Yankov , Michał Lytek +// Definitions by: Boris Yankov , Michał Lytek , Kacper Polak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // This extracts the core definitions from express to prevent a circular dependency between express and serve-static /// From 3b2f53cf6acd51b136f6c62e0ceef841b6a0adea Mon Sep 17 00:00:00 2001 From: Christian Date: Sat, 10 Jun 2017 00:05:33 +0200 Subject: [PATCH 90/98] hapi: fix incorrect connection.table() result type (#17070) --- types/hapi/index.d.ts | 19 ++++++++++++++++--- types/hapi/test/connection/table.ts | 2 ++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 9b03944e9a..efce9f3dc4 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1256,13 +1256,14 @@ export interface RoutingTableEntry { /** * [See docs](https://hapijs.com/api/16.1.1#servertablehost) > return value + * For source [See source](https://github.com/hapijs/hapi/blob/v16.1.1/lib/route.js#L71) */ export interface Route { /** * the route config with defaults applied. * TODO check type of RouteConfiguration here is correct */ - settings: RouteConfiguration; + settings: RouteAdditionalConfigurationOptions; /** * the HTTP method in lower case. * TODO, check if it can contain 'head' or not. @@ -1270,6 +1271,18 @@ export interface Route { method: HTTP_METHODS_PARTIAL_lowercase; /** the route path. */ path: string; + + params: string[]; + + connection: ServerConnection; + + fingerprint: string; + + plugin?: any; + + public: RoutePublicInterface; + + server: Server; } /** @@ -1618,8 +1631,8 @@ export interface ServerConnection { /** Described in server.inject [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) */ inject(options: string | InjectedRequestOptions, callback: (res: InjectedResponseObject) => void): void; inject(options: string | InjectedRequestOptions, ): Promise; - /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#servertablehost) */ - table(host?: string): RoutingTableEntry; + /** Mentioned but not documented under server.connections [See docs](https://hapijs.com/api/16.1.1#serverconnections) */ + table(host?: string): Route[]; /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#serverlookupid) */ lookup(id: string): RoutePublicInterface | null; /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#servermatchmethod-path-host) */ diff --git a/types/hapi/test/connection/table.ts b/types/hapi/test/connection/table.ts index dee4741b07..24eaa28ddc 100644 --- a/types/hapi/test/connection/table.ts +++ b/types/hapi/test/connection/table.ts @@ -18,3 +18,5 @@ const table = connection.table(); } ] */ + +table.map(({method, path, settings: {description}}) => { }); From a6adbf4108231cb8735ccaf862154b978c740892 Mon Sep 17 00:00:00 2001 From: Clark Stevenson Date: Sat, 10 Jun 2017 00:54:32 +0100 Subject: [PATCH 91/98] Pixi.js v4.5 Update --- types/pixi.js/index.d.ts | 764 +++++++++++++++++++++------------ types/pixi.js/pixi.js-tests.ts | 5 +- 2 files changed, 501 insertions(+), 268 deletions(-) diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index 88ed75eced..bcf403d475 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Pixi.js 4.4 +// Type definitions for Pixi.js 4.5 // Project: https://github.com/pixijs/pixi.js/tree/dev // Definitions by: clark-stevenson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -20,8 +20,10 @@ declare namespace PIXI { const GC_MODES: typeof CONST.GC_MODES; const SHAPES: typeof CONST.SHAPES; const TEXT_GRADIENT: typeof CONST.TEXT_GRADIENT; + const UPDATE_PRIORITY: typeof CONST.UPDATE_PRIORITY; - function autoDetectRenderer(width: number, height: number, options?: PIXI.IRendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; + function autoDetectRenderer(width: number, height: number, options?: PIXI.RendererOptions, forceCanvas?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; + function autoDetectRenderer(options?: PIXI.RendererOptions): PIXI.WebGLRenderer | PIXI.CanvasRenderer; const loader: PIXI.loaders.Loader; ////////////////////////////////////////////////////////////////////////////// @@ -46,6 +48,9 @@ declare namespace PIXI { clearBeforeRender: boolean, preserveDrawingBuffer: boolean, roundPixels: boolean + width: number, + height: number, + legacy: boolean, }; let TRANSFORM_MODE: number; let GC_MODE: number; @@ -53,6 +58,8 @@ declare namespace PIXI { let GC_MAX_CHECK_COUNT: number; let WRAP_MODE: number; let SCALE_MODE: number; + let PRECISION_VERTEX: string; + let PRECISION_FRAGMENT: string; let PRECISION: string; let UPLOADS_PER_FRAME: number; let CAN_UPLOAD_SAME_BUFFER: boolean; @@ -66,20 +73,19 @@ declare namespace PIXI { // accessibility class AccessibilityManager { constructor(renderer: CanvasRenderer | WebGLRenderer); - + activate(): void; + deactivate(): void; protected div: HTMLElement; protected pool: HTMLElement[]; protected renderId: number; debug: boolean; renderer: SystemRenderer; - protected children: IAccessibleTarget[]; + protected children: AccessibleTarget[]; protected isActive: boolean; - protected activate(): void; - protected deactivate(): void; protected updateAccessibleObjects(displayObject: DisplayObject): void; protected update(): void; - protected capHitArea(hitArea: IHitArea): void; + protected capHitArea(hitArea: HitArea): void; protected addChild(displayObject: DisplayObject): void; protected _onClick(e: interaction.InteractionEvent): void; protected _onFocus(e: interaction.InteractionEvent): void; @@ -89,7 +95,7 @@ declare namespace PIXI { destroy(): void; } - interface IAccessibleTarget { + interface AccessibleTarget { accessible: boolean; accessibleTitle: string | null; accessibleHint: string | null; @@ -132,6 +138,9 @@ declare namespace PIXI { SATURATION: number; COLOR: number; LUMINOSITY: number; + NORMAL_NPM: number; + ADD_NPM: number; + SCREEN_NPM: number; }; const DRAW_MODES: { POINTS: number; @@ -179,11 +188,18 @@ declare namespace PIXI { LINEAR_VERTICAL: number; LINEAR_HORIZONTAL: number; }; + const UPDATE_PRIORITY: { + INTERACTION: number; + HIGH: number; + NORMAL: number; + LOW: number; + UTILITY: number; + }; } // display - interface IApplicationOptions extends IRendererOptions { + interface ApplicationOptions extends RendererOptions { view?: HTMLCanvasElement; transparent?: boolean; autoResize?: boolean; @@ -195,10 +211,16 @@ declare namespace PIXI { context?: WebGLRenderingContext; preserveDrawingBuffer?: boolean; legacy?: boolean; + width?: number; + height?: number; + forceCanvas?: boolean; + sharedTicker?: boolean; + sharedLoader?: boolean; } class Application { - constructor(width?: number, height?: number, options?: IApplicationOptions, noWebGL?: boolean, useSharedTicker?: boolean); + constructor(options?: ApplicationOptions) + constructor(width?: number, height?: number, options?: ApplicationOptions, noWebGL?: boolean, sharedTicker?: boolean, sharedLoader?: boolean); private _ticker: ticker.Ticker; @@ -214,7 +236,7 @@ declare namespace PIXI { readonly view: HTMLCanvasElement; } - interface IDestroyOptions { + interface DestroyOptions { children?: boolean; texture?: boolean; baseTexture?: boolean; @@ -266,17 +288,18 @@ declare namespace PIXI { protected _renderWebGL(renderer: WebGLRenderer): void; protected _renderCanvas(renderer: CanvasRenderer): void; renderCanvas(renderer: CanvasRenderer): void; - destroy(options?: IDestroyOptions | boolean): void; + destroy(options?: DestroyOptions | boolean): void; - once(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): this; - once(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): this; + once(event: "added" | "removed", fn: (displayObject: DisplayObject) => void, context?: any): this; + //tslint:disable-next-line:ban-types forbidden-types once(event: string, fn: Function, context?: any): this; - on(event: "added", fn: (displayObject: DisplayObject) => void, context?: any): this; - on(event: "removed", fn: (DisplayObject: DisplayObject) => void, context?: any): this; + on(event: "added" | "removed", fn: (displayObject: DisplayObject) => void, context?: any): this; + //tslint:disable-next-line:ban-types forbidden-types on(event: string, fn: Function, context?: any): this; - off(event: string, fn: Function, context?: any): this; + //tslint:disable-next-line:ban-types forbidden-types + off(event: "added" | "removed" | string, fn?: Function, context?: any): this; } - class DisplayObject extends utils.EventEmitter implements interaction.InteractiveTarget, accessibility.IAccessibleTarget { + class DisplayObject extends utils.EventEmitter implements interaction.InteractiveTarget, accessibility.AccessibleTarget { // begin extras.cacheAsBitmap protected _cacheAsBitmap: boolean; protected _cacheData: boolean; @@ -288,7 +311,7 @@ declare namespace PIXI { protected _calculateCachedBounds(): Rectangle; protected _getCachedLocalBounds(): Rectangle; protected _destroyCachedDisplayObject(): void; - protected _cacheAsBitmapDestroy(): void; + protected _cacheAsBitmapDestroy(options: boolean | any): void; // end extras.cacheAsBitmap // begin extras.getChildByName @@ -332,14 +355,15 @@ declare namespace PIXI { protected _boundsRect: Rectangle; protected _localBoundsRect: Rectangle; protected _mask: PIXI.Graphics | PIXI.Sprite; + protected readonly _destroyed: boolean; x: number; y: number; worldTransform: Matrix; localTransform: Matrix; - position: Point; - scale: Point; - pivot: Point; - skew: Point; + position: Point | ObservablePoint; + scale: Point | ObservablePoint; + pivot: Point | ObservablePoint; + skew: ObservablePoint; rotation: number; worldVisible: boolean; mask: PIXI.Graphics | PIXI.Sprite; @@ -350,55 +374,27 @@ declare namespace PIXI { protected _recursivePostUpdateTransform(): void; getBounds(skipUpdate?: boolean, rect?: Rectangle): Rectangle; getLocalBounds(rect?: Rectangle): Rectangle; - toGlobal(position: Point, point?: Point, skipUpdate?: boolean): Point; - toLocal(position: Point, from?: DisplayObject, point?: Point, skipUpdate?: boolean): Point; + //creates and returns a new point + toGlobal(position: PointLike): Point; + //modifies the x and y of the passed point and returns it + toGlobal(position: PointLike, point?: T, skipUpdate?: boolean): T; + //creates and returns a new point + toLocal(position: PointLike, from?: DisplayObject): Point; + //modifies the x and y of the passed point and returns it + toLocal(position: PointLike, from?: DisplayObject, point?: T, skipUpdate?: boolean): T; renderWebGL(renderer: WebGLRenderer): void; renderCanvas(renderer: CanvasRenderer): void; setParent(container: Container): Container; setTransform(x?: number, y?: number, scaleX?: number, scaleY?: number, rotation?: number, skewX?: number, skewY?: number, pivotX?: number, pivotY?: number): DisplayObject; destroy(): void; - on(event: string, fn: Function, context?: any): this; - once(event: string, fn: Function, context?: any): this; - off(event: string, fn: Function, context?: any): this; - - /* - on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - - once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): this; - */ + on(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; + once(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; + removeListener(event: interaction.InteractionEventTypes, fn?: (event: interaction.InteractionEvent) => void, context?: any): this; + removeAllListeners(event: interaction.InteractionEventTypes): this; + off(event: interaction.InteractionEventTypes, fn?: (event: interaction.InteractionEvent) => void, context?: any): this; + addListener(event: interaction.InteractionEventTypes, fn: (event: interaction.InteractionEvent) => void, context?: any): this; } - class TransformBase { static IDENTITY: TransformBase; @@ -429,7 +425,6 @@ declare namespace PIXI { updateLocalTransform(): void; updateTransform(parentTransform: TransformBase): void; setFromMatrix(matrix: Matrix): void; - rotation: number; } class Transform extends TransformBase { @@ -453,9 +448,7 @@ declare namespace PIXI { rotation: number; } - // graphics - class GraphicsData { constructor( lineWidth: number, @@ -465,8 +458,7 @@ declare namespace PIXI { fillAlpha: number, fill: boolean, nativeLines: boolean, - shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon); - + shape: Circle | Rectangle | Ellipse | Polygon | RoundedRectangle | any); lineWidth: number; nativeLines: boolean; lineColor: number; @@ -476,12 +468,12 @@ declare namespace PIXI { fillAlpha: number; protected _fillTint: number; fill: boolean; - protected holes: IShape[]; - shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon; + protected holes: Circle[] | Rectangle[] | Ellipse[] | Polygon[] | RoundedRectangle[] | any[]; + shape: Circle | Rectangle | Ellipse | Polygon | RoundedRectangle | any; type?: number; clone(): GraphicsData; - addHole(shape: IShape | Circle | Rectangle | RoundedRectangle | Ellipse | Polygon): void; - destroy(options?: IDestroyOptions | boolean): void; + addHole(shape: Circle | Rectangle | Ellipse | Polygon | RoundedRectangle | any): void; + destroy(options?: DestroyOptions | boolean): void; } class Graphics extends Container { constructor(nativeLines?: boolean); @@ -499,7 +491,7 @@ declare namespace PIXI { isMask: boolean; boundsPadding: number; protected _localBounds: Bounds; - dirty: boolean; + dirty: number; fastRectDirty: number; clearDirty: number; boundsDirty: number; @@ -531,11 +523,11 @@ declare namespace PIXI { protected _renderSpriteRect(renderer: PIXI.SystemRenderer): void; containsPoint(point: Point): boolean; updateLocalBounds(): void; - drawShape(shape: IShape | Circle | Rectangle | Ellipse | Polygon | RoundedRectangle): GraphicsData; + drawShape(shape: Circle | Rectangle | Ellipse | Polygon | RoundedRectangle | any): GraphicsData; generateCanvasTexture(scaleMode?: number, resolution?: number): Texture; protected closePath(): Graphics; protected addHole(): Graphics; - destroy(options?: IDestroyOptions | boolean): void; + destroy(options?: DestroyOptions | boolean): void; } class CanvasGraphicsRenderer { constructor(renderer: SystemRenderer); @@ -556,10 +548,10 @@ declare namespace PIXI { destroy(): void; render(graphics: Graphics): void; protected updateGraphics(graphics: PIXI.Graphics): void; - getWebGLData(webGL: WebGLRenderingContext, type: number): WebGLGraphicsData; + getWebGLData(webGL: WebGLRenderingContext, type: number, nativeLines: number): WebGLGraphicsData; } class WebGLGraphicsData { - constructor(gl: WebGLRenderingContext, shader: glCore.GLShader, attribsState: glCore.IAttribState); + constructor(gl: WebGLRenderingContext, shader: glCore.GLShader, attribsState: glCore.AttribState); gl: WebGLRenderingContext; color: number[]; @@ -572,6 +564,7 @@ declare namespace PIXI { glIndices: number[]; shader: glCore.GLShader; vao: glCore.VertexArrayObject; + nativeLines: boolean; reset(): void; upload(): void; @@ -592,7 +585,6 @@ declare namespace PIXI { const NE: number; const MIRROR_HORIZONTAL: number; const MIRROR_VERTICAL: number; - function uX(ind: number): number; function uY(ind: number): number; function vX(ind: number): number; @@ -635,32 +627,24 @@ declare namespace PIXI { static IDENTITY: Matrix; static TEMP_MATRIX: Matrix; } - class ObservablePoint { - constructor(cb: Function, scope?: any, x?: number, y?: number); - + class PointLike { x: number; y: number; + + set(x?: number, y?: number): void; + copy(point: PointLike): void; + } + class ObservablePoint extends PointLike { + constructor(cb: () => any, scope?: any, x?: number, y?: number); cb: () => any; scope: any; - - set(x?: number, y?: number): void; - copy(point: Point | ObservablePoint): void; } - class Point { + class Point extends PointLike { constructor(x?: number, y?: number); - - x: number; - y: number; - clone(): Point; - copy(p: Point): void; - equals(p: Point): boolean; - set(x?: number, y?: number): void; + equals(p: PointLike): boolean; } - - interface IShape { - } - interface IHitArea extends IShape { + interface HitArea { contains(x: number, y: number): boolean; } class Circle { @@ -690,7 +674,10 @@ declare namespace PIXI { } class Polygon { constructor(points: Point[] | number[]); + // Note - Rest Params cannot be combined with | + //tslint:disable-next-line:unified-signatures constructor(...points: Point[]); + //tslint:disable-next-line:unified-signatures constructor(...points: number[]); closed: boolean; @@ -736,10 +723,8 @@ declare namespace PIXI { clone(): RoundedRectangle; contains(x: number, y: number): boolean; } - // renderers - - interface IRendererOptions { + interface RendererOptions { view?: HTMLCanvasElement; transparent?: boolean; autoResize?: boolean; @@ -749,11 +734,16 @@ declare namespace PIXI { backgroundColor?: number; roundPixels?: boolean; context?: WebGLRenderingContext; + width?: number; + height?: number; + forceCanvas?: boolean; } class SystemRenderer extends utils.EventEmitter { - constructor(system: string, screenWidth?: number, screenHeight?: number, options?: IRendererOptions); + constructor(system: string, options?: RendererOptions); + constructor(system: string, screenWidth?: number, screenHeight?: number, options?: RendererOptions); type: number; + options: RendererOptions; screen: Rectangle; readonly width: number; readonly height: number; @@ -770,7 +760,6 @@ declare namespace PIXI { protected _backgroundColorString: string; protected _tempDisplayObjectParent: Container; protected _lastObjectRendered: DisplayObject; - backgroundColor: number; resize(screenWidth: number, screenHeight: number): void; generateTexture(displayObject: DisplayObject, scaleMode?: number, resolution?: number): RenderTexture; @@ -779,7 +768,8 @@ declare namespace PIXI { } class CanvasRenderer extends SystemRenderer { // plugintarget mixin start - static __plugins: Object; + static __plugins: any; + //tslint:disable-next-line:ban-types forbidden-types static registerPlugin(pluginName: string, ctor: Function): void; plugins: any; initPlugins(): void; @@ -789,7 +779,8 @@ declare namespace PIXI { // from InteractionManager interaction?: interaction.InteractionManager; - constructor(screenWidth?: number, screenHeight?: number, options?: IRendererOptions); + constructor(options?: RendererOptions); + constructor(screenWidth?: number, screenHeight?: number, options?: RendererOptions); rootContext: CanvasRenderingContext2D; rootResolution?: number; @@ -805,13 +796,12 @@ declare namespace PIXI { destroy(removeView?: boolean): void; clear(clearColor?: string): void; - on(event: "prerender", fn: () => void, context?: any): this; - on(event: "postrender", fn: () => void, context?: any): this; - on(event: string, fn: Function, context?: any): this; - once(event: "prerender", fn: () => void, context?: any): this; - once(event: "postrender", fn: () => void, context?: any): this; - once(event: string, fn: Function, context?: any): this; - off(event: string, fn: Function, context?: any): this; + on(event: "prerender" | "postrender", fn: () => void, context?: any): this; + once(event: "prerender" | "postrender", fn: () => void, context?: any): this; + removeListener(event: "prerender" | "postrender", fn?: () => void, context?: any): this; + removeAllListeners(event: "prerender" | "postrender"): this; + off(event: "prerender" | "postrender", fn?: () => void, context?: any): this; + addListener(event: "prerender" | "postrender", fn: () => void, context?: any): this; } class CanvasMaskManager { constructor(renderer: CanvasRenderer); @@ -835,16 +825,25 @@ declare namespace PIXI { resize(width: number, height: number): void; destroy(): void; } - - interface IWebGLRendererOptions extends IRendererOptions { + interface WebGLRendererOptions { + view?: HTMLCanvasElement; + transparent?: boolean; + autoResize?: boolean; + antialias?: boolean; forceFXAA?: boolean; + resolution?: number; + clearBeforeRender?: boolean; + backgroundColor?: number; preserveDrawingBuffer?: boolean; + roundPixels?: boolean; legacy?: boolean; + width?: number; + height?: number; } - class WebGLRenderer extends SystemRenderer { // plugintarget mixin start - static __plugins: Object; + static __plugins: any; + //tslint:disable-next-line:ban-types forbidden-types static registerPlugin(pluginName: string, ctor: Function): void; plugins: any; initPlugins(): void; @@ -854,7 +853,8 @@ declare namespace PIXI { // from InteractionManager interaction: interaction.InteractionManager; - constructor(screenWidth?: number, screenHeight?: number, options?: IWebGLRendererOptions); + constructor(options?: WebGLRendererOptions); + constructor(screenWidth?: number, screenHeight?: number, options?: WebGLRendererOptions); protected _contextOptions: { alpha: boolean; @@ -875,6 +875,7 @@ declare namespace PIXI { boundTextures: Texture[]; filterManager: FilterManager; textureManager?: TextureManager; + textureGC?: TextureGarbageCollector; extract: extract.WebGLExtract; protected drawModes: any; protected _activeShader: Shader; @@ -900,15 +901,17 @@ declare namespace PIXI { handleContextRestored: () => void; destroy(removeView?: boolean): void; + on(event: "prerender" | "postrender", fn: () => void, context?: any): this; on(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): this; - on(event: "prerender", fn: () => void, context?: any): this; - on(event: "postrender", fn: () => void, context?: any): this; - on(event: string, fn: Function, context?: any): this; + once(event: "prerender" | "postrender", fn: () => void, context?: any): this; once(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): this; - once(event: "prerender", fn: () => void, context?: any): this; - once(event: "postrender", fn: () => void, context?: any): this; - once(event: string, fn: Function, context?: any): this; - off(event: string, fn: Function, context?: any): this; + removeListener(event: "prerender" | "postrender", fn?: () => void, context?: any): this; + removeListener(event: "context", fn?: (gl: WebGLRenderingContext) => void, context?: any): this; + removeAllListeners(event: "prerender" | "postrender" | "context"): this; + off(event: "prerender" | "postrender", fn?: () => void, context?: any): this; + off(event: "context", fn?: (gl: WebGLRenderingContext) => void, context?: any): this; + addListener(event: "prerender" | "postrender", fn: () => void, context?: any): this; + addListener(event: "context", fn: (gl: WebGLRenderingContext) => void, context?: any): this; } class WebGLState { constructor(gl: WebGLRenderingContext); @@ -919,7 +922,7 @@ declare namespace PIXI { stack: number[]; gl: WebGLRenderingContext; maxAttribs: number; - attribState: glCore.IAttribState; + attribState: glCore.AttribState; nativeVaoExtension: any; push(): void; @@ -938,7 +941,7 @@ declare namespace PIXI { renderer: WebGLRenderer; gl: WebGLRenderingContext; - protected _managedTextures: WebGLTexture[]; + protected _managedTextures: Texture[]; bindTexture(): void; getTexture(): WebGLTexture; @@ -985,6 +988,11 @@ declare namespace PIXI { upload(): Quad; destroy(): void; } + interface FilterDataStackItem { + renderTarget: RenderTarget; + filter: any[]; + bounds: Rectangle; + } class RenderTarget { constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root?: boolean); @@ -1004,11 +1012,7 @@ declare namespace PIXI { stencilMaskStack: Graphics[]; filterData: { index: number, - stack: Array<{ - renderTarget: RenderTarget, - filter: any[]; - bounds: Rectangle - }> + stack: FilterDataStackItem[]; }; scaleMode: number; root: boolean; @@ -1029,19 +1033,19 @@ declare namespace PIXI { setBlendMode(blendMode: number): boolean; } + interface FilterManagerStackItem { + renderTarget: RenderTarget; + sourceFrame: Rectangle; + destinationFrame: Rectangle; + filters: Filter[]; + target: any; + resolution: number; + } class FilterManager extends WebGLManager { constructor(renderer: WebGLRenderer); - gl: WebGLRenderingContext; quad: Quad; - stack: Array<{ - renderTarget: RenderTarget; - sourceFrame: Rectangle; - destinationFrame: Rectangle; - filters: Filter[]; - target: any; - resolution: number; - }>; + stack: FilterManagerStackItem[]; stackIndex: number; shaderCache: any; filterData: any; @@ -1098,7 +1102,7 @@ declare namespace PIXI { onContextChange(): void; destroy(): void; } - interface IUniformData { + interface UniformData { type: string; value: any; @@ -1106,19 +1110,20 @@ declare namespace PIXI { name?: string; } class Filter { - constructor(vertexSrc?: string, fragmentSrc?: string, uniforms?: { [name: string]: IUniformData }); + constructor(vertexSrc?: string, fragmentSrc?: string, uniforms?: { [name: string]: UniformData }); vertextSrc?: string; fragmentSrc: string; blendMode: number; - protected uniformData: { [name: string]: IUniformData }; + protected uniformData: { [name: string]: UniformData }; uniforms: { [name: string]: any } | any; glShaders: any; glShaderKey?: number; padding: number; resolution: number; enabled: boolean; - apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget, clear?: boolean): void; + autoFit: boolean; + apply(filterManager: FilterManager, input: RenderTarget, output: RenderTarget, clear?: boolean, currentState?: any): void; static defaultVertexSrc: string; static defaultFragmentSrc: string; @@ -1167,7 +1172,7 @@ declare namespace PIXI { protected _renderCanvas(renderer: CanvasRenderer): void; getLocalBounds(): Rectangle; containsPoint(point: Point): boolean; - destroy(options?: IDestroyOptions | boolean): void; + destroy(options?: DestroyOptions | boolean): void; static from(source: number | string | BaseTexture | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement): Sprite; static fromFrame(frameId: string): Sprite; @@ -1222,7 +1227,7 @@ declare namespace PIXI { let cacheStepsPerColorChannel: number; let convertTintToImage: boolean; let canUseMultiply: boolean; - let tintMethod: Function; + let tintMethod: number; } // text @@ -1318,12 +1323,35 @@ declare namespace PIXI { wordWrap: boolean; protected _wordWrapWidth: number; wordWrapWidth: number; + toFontString(): string; } + class TextMetrics { + protected _canvas: HTMLCanvasElement; + protected _context: CanvasRenderingContext2D; + protected _fonts: FontMetrics; + text: string; + style: TextStyle; + width: number; + height: number; + lines: number[]; + lineWidgets: number[]; + lineHeight: number; + maxLineWidth: number; + fontProperties: any; + + constructor(text: string, style: TextStyle, width: number, height: number, lines: number[], lineWidths: number[], lineHeight: number, maxLineWidth: number, fontProperties: any); + + static measureText(text: string, style: TextStyle, wordWrap?: boolean, canvas?: HTMLCanvasElement): TextMetrics; + static wordWrap(text: string, style: TextStyle, canvas?: HTMLCanvasElement): string; + static measureFont(font: string): FontMetrics; + } + interface FontMetrics { + ascent: number; + descent: number; + fontSize: number; + } class Text extends Sprite { - static getFontStyle(style: TextStyleOptions): string; - static calculateFontProperties(style: string): any; - constructor(text?: string, style?: TextStyleOptions, canvas?: HTMLCanvasElement); canvas: HTMLCanvasElement; @@ -1331,14 +1359,11 @@ declare namespace PIXI { resolution: number; protected _text: string; protected _style: TextStyle; + //tslint:disable-next-line:ban-types forbidden-types protected _styleListener: Function; protected _font: string; protected localStyleID: number; - static fontPropertiesCache: any; - static fontPropertiesCanvas: HTMLCanvasElement; - static fontPropertiesContext: CanvasRenderingContext2D; - width: number; height: number; style: TextStyle; @@ -1349,17 +1374,14 @@ declare namespace PIXI { protected updateTexture(): void; renderWebGL(renderer: WebGLRenderer): void; protected _renderCanvas(renderer: CanvasRenderer): void; - protected wordWrap(text: string): string; getLocalBounds(rect?: Rectangle): Rectangle; protected _calculateBounds(): void; protected _onStyleChange: () => void; protected _generateFillStyle(style: TextStyle, lines: string[]): string | number | CanvasGradient; - destroy(options?: IDestroyOptions | boolean): void; + destroy(options?: DestroyOptions | boolean): void; dirty: boolean; } - // textures - class BaseRenderTexture extends BaseTexture { constructor(width?: number, height?: number, scaleMode?: number, resolution?: number); @@ -1377,11 +1399,12 @@ declare namespace PIXI { resize(width: number, height: number): void; destroy(): void; - once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; - once(event: string, fn: Function, context?: any): this; on(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; - on(event: string, fn: Function, context?: any): this; - off(event: string, fn: Function, context?: any): this; + once(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; + removeListener(event: "update", fn?: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; + removeAllListeners(event: "update"): this; + off(event: "update", fn?: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; + addListener(event: "update", fn: (baseRenderTexture: BaseRenderTexture) => void, context?: any): this; } class BaseTexture extends utils.EventEmitter { static from(source: string | HTMLImageElement | HTMLCanvasElement, scaleMode?: number, sourceScale?: number): BaseTexture; @@ -1411,6 +1434,9 @@ declare namespace PIXI { protected _glTextures: any; protected _enabled: number; protected _id?: number; + protected _virtualBoundId: number; + protected readonly _destroyed: boolean; + textureCacheIds: string[]; update(): void; protected _updateDimensions(): void; @@ -1426,19 +1452,16 @@ declare namespace PIXI { updateSourceImage(newSrc: string): void; static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number, sourceScale?: number): BaseTexture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number, origin?: string): BaseTexture; + static addToCache(baseTexture: BaseTexture, id: string): void; + static removeFromCache(baseTexture: string | BaseTexture): BaseTexture; - on(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): this; - on(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): this; - on(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): this; - on(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; - on(event: string, fn: Function, context?: any): this; - once(event: "update", fn: (baseTexture: BaseTexture) => void, context?: any): this; - once(event: "loaded", fn: (baseTexture: BaseTexture) => void, context?: any): this; - once(event: "error", fn: (baseTexture: BaseTexture) => void, context?: any): this; - once(event: "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; - once(event: string, fn: Function, context?: any): this; - off(event: string, fn: Function, context?: any): this; + on(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; + once(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; + removeListener(event: "update" | "loaded" | "error" | "dispose", fn?: (baseTexture: BaseTexture) => void, context?: any): this; + removeAllListeners(event: "update" | "loaded" | "error" | "dispose"): this; + off(event: "update" | "loaded" | "error" | "dispose", fn?: (baseTexture: BaseTexture) => void, context?: any): this; + addListener(event: "update" | "loaded" | "error" | "dispose", fn: (baseTexture: BaseTexture) => void, context?: any): this; } class RenderTexture extends Texture { constructor(baseRenderTexture: BaseRenderTexture, frame?: Rectangle); @@ -1451,8 +1474,6 @@ declare namespace PIXI { static create(width?: number, height?: number, scaleMode?: number, resolution?: number): RenderTexture; } class Texture extends utils.EventEmitter { - static from(source: number | string | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | BaseTexture): Texture; - constructor(baseTexture: BaseTexture, frame?: Rectangle, orig?: Rectangle, trim?: Rectangle, rotate?: number); noFrame: boolean; @@ -1465,6 +1486,7 @@ declare namespace PIXI { orig: Rectangle; protected _updateID: number; transform: any; + textureCacheIds: string[]; update(): void; protected onBaseTextureLoaded(baseTexture: BaseTexture): void; @@ -1475,12 +1497,17 @@ declare namespace PIXI { static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number, sourceScale?: number): Texture; static fromFrame(frameId: string): Texture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number, origin?: string): Texture; static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; + static from(source: number | string | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | BaseTexture): Texture; static fromLoader(source: HTMLImageElement | HTMLCanvasElement, imageUrl: string, name?: string): Texture; + static addToCache(texture: Texture, id: string): void; + static removeFromCache(texture: string | Texture): Texture; + + // depreciation static addTextureToCache(texture: Texture, id: string): void; - static removeTextureFromCache(id: string): Texture | undefined; + static removeTextureFromCache(id: string): Texture; frame: Rectangle; protected _rotate: boolean | 0; @@ -1489,12 +1516,14 @@ declare namespace PIXI { height: number; static EMPTY: Texture; + static WHITE: Texture; on(event: "update", fn: (texture: Texture) => void, context?: any): this; - on(event: string, fn: Function, context?: any): this; once(event: "update", fn: (texture: Texture) => void, context?: any): this; - once(event: string, fn: Function, context?: any): this; - off(event: string, fn: Function, context?: any): this; + removeListener(event: "update", fn?: (texture: Texture) => void, context?: any): this; + removeAllListeners(event: "update"): this; + off(event: "update", fn?: (texture: Texture) => void, context?: any): this; + addListener(event: "update", fn: (texture: Texture) => void, context?: any): this; } class TextureUvs { x0: number; @@ -1560,16 +1589,26 @@ declare namespace PIXI { namespace ticker { const shared: Ticker; + class TickerListener { + constructor(fn: (deltaTime: number) => void, context?: any, priority?: number, once?: boolean); + fn: (deltaTime: number) => void; + context: any; + priority: number; + once: boolean; + next: TickerListener; + previous: TickerListener; + protected _destroyed: boolean; + match(fn: (deltaTime: number) => void, context?: any): boolean; + emit(deltaTime: number): TickerListener; + connect(previous: TickerListener): void; + destroy(hard?: boolean): void; + } class Ticker { - protected _tick(time: number): void; - protected _emitter: utils.EventEmitter; + protected _tick: (time: number) => void; + protected _head: TickerListener; protected _requestId: number | null; protected _maxElapsedMS: number; - protected _requestIfNeeded(): void; - protected _cancelIfNeeded(): void; - protected _startIfPossible(): void; - autoStart: boolean; deltaTime: number; elapsedMS: number; @@ -1577,15 +1616,22 @@ declare namespace PIXI { speed: number; started: boolean; - FPS: number; + protected _requestIfNeeded(): void; + protected _cancelIfNeeded(): void; + protected _startIfPossible(): void; + + add(fn: (deltaTime: number) => void, context?: any, priority?: number): Ticker; + addOnce(fn: (deltaTime: number) => void, context?: any, priority?: number): Ticker; + //tslint:disable-next-line:ban-types forbidden-types + remove(fn: Function, context?: any, priority?: number): Ticker; + protected _addListener(listener: TickerListener): Ticker; + readonly FPS: number; minFPS: number; - add(fn: (deltaTime: number) => void, context?: any): Ticker; - addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; - remove(fn: (deltaTime: number) => void, context?: any): Ticker; start(): void; stop(): void; - update(): void; + destroy(): void; + update(currentTime?: number): void; } } @@ -1629,7 +1675,7 @@ declare namespace PIXI { ////////////////////////////////////////////////////////////////////////////// namespace extras { - interface IBitmapTextStyle { + interface BitmapTextStyle { font?: string | { name?: string; size?: number; @@ -1640,7 +1686,7 @@ declare namespace PIXI { class BitmapText extends Container { static registerFont(xml: XMLDocument, texture: Texture): any; - constructor(text: string, style?: IBitmapTextStyle); + constructor(text: string, style?: BitmapTextStyle); protected _textWidth: number; protected _textHeight: number; @@ -1656,7 +1702,9 @@ declare namespace PIXI { size?: number; }; protected _text: string; + protected _maxWidth: number; maxWidth: number; + protected _maxLineHeight: number; maxLineHeight: number; protected _anchor: ObservablePoint; dirty: boolean; @@ -1672,17 +1720,22 @@ declare namespace PIXI { static fonts: any; } + interface AnimatedSpriteTextureTimeObject { + texture: Texture; + time?: number; + } class AnimatedSprite extends Sprite { - constructor(textures: Texture[] | Array<{ texture: Texture, time?: number }>, autoUpdate?: boolean); + constructor(textures: Texture[] | AnimatedSpriteTextureTimeObject[], autoUpdate?: boolean); protected _autoUpdate: boolean; protected _textures: Texture[]; protected _durations: number[]; - textures: Texture[] | Array<{ texture: Texture, time?: number }>; + textures: Texture[] | AnimatedSpriteTextureTimeObject[]; animationSpeed: number; loop: boolean; onComplete: () => void; onFrameChange: (currentFrame: number) => void; + onLoop: () => void; protected _currentTime: number; playing: boolean; totalFrames: number; @@ -1692,7 +1745,7 @@ declare namespace PIXI { gotoAndStop(frameNumber: number): void; gotoAndPlay(frameNumber: number): void; protected update(deltaTime: number): void; - destroy(): void; + destroy(options?: DestroyOptions | boolean): void; static fromFrames(frame: string[]): AnimatedSprite; static fromImages(images: string[]): AnimatedSprite; @@ -1711,7 +1764,7 @@ declare namespace PIXI { texture: Texture; - update(forceUpdate?: boolean): void; + update(forceUpdate?: boolean): boolean; } class TilingSprite extends Sprite { constructor(texture: Texture, width?: number, height?: number); @@ -1727,13 +1780,14 @@ declare namespace PIXI { tileScale: Point | ObservablePoint; tilePosition: Point | ObservablePoint; + multiplyUvs(uvs: Float32Array, out: Float32Array): Float32Array; protected _onTextureUpdate(): void; protected _renderWebGL(renderer: WebGLRenderer): void; protected _renderCanvas(renderer: CanvasRenderer): void; protected _calculateBounds(): void; getLocalBounds(rect?: Rectangle): Rectangle; containsPoint(point: Point): boolean; - destroy(): void; + destroy(options?: DestroyOptions | boolean): void; static from(source: number | string | BaseTexture | HTMLCanvasElement | HTMLVideoElement, width?: number, height?: number): TilingSprite; static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; @@ -1802,6 +1856,7 @@ declare namespace PIXI { protected _colorMatrix(matrix: number[]): void; matrix: number[]; + alpha: number; brightness(b: number, multiply?: boolean): void; greyscale(scale: number, multiply?: boolean): void; @@ -1837,7 +1892,9 @@ declare namespace PIXI { // pixi-filters.d.ts todo // https://github.com/pixijs/pixi-filters/ class NoiseFilter extends Filter { + constructor(noise?: number, seed?: number); noise: number; + seed: number; } } @@ -1876,11 +1933,33 @@ declare namespace PIXI { class InteractionData { global: Point; target: DisplayObject; - originalEvent: Event; - identifier?: number; - + originalEvent: MouseEvent | TouchEvent | PointerEvent; + identifier: number; + isPrimary: boolean; + button: number; + buttons: number; + width: number; + height: number; + tiltX: number; + tiltY: number; + pointerType: string; + pressure: number; + rotationAngle: number; + twist: number; + tangentialPressure: number; + readonly pointerID: number; + protected _copyEvent(event: Touch | MouseEvent | PointerEvent): void; + protected _reset(): void; getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; } + type InteractionPointerEvents = "pointerdown" | "pointercancel" | "pointerup" | + "pointertap" | "pointerupoutside" | "pointermove" | "pointerover" | "pointerout"; + type InteractionTouchEvents = "touchstart" | "touchcancel" | "touchend" | + "touchendoutside" | "touchmove" | "tap"; + type InteractionMouseEvents = "rightdown" | "mousedown" | "rightup" | "mouseup" | + "rightclick" | "click" | "rightupoutside" | "mouseupoutside" | "mousemove" | + "mouseover" | "mouseout" | "mouseover"; + type InteractionEventTypes = InteractionPointerEvents | InteractionTouchEvents | InteractionMouseEvents; interface InteractionManagerOptions { autoPreventDefault?: boolean; interactionFrequency?: number; @@ -1920,6 +1999,7 @@ declare namespace PIXI { cursor: string; protected _tempPoint: Point; resolution: number; + hitTest(globalPoint: Point, root?: Container): DisplayObject; protected setTargetElement(element: HTMLCanvasElement, resolution?: number): void; protected addEvents(): void; protected removeEvents(): void; @@ -1927,15 +2007,22 @@ declare namespace PIXI { setCursorMode(mode: string): void; protected dispatchEvent(displayObject: Container | Sprite | extras.TilingSprite, eventString: string, eventData: any): void; mapPositionToPoint(point: Point, x: number, y: number): void; + //tslint:disable-next-line:ban-types forbidden-types protected processInteractive( interactionEvent: InteractionEvent, displayObject: PIXI.Container | PIXI.Sprite | PIXI.extras.TilingSprite, func?: Function, hitTest?: boolean, - interactive?: boolean): boolean; - protected onPointerComplete(originalEvent: PointerEvent, cancelled: boolean, func: Function): void; + interactive?: boolean + ): boolean; + //tslint:disable-next-line:ban-types forbidden-types + protected onPointerComplete( + originalEvent: PointerEvent, + cancelled: boolean, + func: Function + ): void; protected getInteractionDataForPointerId(pointerId: number): InteractionData; - protected releaseInteractionDataForPointerId(pointerId: number): void; + protected releaseInteractionDataForPointerId(event: PointerEvent): void; protected configureInteractionEventForDOMEvent(interactionEvent: InteractionEvent, pointerEvent: PointerEvent, interactionData: InteractionData): InteractionEvent; protected normalizeToPointerData(event: TouchEvent | MouseEvent | PointerEvent): PointerEvent[]; destroy(): void; @@ -1955,8 +2042,10 @@ declare namespace PIXI { // 2.0.6 class MiniSignalBinding { + //tslint:disable-next-line:ban-types forbidden-types constructor(fn: Function, once?: boolean, thisArg?: any); + //tslint:disable-next-line:ban-types forbidden-types protected _fn: Function; protected _once: boolean; protected _thisArg: any; @@ -1978,14 +2067,16 @@ declare namespace PIXI { has(node: MiniSignalBinding): boolean; dispatch(): boolean; + //tslint:disable-next-line:ban-types forbidden-types add(fn: Function, thisArg?: any): any; + //tslint:disable-next-line:ban-types forbidden-types once(fn: Function, thisArg?: any): any; detach(node: MiniSignalBinding): MiniSignal; detachAll(): MiniSignal; } namespace loaders { - interface ILoaderOptions { + interface LoaderOptions { crossOrigin?: boolean | string; loadType?: number; xhrType?: string; @@ -1993,7 +2084,7 @@ declare namespace PIXI { loadElement?: HTMLImageElement | HTMLAudioElement | HTMLVideoElement; skipSource?: boolean; } - interface IResourceDictionary { + interface ResourceDictionary { [index: string]: PIXI.loaders.Resource; } @@ -2001,6 +2092,7 @@ declare namespace PIXI { // However, for depreciation reasons, it remains. class Loader extends utils.EventEmitter { // pixi overrides here + //tslint:disable-next-line:ban-types forbidden-types static addPixiMiddleware(fn: Function): void; // below this line is the original non-pixi loader @@ -2016,13 +2108,16 @@ declare namespace PIXI { loading: boolean; defaultQueryString: string; + //tslint:disable-next-line:ban-types forbidden-types protected _beforeMiddleware: Function[]; + //tslint:disable-next-line:ban-types forbidden-types protected _afterMiddleware: Function[]; protected _resourcesParsing: Resource[]; + //tslint:disable-next-line:ban-types forbidden-types protected _boundLoadResource: (r: Resource, d: Function) => void; protected _queue: any; - resources: IResourceDictionary; + resources: ResourceDictionary; onProgress: MiniSignal; onError: MiniSignal; @@ -2031,44 +2126,49 @@ declare namespace PIXI { onComplete: MiniSignal; add(...params: any[]): this; - add(name: string, url: string, options?: ILoaderOptions, cb?: Function): this; - add(url: string, options?: ILoaderOptions, cb?: Function): this; - add(obj: any | any[], options?: ILoaderOptions, cb?: Function): this; + //tslint:disable-next-line:ban-types forbidden-types + add(name: string, url: string, options?: LoaderOptions, cb?: Function): this; + //tslint:disable-next-line:ban-types forbidden-types + add(obj: string | any | any[], options?: LoaderOptions, cb?: Function): this; + //tslint:disable-next-line:ban-types forbidden-types pre(fn: Function): this; + //tslint:disable-next-line:ban-types forbidden-types use(fn: Function): this; reset(): this; + //tslint:disable-next-line:ban-types forbidden-types load(cb?: Function): this; protected _prepareUrl(url: string): string; + //tslint:disable-next-line:ban-types forbidden-types protected _loadResource(resource: Resource, dequeue: Function): void; protected _onComplete(): void; protected _onLoad(resource: Resource): void; + destroy(): void; + // depreciation on(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): this; on(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): this; - on(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; - on(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; + on(event: "load" | "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; on(event: "start", fn: (loader: loaders.Loader) => void, context?: any): this; - on(event: string, fn: Function, context?: any): this; once(event: "complete", fn: (loader: loaders.Loader, object: any) => void, context?: any): this; once(event: "error", fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): this; - once(event: "load", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; - once(event: "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; + once(event: "load" | "progress", fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): this; once(event: "start", fn: (loader: loaders.Loader) => void, context?: any): this; - once(event: string, fn: Function, context?: any): this; + //tslint:disable-next-line:ban-types forbidden-types + off(event: "complete" | "error" | "load" | "progress" | "start" | string, fn?: Function, context?: any): this; } - interface ITextureDictionary { + interface TextureDictionary { [index: string]: PIXI.Texture; } class Resource { static setExtensionLoadType(extname: string, loadType: number): void; static setExtensionXhrType(extname: string, xhrType: string): void; - constructor(name: string, url: string | string[], options?: ILoaderOptions); + constructor(name: string, url: string | string[], options?: LoaderOptions); protected _flags: number; @@ -2086,14 +2186,23 @@ declare namespace PIXI { type: number; progressChunk: number; + //tslint:disable-next-line:ban-types forbidden-types protected _dequeue: Function; + //tslint:disable-next-line:ban-types forbidden-types protected _onLoadBinding: Function; + //tslint:disable-next-line:ban-types forbidden-types protected _boundComplete: Function; + //tslint:disable-next-line:ban-types forbidden-types protected _boundOnError: Function; + //tslint:disable-next-line:ban-types forbidden-types protected _boundOnProgress: Function; + //tslint:disable-next-line:ban-types forbidden-types protected _boundXhrOnError: Function; + //tslint:disable-next-line:ban-types forbidden-types protected _boundXhrOnAbort: Function; + //tslint:disable-next-line:ban-types forbidden-types protected _boundXhrOnLoad: Function; + //tslint:disable-next-line:ban-types forbidden-types protected _boundXdrOnTimeout: Function; onStart: MiniSignal; @@ -2106,6 +2215,7 @@ declare namespace PIXI { isLoading: boolean; complete(): void; abort(message?: string): void; + //tslint:disable-next-line:ban-types forbidden-types load(cb?: Function): void; protected _hasFlag(flag: number): boolean; @@ -2165,7 +2275,7 @@ declare namespace PIXI { texture: Texture; spineAtlas: any; spineData: any; - textures?: ITextureDictionary; + textures?: TextureDictionary; } } @@ -2192,6 +2302,11 @@ declare namespace PIXI { texture: Texture; tintRgb: Float32Array; protected _glDatas: { [n: number]: any; }; + protected _uvTransform: extras.TextureTransform; + uploadUvTransform: boolean; + multiplyUvs(): void; + refresh(forceUpdate?: boolean): void; + protected _refresh(): void; protected _renderWebGL(renderer: WebGLRenderer): void; protected _renderCanvas(renderer: CanvasRenderer): void; protected _onTextureUpdate(): void; @@ -2262,6 +2377,7 @@ declare namespace PIXI { updateHorizontalVertices(): void; updateVerticalVertices(): void; protected drawSegment(context: CanvasRenderingContext2D | WebGLRenderingContext, textureSource: any, w: number, h: number, x1: number, y1: number, x2: number, y2: number): void; + protected _refresh(): void; } class Rope extends Mesh { @@ -2269,20 +2385,17 @@ declare namespace PIXI { points: Point[]; colors: number[]; - protected _ready: boolean; - refresh(): void; + autoUpdate: boolean; + protected _refresh(): void; - protected _onTextureUpdate(): void; - updateTransform(): void; + refreshVertices(): void; } } - ////////////////////////////////////////////////////////////////////////////// /////////////////////////////PARTICLES//////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - namespace particles { - interface IParticleContainerProperties { + interface ParticleContainerProperties { scale?: boolean; position?: boolean; rotation?: boolean; @@ -2290,8 +2403,10 @@ declare namespace PIXI { alpha?: boolean; } class ParticleContainer extends Container { - constructor(size?: number, properties?: IParticleContainerProperties, batchSize?: number); - + constructor(size?: number, properties?: ParticleContainerProperties, batchSize?: number); + protected _tint: number; + protected tintRgb: number | any[]; + tint: number; protected _properties: boolean[]; protected _maxSize: number; protected _batchSize: number; @@ -2302,10 +2417,10 @@ declare namespace PIXI { roundPixels: boolean; baseTexture: BaseTexture; - setProperties(properties: IParticleContainerProperties): void; + setProperties(properties: ParticleContainerProperties): void; protected onChildrenChange: (smallestChildIndex?: number) => void; - destroy(options?: IDestroyOptions | boolean): void; + destroy(options?: DestroyOptions | boolean): void; } class ParticleBuffer { constructor(gl: WebGLRenderingContext, properties: any, dynamicPropertyFlags: any[], size: number); @@ -2325,7 +2440,7 @@ declare namespace PIXI { destroy(): void; } - interface IParticleRendererProperty { + interface ParticleRendererProperty { attribute: number; size: number; uploadFunction(children: PIXI.DisplayObject[], startIndex: number, amount: number, array: number[], stride: number, offset: number): void; @@ -2336,7 +2451,7 @@ declare namespace PIXI { shader: glCore.GLShader; indexBuffer: WebGLBuffer; - properties: IParticleRendererProperty[]; + properties: ParticleRendererProperty[]; protected tempMatrix: Matrix; start(): void; @@ -2350,13 +2465,10 @@ declare namespace PIXI { indices: Uint16Array; } - interface IParticleShader extends glCore.GLShader { } } - ////////////////////////////////////////////////////////////////////////////// ////////////////////////////PREPARE/////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - namespace prepare { type AddHook = (item: any, queue: any[]) => boolean; type UploadHook = (prepare: UploadHookSource, item: any) => boolean; @@ -2369,14 +2481,20 @@ declare namespace PIXI { protected queue: any[]; protected addHooks: AddHook[]; protected uploadHooks: Array>; + //tslint:disable-next-line:ban-types forbidden-types protected completes: Function[]; protected ticking: boolean; protected delayedTick: () => void; + //tslint:disable-next-line:ban-types forbidden-types upload(item: Function | DisplayObject | Container | BaseTexture | Texture | Graphics | Text | any, done?: () => void): void; protected tick(): void; protected prepareItems(): void; - register(addHook?: AddHook, uploadHook?: UploadHook): this; + registerFindHook(addHook: AddHook): this; + registerUploadHook(uploadHook: UploadHook): this; + protected findMultipleBaseTextures(item: PIXI.DisplayObject, queue: any[]): boolean; + protected findBaseTexture(item: PIXI.DisplayObject, queue: any[]): boolean; + protected findTexture(item: PIXI.DisplayObject, queue: any[]): boolean; add(item: PIXI.DisplayObject | PIXI.Container | PIXI.BaseTexture | PIXI.Texture | PIXI.Graphics | PIXI.Text | any): this; destroy(): void; } @@ -2410,7 +2528,7 @@ declare namespace PIXI { // sharedArrayBuffer as a type is not available yet. // need to fully define what an `Attrib` is. namespace glCore { - interface IContextOptions { + interface ContextOptions { /** * Boolean that indicates if the canvas contains an alpha buffer. */ @@ -2440,8 +2558,8 @@ declare namespace PIXI { */ failIfMajorPerformanceCaveat?: boolean; } - function createContext(view: HTMLCanvasElement, options?: IContextOptions): WebGLRenderingContext; - function setVertexAttribArrays(gl: WebGLRenderingContext, attribs: IAttrib[], state?: WebGLState): WebGLRenderingContext | undefined; + function createContext(view: HTMLCanvasElement, options?: ContextOptions): WebGLRenderingContext; + function setVertexAttribArrays(gl: WebGLRenderingContext, attribs: Attrib[], state?: WebGLState): WebGLRenderingContext | undefined; class GLBuffer { constructor(gl: WebGLRenderingContext, type: number, data: ArrayBuffer | ArrayBufferView | any, drawType: number); @@ -2483,7 +2601,7 @@ declare namespace PIXI { static createFloat32(gl: WebGLRenderingContext, width: number, height: number, data: ArrayBuffer | ArrayBufferView | any): GLFramebuffer; } class GLShader { - constructor(gl: WebGLRenderingContext, vertexSrc: string | string[], fragmentSrc: string | string[], precision: string, attributeLocations: { [key: string]: number }); + constructor(gl: WebGLRenderingContext, vertexSrc: string | string[], fragmentSrc: string | string[], precision?: string, attributeLocations?: { [key: string]: number }); gl: WebGLRenderingContext; program?: WebGLProgram | null; @@ -2507,7 +2625,7 @@ declare namespace PIXI { type: number; upload(source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement): void; - uploadData(data: number, width: number, height: number): void; + uploadData(data: ArrayBuffer | ArrayBufferView, width: number, height: number): void; bind(location?: number): void; unbind(): void; minFilter(linear: boolean): void; @@ -2523,9 +2641,9 @@ declare namespace PIXI { static fromSource(gl: WebGLRenderingContext, source: HTMLImageElement | ImageData | HTMLVideoElement | HTMLCanvasElement, premultipleAlpha?: boolean): GLTexture; static fromData(gl: WebGLRenderingContext, data: number[], width: number, height: number): GLTexture; } - interface IAttrib { + interface Attrib { attribute: { - location: boolean; + location: number; size: number; }; normalized: boolean; @@ -2533,7 +2651,7 @@ declare namespace PIXI { start: number; buffer: ArrayBuffer; } - interface IWebGLRenderingContextAttribute { + interface WebGLRenderingContextAttribute { buffer: WebGLBuffer; attribute: any; type: number; @@ -2541,28 +2659,27 @@ declare namespace PIXI { stride: number; start: number; } - interface IAttribState { - tempAttribState: IAttrib[]; - attribState: IAttrib[]; + interface AttribState { + tempAttribState: Attrib[]; + attribState: Attrib[]; } - class VertexArrayObject { static FORCE_NATIVE: boolean; constructor(gl: WebGLRenderingContext, state: WebGLState); protected nativeVaoExtension: any; - protected nativeState: IAttribState; + protected nativeState: AttribState; protected nativeVao: VertexArrayObject; gl: WebGLRenderingContext; - attributes: IAttrib[]; + attributes: Attrib[]; indexBuffer: GLBuffer; dirty: boolean; bind(): VertexArrayObject; unbind(): VertexArrayObject; activate(): VertexArrayObject; - addAttribute(buffer: GLBuffer, attribute: IAttrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; + addAttribute(buffer: GLBuffer, attribute: Attrib, type: number, normalized: boolean, stride: number, start: number): VertexArrayObject; addIndex(buffer: GLBuffer, options?: any): VertexArrayObject; clear(): VertexArrayObject; draw(type: number, size: number, start: number): VertexArrayObject; @@ -2574,7 +2691,7 @@ declare namespace PIXI { ///////////////////////////////UTILS////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - interface IDecomposedDataUri { + interface DecomposedDataUri { mediaType: string; subType: string; encoding: string; @@ -2585,11 +2702,11 @@ declare namespace PIXI { function uid(): number; function hex2rgb(hex: number, out?: number[]): number[]; function hex2string(hex: number): string; - function rgb2hex(rgb: Number[]): number; + function rgb2hex(rgb: number[]): number; function canUseNewCanvasBlendModes(): boolean; function getResolutionOfUrl(url: string, defaultValue?: number): number; function getSvgSize(svgString: string): any; - function decomposeDataUri(dataUri: string): IDecomposedDataUri | void; + function decomposeDataUri(dataUri: string): DecomposedDataUri | void; function getUrlFileExtension(url: string): string | void; function sayHello(type: string): void; function skipHello(): void; @@ -2635,22 +2752,107 @@ declare namespace PIXI { const phone: boolean; const tablet: boolean; } - // https://github.com/primus/eventemitter3 class EventEmitter { - listeners(event: string, exists?: boolean): Function[]; - emit(event: string, ...args: any[]): boolean; - on(event: string, fn: Function, context?: any): this; - once(event: string, fn: Function, context?: any): this; - removeListener(event: string, fn: Function, context?: any, once?: boolean): this; - removeAllListeners(event?: string): this; - eventNames(): string[]; - - off(event: string, fn: Function, context?: any, once?: boolean): this; - addListener(event: string, fn: Function, context?: any): this; + static prefixed: string | boolean; + static EventEmitter: { + new (): EventEmitter; + prefixed: string | boolean; + }; + /** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + * + * @constructor + * @api public + */ + constructor(); + /** + * Return an array listing the events for which the emitter has registered listeners. + * + * @returns {(string | symbol)[]} + */ + eventNames(): Array<(string | symbol)>; + /** + * Return the listeners registered for a given event. + * + * @param {(string | symbol)} event The event name. + * @returns {Function[]} + */ + //tslint:disable-next-line:ban-types forbidden-types + listeners(event: string | symbol): Function[]; + /** + * Check if there listeners for a given event. + * If `exists` argument is not `true` lists listeners. + * + * @param {(string | symbol)} event The event name. + * @param {boolean} exists Only check if there are listeners. + * @returns {boolean} + */ + listeners(event: string | symbol, exists: boolean): boolean; + /** + * Calls each of the listeners registered for a given event. + * + * @param {(string | symbol)} event The event name. + * @param {...*} args Arguments that are passed to registered listeners + * @returns {boolean} `true` if the event had listeners, else `false`. + */ + emit(event: string | symbol, ...args: any[]): boolean; + /** + * Add a listener for a given event. + * + * @param {(string | symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + */ + //tslint:disable-next-line:ban-types forbidden-types + on(event: string | symbol, fn: Function, context?: any): this; + /** + * Add a one-time listener for a given event. + * + * @param {(string | symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + */ + //tslint:disable-next-line:ban-types forbidden-types + once(event: string | symbol, fn: Function, context?: any): this; + /** + * Remove the listeners of a given event. + * + * @param {(string | symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + */ + //tslint:disable-next-line:ban-types forbidden-types + removeListener(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; + /** + * Remove all listeners, or those of the specified event. + * + * @param {(string | symbol)} event The event name. + * @returns {EventEmitter} `this`. + */ + removeAllListeners(event?: string | symbol): this; + /** + * Alias method for `removeListener` + */ + //tslint:disable-next-line:ban-types forbidden-types + off(event: string | symbol, fn?: Function, context?: any, once?: boolean): this; + /** + * Alias method for `on` + */ + //tslint:disable-next-line:ban-types forbidden-types + addListener(event: string | symbol, fn: Function, context?: any): this; + /** + * This function doesn't apply anymore. + * @deprecated + */ + setMaxListeners(): this; } } - ////////////////////////////////////////////////////////////////////////////// /////////////////////////////depreciation///////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// @@ -2748,6 +2950,16 @@ declare namespace PIXI { */ type TilingSprite = extras.TilingSprite; + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + type BaseTextureCache = any; + /** * @class * @private @@ -2857,6 +3069,15 @@ declare namespace PIXI { * @deprecated since version 4.2.0 */ type DEFAULT_RENDER_OPTIONS = number; + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + type PRECISION = string; } namespace extras { @@ -2869,12 +3090,23 @@ declare namespace PIXI { */ type MovieClip = extras.AnimatedSprite; } + namespace settings { + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + type PRECISION = number; + } } declare namespace pixi { const gl: typeof PIXI.glCore; } +//tslint:disable-next-line:no-single-declare-module declare module "pixi.js" { export = PIXI; } diff --git a/types/pixi.js/pixi.js-tests.ts b/types/pixi.js/pixi.js-tests.ts index f73dfd7021..d14d3e0e71 100644 --- a/types/pixi.js/pixi.js-tests.ts +++ b/types/pixi.js/pixi.js-tests.ts @@ -24,7 +24,7 @@ function basics() { private renderer: PIXI.WebGLRenderer; constructor() { // Renderer should allow options from both WebGLRenderer and underlying SystemRenderer - this.renderer = new PIXI.WebGLRenderer(0, 0, { backgroundColor : 0x272d37, forceFXAA: true }); + this.renderer = new PIXI.WebGLRenderer(0, 0, { backgroundColor: 0x272d37, forceFXAA: true }); } } @@ -1507,7 +1507,8 @@ function filters() { maggot.position.y = Math.random() * bounds.height; maggot.scale.set(1 + Math.random() * 0.3); - maggot.original = maggot.scale.clone(); + //tslint:disable-next-line:whitespace + maggot.original = (maggot.scale).clone(); this.maggots.push(maggot); } From 26d632b5f4433ec98028e2037950614be644d151 Mon Sep 17 00:00:00 2001 From: Stephen King Date: Fri, 9 Jun 2017 15:44:58 -0600 Subject: [PATCH 92/98] ramda: Allow currying of type guards --- types/ramda/index.d.ts | 46 +++++++++++++++++++++++++++++++++++++- types/ramda/ramda-tests.ts | 19 ++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 9666c1b78f..79d1b1f6cf 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for ramda // Project: https://github.com/donnut/typescript-ramda -// Definitions by: Erwin Poeze , Matt DeKrey , Liam Goodacre , Matt Dziuban +// Definitions by: Erwin Poeze +// Matt DeKrey +// Liam Goodacre +// Matt Dziuban +// Stephen King // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -75,6 +79,41 @@ declare namespace R { } // @see https://gist.github.com/donnut/fd56232da58d25ceecf1, comment by @albrow + interface CurriedTypeGuard2 { + (t1: T1): (t2: T2) => t2 is R; + (t1: T1, t2: T2): t2 is R; + } + + interface CurriedTypeGuard3 { + (t1: T1): CurriedTypeGuard2; + (t1: T1, t2: T2): (t3: T3) => t3 is R; + (t1: T1, t2: T2, t3: T3): t3 is R; + } + + interface CurriedTypeGuard4 { + (t1: T1): CurriedTypeGuard3; + (t1: T1, t2: T2): CurriedTypeGuard2; + (t1: T1, t2: T2, t3: T3): (t4: T4) => t4 is R; + (t1: T1, t2: T2, t3: T3, t4: T4): t4 is R; + } + + interface CurriedTypeGuard5 { + (t1: T1): CurriedTypeGuard4; + (t1: T1, t2: T2): CurriedTypeGuard3; + (t1: T1, t2: T2, t3: T3): CurriedTypeGuard2; + (t1: T1, t2: T2, t3: T3, t4: T4): (t5: T5) => t5 is R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): t5 is R; + } + + interface CurriedTypeGuard6 { + (t1: T1): CurriedTypeGuard5; + (t1: T1, t2: T2): CurriedTypeGuard4; + (t1: T1, t2: T2, t3: T3): CurriedTypeGuard3; + (t1: T1, t2: T2, t3: T3, t4: T4): CurriedTypeGuard2; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): (t6: T6) => t6 is R; + (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): t6 is R; + } + interface CurriedFunction2 { (t1: T1): (t2: T2) => R; (t1: T1, t2: T2): R; @@ -392,6 +431,11 @@ declare namespace R { * Returns a curried equivalent of the provided function. The curried function has two unusual capabilities. * First, its arguments needn't be provided one at a time. */ + curry(fn: (a: T1, b: T2) => b is TResult): CurriedTypeGuard2 + curry(fn: (a: T1, b: T2, c: T3) => c is TResult): CurriedTypeGuard3 + curry(fn: (a: T1, b: T2, c: T3, d: T4) => d is TResult): CurriedTypeGuard4 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => e is TResult): CurriedTypeGuard5 + curry(fn: (a: T1, b: T2, c: T3, d: T4, e: T5, f: T6) => f is TResult): CurriedTypeGuard6 curry(fn: (a: T1, b: T2) => TResult): CurriedFunction2 curry(fn: (a: T1, b: T2, c: T3) => TResult): CurriedFunction3 curry(fn: (a: T1, b: T2, c: T3, d: T4) => TResult): CurriedFunction4 diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index f9b272f8ca..8fbbb5c7ba 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -86,6 +86,25 @@ class F2 { var z2:number = addTwoNumbersCurried(2,3); } +() => { + interface Car { speed?: number; } + interface FastCar { speed: number; } + + const typeGuard = function(a: number, b: number, c: number, d: number, e: number, car: Car): car is FastCar { + return car.speed !== undefined; + } + const typeGuardCurried = R.curry(typeGuard); + + const drive = function(fastCar: FastCar) {}; + + const cars: Car[] = [{ speed: 65 }, {}]; + for (const car of cars) { + if (typeGuardCurried(1)(2)(3)(4)(5)(car)) { + drive(car); + } + } +} + () => { const addFour = (a:number) => (b:number) => (c:number) => (d:number) => a + b + c + d; const uncurriedAddFour = R.uncurryN(4, addFour); From 6b44fac17517f6501ed75b2dd97b8c06b5658310 Mon Sep 17 00:00:00 2001 From: clarenceh Date: Sat, 10 Jun 2017 13:22:28 +0800 Subject: [PATCH 93/98] Updated for massive 3.0.0-rc1 --- types/massive/index.d.ts | 146 +++++++++++---------------------- types/massive/massive-tests.ts | 18 +++- types/massive/tsconfig.json | 4 +- 3 files changed, 66 insertions(+), 102 deletions(-) diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index 512c9067e2..f97d047c30 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -1,105 +1,57 @@ -// Type definitions for massive-js 2.2 -// Project: https://github.com/robconery/massive-js +// Type definitions for massive 3.0.0-rc1 +// Project: https://github.com/dmfay/massive-js.git // Definitions by: Pascal Birchler +// Clarence Ho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export namespace massive { - interface ConnectionOptions { - connectionString?: string; - db?: string; - } +/// - interface Doc { - findDoc(context: any, callback: ResultCallback): void; - searchDoc( - options: { keys: string[], term: string }, - callback: ResultCallback): void; - saveDoc(context: string, callback: ResultCallback): void; - destroy(context: any, callback: ResultCallback): void; - } +export = massive; - interface QueryFile { - schema: string; - name: string; - db: Massive; - delimitedName: string; - delimitedSchema: string; - fullname: string; - delimitedFullName: string; - sql: string; - filePath: string; - } +declare function massive( + connection: object | string, + loaderConfig?: object, + driverConfig?: object): Promise; - interface QueryFunction { - find(params: any|any[], callback: ResultCallback): void; - } +declare namespace massive { + + export interface ConnectionInfo { + + user?: string; + database?: string; + password?: string | null; + port?: number; + host?: string; + ssl?: boolean; + application_name?: string; + fallback_application_name?: boolean; + + } + + export interface Database { + + attach(ctor: Function, ...sources: (Function | Promise)[]): Promise; + + detach(entity: string, collection: string): void; + + reload(): void; + + query(query: any, params: any, options: any): Promise; + + saveDoc(collection: any, doc: any): any; + + createDocumentTable(path: any): Promise; + + getObject(path: any, collection: any): object; + + dropTable(table: string, options: any): void; + + createSchema(schemaName: string): void; + + dropSchema(schemaName: string, options: any): void; + + [name: string]: any; + + } - interface QueryArguments { - sql: string; - options: any; - params: any; - next: ResultCallback; - } } - -export interface Massive { - custom: any; - comment: Table; - friendship: Table; - participation: Table; - person: Table; - practice: Table; - practicesession: Table; - sport: Table; - testdata(callback: ResultCallback): void; - team: Table; - teammember: Table; - teamsport: Table; - scriptsDir: string; - connectionString: string; - query(): void; - stream(): void; - executeSqlFile(args: any, next: ResultCallback): void; - end(): void; - tables: Array; - views: any[]; - queryFiles: massive.QueryFile[]; - schemas: any[]; - functions: any[]; - allowedSchemas: string; - blacklist: string; - exceptions: string; - excludeFunctions: boolean; - functionBlacklist: string; -} - -export type ResultCallback = (err: Error, res: any) => void; -export type ConnectCallback = (err: Error, db: Massive) => void; - -export interface QueryOptions { - limit?: number; - order?: string; - offset?: number; - columns?: string[]; -} - -export interface Table { - count(context: any, callback: ResultCallback): void; - find(context: any, callback: ResultCallback): void; - find(context: any, options: QueryOptions, callback: ResultCallback): void; - findOne(context: any, callback: ResultCallback): void; - findOne(context: any, options: QueryOptions, callback: ResultCallback): void; - insert(context: any, callback: ResultCallback): void; - save(context: any, callback: ResultCallback): void; - update(context: any, callback: ResultCallback): void; - update(context: any, data: any, callback: ResultCallback): void; - destroy(context: any, callback: ResultCallback): void; -} - -export function connectSync(options: massive.ConnectionOptions): Massive; - -export function connect(options: massive.ConnectionOptions, callback: ConnectCallback): void; - -export function run(context: string, filter: number|number[], callback: ResultCallback): void; - -export function saveDoc(name: string, data: any, callback: ResultCallback): void; diff --git a/types/massive/massive-tests.ts b/types/massive/massive-tests.ts index cb53e3e7c8..9a28910c23 100644 --- a/types/massive/massive-tests.ts +++ b/types/massive/massive-tests.ts @@ -1,5 +1,17 @@ -import * as Massive from 'massive'; +import massive = require('massive'); -Massive.connect({connectionString: 'foo'}, (err: Error, db: Massive.Massive) => {}); +let dbconn: massive.Database; -Massive.run('foo', 123, (err: Error, db: Massive.Massive) => {}); +function findUserById(id: number): Promise { + return dbconn.users.findOne({id: id}); +} + +massive('postgres://app:password@localhost:5432/app').then( db => { + + console.log(`DB connected successfully`); + + dbconn = db; + + findUserById(1).then(user => console.log(`User: ${JSON.stringify(user)}`)); + +}); diff --git a/types/massive/tsconfig.json b/types/massive/tsconfig.json index 7c91e19b44..cfa32399c8 100644 --- a/types/massive/tsconfig.json +++ b/types/massive/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5" + "es2015" ], "noImplicitAny": true, "noImplicitThis": true, @@ -19,4 +19,4 @@ "index.d.ts", "massive-tests.ts" ] -} \ No newline at end of file +} From 89da66a28bdb0a4354c5552a33a54edf947e3fef Mon Sep 17 00:00:00 2001 From: clarenceh Date: Sat, 10 Jun 2017 14:19:30 +0800 Subject: [PATCH 94/98] Minor updates --- types/massive/index.d.ts | 2 +- types/massive/massive-tests.ts | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index f97d047c30..9f68b030ce 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -30,7 +30,7 @@ declare namespace massive { export interface Database { - attach(ctor: Function, ...sources: (Function | Promise)[]): Promise; + attach(ctor: any, ...sources: Array): Promise; detach(entity: string, collection: string): void; diff --git a/types/massive/massive-tests.ts b/types/massive/massive-tests.ts index 9a28910c23..30cb977596 100644 --- a/types/massive/massive-tests.ts +++ b/types/massive/massive-tests.ts @@ -12,6 +12,8 @@ massive('postgres://app:password@localhost:5432/app').then( db => { dbconn = db; - findUserById(1).then(user => console.log(`User: ${JSON.stringify(user)}`)); +}).catch(err => { + + console.error(`Error connecting DB`); }); From 09a3e2fa0ef0cf15aecd5179da72411e80446887 Mon Sep 17 00:00:00 2001 From: clarenceh Date: Sat, 10 Jun 2017 14:37:53 +0800 Subject: [PATCH 95/98] Fix lint and test errors --- types/massive/index.d.ts | 25 +++++-------------------- types/massive/massive-tests.ts | 9 --------- 2 files changed, 5 insertions(+), 29 deletions(-) diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index 9f68b030ce..08a4ed6b7b 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for massive 3.0.0-rc1 +// Type definitions for massive 3.0 // Project: https://github.com/dmfay/massive-js.git // Definitions by: Pascal Birchler // Clarence Ho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -14,9 +15,7 @@ declare function massive( driverConfig?: object): Promise; declare namespace massive { - - export interface ConnectionInfo { - + interface ConnectionInfo { user?: string; database?: string; password?: string | null; @@ -25,33 +24,19 @@ declare namespace massive { ssl?: boolean; application_name?: string; fallback_application_name?: boolean; - } - export interface Database { - - attach(ctor: any, ...sources: Array): Promise; - + interface Database { + attach(ctor: any, ...sources: any[]): Promise; detach(entity: string, collection: string): void; - reload(): void; - query(query: any, params: any, options: any): Promise; - saveDoc(collection: any, doc: any): any; - createDocumentTable(path: any): Promise; - getObject(path: any, collection: any): object; - dropTable(table: string, options: any): void; - createSchema(schemaName: string): void; - dropSchema(schemaName: string, options: any): void; - [name: string]: any; - } - } diff --git a/types/massive/massive-tests.ts b/types/massive/massive-tests.ts index 30cb977596..e43755b7f3 100644 --- a/types/massive/massive-tests.ts +++ b/types/massive/massive-tests.ts @@ -2,18 +2,9 @@ import massive = require('massive'); let dbconn: massive.Database; -function findUserById(id: number): Promise { - return dbconn.users.findOne({id: id}); -} - massive('postgres://app:password@localhost:5432/app').then( db => { - console.log(`DB connected successfully`); - dbconn = db; - }).catch(err => { - console.error(`Error connecting DB`); - }); From c8f6820103e777d5775dd896ba76b2836a2d9cae Mon Sep 17 00:00:00 2001 From: clarenceh Date: Sat, 10 Jun 2017 14:43:31 +0800 Subject: [PATCH 96/98] Update massive version number --- types/massive/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index 08a4ed6b7b..2e1493242f 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for massive 3.0 +// Type definitions for massive 3.0.0 // Project: https://github.com/dmfay/massive-js.git // Definitions by: Pascal Birchler // Clarence Ho From c3c731a101d24bd1bfd8100226ba56e55bc5657d Mon Sep 17 00:00:00 2001 From: clarenceh Date: Sat, 10 Jun 2017 14:46:28 +0800 Subject: [PATCH 97/98] Updated version no. --- types/massive/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index 2e1493242f..8a55659414 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for massive 3.0.0 +// Type definitions for massive v3.x // Project: https://github.com/dmfay/massive-js.git // Definitions by: Pascal Birchler // Clarence Ho From 88ce1b7d5775ab4bf3cbc45ec60461a9cfd0daae Mon Sep 17 00:00:00 2001 From: clarenceh Date: Sat, 10 Jun 2017 14:51:03 +0800 Subject: [PATCH 98/98] Updated version --- types/massive/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index 8a55659414..1ed6b62ac6 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for massive v3.x +// Type definitions for massive 3.x // Project: https://github.com/dmfay/massive-js.git // Definitions by: Pascal Birchler // Clarence Ho